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){
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 am.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 if (ec.InferReturnType) {
745 ec.ReturnType = Expr.Type;
747 Expr = Convert.ImplicitConversionRequired (
748 ec, Expr, ec.ReturnType, loc);
755 int errors = Report.Errors;
756 unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
758 ec.NeedReturnLabel ();
759 ec.CurrentBranching.CurrentUsageVector.Goto ();
760 return errors == Report.Errors;
763 protected override void DoEmit (EmitContext ec)
769 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
773 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
775 ec.ig.Emit (OpCodes.Ret);
778 protected override void CloneTo (CloneContext clonectx, Statement t)
780 Return target = (Return) t;
782 target.Expr = Expr.Clone (clonectx);
786 public class Goto : Statement {
788 LabeledStatement label;
791 public override bool Resolve (EmitContext ec)
793 int errors = Report.Errors;
794 unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
795 ec.CurrentBranching.CurrentUsageVector.Goto ();
796 return errors == Report.Errors;
799 public Goto (string label, Location l)
805 public string Target {
806 get { return target; }
809 public void SetResolvedTarget (LabeledStatement label)
812 label.AddReference ();
815 protected override void DoEmit (EmitContext ec)
818 throw new InternalErrorException ("goto emitted before target resolved");
819 Label l = label.LabelTarget (ec);
820 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
824 public class LabeledStatement : Statement {
831 FlowBranching.UsageVector vectors;
833 public LabeledStatement (string name, Location l)
839 public Label LabelTarget (EmitContext ec)
844 label = ec.ig.DefineLabel ();
854 public bool IsDefined {
855 get { return defined; }
858 public bool HasBeenReferenced {
859 get { return referenced; }
862 public FlowBranching.UsageVector JumpOrigins {
863 get { return vectors; }
866 public void AddUsageVector (FlowBranching.UsageVector vector)
868 vector = vector.Clone ();
869 vector.Next = vectors;
873 public override bool Resolve (EmitContext ec)
875 // this flow-branching will be terminated when the surrounding block ends
876 ec.StartFlowBranching (this);
880 protected override void DoEmit (EmitContext ec)
882 if (ig != null && ig != ec.ig)
883 throw new InternalErrorException ("cannot happen");
885 ec.ig.MarkLabel (label);
888 public void AddReference ()
896 /// `goto default' statement
898 public class GotoDefault : Statement {
900 public GotoDefault (Location l)
905 public override bool Resolve (EmitContext ec)
907 ec.CurrentBranching.CurrentUsageVector.Goto ();
911 protected override void DoEmit (EmitContext ec)
913 if (ec.Switch == null){
914 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
918 if (!ec.Switch.GotDefault){
919 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
922 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
927 /// `goto case' statement
929 public class GotoCase : Statement {
933 public GotoCase (Expression e, Location l)
939 public override bool Resolve (EmitContext ec)
941 if (ec.Switch == null){
942 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
946 expr = expr.Resolve (ec);
950 Constant c = expr as Constant;
952 Error (150, "A constant value is expected");
956 Type type = ec.Switch.SwitchType;
957 if (!Convert.ImplicitStandardConversionExists (c, type))
958 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
959 "convertible to type `{0}'", TypeManager.CSharpName (type));
962 object val = c.GetValue ();
963 if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
964 val = TypeManager.ChangeType (val, type, out fail);
967 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
968 c.GetSignatureForError (), TypeManager.CSharpName (type));
973 val = SwitchLabel.NullStringCase;
975 sl = (SwitchLabel) ec.Switch.Elements [val];
978 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
982 ec.CurrentBranching.CurrentUsageVector.Goto ();
986 protected override void DoEmit (EmitContext ec)
988 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
991 protected override void CloneTo (CloneContext clonectx, Statement t)
993 GotoCase target = (GotoCase) t;
995 target.expr = expr.Clone (clonectx);
996 target.sl = sl.Clone (clonectx);
1000 public class Throw : Statement {
1003 public Throw (Expression expr, Location l)
1009 public override bool Resolve (EmitContext ec)
1011 ec.CurrentBranching.CurrentUsageVector.Goto ();
1014 expr = expr.Resolve (ec);
1018 ExprClass eclass = expr.eclass;
1020 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1021 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1022 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
1028 if ((t != TypeManager.exception_type) &&
1029 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
1030 !(expr is NullLiteral)) {
1032 "The type caught or thrown must be derived " +
1033 "from System.Exception");
1040 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
1045 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1051 protected override void DoEmit (EmitContext ec)
1054 ec.ig.Emit (OpCodes.Rethrow);
1058 ec.ig.Emit (OpCodes.Throw);
1062 protected override void CloneTo (CloneContext clonectx, Statement t)
1064 Throw target = (Throw) t;
1066 target.expr = expr.Clone (clonectx);
1070 public class Break : Statement {
1072 public Break (Location l)
1077 bool unwind_protect;
1079 public override bool Resolve (EmitContext ec)
1081 int errors = Report.Errors;
1082 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1083 ec.CurrentBranching.CurrentUsageVector.Goto ();
1084 return errors == Report.Errors;
1087 protected override void DoEmit (EmitContext ec)
1089 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
1093 public class Continue : Statement {
1095 public Continue (Location l)
1100 bool unwind_protect;
1102 public override bool Resolve (EmitContext ec)
1104 int errors = Report.Errors;
1105 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1106 ec.CurrentBranching.CurrentUsageVector.Goto ();
1107 return errors == Report.Errors;
1110 protected override void DoEmit (EmitContext ec)
1112 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
1116 public abstract class Variable
1118 public abstract Type Type {
1122 public abstract bool HasInstance {
1126 public abstract bool NeedsTemporary {
1130 public abstract void EmitInstance (EmitContext ec);
1132 public abstract void Emit (EmitContext ec);
1134 public abstract void EmitAssign (EmitContext ec);
1136 public abstract void EmitAddressOf (EmitContext ec);
1140 // The information about a user-perceived local variable
1142 public class LocalInfo {
1143 public Expression Type;
1145 public Type VariableType;
1146 public readonly string Name;
1147 public readonly Location Location;
1148 public readonly Block Block;
1150 public VariableInfo VariableInfo;
1153 public Variable Variable {
1165 CompilerGenerated = 64,
1169 public enum ReadOnlyContext: byte {
1176 ReadOnlyContext ro_context;
1177 LocalBuilder builder;
1179 public LocalInfo (Expression type, string name, Block block, Location l)
1187 public LocalInfo (DeclSpace ds, Block block, Location l)
1189 VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
1194 public void ResolveVariable (EmitContext ec)
1196 Block theblock = Block;
1197 if (theblock.ScopeInfo != null)
1198 var = theblock.ScopeInfo.GetCapturedVariable (this);
1203 // This is needed to compile on both .NET 1.x and .NET 2.x
1204 // the later introduced `DeclareLocal (Type t, bool pinned)'
1206 builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1208 builder = ec.ig.DeclareLocal (VariableType);
1210 var = new LocalVariable (this, builder);
1214 public void EmitSymbolInfo (EmitContext ec, string name)
1216 if (builder != null)
1217 ec.DefineLocalVariable (name, builder);
1220 public bool IsThisAssigned (EmitContext ec)
1222 if (VariableInfo == null)
1223 throw new Exception ();
1225 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1228 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, ec.loc);
1231 public bool IsAssigned (EmitContext ec)
1233 if (VariableInfo == null)
1234 throw new Exception ();
1236 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1239 public bool Resolve (EmitContext ec)
1241 if (VariableType == null) {
1242 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1246 VariableType = texpr.Type;
1249 if (TypeManager.IsGenericParameter (VariableType))
1252 if (VariableType == TypeManager.void_type) {
1253 Expression.Error_VoidInvalidInTheContext (Location);
1257 if (VariableType.IsAbstract && VariableType.IsSealed) {
1258 FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
1262 if (VariableType.IsPointer && !ec.InUnsafe)
1263 Expression.UnsafeError (Location);
1268 public bool IsCaptured {
1270 return (flags & Flags.Captured) != 0;
1274 flags |= Flags.Captured;
1278 public bool IsConstant {
1280 return (flags & Flags.IsConstant) != 0;
1283 flags |= Flags.IsConstant;
1287 public bool AddressTaken {
1289 return (flags & Flags.AddressTaken) != 0;
1293 flags |= Flags.AddressTaken;
1297 public bool CompilerGenerated {
1299 return (flags & Flags.CompilerGenerated) != 0;
1303 flags |= Flags.CompilerGenerated;
1307 public override string ToString ()
1309 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1310 Name, Type, VariableInfo, Location);
1315 return (flags & Flags.Used) != 0;
1318 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1322 public bool ReadOnly {
1324 return (flags & Flags.ReadOnly) != 0;
1328 public void SetReadOnlyContext (ReadOnlyContext context)
1330 flags |= Flags.ReadOnly;
1331 ro_context = context;
1334 public string GetReadOnlyContext ()
1337 throw new InternalErrorException ("Variable is not readonly");
1339 switch (ro_context) {
1340 case ReadOnlyContext.Fixed:
1341 return "fixed variable";
1342 case ReadOnlyContext.Foreach:
1343 return "foreach iteration variable";
1344 case ReadOnlyContext.Using:
1345 return "using variable";
1347 throw new NotImplementedException ();
1351 // Whether the variable is pinned, if Pinned the variable has been
1352 // allocated in a pinned slot with DeclareLocal.
1354 public bool Pinned {
1356 return (flags & Flags.Pinned) != 0;
1359 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1363 public bool IsThis {
1365 return (flags & Flags.IsThis) != 0;
1368 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1372 protected class LocalVariable : Variable
1374 public readonly LocalInfo LocalInfo;
1375 LocalBuilder builder;
1377 public LocalVariable (LocalInfo local, LocalBuilder builder)
1379 this.LocalInfo = local;
1380 this.builder = builder;
1383 public override Type Type {
1384 get { return LocalInfo.VariableType; }
1387 public override bool HasInstance {
1388 get { return false; }
1391 public override bool NeedsTemporary {
1392 get { return false; }
1395 public override void EmitInstance (EmitContext ec)
1400 public override void Emit (EmitContext ec)
1402 ec.ig.Emit (OpCodes.Ldloc, builder);
1405 public override void EmitAssign (EmitContext ec)
1407 ec.ig.Emit (OpCodes.Stloc, builder);
1410 public override void EmitAddressOf (EmitContext ec)
1412 ec.ig.Emit (OpCodes.Ldloca, builder);
1416 public LocalInfo Clone (CloneContext clonectx)
1418 // Only this kind is created by the parser.
1419 return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
1424 /// Block represents a C# block.
1428 /// This class is used in a number of places: either to represent
1429 /// explicit blocks that the programmer places or implicit blocks.
1431 /// Implicit blocks are used as labels or to introduce variable
1434 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1435 /// they contain extra information that is not necessary on normal blocks.
1437 public class Block : Statement {
1438 public Block Parent;
1439 public readonly Location StartLocation;
1440 public Location EndLocation = Location.Null;
1442 public readonly ToplevelBlock Toplevel;
1445 public enum Flags : ushort {
1449 VariablesInitialized = 8,
1454 HasVarargs = 256, // Used in ToplevelBlock
1458 protected Flags flags;
1460 public bool Implicit {
1461 get { return (flags & Flags.Implicit) != 0; }
1464 public bool Unchecked {
1465 get { return (flags & Flags.Unchecked) != 0; }
1466 set { flags |= Flags.Unchecked; }
1469 public bool Unsafe {
1470 get { return (flags & Flags.Unsafe) != 0; }
1471 set { flags |= Flags.Unsafe; }
1475 // The statements in this block
1477 protected ArrayList statements;
1481 // An array of Blocks. We keep track of children just
1482 // to generate the local variable declarations.
1484 // Statements and child statements are handled through the
1490 // Labels. (label, block) pairs.
1495 // Keeps track of (name, type) pairs
1497 IDictionary variables;
1500 // Keeps track of constants
1501 Hashtable constants;
1504 // Temporary variables.
1506 ArrayList temporary_variables;
1509 // If this is a switch section, the enclosing switch block.
1513 ExpressionStatement scope_init;
1515 ArrayList anonymous_children;
1517 protected static int id;
1521 public Block (Block parent)
1522 : this (parent, (Flags) 0, Location.Null, Location.Null)
1525 public Block (Block parent, Flags flags)
1526 : this (parent, flags, Location.Null, Location.Null)
1529 public Block (Block parent, Location start, Location end)
1530 : this (parent, (Flags) 0, start, end)
1533 public Block (Block parent, Flags flags, Location start, Location end)
1536 parent.AddChild (this);
1538 this.Parent = parent;
1540 this.StartLocation = start;
1541 this.EndLocation = end;
1544 statements = new ArrayList ();
1546 if ((flags & Flags.IsToplevel) != 0)
1547 Toplevel = (ToplevelBlock) this;
1549 Toplevel = parent.Toplevel;
1551 if (parent != null && Implicit) {
1552 if (parent.known_variables == null)
1553 parent.known_variables = new Hashtable ();
1554 // share with parent
1555 known_variables = parent.known_variables;
1559 public Block CreateSwitchBlock (Location start)
1561 Block new_block = new Block (this, start, start);
1562 new_block.switch_block = this;
1567 get { return this_id; }
1570 public IDictionary Variables {
1572 if (variables == null)
1573 variables = new ListDictionary ();
1578 void AddChild (Block b)
1580 if (children == null)
1581 children = new ArrayList ();
1586 public void SetEndLocation (Location loc)
1591 protected static void Error_158 (string name, Location loc)
1593 Report.Error (158, loc, "The label `{0}' shadows another label " +
1594 "by the same name in a contained scope.", name);
1598 /// Adds a label to the current block.
1602 /// false if the name already exists in this block. true
1606 public bool AddLabel (LabeledStatement target)
1608 if (switch_block != null)
1609 return switch_block.AddLabel (target);
1611 string name = target.Name;
1614 while (cur != null) {
1615 if (cur.DoLookupLabel (name) != null) {
1616 Report.Error (140, target.loc,
1617 "The label `{0}' is a duplicate", name);
1627 while (cur != null) {
1628 if (cur.DoLookupLabel (name) != null) {
1629 Error_158 (name, target.loc);
1633 if (children != null) {
1634 foreach (Block b in children) {
1635 LabeledStatement s = b.DoLookupLabel (name);
1639 Error_158 (name, target.loc);
1647 Toplevel.CheckError158 (name, target.loc);
1650 labels = new Hashtable ();
1652 labels.Add (name, target);
1656 public LabeledStatement LookupLabel (string name)
1658 LabeledStatement s = DoLookupLabel (name);
1662 if (children == null)
1665 foreach (Block child in children) {
1666 if (!child.Implicit)
1669 s = child.LookupLabel (name);
1677 LabeledStatement DoLookupLabel (string name)
1679 if (switch_block != null)
1680 return switch_block.LookupLabel (name);
1683 if (labels.Contains (name))
1684 return ((LabeledStatement) labels [name]);
1689 Hashtable known_variables;
1692 // Marks a variable with name @name as being used in this or a child block.
1693 // If a variable name has been used in a child block, it's illegal to
1694 // declare a variable with the same name in the current block.
1696 void AddKnownVariable (string name, LocalInfo info)
1698 if (known_variables == null)
1699 known_variables = new Hashtable ();
1701 known_variables [name] = info;
1704 LocalInfo GetKnownVariableInfo (string name, bool recurse)
1706 if (known_variables != null) {
1707 LocalInfo vi = (LocalInfo) known_variables [name];
1712 if (!recurse || (children == null))
1715 foreach (Block block in children) {
1716 LocalInfo vi = block.GetKnownVariableInfo (name, true);
1724 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1727 LocalInfo kvi = b.GetKnownVariableInfo (name, true);
1728 while (kvi == null) {
1734 kvi = b.GetKnownVariableInfo (name, false);
1740 // Is kvi.Block nested inside 'b'
1741 if (b.known_variables != kvi.Block.known_variables) {
1743 // If a variable by the same name it defined in a nested block of this
1744 // block, we violate the invariant meaning in a block.
1747 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1748 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1753 // It's ok if the definition is in a nested subblock of b, but not
1754 // nested inside this block -- a definition in a sibling block
1755 // should not affect us.
1761 // Block 'b' and kvi.Block are the same textual block.
1762 // However, different variables are extant.
1764 // Check if the variable is in scope in both blocks. We use
1765 // an indirect check that depends on AddVariable doing its
1766 // part in maintaining the invariant-meaning-in-block property.
1768 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1772 // Even though we detected the error when the name is used, we
1773 // treat it as if the variable declaration was in error.
1775 Report.SymbolRelatedToPreviousError (loc, name);
1776 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1780 public bool CheckError136_InParents (string name, Location loc)
1782 for (Block b = Parent; b != null; b = b.Parent) {
1783 if (!b.DoCheckError136 (name, "parent or current", loc))
1787 for (Block b = Toplevel.ContainerBlock; b != null; b = b.Toplevel.ContainerBlock) {
1788 if (!b.CheckError136_InParents (name, loc))
1795 public bool CheckError136_InChildren (string name, Location loc)
1797 if (!DoCheckError136_InChildren (name, loc))
1801 while (b.Implicit) {
1802 if (!b.Parent.DoCheckError136_InChildren (name, loc))
1810 protected bool DoCheckError136_InChildren (string name, Location loc)
1812 if (!DoCheckError136 (name, "child", loc))
1815 if (AnonymousChildren != null) {
1816 foreach (ToplevelBlock child in AnonymousChildren) {
1817 if (!child.DoCheckError136_InChildren (name, loc))
1822 if (children != null) {
1823 foreach (Block child in children) {
1824 if (!child.DoCheckError136_InChildren (name, loc))
1832 public bool CheckError136 (string name, string scope, bool check_parents,
1833 bool check_children, Location loc)
1835 if (!DoCheckError136 (name, scope, loc))
1838 if (check_parents) {
1839 if (!CheckError136_InParents (name, loc))
1843 if (check_children) {
1844 if (!CheckError136_InChildren (name, loc))
1848 for (Block c = Toplevel.ContainerBlock; c != null; c = c.Toplevel.ContainerBlock) {
1849 if (!c.DoCheckError136 (name, "parent or current", loc))
1856 protected bool DoCheckError136 (string name, string scope, Location loc)
1858 LocalInfo vi = GetKnownVariableInfo (name, false);
1860 Report.SymbolRelatedToPreviousError (vi.Location, name);
1861 Error_AlreadyDeclared (loc, name, scope != null ? scope : "child");
1866 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1868 Report.SymbolRelatedToPreviousError (p.Location, name);
1869 Error_AlreadyDeclared (
1870 loc, name, scope != null ? scope : "method argument");
1877 public LocalInfo AddVariable (Expression type, string name, Location l)
1879 LocalInfo vi = GetLocalInfo (name);
1881 Report.SymbolRelatedToPreviousError (vi.Location, name);
1882 if (known_variables == vi.Block.known_variables)
1883 Report.Error (128, l,
1884 "A local variable named `{0}' is already defined in this scope", name);
1886 Error_AlreadyDeclared (l, name, "parent");
1890 if (!CheckError136 (name, null, true, true, l))
1893 vi = new LocalInfo (type, name, this, l);
1894 Variables.Add (name, vi);
1895 AddKnownVariable (name, vi);
1897 if ((flags & Flags.VariablesInitialized) != 0)
1898 throw new Exception ();
1903 void Error_AlreadyDeclared (Location loc, string var, string reason)
1905 Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1906 "in this scope because it would give a different meaning " +
1907 "to `{0}', which is already used in a `{1}' scope " +
1908 "to denote something else", var, reason);
1911 public bool AddConstant (Expression type, string name, Expression value, Location l)
1913 if (AddVariable (type, name, l) == null)
1916 if (constants == null)
1917 constants = new Hashtable ();
1919 constants.Add (name, value);
1921 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1926 static int next_temp_id = 0;
1928 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1930 Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1932 if (temporary_variables == null)
1933 temporary_variables = new ArrayList ();
1935 int id = ++next_temp_id;
1936 string name = "$s_" + id.ToString ();
1938 LocalInfo li = new LocalInfo (te, name, this, loc);
1939 li.CompilerGenerated = true;
1940 temporary_variables.Add (li);
1944 public LocalInfo GetLocalInfo (string name)
1946 for (Block b = this; b != null; b = b.Parent) {
1947 if (b.variables != null) {
1948 LocalInfo ret = b.variables [name] as LocalInfo;
1956 public Expression GetVariableType (string name)
1958 LocalInfo vi = GetLocalInfo (name);
1959 return vi == null ? null : vi.Type;
1962 public Expression GetConstantExpression (string name)
1964 for (Block b = this; b != null; b = b.Parent) {
1965 if (b.constants != null) {
1966 Expression ret = b.constants [name] as Expression;
1974 public void AddStatement (Statement s)
1977 flags |= Flags.BlockUsed;
1981 get { return (flags & Flags.BlockUsed) != 0; }
1986 flags |= Flags.BlockUsed;
1989 public bool HasRet {
1990 get { return (flags & Flags.HasRet) != 0; }
1993 public bool IsDestructor {
1994 get { return (flags & Flags.IsDestructor) != 0; }
1997 public void SetDestructor ()
1999 flags |= Flags.IsDestructor;
2002 VariableMap param_map, local_map;
2004 public VariableMap ParameterMap {
2006 if ((flags & Flags.VariablesInitialized) == 0){
2007 throw new Exception ("Variables have not been initialized yet");
2014 public VariableMap LocalMap {
2016 if ((flags & Flags.VariablesInitialized) == 0)
2017 throw new Exception ("Variables have not been initialized yet");
2023 protected ScopeInfo scope_info;
2025 public ScopeInfo ScopeInfo {
2026 get { return scope_info; }
2029 public ScopeInfo CreateScopeInfo ()
2031 if (scope_info == null)
2032 scope_info = ScopeInfo.CreateScope (this);
2037 public ArrayList AnonymousChildren {
2038 get { return anonymous_children; }
2041 public void AddAnonymousChild (ToplevelBlock b)
2043 if (anonymous_children == null)
2044 anonymous_children = new ArrayList ();
2046 anonymous_children.Add (b);
2050 /// Emits the variable declarations and labels.
2053 /// tc: is our typecontainer (to resolve type references)
2054 /// ig: is the code generator:
2056 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
2058 Report.Debug (64, "BLOCK RESOLVE META", this, Parent, toplevel);
2060 // If some parent block was unsafe, we remain unsafe even if this block
2061 // isn't explicitly marked as such.
2062 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
2064 // Compute the VariableMap's.
2066 // Unfortunately, we don't know the type when adding variables with
2067 // AddVariable(), so we need to compute this info here.
2071 if (variables != null) {
2072 foreach (LocalInfo li in variables.Values)
2075 locals = new LocalInfo [variables.Count];
2076 variables.Values.CopyTo (locals, 0);
2078 locals = new LocalInfo [0];
2081 local_map = new VariableMap (Parent.LocalMap, locals);
2083 local_map = new VariableMap (locals);
2085 param_map = new VariableMap (ip);
2086 flags |= Flags.VariablesInitialized;
2089 // Process this block variables
2091 if (variables != null) {
2092 foreach (DictionaryEntry de in variables) {
2093 string name = (string) de.Key;
2094 LocalInfo vi = (LocalInfo) de.Value;
2095 Type variable_type = vi.VariableType;
2097 if (variable_type == null)
2100 if (variable_type.IsPointer) {
2102 // Am not really convinced that this test is required (Microsoft does it)
2103 // but the fact is that you would not be able to use the pointer variable
2106 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
2111 if (constants == null)
2114 Expression cv = (Expression) constants [name];
2118 // Don't let 'const int Foo = Foo;' succeed.
2119 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
2120 // which in turn causes the 'must be constant' error to be triggered.
2121 constants.Remove (name);
2123 if (!Const.IsConstantTypeValid (variable_type)) {
2124 Const.Error_InvalidConstantType (variable_type, loc);
2128 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
2129 ec.CurrentBlock = this;
2130 Expression e = cv.Resolve (ec);
2134 Constant ce = e as Constant;
2136 Const.Error_ExpressionMustBeConstant (vi.Location, name);
2140 e = ce.ConvertImplicitly (variable_type);
2142 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue)
2143 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
2145 ce.Error_ValueCannotBeConverted (null, vi.Location, variable_type, false);
2149 constants.Add (name, e);
2150 vi.IsConstant = true;
2156 // Now, handle the children
2158 if (children != null) {
2159 foreach (Block b in children)
2160 b.ResolveMeta (toplevel, ec, ip);
2166 // Emits the local variable declarations for a block
2168 public virtual void EmitMeta (EmitContext ec)
2170 Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
2171 if (ScopeInfo != null) {
2172 scope_init = ScopeInfo.GetScopeInitializer (ec);
2173 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
2177 if (variables != null){
2178 foreach (LocalInfo vi in variables.Values)
2179 vi.ResolveVariable (ec);
2182 if (temporary_variables != null) {
2183 foreach (LocalInfo vi in temporary_variables)
2184 vi.ResolveVariable (ec);
2187 if (children != null){
2188 foreach (Block b in children)
2193 void UsageWarning (FlowBranching.UsageVector vector)
2197 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
2198 foreach (DictionaryEntry de in variables){
2199 LocalInfo vi = (LocalInfo) de.Value;
2204 name = (string) de.Key;
2206 // vi.VariableInfo can be null for 'catch' variables
2207 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2208 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2210 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2216 bool unreachable_shown;
2219 private void CheckPossibleMistakenEmptyStatement (Statement s)
2223 // Some statements are wrapped by a Block. Since
2224 // others' internal could be changed, here I treat
2225 // them as possibly wrapped by Block equally.
2226 Block b = s as Block;
2227 if (b != null && b.statements.Count == 1)
2228 s = (Statement) b.statements [0];
2231 body = ((Lock) s).Statement;
2233 body = ((For) s).Statement;
2234 else if (s is Foreach)
2235 body = ((Foreach) s).Statement;
2236 else if (s is While)
2237 body = ((While) s).Statement;
2238 else if (s is Using)
2239 body = ((Using) s).Statement;
2240 else if (s is Fixed)
2241 body = ((Fixed) s).Statement;
2245 if (body == null || body is EmptyStatement)
2246 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2249 public override bool Resolve (EmitContext ec)
2251 Block prev_block = ec.CurrentBlock;
2254 int errors = Report.Errors;
2256 ec.CurrentBlock = this;
2257 ec.StartFlowBranching (this);
2259 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2262 // This flag is used to notate nested statements as unreachable from the beginning of this block.
2263 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
2264 // from the beginning of the function. The outer Resolve() that detected the unreachability is
2265 // responsible for handling the situation.
2267 int statement_count = statements.Count;
2268 for (int ix = 0; ix < statement_count; ix++){
2269 Statement s = (Statement) statements [ix];
2270 // Check possible empty statement (CS0642)
2271 if (RootContext.WarningLevel >= 3 &&
2272 ix + 1 < statement_count &&
2273 statements [ix + 1] is Block)
2274 CheckPossibleMistakenEmptyStatement (s);
2277 // Warn if we detect unreachable code.
2280 if (s is EmptyStatement)
2284 ((Block) s).unreachable = true;
2286 if (!unreachable_shown && !(s is LabeledStatement)) {
2287 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2288 unreachable_shown = true;
2293 // Note that we're not using ResolveUnreachable() for unreachable
2294 // statements here. ResolveUnreachable() creates a temporary
2295 // flow branching and kills it afterwards. This leads to problems
2296 // if you have two unreachable statements where the first one
2297 // assigns a variable and the second one tries to access it.
2300 if (!s.Resolve (ec)) {
2302 statements [ix] = EmptyStatement.Value;
2306 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2307 statements [ix] = EmptyStatement.Value;
2309 num_statements = ix + 1;
2311 unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
2312 if (unreachable && s is LabeledStatement)
2313 throw new InternalErrorException ("should not happen");
2316 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2317 ec.CurrentBranching, statement_count, num_statements);
2322 while (ec.CurrentBranching is FlowBranchingLabeled)
2323 ec.EndFlowBranching ();
2325 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2327 ec.CurrentBlock = prev_block;
2329 // If we're a non-static `struct' constructor which doesn't have an
2330 // initializer, then we must initialize all of the struct's fields.
2331 if ((flags & Flags.IsToplevel) != 0 &&
2332 !Toplevel.IsThisAssigned (ec) &&
2333 !vector.IsUnreachable)
2336 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2337 foreach (LabeledStatement label in labels.Values)
2338 if (!label.HasBeenReferenced)
2339 Report.Warning (164, 2, label.loc,
2340 "This label has not been referenced");
2343 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2345 if (vector.IsUnreachable)
2346 flags |= Flags.HasRet;
2348 if (ok && (errors == Report.Errors)) {
2349 if (RootContext.WarningLevel >= 3)
2350 UsageWarning (vector);
2356 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2358 unreachable_shown = true;
2362 Report.Warning (162, 2, loc, "Unreachable code detected");
2364 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2365 bool ok = Resolve (ec);
2366 ec.KillFlowBranching ();
2371 protected override void DoEmit (EmitContext ec)
2373 for (int ix = 0; ix < num_statements; ix++){
2374 Statement s = (Statement) statements [ix];
2376 // Check whether we are the last statement in a
2379 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2380 ec.IsLastStatement = true;
2382 ec.IsLastStatement = false;
2388 public override void Emit (EmitContext ec)
2390 Block prev_block = ec.CurrentBlock;
2392 ec.CurrentBlock = this;
2394 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2395 bool is_lexical_block = !Implicit && (Parent != null);
2397 if (emit_debug_info) {
2398 if (is_lexical_block)
2401 ec.Mark (StartLocation, true);
2402 if (scope_init != null)
2403 scope_init.EmitStatement (ec);
2405 ec.Mark (EndLocation, true);
2407 if (emit_debug_info) {
2408 if (is_lexical_block)
2411 if (variables != null) {
2412 foreach (DictionaryEntry de in variables) {
2413 string name = (string) de.Key;
2414 LocalInfo vi = (LocalInfo) de.Value;
2416 vi.EmitSymbolInfo (ec, name);
2421 ec.CurrentBlock = prev_block;
2425 // Returns true if we ar ea child of `b'.
2427 public bool IsChildOf (Block b)
2429 Block current = this;
2432 if (current.Parent == b)
2434 current = current.Parent;
2435 } while (current != null);
2439 public override string ToString ()
2441 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2444 protected override void CloneTo (CloneContext clonectx, Statement t)
2446 Block target = (Block) t;
2449 target.Parent = clonectx.LookupBlock (Parent);
2451 target.statements = new ArrayList ();
2452 if (target.children != null){
2453 target.children = new ArrayList ();
2454 foreach (Block b in children){
2455 Block newblock = (Block) b.Clone (clonectx);
2457 target.children.Add (newblock);
2462 foreach (Statement s in statements)
2463 target.statements.Add (s.Clone (clonectx));
2465 if (variables != null){
2466 target.variables = new Hashtable ();
2468 foreach (DictionaryEntry de in variables){
2469 LocalInfo newlocal = ((LocalInfo) de.Value).Clone (clonectx);
2470 target.variables [de.Key] = newlocal;
2471 clonectx.AddVariableMap ((LocalInfo) de.Value, newlocal);
2476 // TODO: labels, switch_block, constants (?), anonymous_children
2482 // A toplevel block contains extra information, the split is done
2483 // only to separate information that would otherwise bloat the more
2484 // lightweight Block.
2486 // In particular, this was introduced when the support for Anonymous
2487 // Methods was implemented.
2489 public class ToplevelBlock : Block {
2491 // Pointer to the host of this anonymous method, or null
2492 // if we are the topmost block
2495 ToplevelBlock child;
2496 GenericMethod generic;
2497 FlowBranchingToplevel top_level_branching;
2498 AnonymousContainer anonymous_container;
2499 RootScopeInfo root_scope;
2501 public bool HasVarargs {
2502 get { return (flags & Flags.HasVarargs) != 0; }
2503 set { flags |= Flags.HasVarargs; }
2506 public bool IsIterator {
2507 get { return (flags & Flags.IsIterator) != 0; }
2511 // The parameters for the block.
2513 Parameters parameters;
2514 public Parameters Parameters {
2515 get { return parameters; }
2518 public bool CompleteContexts (EmitContext ec)
2520 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this,
2521 container, root_scope);
2523 if (root_scope != null)
2524 root_scope.LinkScopes ();
2526 if ((container == null) && (root_scope != null)) {
2527 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this,
2530 if (root_scope.DefineType () == null)
2532 if (!root_scope.ResolveType ())
2534 if (!root_scope.ResolveMembers ())
2536 if (!root_scope.DefineMembers ())
2543 public GenericMethod GenericMethod {
2544 get { return generic; }
2547 public ToplevelBlock Container {
2548 get { return container != null ? container.Toplevel : null; }
2551 public Block ContainerBlock {
2552 get { return container; }
2555 public AnonymousContainer AnonymousContainer {
2556 get { return anonymous_container; }
2557 set { anonymous_container = value; }
2561 // Parent is only used by anonymous blocks to link back to their
2564 public ToplevelBlock (Block container, Parameters parameters, Location start) :
2565 this (container, (Flags) 0, parameters, start)
2569 public ToplevelBlock (Block container, Parameters parameters, GenericMethod generic,
2571 this (container, parameters, start)
2573 this.generic = generic;
2576 public ToplevelBlock (Parameters parameters, Location start) :
2577 this (null, (Flags) 0, parameters, start)
2581 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2582 this (null, flags, parameters, start)
2586 public ToplevelBlock (Block container, Flags flags, Parameters parameters, Location start) :
2587 base (null, flags | Flags.IsToplevel, start, Location.Null)
2589 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2590 this.container = container;
2593 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2597 public bool CheckError158 (string name, Location loc)
2599 if (AnonymousChildren != null) {
2600 foreach (ToplevelBlock child in AnonymousChildren) {
2601 if (!child.CheckError158 (name, loc))
2606 for (ToplevelBlock c = Container; c != null; c = c.Container) {
2607 if (!c.DoCheckError158 (name, loc))
2614 bool DoCheckError158 (string name, Location loc)
2616 LabeledStatement s = LookupLabel (name);
2618 Error_158 (name, loc);
2625 public RootScopeInfo CreateRootScope (TypeContainer host)
2627 if (root_scope != null)
2630 if (Container == null)
2631 root_scope = new RootScopeInfo (
2632 this, host, generic, StartLocation);
2634 if (scope_info != null)
2635 throw new InternalErrorException ();
2637 scope_info = root_scope;
2641 public void CreateIteratorHost (RootScopeInfo root)
2643 Report.Debug (64, "CREATE ITERATOR HOST", this, root,
2644 container, root_scope);
2646 if ((container != null) || (root_scope != null))
2647 throw new InternalErrorException ();
2649 scope_info = root_scope = root;
2652 public RootScopeInfo RootScope {
2654 if (root_scope != null)
2656 else if (Container != null)
2657 return Container.RootScope;
2663 public FlowBranchingToplevel TopLevelBranching {
2664 get { return top_level_branching; }
2668 // This is used if anonymous methods are used inside an iterator
2669 // (see 2test-22.cs for an example).
2671 // The AnonymousMethod is created while parsing - at a time when we don't
2672 // know yet that we're inside an iterator, so it's `Container' is initially
2673 // null. Later on, when resolving the iterator, we need to move the
2674 // anonymous method into that iterator.
2676 public void ReParent (ToplevelBlock new_parent)
2678 container = new_parent;
2679 Parent = new_parent;
2680 new_parent.child = this;
2684 // Returns a `ParameterReference' for the given name, or null if there
2685 // is no such parameter
2687 public ParameterReference GetParameterReference (string name, Location loc)
2692 for (ToplevelBlock t = this; t != null; t = t.Container) {
2693 Parameters pars = t.Parameters;
2694 par = pars.GetParameterByName (name, out idx);
2696 return new ParameterReference (par, this, idx, loc);
2702 // Whether the parameter named `name' is local to this block,
2703 // or false, if the parameter belongs to an encompassing block.
2705 public bool IsLocalParameter (string name)
2707 return Parameters.GetParameterByName (name) != null;
2711 // Whether the `name' is a parameter reference
2713 public bool IsParameterReference (string name)
2715 for (ToplevelBlock t = this; t != null; t = t.Container) {
2716 if (t.IsLocalParameter (name))
2722 LocalInfo this_variable = null;
2725 // Returns the "this" instance variable of this block.
2726 // See AddThisVariable() for more information.
2728 public LocalInfo ThisVariable {
2729 get { return this_variable; }
2734 // This is used by non-static `struct' constructors which do not have an
2735 // initializer - in this case, the constructor must initialize all of the
2736 // struct's fields. To do this, we add a "this" variable and use the flow
2737 // analysis code to ensure that it's been fully initialized before control
2738 // leaves the constructor.
2740 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2742 if (this_variable == null) {
2743 this_variable = new LocalInfo (ds, this, l);
2744 this_variable.Used = true;
2745 this_variable.IsThis = true;
2747 Variables.Add ("this", this_variable);
2750 return this_variable;
2753 public bool IsThisAssigned (EmitContext ec)
2755 return this_variable == null || this_variable.IsThisAssigned (ec);
2758 public bool ResolveMeta (EmitContext ec, Parameters ip)
2760 int errors = Report.Errors;
2762 if (top_level_branching != null)
2768 if (!IsIterator && (container != null) && (parameters != null)) {
2769 foreach (Parameter p in parameters.FixedParameters) {
2770 if (!CheckError136_InParents (p.Name, loc))
2775 ResolveMeta (this, ec, ip);
2778 child.ResolveMeta (this, ec, ip);
2780 top_level_branching = ec.StartFlowBranching (this);
2782 return Report.Errors == errors;
2785 public override void EmitMeta (EmitContext ec)
2788 parameters.ResolveVariable (this);
2791 public void MakeIterator (Iterator iterator)
2793 flags |= Flags.IsIterator;
2795 Block block = new Block (this);
2796 foreach (Statement stmt in statements)
2797 block.AddStatement (stmt);
2798 statements = new ArrayList ();
2799 statements.Add (new MoveNextStatement (iterator, block));
2802 protected class MoveNextStatement : Statement {
2806 public MoveNextStatement (Iterator iterator, Block block)
2808 this.iterator = iterator;
2810 this.loc = iterator.Location;
2813 public override bool Resolve (EmitContext ec)
2815 return block.Resolve (ec);
2818 protected override void DoEmit (EmitContext ec)
2820 iterator.EmitMoveNext (ec, block);
2824 public override string ToString ()
2826 return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2827 root_scope, anonymous_container != null ?
2828 anonymous_container.Scope : null);
2832 public class SwitchLabel {
2839 Label il_label_code;
2840 bool il_label_code_set;
2842 public static readonly object NullStringCase = new object ();
2845 // if expr == null, then it is the default case.
2847 public SwitchLabel (Expression expr, Location l)
2853 public Expression Label {
2859 public object Converted {
2865 public Label GetILLabel (EmitContext ec)
2868 il_label = ec.ig.DefineLabel ();
2869 il_label_set = true;
2874 public Label GetILLabelCode (EmitContext ec)
2876 if (!il_label_code_set){
2877 il_label_code = ec.ig.DefineLabel ();
2878 il_label_code_set = true;
2880 return il_label_code;
2884 // Resolves the expression, reduces it to a literal if possible
2885 // and then converts it to the requested type.
2887 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2889 Expression e = label.Resolve (ec);
2894 Constant c = e as Constant;
2896 Report.Error (150, loc, "A constant value is expected");
2900 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2901 converted = NullStringCase;
2905 if (allow_nullable && c.GetValue () == null) {
2906 converted = NullStringCase;
2910 c = c.ImplicitConversionRequired (required_type, loc);
2914 converted = c.GetValue ();
2918 public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
2921 if (converted == null)
2923 else if (converted == NullStringCase)
2925 else if (TypeManager.IsEnumType (switchType))
2926 label = TypeManager.CSharpEnumValue (switchType, converted);
2928 label = converted.ToString ();
2930 Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
2931 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2934 public SwitchLabel Clone (CloneContext clonectx)
2936 return new SwitchLabel (label.Clone (clonectx), loc);
2940 public class SwitchSection {
2941 // An array of SwitchLabels.
2942 public readonly ArrayList Labels;
2943 public readonly Block Block;
2945 public SwitchSection (ArrayList labels, Block block)
2951 public SwitchSection Clone (CloneContext clonectx)
2953 ArrayList cloned_labels = new ArrayList ();
2955 foreach (SwitchLabel sl in cloned_labels)
2956 cloned_labels.Add (sl.Clone (clonectx));
2958 return new SwitchSection (cloned_labels, clonectx.LookupBlock (Block));
2962 public class Switch : Statement {
2963 public ArrayList Sections;
2964 public Expression Expr;
2967 /// Maps constants whose type type SwitchType to their SwitchLabels.
2969 public IDictionary Elements;
2972 /// The governing switch type
2974 public Type SwitchType;
2979 Label default_target;
2981 Expression new_expr;
2983 SwitchSection constant_section;
2984 SwitchSection default_section;
2988 // Nullable Types support for GMCS.
2990 Nullable.Unwrap unwrap;
2992 protected bool HaveUnwrap {
2993 get { return unwrap != null; }
2996 protected bool HaveUnwrap {
2997 get { return false; }
3002 // The types allowed to be implicitly cast from
3003 // on the governing type
3005 static Type [] allowed_types;
3007 public Switch (Expression e, ArrayList sects, Location l)
3014 public bool GotDefault {
3016 return default_section != null;
3020 public Label DefaultTarget {
3022 return default_target;
3027 // Determines the governing type for a switch. The returned
3028 // expression might be the expression from the switch, or an
3029 // expression that includes any potential conversions to the
3030 // integral types or to string.
3032 Expression SwitchGoverningType (EmitContext ec, Expression expr)
3034 Type t = TypeManager.DropGenericTypeArguments (expr.Type);
3036 if (t == TypeManager.byte_type ||
3037 t == TypeManager.sbyte_type ||
3038 t == TypeManager.ushort_type ||
3039 t == TypeManager.short_type ||
3040 t == TypeManager.uint32_type ||
3041 t == TypeManager.int32_type ||
3042 t == TypeManager.uint64_type ||
3043 t == TypeManager.int64_type ||
3044 t == TypeManager.char_type ||
3045 t == TypeManager.string_type ||
3046 t == TypeManager.bool_type ||
3047 t.IsSubclassOf (TypeManager.enum_type))
3050 if (allowed_types == null){
3051 allowed_types = new Type [] {
3052 TypeManager.sbyte_type,
3053 TypeManager.byte_type,
3054 TypeManager.short_type,
3055 TypeManager.ushort_type,
3056 TypeManager.int32_type,
3057 TypeManager.uint32_type,
3058 TypeManager.int64_type,
3059 TypeManager.uint64_type,
3060 TypeManager.char_type,
3061 TypeManager.string_type,
3062 TypeManager.bool_type
3067 // Try to find a *user* defined implicit conversion.
3069 // If there is no implicit conversion, or if there are multiple
3070 // conversions, we have to report an error
3072 Expression converted = null;
3073 foreach (Type tt in allowed_types){
3076 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
3081 // Ignore over-worked ImplicitUserConversions that do
3082 // an implicit conversion in addition to the user conversion.
3084 if (!(e is UserCast))
3087 if (converted != null){
3088 Report.ExtraInformation (
3090 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
3091 TypeManager.CSharpName (expr.Type)));
3101 // Performs the basic sanity checks on the switch statement
3102 // (looks for duplicate keys and non-constant expressions).
3104 // It also returns a hashtable with the keys that we will later
3105 // use to compute the switch tables
3107 bool CheckSwitch (EmitContext ec)
3110 Elements = Sections.Count > 10 ?
3111 (IDictionary)new Hashtable () :
3112 (IDictionary)new ListDictionary ();
3114 foreach (SwitchSection ss in Sections){
3115 foreach (SwitchLabel sl in ss.Labels){
3116 if (sl.Label == null){
3117 if (default_section != null){
3118 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
3121 default_section = ss;
3125 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
3130 object key = sl.Converted;
3132 Elements.Add (key, sl);
3133 } catch (ArgumentException) {
3134 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
3142 void EmitObjectInteger (ILGenerator ig, object k)
3145 IntConstant.EmitInt (ig, (int) k);
3146 else if (k is Constant) {
3147 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3150 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3153 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3155 IntConstant.EmitInt (ig, (int) (long) k);
3156 ig.Emit (OpCodes.Conv_I8);
3159 LongConstant.EmitLong (ig, (long) k);
3161 else if (k is ulong)
3163 ulong ul = (ulong) k;
3166 IntConstant.EmitInt (ig, unchecked ((int) ul));
3167 ig.Emit (OpCodes.Conv_U8);
3171 LongConstant.EmitLong (ig, unchecked ((long) ul));
3175 IntConstant.EmitInt (ig, (int) ((char) k));
3176 else if (k is sbyte)
3177 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3179 IntConstant.EmitInt (ig, (int) ((byte) k));
3180 else if (k is short)
3181 IntConstant.EmitInt (ig, (int) ((short) k));
3182 else if (k is ushort)
3183 IntConstant.EmitInt (ig, (int) ((ushort) k));
3185 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3187 throw new Exception ("Unhandled case");
3190 // structure used to hold blocks of keys while calculating table switch
3191 class KeyBlock : IComparable
3193 public KeyBlock (long _nFirst)
3195 nFirst = nLast = _nFirst;
3199 public ArrayList rgKeys = null;
3200 // how many items are in the bucket
3201 public int Size = 1;
3204 get { return (int) (nLast - nFirst + 1); }
3206 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3208 return kbLast.nLast - kbFirst.nFirst + 1;
3210 public int CompareTo (object obj)
3212 KeyBlock kb = (KeyBlock) obj;
3213 int nLength = Length;
3214 int nLengthOther = kb.Length;
3215 if (nLengthOther == nLength)
3216 return (int) (kb.nFirst - nFirst);
3217 return nLength - nLengthOther;
3222 /// This method emits code for a lookup-based switch statement (non-string)
3223 /// Basically it groups the cases into blocks that are at least half full,
3224 /// and then spits out individual lookup opcodes for each block.
3225 /// It emits the longest blocks first, and short blocks are just
3226 /// handled with direct compares.
3228 /// <param name="ec"></param>
3229 /// <param name="val"></param>
3230 /// <returns></returns>
3231 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3233 int cElements = Elements.Count;
3234 object [] rgKeys = new object [cElements];
3235 Elements.Keys.CopyTo (rgKeys, 0);
3236 Array.Sort (rgKeys);
3238 // initialize the block list with one element per key
3239 ArrayList rgKeyBlocks = new ArrayList ();
3240 foreach (object key in rgKeys)
3241 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3244 // iteratively merge the blocks while they are at least half full
3245 // there's probably a really cool way to do this with a tree...
3246 while (rgKeyBlocks.Count > 1)
3248 ArrayList rgKeyBlocksNew = new ArrayList ();
3249 kbCurr = (KeyBlock) rgKeyBlocks [0];
3250 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3252 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3253 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3256 kbCurr.nLast = kb.nLast;
3257 kbCurr.Size += kb.Size;
3261 // start a new block
3262 rgKeyBlocksNew.Add (kbCurr);
3266 rgKeyBlocksNew.Add (kbCurr);
3267 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3269 rgKeyBlocks = rgKeyBlocksNew;
3272 // initialize the key lists
3273 foreach (KeyBlock kb in rgKeyBlocks)
3274 kb.rgKeys = new ArrayList ();
3276 // fill the key lists
3278 if (rgKeyBlocks.Count > 0) {
3279 kbCurr = (KeyBlock) rgKeyBlocks [0];
3280 foreach (object key in rgKeys)
3282 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3283 System.Convert.ToInt64 (key) > kbCurr.nLast;
3285 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3286 kbCurr.rgKeys.Add (key);
3290 // sort the blocks so we can tackle the largest ones first
3291 rgKeyBlocks.Sort ();
3293 // okay now we can start...
3294 ILGenerator ig = ec.ig;
3295 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3296 Label lblDefault = ig.DefineLabel ();
3298 Type typeKeys = null;
3299 if (rgKeys.Length > 0)
3300 typeKeys = rgKeys [0].GetType (); // used for conversions
3304 if (TypeManager.IsEnumType (SwitchType))
3305 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3307 compare_type = SwitchType;
3309 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3311 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3312 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3315 foreach (object key in kb.rgKeys)
3317 ig.Emit (OpCodes.Ldloc, val);
3318 EmitObjectInteger (ig, key);
3319 SwitchLabel sl = (SwitchLabel) Elements [key];
3320 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3325 // TODO: if all the keys in the block are the same and there are
3326 // no gaps/defaults then just use a range-check.
3327 if (compare_type == TypeManager.int64_type ||
3328 compare_type == TypeManager.uint64_type)
3330 // TODO: optimize constant/I4 cases
3332 // check block range (could be > 2^31)
3333 ig.Emit (OpCodes.Ldloc, val);
3334 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3335 ig.Emit (OpCodes.Blt, lblDefault);
3336 ig.Emit (OpCodes.Ldloc, val);
3337 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3338 ig.Emit (OpCodes.Bgt, lblDefault);
3341 ig.Emit (OpCodes.Ldloc, val);
3344 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3345 ig.Emit (OpCodes.Sub);
3347 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3352 ig.Emit (OpCodes.Ldloc, val);
3353 int nFirst = (int) kb.nFirst;
3356 IntConstant.EmitInt (ig, nFirst);
3357 ig.Emit (OpCodes.Sub);
3359 else if (nFirst < 0)
3361 IntConstant.EmitInt (ig, -nFirst);
3362 ig.Emit (OpCodes.Add);
3366 // first, build the list of labels for the switch
3368 int cJumps = kb.Length;
3369 Label [] rgLabels = new Label [cJumps];
3370 for (int iJump = 0; iJump < cJumps; iJump++)
3372 object key = kb.rgKeys [iKey];
3373 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3375 SwitchLabel sl = (SwitchLabel) Elements [key];
3376 rgLabels [iJump] = sl.GetILLabel (ec);
3380 rgLabels [iJump] = lblDefault;
3382 // emit the switch opcode
3383 ig.Emit (OpCodes.Switch, rgLabels);
3386 // mark the default for this block
3388 ig.MarkLabel (lblDefault);
3391 // TODO: find the default case and emit it here,
3392 // to prevent having to do the following jump.
3393 // make sure to mark other labels in the default section
3395 // the last default just goes to the end
3396 ig.Emit (OpCodes.Br, lblDefault);
3398 // now emit the code for the sections
3399 bool fFoundDefault = false;
3400 bool fFoundNull = false;
3401 foreach (SwitchSection ss in Sections)
3403 foreach (SwitchLabel sl in ss.Labels)
3404 if (sl.Converted == SwitchLabel.NullStringCase)
3408 foreach (SwitchSection ss in Sections)
3410 foreach (SwitchLabel sl in ss.Labels)
3412 ig.MarkLabel (sl.GetILLabel (ec));
3413 ig.MarkLabel (sl.GetILLabelCode (ec));
3414 if (sl.Converted == SwitchLabel.NullStringCase)
3415 ig.MarkLabel (null_target);
3416 else if (sl.Label == null) {
3417 ig.MarkLabel (lblDefault);
3418 fFoundDefault = true;
3420 ig.MarkLabel (null_target);
3426 if (!fFoundDefault) {
3427 ig.MarkLabel (lblDefault);
3429 ig.MarkLabel (lblEnd);
3432 // This simple emit switch works, but does not take advantage of the
3434 // TODO: remove non-string logic from here
3435 // TODO: binary search strings?
3437 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3439 ILGenerator ig = ec.ig;
3440 Label end_of_switch = ig.DefineLabel ();
3441 Label next_test = ig.DefineLabel ();
3442 bool first_test = true;
3443 bool pending_goto_end = false;
3444 bool null_marked = false;
3446 int section_count = Sections.Count;
3448 // TODO: implement switch optimization for string by using Hashtable
3449 //if (SwitchType == TypeManager.string_type && section_count > 7)
3450 // Console.WriteLine ("Switch optimization possible " + loc);
3452 ig.Emit (OpCodes.Ldloc, val);
3454 if (Elements.Contains (SwitchLabel.NullStringCase)){
3455 ig.Emit (OpCodes.Brfalse, null_target);
3457 ig.Emit (OpCodes.Brfalse, default_target);
3459 ig.Emit (OpCodes.Ldloc, val);
3460 ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
3461 ig.Emit (OpCodes.Stloc, val);
3463 for (int section = 0; section < section_count; section++){
3464 SwitchSection ss = (SwitchSection) Sections [section];
3466 if (ss == default_section)
3469 Label sec_begin = ig.DefineLabel ();
3471 ig.Emit (OpCodes.Nop);
3473 if (pending_goto_end)
3474 ig.Emit (OpCodes.Br, end_of_switch);
3476 int label_count = ss.Labels.Count;
3478 for (int label = 0; label < label_count; label++){
3479 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3480 ig.MarkLabel (sl.GetILLabel (ec));
3483 ig.MarkLabel (next_test);
3484 next_test = ig.DefineLabel ();
3487 // If we are the default target
3489 if (sl.Label != null){
3490 object lit = sl.Converted;
3492 if (lit == SwitchLabel.NullStringCase){
3494 if (label + 1 == label_count)
3495 ig.Emit (OpCodes.Br, next_test);
3499 ig.Emit (OpCodes.Ldloc, val);
3500 ig.Emit (OpCodes.Ldstr, (string)lit);
3501 if (label_count == 1)
3502 ig.Emit (OpCodes.Bne_Un, next_test);
3504 if (label+1 == label_count)
3505 ig.Emit (OpCodes.Bne_Un, next_test);
3507 ig.Emit (OpCodes.Beq, sec_begin);
3512 ig.MarkLabel (null_target);
3515 ig.MarkLabel (sec_begin);
3516 foreach (SwitchLabel sl in ss.Labels)
3517 ig.MarkLabel (sl.GetILLabelCode (ec));
3520 pending_goto_end = !ss.Block.HasRet;
3523 ig.MarkLabel (next_test);
3524 ig.MarkLabel (default_target);
3526 ig.MarkLabel (null_target);
3527 if (default_section != null)
3528 default_section.Block.Emit (ec);
3529 ig.MarkLabel (end_of_switch);
3532 SwitchSection FindSection (SwitchLabel label)
3534 foreach (SwitchSection ss in Sections){
3535 foreach (SwitchLabel sl in ss.Labels){
3544 public override bool Resolve (EmitContext ec)
3546 Expr = Expr.Resolve (ec);
3550 new_expr = SwitchGoverningType (ec, Expr);
3553 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3554 unwrap = Nullable.Unwrap.Create (Expr, ec);
3558 new_expr = SwitchGoverningType (ec, unwrap);
3562 if (new_expr == null){
3563 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3568 SwitchType = new_expr.Type;
3570 if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
3571 Report.FeatureIsNotISO1 (loc, "switch expression of boolean type");
3575 if (!CheckSwitch (ec))
3579 Elements.Remove (SwitchLabel.NullStringCase);
3581 Switch old_switch = ec.Switch;
3583 ec.Switch.SwitchType = SwitchType;
3585 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3586 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3588 is_constant = new_expr is Constant;
3590 object key = ((Constant) new_expr).GetValue ();
3591 SwitchLabel label = (SwitchLabel) Elements [key];
3593 constant_section = FindSection (label);
3594 if (constant_section == null)
3595 constant_section = default_section;
3599 foreach (SwitchSection ss in Sections){
3601 ec.CurrentBranching.CreateSibling (
3602 null, FlowBranching.SiblingType.SwitchSection);
3606 if (is_constant && (ss != constant_section)) {
3607 // If we're a constant switch, we're only emitting
3608 // one single section - mark all the others as
3610 ec.CurrentBranching.CurrentUsageVector.Goto ();
3611 if (!ss.Block.ResolveUnreachable (ec, true))
3614 if (!ss.Block.Resolve (ec))
3619 if (default_section == null)
3620 ec.CurrentBranching.CreateSibling (
3621 null, FlowBranching.SiblingType.SwitchSection);
3623 ec.EndFlowBranching ();
3624 ec.Switch = old_switch;
3626 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
3631 protected override void DoEmit (EmitContext ec)
3633 ILGenerator ig = ec.ig;
3635 default_target = ig.DefineLabel ();
3636 null_target = ig.DefineLabel ();
3638 // Store variable for comparission purposes
3641 value = ig.DeclareLocal (SwitchType);
3643 unwrap.EmitCheck (ec);
3644 ig.Emit (OpCodes.Brfalse, null_target);
3646 ig.Emit (OpCodes.Stloc, value);
3648 } else if (!is_constant) {
3649 value = ig.DeclareLocal (SwitchType);
3651 ig.Emit (OpCodes.Stloc, value);
3656 // Setup the codegen context
3658 Label old_end = ec.LoopEnd;
3659 Switch old_switch = ec.Switch;
3661 ec.LoopEnd = ig.DefineLabel ();
3666 if (constant_section != null)
3667 constant_section.Block.Emit (ec);
3668 } else if (SwitchType == TypeManager.string_type)
3669 SimpleSwitchEmit (ec, value);
3671 TableSwitchEmit (ec, value);
3673 // Restore context state.
3674 ig.MarkLabel (ec.LoopEnd);
3677 // Restore the previous context
3679 ec.LoopEnd = old_end;
3680 ec.Switch = old_switch;
3683 protected override void CloneTo (CloneContext clonectx, Statement t)
3685 Switch target = (Switch) t;
3687 target.Expr = Expr.Clone (clonectx);
3688 target.Sections = new ArrayList ();
3689 foreach (SwitchSection ss in Sections){
3690 target.Sections.Add (ss.Clone (clonectx));
3695 public abstract class ExceptionStatement : Statement
3697 public abstract void EmitFinally (EmitContext ec);
3699 protected bool emit_finally = true;
3700 ArrayList parent_vectors;
3702 protected void DoEmitFinally (EmitContext ec)
3705 ec.ig.BeginFinallyBlock ();
3706 else if (ec.InIterator)
3707 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3711 protected void ResolveFinally (FlowBranchingException branching)
3713 emit_finally = branching.EmitFinally;
3715 branching.Parent.StealFinallyClauses (ref parent_vectors);
3719 public class Lock : ExceptionStatement {
3721 public Statement Statement;
3722 TemporaryVariable temp;
3724 public Lock (Expression expr, Statement stmt, Location l)
3731 public override bool Resolve (EmitContext ec)
3733 expr = expr.Resolve (ec);
3737 if (expr.Type.IsValueType){
3738 Report.Error (185, loc,
3739 "`{0}' is not a reference type as required by the lock statement",
3740 TypeManager.CSharpName (expr.Type));
3744 FlowBranchingException branching = ec.StartFlowBranching (this);
3745 bool ok = Statement.Resolve (ec);
3747 ResolveFinally (branching);
3749 ec.EndFlowBranching ();
3751 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
3752 // So, ensure there's some IL code after the finally block.
3753 ec.NeedReturnLabel ();
3755 // Avoid creating libraries that reference the internal
3758 if (t == TypeManager.null_type)
3759 t = TypeManager.object_type;
3761 temp = new TemporaryVariable (t, loc);
3767 protected override void DoEmit (EmitContext ec)
3769 ILGenerator ig = ec.ig;
3771 temp.Store (ec, expr);
3773 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3777 ig.BeginExceptionBlock ();
3778 Statement.Emit (ec);
3783 ig.EndExceptionBlock ();
3786 public override void EmitFinally (EmitContext ec)
3789 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3792 protected override void CloneTo (CloneContext clonectx, Statement t)
3794 Lock target = (Lock) t;
3796 target.expr = expr.Clone (clonectx);
3797 target.Statement = Statement.Clone (clonectx);
3801 public class Unchecked : Statement {
3804 public Unchecked (Block b)
3810 public override bool Resolve (EmitContext ec)
3812 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3813 return Block.Resolve (ec);
3816 protected override void DoEmit (EmitContext ec)
3818 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3822 protected override void CloneTo (CloneContext clonectx, Statement t)
3824 Unchecked target = (Unchecked) t;
3826 target.Block = clonectx.LookupBlock (Block);
3830 public class Checked : Statement {
3833 public Checked (Block b)
3836 b.Unchecked = false;
3839 public override bool Resolve (EmitContext ec)
3841 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3842 return Block.Resolve (ec);
3845 protected override void DoEmit (EmitContext ec)
3847 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3851 protected override void CloneTo (CloneContext clonectx, Statement t)
3853 Checked target = (Checked) t;
3855 target.Block = clonectx.LookupBlock (Block);
3859 public class Unsafe : Statement {
3862 public Unsafe (Block b)
3865 Block.Unsafe = true;
3868 public override bool Resolve (EmitContext ec)
3870 using (ec.With (EmitContext.Flags.InUnsafe, true))
3871 return Block.Resolve (ec);
3874 protected override void DoEmit (EmitContext ec)
3876 using (ec.With (EmitContext.Flags.InUnsafe, true))
3879 protected override void CloneTo (CloneContext clonectx, Statement t)
3881 Unsafe target = (Unsafe) t;
3883 target.Block = clonectx.LookupBlock (Block);
3890 public class Fixed : Statement {
3892 ArrayList declarators;
3893 Statement statement;
3898 abstract class Emitter
3900 protected LocalInfo vi;
3901 protected Expression converted;
3903 protected Emitter (Expression expr, LocalInfo li)
3909 public abstract void Emit (EmitContext ec);
3910 public abstract void EmitExit (EmitContext ec);
3913 class ExpressionEmitter : Emitter {
3914 public ExpressionEmitter (Expression converted, LocalInfo li) :
3915 base (converted, li)
3919 public override void Emit (EmitContext ec) {
3921 // Store pointer in pinned location
3923 converted.Emit (ec);
3924 vi.Variable.EmitAssign (ec);
3927 public override void EmitExit (EmitContext ec)
3929 ec.ig.Emit (OpCodes.Ldc_I4_0);
3930 ec.ig.Emit (OpCodes.Conv_U);
3931 vi.Variable.EmitAssign (ec);
3935 class StringEmitter : Emitter {
3936 LocalBuilder pinned_string;
3939 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3945 public override void Emit (EmitContext ec)
3947 ILGenerator ig = ec.ig;
3948 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3950 converted.Emit (ec);
3951 ig.Emit (OpCodes.Stloc, pinned_string);
3953 Expression sptr = new StringPtr (pinned_string, loc);
3954 converted = Convert.ImplicitConversionRequired (
3955 ec, sptr, vi.VariableType, loc);
3957 if (converted == null)
3960 converted.Emit (ec);
3961 vi.Variable.EmitAssign (ec);
3964 public override void EmitExit (EmitContext ec)
3966 ec.ig.Emit (OpCodes.Ldnull);
3967 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3971 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3974 declarators = decls;
3979 public Statement Statement {
3980 get { return statement; }
3983 public override bool Resolve (EmitContext ec)
3986 Expression.UnsafeError (loc);
3990 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3994 expr_type = texpr.Type;
3996 data = new Emitter [declarators.Count];
3998 if (!expr_type.IsPointer){
3999 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
4004 foreach (Pair p in declarators){
4005 LocalInfo vi = (LocalInfo) p.First;
4006 Expression e = (Expression) p.Second;
4008 vi.VariableInfo.SetAssigned (ec);
4009 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
4012 // The rules for the possible declarators are pretty wise,
4013 // but the production on the grammar is more concise.
4015 // So we have to enforce these rules here.
4017 // We do not resolve before doing the case 1 test,
4018 // because the grammar is explicit in that the token &
4019 // is present, so we need to test for this particular case.
4023 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
4028 // Case 1: & object.
4030 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4031 Expression child = ((Unary) e).Expr;
4033 if (child is ParameterReference || child is LocalVariableReference){
4036 "No need to use fixed statement for parameters or " +
4037 "local variable declarations (address is already " +
4042 ec.InFixedInitializer = true;
4044 ec.InFixedInitializer = false;
4048 child = ((Unary) e).Expr;
4050 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4053 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
4054 e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
4058 data [i] = new ExpressionEmitter (e, vi);
4064 ec.InFixedInitializer = true;
4066 ec.InFixedInitializer = false;
4073 if (e.Type.IsArray){
4074 Type array_type = TypeManager.GetElementType (e.Type);
4077 // Provided that array_type is unmanaged,
4079 if (!TypeManager.VerifyUnManaged (array_type, loc))
4083 // and T* is implicitly convertible to the
4084 // pointer type given in the fixed statement.
4086 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
4088 Expression converted = Convert.ImplicitConversionRequired (
4089 ec, array_ptr, vi.VariableType, loc);
4090 if (converted == null)
4093 data [i] = new ExpressionEmitter (converted, vi);
4102 if (e.Type == TypeManager.string_type){
4103 data [i] = new StringEmitter (e, vi, loc);
4108 // Case 4: fixed buffer
4109 FieldExpr fe = e as FieldExpr;
4111 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
4113 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
4115 Expression converted = Convert.ImplicitConversionRequired (
4116 ec, fixed_buffer_ptr, vi.VariableType, loc);
4117 if (converted == null)
4120 data [i] = new ExpressionEmitter (converted, vi);
4128 // For other cases, flag a `this is already fixed expression'
4130 if (e is LocalVariableReference || e is ParameterReference ||
4131 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
4133 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
4137 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
4141 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
4142 bool ok = statement.Resolve (ec);
4143 bool flow_unreachable = ec.EndFlowBranching ();
4144 has_ret = flow_unreachable;
4149 protected override void DoEmit (EmitContext ec)
4151 for (int i = 0; i < data.Length; i++) {
4155 statement.Emit (ec);
4161 // Clear the pinned variable
4163 for (int i = 0; i < data.Length; i++) {
4164 data [i].EmitExit (ec);
4168 protected override void CloneTo (CloneContext clonectx, Statement t)
4170 Fixed target = (Fixed) t;
4172 target.type = type.Clone (clonectx);
4173 target.declarators = new ArrayList ();
4174 foreach (LocalInfo var in declarators)
4175 target.declarators.Add (clonectx.LookupVariable (var));
4176 target.statement = statement.Clone (clonectx);
4180 public class Catch : Statement {
4181 public readonly string Name;
4183 public Block VarBlock;
4185 Expression type_expr;
4188 public Catch (Expression type, string name, Block block, Block var_block, Location l)
4193 VarBlock = var_block;
4197 public Type CatchType {
4203 public bool IsGeneral {
4205 return type_expr == null;
4209 protected override void DoEmit(EmitContext ec)
4211 ILGenerator ig = ec.ig;
4213 if (CatchType != null)
4214 ig.BeginCatchBlock (CatchType);
4216 ig.BeginCatchBlock (TypeManager.object_type);
4218 if (VarBlock != null)
4222 LocalInfo vi = Block.GetLocalInfo (Name);
4224 throw new Exception ("Variable does not exist in this block");
4226 if (vi.Variable.NeedsTemporary) {
4227 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
4228 ig.Emit (OpCodes.Stloc, e);
4230 vi.Variable.EmitInstance (ec);
4231 ig.Emit (OpCodes.Ldloc, e);
4232 vi.Variable.EmitAssign (ec);
4234 vi.Variable.EmitAssign (ec);
4236 ig.Emit (OpCodes.Pop);
4241 public override bool Resolve (EmitContext ec)
4243 using (ec.With (EmitContext.Flags.InCatch, true)) {
4244 if (type_expr != null) {
4245 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
4251 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4252 Error (155, "The type caught or thrown must be derived from System.Exception");
4258 if (!Block.Resolve (ec))
4261 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4262 // emit the "unused variable" warnings.
4263 if (VarBlock != null)
4264 return VarBlock.Resolve (ec);
4270 protected override void CloneTo (CloneContext clonectx, Statement t)
4272 Catch target = (Catch) t;
4274 target.type_expr = type_expr.Clone (clonectx);
4275 target.Block = clonectx.LookupBlock (Block);
4276 target.VarBlock = clonectx.LookupBlock (VarBlock);
4280 public class Try : ExceptionStatement {
4281 public Block Fini, Block;
4282 public ArrayList Specific;
4283 public Catch General;
4285 bool need_exc_block;
4288 // specific, general and fini might all be null.
4290 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4292 if (specific == null && general == null){
4293 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4297 this.Specific = specific;
4298 this.General = general;
4303 public override bool Resolve (EmitContext ec)
4307 FlowBranchingException branching = ec.StartFlowBranching (this);
4309 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4311 if (!Block.Resolve (ec))
4314 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4316 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4318 Type[] prevCatches = new Type [Specific.Count];
4320 foreach (Catch c in Specific){
4321 ec.CurrentBranching.CreateSibling (
4322 c.Block, FlowBranching.SiblingType.Catch);
4324 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4326 if (c.Name != null) {
4327 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4329 throw new Exception ();
4331 vi.VariableInfo = null;
4334 if (!c.Resolve (ec))
4337 Type resolvedType = c.CatchType;
4338 for (int ii = 0; ii < last_index; ++ii) {
4339 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4340 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4345 prevCatches [last_index++] = resolvedType;
4346 need_exc_block = true;
4349 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4351 if (General != null){
4352 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4353 foreach (Catch c in Specific){
4354 if (c.CatchType == TypeManager.exception_type) {
4355 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'");
4360 ec.CurrentBranching.CreateSibling (
4361 General.Block, FlowBranching.SiblingType.Catch);
4363 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4365 if (!General.Resolve (ec))
4368 need_exc_block = true;
4371 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4375 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4377 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4378 using (ec.With (EmitContext.Flags.InFinally, true)) {
4379 if (!Fini.Resolve (ec))
4384 need_exc_block = true;
4387 if (ec.InIterator) {
4388 ResolveFinally (branching);
4389 need_exc_block |= emit_finally;
4391 emit_finally = Fini != null;
4393 ec.EndFlowBranching ();
4395 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4396 // So, ensure there's some IL code after the finally block.
4397 ec.NeedReturnLabel ();
4399 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4401 Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
4406 protected override void DoEmit (EmitContext ec)
4408 ILGenerator ig = ec.ig;
4411 ig.BeginExceptionBlock ();
4414 foreach (Catch c in Specific)
4417 if (General != null)
4422 ig.EndExceptionBlock ();
4425 public override void EmitFinally (EmitContext ec)
4431 public bool HasCatch
4434 return General != null || Specific.Count > 0;
4438 protected override void CloneTo (CloneContext clonectx, Statement t)
4440 Try target = (Try) t;
4442 target.Block = clonectx.LookupBlock (Block);
4444 target.Fini = clonectx.LookupBlock (Fini);
4445 if (General != null)
4446 target.General = (Catch) General.Clone (clonectx);
4447 if (Specific != null){
4448 target.Specific = new ArrayList ();
4449 foreach (Catch c in Specific)
4450 target.Specific.Add (c.Clone (clonectx));
4455 public class Using : ExceptionStatement {
4456 object expression_or_block;
4457 public Statement Statement;
4461 Expression [] resolved_vars;
4462 Expression [] converted_vars;
4463 ExpressionStatement [] assign;
4464 TemporaryVariable local_copy;
4466 public Using (object expression_or_block, Statement stmt, Location l)
4468 this.expression_or_block = expression_or_block;
4474 // Resolves for the case of using using a local variable declaration.
4476 bool ResolveLocalVariableDecls (EmitContext ec)
4480 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
4484 expr_type = texpr.Type;
4487 // The type must be an IDisposable or an implicit conversion
4490 converted_vars = new Expression [var_list.Count];
4491 resolved_vars = new Expression [var_list.Count];
4492 assign = new ExpressionStatement [var_list.Count];
4494 bool need_conv = !TypeManager.ImplementsInterface (
4495 expr_type, TypeManager.idisposable_type);
4497 foreach (DictionaryEntry e in var_list){
4498 Expression var = (Expression) e.Key;
4500 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
4504 resolved_vars [i] = var;
4511 converted_vars [i] = Convert.ImplicitConversion (
4512 ec, var, TypeManager.idisposable_type, loc);
4514 if (converted_vars [i] == null) {
4515 Error_IsNotConvertibleToIDisposable ();
4523 foreach (DictionaryEntry e in var_list){
4524 Expression var = resolved_vars [i];
4525 Expression new_expr = (Expression) e.Value;
4528 a = new Assign (var, new_expr, loc);
4534 converted_vars [i] = var;
4535 assign [i] = (ExpressionStatement) a;
4542 void Error_IsNotConvertibleToIDisposable ()
4544 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4545 TypeManager.CSharpName (expr_type));
4548 bool ResolveExpression (EmitContext ec)
4550 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4551 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4552 Error_IsNotConvertibleToIDisposable ();
4557 local_copy = new TemporaryVariable (expr_type, loc);
4558 local_copy.Resolve (ec);
4564 // Emits the code for the case of using using a local variable declaration.
4566 void EmitLocalVariableDecls (EmitContext ec)
4568 ILGenerator ig = ec.ig;
4571 for (i = 0; i < assign.Length; i++) {
4572 assign [i].EmitStatement (ec);
4575 ig.BeginExceptionBlock ();
4577 Statement.Emit (ec);
4579 var_list.Reverse ();
4584 void EmitLocalVariableDeclFinally (EmitContext ec)
4586 ILGenerator ig = ec.ig;
4588 int i = assign.Length;
4589 for (int ii = 0; ii < var_list.Count; ++ii){
4590 Expression var = resolved_vars [--i];
4591 Label skip = ig.DefineLabel ();
4594 ig.BeginFinallyBlock ();
4596 if (!var.Type.IsValueType) {
4598 ig.Emit (OpCodes.Brfalse, skip);
4599 converted_vars [i].Emit (ec);
4600 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4602 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4604 if (!(ml is MethodGroupExpr)) {
4606 ig.Emit (OpCodes.Box, var.Type);
4607 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4609 MethodInfo mi = null;
4611 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4612 if (TypeManager.GetParameterData (mk).Count == 0) {
4619 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4623 IMemoryLocation mloc = (IMemoryLocation) var;
4625 mloc.AddressOf (ec, AddressOp.Load);
4626 ig.Emit (OpCodes.Call, mi);
4630 ig.MarkLabel (skip);
4633 ig.EndExceptionBlock ();
4635 ig.BeginFinallyBlock ();
4640 void EmitExpression (EmitContext ec)
4643 // Make a copy of the expression and operate on that.
4645 ILGenerator ig = ec.ig;
4647 local_copy.Store (ec, expr);
4650 ig.BeginExceptionBlock ();
4652 Statement.Emit (ec);
4656 ig.EndExceptionBlock ();
4659 void EmitExpressionFinally (EmitContext ec)
4661 ILGenerator ig = ec.ig;
4662 if (!expr_type.IsValueType) {
4663 Label skip = ig.DefineLabel ();
4664 local_copy.Emit (ec);
4665 ig.Emit (OpCodes.Brfalse, skip);
4666 local_copy.Emit (ec);
4667 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4668 ig.MarkLabel (skip);
4670 Expression ml = Expression.MemberLookup (
4671 ec.ContainerType, TypeManager.idisposable_type, expr_type,
4672 "Dispose", Location.Null);
4674 if (!(ml is MethodGroupExpr)) {
4675 local_copy.Emit (ec);
4676 ig.Emit (OpCodes.Box, expr_type);
4677 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4679 MethodInfo mi = null;
4681 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4682 if (TypeManager.GetParameterData (mk).Count == 0) {
4689 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4693 local_copy.AddressOf (ec, AddressOp.Load);
4694 ig.Emit (OpCodes.Call, mi);
4699 public override bool Resolve (EmitContext ec)
4701 if (expression_or_block is DictionaryEntry){
4702 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4703 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4705 if (!ResolveLocalVariableDecls (ec))
4708 } else if (expression_or_block is Expression){
4709 expr = (Expression) expression_or_block;
4711 expr = expr.Resolve (ec);
4715 expr_type = expr.Type;
4717 if (!ResolveExpression (ec))
4721 FlowBranchingException branching = ec.StartFlowBranching (this);
4723 bool ok = Statement.Resolve (ec);
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 IsOverride (MethodInfo m)
5182 m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
5184 if (!m.IsVirtual || ((m.Attributes & MethodAttributes.NewSlot) != 0))
5186 if (m is MethodBuilder)
5189 MethodInfo base_method = m.GetBaseDefinition ();
5190 return base_method != m;
5193 bool TryType (EmitContext ec, Type t)
5195 MethodGroupExpr mg = Expression.MemberLookup (
5196 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
5197 Expression.AllBindingFlags, loc) as MethodGroupExpr;
5201 MethodInfo result = null;
5202 MethodInfo tmp_move_next = null;
5203 PropertyExpr tmp_get_cur = null;
5204 Type tmp_enumerator_type = enumerator_type;
5205 foreach (MethodInfo mi in mg.Methods) {
5206 if (TypeManager.GetParameterData (mi).Count != 0)
5209 // Check whether GetEnumerator is public
5210 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
5213 if (IsOverride (mi))
5216 enumerator_found = true;
5218 if (!GetEnumeratorFilter (ec, mi))
5221 if (result != null) {
5222 if (TypeManager.IsGenericType (result.ReturnType)) {
5223 if (!TypeManager.IsGenericType (mi.ReturnType))
5226 MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
5227 Report.SymbolRelatedToPreviousError (t);
5228 Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
5229 "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
5230 TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
5234 // Always prefer generics enumerators
5235 if (!TypeManager.IsGenericType (mi.ReturnType)) {
5236 if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
5237 TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
5240 Report.SymbolRelatedToPreviousError (result);
5241 Report.SymbolRelatedToPreviousError (mi);
5242 Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
5243 TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
5248 tmp_move_next = move_next;
5249 tmp_get_cur = get_current;
5250 tmp_enumerator_type = enumerator_type;
5251 if (mi.DeclaringType == t)
5255 if (result != null) {
5256 move_next = tmp_move_next;
5257 get_current = tmp_get_cur;
5258 enumerator_type = tmp_enumerator_type;
5259 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
5260 get_enumerator = new MethodGroupExpr (mi, loc);
5262 if (t != expr.Type) {
5263 expr = Convert.ExplicitConversion (
5266 throw new InternalErrorException ();
5269 get_enumerator.InstanceExpression = expr;
5270 get_enumerator.IsBase = t != expr.Type;
5278 bool ProbeCollectionType (EmitContext ec, Type t)
5280 int errors = Report.Errors;
5281 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
5282 if (TryType (ec, tt))
5287 if (Report.Errors > errors)
5291 // Now try to find the method in the interfaces
5293 Type [] ifaces = TypeManager.GetInterfaces (t);
5294 foreach (Type i in ifaces){
5295 if (TryType (ec, i))
5302 public override bool Resolve (EmitContext ec)
5304 enumerator_type = TypeManager.ienumerator_type;
5305 is_disposable = true;
5307 if (!ProbeCollectionType (ec, expr.Type)) {
5308 Error_Enumerator ();
5312 enumerator = new TemporaryVariable (enumerator_type, loc);
5313 enumerator.Resolve (ec);
5315 init = new Invocation (get_enumerator, new ArrayList ());
5316 init = init.Resolve (ec);
5320 Expression move_next_expr;
5322 MemberInfo[] mi = new MemberInfo[] { move_next };
5323 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5324 mg.InstanceExpression = enumerator;
5326 move_next_expr = new Invocation (mg, new ArrayList ());
5329 get_current.InstanceExpression = enumerator;
5331 Statement block = new CollectionForeachStatement (
5332 var_type, variable, get_current, statement, loc);
5334 loop = new While (move_next_expr, block, loc);
5338 FlowBranchingException branching = null;
5340 branching = ec.StartFlowBranching (this);
5342 if (!loop.Resolve (ec))
5345 if (is_disposable) {
5346 ResolveFinally (branching);
5347 ec.EndFlowBranching ();
5349 emit_finally = true;
5354 protected override void DoEmit (EmitContext ec)
5356 ILGenerator ig = ec.ig;
5358 enumerator.Store (ec, init);
5361 // Protect the code in a try/finalize block, so that
5362 // if the beast implement IDisposable, we get rid of it
5364 if (is_disposable && emit_finally)
5365 ig.BeginExceptionBlock ();
5370 // Now the finally block
5372 if (is_disposable) {
5375 ig.EndExceptionBlock ();
5380 public override void EmitFinally (EmitContext ec)
5382 ILGenerator ig = ec.ig;
5384 if (enumerator_type.IsValueType) {
5385 MethodInfo mi = FetchMethodDispose (enumerator_type);
5387 enumerator.EmitLoadAddress (ec);
5388 ig.Emit (OpCodes.Call, mi);
5390 enumerator.Emit (ec);
5391 ig.Emit (OpCodes.Box, enumerator_type);
5392 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5395 Label call_dispose = ig.DefineLabel ();
5397 enumerator.Emit (ec);
5398 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5399 ig.Emit (OpCodes.Dup);
5400 ig.Emit (OpCodes.Brtrue_S, call_dispose);
5401 ig.Emit (OpCodes.Pop);
5403 Label end_finally = ig.DefineLabel ();
5404 ig.Emit (OpCodes.Br, end_finally);
5406 ig.MarkLabel (call_dispose);
5407 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5408 ig.MarkLabel (end_finally);
5413 protected class CollectionForeachStatement : Statement
5416 Expression variable, current, conv;
5417 Statement statement;
5420 public CollectionForeachStatement (Type type, Expression variable,
5421 Expression current, Statement statement,
5425 this.variable = variable;
5426 this.current = current;
5427 this.statement = statement;
5431 public override bool Resolve (EmitContext ec)
5433 current = current.Resolve (ec);
5434 if (current == null)
5437 conv = Convert.ExplicitConversion (ec, current, type, loc);
5441 assign = new Assign (variable, conv, loc);
5442 if (assign.Resolve (ec) == null)
5445 if (!statement.Resolve (ec))
5451 protected override void DoEmit (EmitContext ec)
5453 assign.EmitStatement (ec);
5454 statement.Emit (ec);
5458 protected override void CloneTo (CloneContext clonectx, Statement t)
5460 Foreach target = (Foreach) t;
5462 target.type = type.Clone (clonectx);
5463 target.variable = variable.Clone (clonectx);
5464 target.expr = expr.Clone (clonectx);
5465 target.statement = statement.Clone (clonectx);