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 ();
102 CloneTo (clonectx, s);
106 public Statement PerformClone ()
108 CloneContext clonectx = new CloneContext ();
110 return Clone (clonectx);
116 // This class is used during the Statement.Clone operation
117 // to remap objects that have been cloned.
119 // Since blocks are cloned by Block.Clone, we need a way for
120 // expressions that must reference the block to be cloned
121 // pointing to the new cloned block.
123 public class CloneContext {
124 Hashtable block_map = new Hashtable ();
125 Hashtable variable_map;
127 public void AddBlockMap (Block from, Block to)
129 if (block_map.Contains (from))
131 block_map [from] = to;
134 public Block LookupBlock (Block from)
136 Block result = (Block) block_map [from];
139 result = (Block) from.Clone (this);
140 block_map [from] = result;
146 public void AddVariableMap (LocalInfo from, LocalInfo to)
148 if (variable_map == null)
149 variable_map = new Hashtable ();
151 if (variable_map.Contains (from))
153 variable_map [from] = to;
156 public LocalInfo LookupVariable (LocalInfo from)
158 LocalInfo result = (LocalInfo) variable_map [from];
161 throw new Exception ("LookupVariable: looking up a variable that has not been registered yet");
167 public sealed class EmptyStatement : Statement {
169 private EmptyStatement () {}
171 public static readonly EmptyStatement Value = new EmptyStatement ();
173 public override bool Resolve (EmitContext ec)
178 public override bool ResolveUnreachable (EmitContext ec, bool warn)
183 protected override void DoEmit (EmitContext ec)
188 public class If : Statement {
190 public Statement TrueStatement;
191 public Statement FalseStatement;
195 public If (Expression expr, Statement trueStatement, Location l)
198 TrueStatement = trueStatement;
202 public If (Expression expr,
203 Statement trueStatement,
204 Statement falseStatement,
208 TrueStatement = trueStatement;
209 FalseStatement = falseStatement;
213 public override bool Resolve (EmitContext ec)
217 Report.Debug (1, "START IF BLOCK", loc);
219 expr = Expression.ResolveBoolean (ec, expr, loc);
225 Assign ass = expr as Assign;
226 if (ass != null && ass.Source is Constant) {
227 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
231 // Dead code elimination
233 if (expr is BoolConstant){
234 bool take = ((BoolConstant) expr).Value;
237 if (!TrueStatement.Resolve (ec))
240 if ((FalseStatement != null) &&
241 !FalseStatement.ResolveUnreachable (ec, true))
243 FalseStatement = null;
245 if (!TrueStatement.ResolveUnreachable (ec, true))
247 TrueStatement = null;
249 if ((FalseStatement != null) &&
250 !FalseStatement.Resolve (ec))
257 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
259 ok &= TrueStatement.Resolve (ec);
261 is_true_ret = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
263 ec.CurrentBranching.CreateSibling ();
265 if (FalseStatement != null)
266 ok &= FalseStatement.Resolve (ec);
268 ec.EndFlowBranching ();
270 Report.Debug (1, "END IF BLOCK", loc);
275 protected override void DoEmit (EmitContext ec)
277 ILGenerator ig = ec.ig;
278 Label false_target = ig.DefineLabel ();
282 // If we're a boolean expression, Resolve() already
283 // eliminated dead code for us.
285 if (expr is BoolConstant){
286 bool take = ((BoolConstant) expr).Value;
289 TrueStatement.Emit (ec);
290 else if (FalseStatement != null)
291 FalseStatement.Emit (ec);
296 expr.EmitBranchable (ec, false_target, false);
298 TrueStatement.Emit (ec);
300 if (FalseStatement != null){
301 bool branch_emitted = false;
303 end = ig.DefineLabel ();
305 ig.Emit (OpCodes.Br, end);
306 branch_emitted = true;
309 ig.MarkLabel (false_target);
310 FalseStatement.Emit (ec);
315 ig.MarkLabel (false_target);
319 protected override void CloneTo (CloneContext clonectx, Statement t)
323 target.expr = expr.Clone (clonectx);
324 target.TrueStatement = TrueStatement.Clone (clonectx);
325 if (FalseStatement != null)
326 target.FalseStatement = FalseStatement.Clone (clonectx);
330 public class Do : Statement {
331 public Expression expr;
332 public Statement EmbeddedStatement;
335 public Do (Statement statement, Expression boolExpr, Location l)
338 EmbeddedStatement = statement;
342 public override bool Resolve (EmitContext ec)
346 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
348 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
350 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
351 if (!EmbeddedStatement.Resolve (ec))
353 ec.EndFlowBranching ();
355 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable && !was_unreachable)
356 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
358 expr = Expression.ResolveBoolean (ec, expr, loc);
361 else if (expr is BoolConstant){
362 bool res = ((BoolConstant) expr).Value;
368 ec.CurrentBranching.CurrentUsageVector.Goto ();
370 ec.EndFlowBranching ();
375 protected override void DoEmit (EmitContext ec)
377 ILGenerator ig = ec.ig;
378 Label loop = ig.DefineLabel ();
379 Label old_begin = ec.LoopBegin;
380 Label old_end = ec.LoopEnd;
382 ec.LoopBegin = ig.DefineLabel ();
383 ec.LoopEnd = ig.DefineLabel ();
386 EmbeddedStatement.Emit (ec);
387 ig.MarkLabel (ec.LoopBegin);
390 // Dead code elimination
392 if (expr is BoolConstant){
393 bool res = ((BoolConstant) expr).Value;
396 ec.ig.Emit (OpCodes.Br, loop);
398 expr.EmitBranchable (ec, loop, true);
400 ig.MarkLabel (ec.LoopEnd);
402 ec.LoopBegin = old_begin;
403 ec.LoopEnd = old_end;
406 protected override void CloneTo (CloneContext clonectx, Statement t)
410 target.EmbeddedStatement = EmbeddedStatement.Clone (clonectx);
411 target.expr = expr.Clone (clonectx);
415 public class While : Statement {
416 public Expression expr;
417 public Statement Statement;
418 bool infinite, empty;
420 public While (Expression boolExpr, Statement statement, Location l)
422 this.expr = boolExpr;
423 Statement = statement;
427 public override bool Resolve (EmitContext ec)
431 expr = Expression.ResolveBoolean (ec, expr, loc);
436 // Inform whether we are infinite or not
438 if (expr is BoolConstant){
439 BoolConstant bc = (BoolConstant) expr;
441 if (bc.Value == false){
442 if (!Statement.ResolveUnreachable (ec, true))
450 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
452 ec.CurrentBranching.CreateSibling ();
454 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
455 if (!Statement.Resolve (ec))
457 ec.EndFlowBranching ();
459 // There's no direct control flow from the end of the embedded statement to the end of the loop
460 ec.CurrentBranching.CurrentUsageVector.Goto ();
462 ec.EndFlowBranching ();
467 protected override void DoEmit (EmitContext ec)
472 ILGenerator ig = ec.ig;
473 Label old_begin = ec.LoopBegin;
474 Label old_end = ec.LoopEnd;
476 ec.LoopBegin = ig.DefineLabel ();
477 ec.LoopEnd = ig.DefineLabel ();
480 // Inform whether we are infinite or not
482 if (expr is BoolConstant){
483 ig.MarkLabel (ec.LoopBegin);
485 ig.Emit (OpCodes.Br, ec.LoopBegin);
488 // Inform that we are infinite (ie, `we return'), only
489 // if we do not `break' inside the code.
491 ig.MarkLabel (ec.LoopEnd);
493 Label while_loop = ig.DefineLabel ();
495 ig.Emit (OpCodes.Br, ec.LoopBegin);
496 ig.MarkLabel (while_loop);
500 ig.MarkLabel (ec.LoopBegin);
502 expr.EmitBranchable (ec, while_loop, true);
504 ig.MarkLabel (ec.LoopEnd);
507 ec.LoopBegin = old_begin;
508 ec.LoopEnd = old_end;
511 protected override void CloneTo (CloneContext clonectx, Statement t)
513 While target = (While) t;
515 target.expr = expr.Clone (clonectx);
516 target.Statement = Statement.Clone (clonectx);
520 public class For : Statement {
522 Statement InitStatement;
524 public Statement Statement;
525 bool infinite, empty;
527 public For (Statement initStatement,
533 InitStatement = initStatement;
535 Increment = increment;
536 Statement = statement;
540 public override bool Resolve (EmitContext ec)
544 if (InitStatement != null){
545 if (!InitStatement.Resolve (ec))
550 Test = Expression.ResolveBoolean (ec, Test, loc);
553 else if (Test is BoolConstant){
554 BoolConstant bc = (BoolConstant) Test;
556 if (bc.Value == false){
557 if (!Statement.ResolveUnreachable (ec, true))
559 if ((Increment != null) &&
560 !Increment.ResolveUnreachable (ec, false))
570 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
572 ec.CurrentBranching.CreateSibling ();
574 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
576 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
577 if (!Statement.Resolve (ec))
579 ec.EndFlowBranching ();
581 if (Increment != null){
582 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable) {
583 if (!Increment.ResolveUnreachable (ec, !was_unreachable))
586 if (!Increment.Resolve (ec))
591 // There's no direct control flow from the end of the embedded statement to the end of the loop
592 ec.CurrentBranching.CurrentUsageVector.Goto ();
594 ec.EndFlowBranching ();
599 protected override void DoEmit (EmitContext ec)
604 ILGenerator ig = ec.ig;
605 Label old_begin = ec.LoopBegin;
606 Label old_end = ec.LoopEnd;
607 Label loop = ig.DefineLabel ();
608 Label test = ig.DefineLabel ();
610 if (InitStatement != null && InitStatement != EmptyStatement.Value)
611 InitStatement.Emit (ec);
613 ec.LoopBegin = ig.DefineLabel ();
614 ec.LoopEnd = ig.DefineLabel ();
616 ig.Emit (OpCodes.Br, test);
620 ig.MarkLabel (ec.LoopBegin);
621 if (Increment != EmptyStatement.Value)
626 // If test is null, there is no test, and we are just
631 // The Resolve code already catches the case for
632 // Test == BoolConstant (false) so we know that
635 if (Test is BoolConstant)
636 ig.Emit (OpCodes.Br, loop);
638 Test.EmitBranchable (ec, loop, true);
641 ig.Emit (OpCodes.Br, loop);
642 ig.MarkLabel (ec.LoopEnd);
644 ec.LoopBegin = old_begin;
645 ec.LoopEnd = old_end;
648 protected override void CloneTo (CloneContext clonectx, Statement t)
650 For target = (For) t;
652 if (InitStatement != null)
653 target.InitStatement = InitStatement.Clone (clonectx);
655 target.Test = Test.Clone (clonectx);
656 if (Increment != null)
657 target.Increment = Increment.Clone (clonectx);
658 target.Statement = Statement.Clone (clonectx);
662 public class StatementExpression : Statement {
663 ExpressionStatement expr;
665 public StatementExpression (ExpressionStatement expr)
671 public override bool Resolve (EmitContext ec)
674 expr = expr.ResolveStatement (ec);
678 protected override void DoEmit (EmitContext ec)
680 expr.EmitStatement (ec);
683 public override string ToString ()
685 return "StatementExpression (" + expr + ")";
688 protected override void CloneTo (CloneContext clonectx, Statement t)
690 StatementExpression target = (StatementExpression) t;
692 target.expr = (ExpressionStatement) expr.Clone (clonectx);
697 /// Implements the return statement
699 public class Return : Statement {
700 public Expression Expr;
702 public Return (Expression expr, Location l)
710 public override bool Resolve (EmitContext ec)
712 AnonymousContainer am = ec.CurrentAnonymousMethod;
713 if ((am != null) && am.IsIterator && ec.InIterator) {
714 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
715 "statement to return a value, or yield break to end the iteration");
719 if (ec.ReturnType == null){
722 Report.Error (1662, loc,
723 "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",
724 am.GetSignatureForError ());
726 Error (127, "A return keyword must not be followed by any expression when method returns void");
731 Error (126, "An object of a type convertible to `{0}' is required " +
732 "for the return statement",
733 TypeManager.CSharpName (ec.ReturnType));
737 Expr = Expr.Resolve (ec);
741 if (Expr.Type != ec.ReturnType) {
742 if (ec.InferReturnType) {
743 ec.ReturnType = Expr.Type;
745 Expr = Convert.ImplicitConversionRequired (
746 ec, Expr, ec.ReturnType, loc);
753 int errors = Report.Errors;
754 unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
756 ec.NeedReturnLabel ();
757 ec.CurrentBranching.CurrentUsageVector.Goto ();
758 return errors == Report.Errors;
761 protected override void DoEmit (EmitContext ec)
767 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
771 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
773 ec.ig.Emit (OpCodes.Ret);
776 protected override void CloneTo (CloneContext clonectx, Statement t)
778 Return target = (Return) t;
780 target.Expr = Expr.Clone (clonectx);
784 public class Goto : Statement {
786 LabeledStatement label;
789 public override bool Resolve (EmitContext ec)
791 int errors = Report.Errors;
792 unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
793 ec.CurrentBranching.CurrentUsageVector.Goto ();
794 return errors == Report.Errors;
797 public Goto (string label, Location l)
803 public string Target {
804 get { return target; }
807 public void SetResolvedTarget (LabeledStatement label)
810 label.AddReference ();
813 protected override void DoEmit (EmitContext ec)
816 throw new InternalErrorException ("goto emitted before target resolved");
817 Label l = label.LabelTarget (ec);
818 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
822 public class LabeledStatement : Statement {
829 FlowBranching.UsageVector vectors;
831 public LabeledStatement (string name, Location l)
837 public Label LabelTarget (EmitContext ec)
842 label = ec.ig.DefineLabel ();
852 public bool IsDefined {
853 get { return defined; }
856 public bool HasBeenReferenced {
857 get { return referenced; }
860 public FlowBranching.UsageVector JumpOrigins {
861 get { return vectors; }
864 public void AddUsageVector (FlowBranching.UsageVector vector)
866 vector = vector.Clone ();
867 vector.Next = vectors;
871 public override bool Resolve (EmitContext ec)
873 // this flow-branching will be terminated when the surrounding block ends
874 ec.StartFlowBranching (this);
878 protected override void DoEmit (EmitContext ec)
880 if (ig != null && ig != ec.ig)
881 throw new InternalErrorException ("cannot happen");
883 ec.ig.MarkLabel (label);
886 public void AddReference ()
894 /// `goto default' statement
896 public class GotoDefault : Statement {
898 public GotoDefault (Location l)
903 public override bool Resolve (EmitContext ec)
905 ec.CurrentBranching.CurrentUsageVector.Goto ();
909 protected override void DoEmit (EmitContext ec)
911 if (ec.Switch == null){
912 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
916 if (!ec.Switch.GotDefault){
917 FlowBranchingBlock.Error_UnknownLabel (loc, "default");
920 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
925 /// `goto case' statement
927 public class GotoCase : Statement {
931 public GotoCase (Expression e, Location l)
937 public override bool Resolve (EmitContext ec)
939 if (ec.Switch == null){
940 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
944 expr = expr.Resolve (ec);
948 Constant c = expr as Constant;
950 Error (150, "A constant value is expected");
954 Type type = ec.Switch.SwitchType;
955 if (!Convert.ImplicitStandardConversionExists (c, type))
956 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
957 "convertible to type `{0}'", TypeManager.CSharpName (type));
960 object val = c.GetValue ();
961 if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
962 val = TypeManager.ChangeType (val, type, out fail);
965 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
966 c.GetSignatureForError (), TypeManager.CSharpName (type));
971 val = SwitchLabel.NullStringCase;
973 sl = (SwitchLabel) ec.Switch.Elements [val];
976 FlowBranchingBlock.Error_UnknownLabel (loc, "case " +
977 (c.GetValue () == null ? "null" : val.ToString ()));
981 ec.CurrentBranching.CurrentUsageVector.Goto ();
985 protected override void DoEmit (EmitContext ec)
987 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
990 protected override void CloneTo (CloneContext clonectx, Statement t)
992 GotoCase target = (GotoCase) t;
994 target.expr = expr.Clone (clonectx);
995 target.sl = sl.Clone (clonectx);
999 public class Throw : Statement {
1002 public Throw (Expression expr, Location l)
1008 public override bool Resolve (EmitContext ec)
1010 ec.CurrentBranching.CurrentUsageVector.Goto ();
1013 expr = expr.Resolve (ec);
1017 ExprClass eclass = expr.eclass;
1019 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1020 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1021 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
1027 if ((t != TypeManager.exception_type) &&
1028 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
1029 !(expr is NullLiteral)) {
1031 "The type caught or thrown must be derived " +
1032 "from System.Exception");
1039 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
1044 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1050 protected override void DoEmit (EmitContext ec)
1053 ec.ig.Emit (OpCodes.Rethrow);
1057 ec.ig.Emit (OpCodes.Throw);
1061 protected override void CloneTo (CloneContext clonectx, Statement t)
1063 Throw target = (Throw) t;
1065 target.expr = expr.Clone (clonectx);
1069 public class Break : Statement {
1071 public Break (Location l)
1076 bool unwind_protect;
1078 public override bool Resolve (EmitContext ec)
1080 int errors = Report.Errors;
1081 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1082 ec.CurrentBranching.CurrentUsageVector.Goto ();
1083 return errors == Report.Errors;
1086 protected override void DoEmit (EmitContext ec)
1088 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
1092 public class Continue : Statement {
1094 public Continue (Location l)
1099 bool unwind_protect;
1101 public override bool Resolve (EmitContext ec)
1103 int errors = Report.Errors;
1104 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1105 ec.CurrentBranching.CurrentUsageVector.Goto ();
1106 return errors == Report.Errors;
1109 protected override void DoEmit (EmitContext ec)
1111 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
1115 public abstract class Variable
1117 public abstract Type Type {
1121 public abstract bool HasInstance {
1125 public abstract bool NeedsTemporary {
1129 public abstract void EmitInstance (EmitContext ec);
1131 public abstract void Emit (EmitContext ec);
1133 public abstract void EmitAssign (EmitContext ec);
1135 public abstract void EmitAddressOf (EmitContext ec);
1138 public interface IKnownVariable {
1139 Block Block { get; }
1140 Location Location { get; }
1144 // The information about a user-perceived local variable
1146 public class LocalInfo : IKnownVariable {
1147 public Expression Type;
1149 public Type VariableType;
1150 public readonly string Name;
1151 public readonly Location Location;
1152 public readonly Block Block;
1154 public VariableInfo VariableInfo;
1157 public Variable Variable {
1169 CompilerGenerated = 64,
1173 public enum ReadOnlyContext: byte {
1180 ReadOnlyContext ro_context;
1181 LocalBuilder builder;
1183 public LocalInfo (Expression type, string name, Block block, Location l)
1191 public LocalInfo (DeclSpace ds, Block block, Location l)
1193 VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
1198 public void ResolveVariable (EmitContext ec)
1200 Block theblock = Block;
1201 if (theblock.ScopeInfo != null)
1202 var = theblock.ScopeInfo.GetCapturedVariable (this);
1207 // This is needed to compile on both .NET 1.x and .NET 2.x
1208 // the later introduced `DeclareLocal (Type t, bool pinned)'
1210 builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1212 builder = ec.ig.DeclareLocal (VariableType);
1214 var = new LocalVariable (this, builder);
1218 public void EmitSymbolInfo (EmitContext ec, string name)
1220 if (builder != null)
1221 ec.DefineLocalVariable (name, builder);
1224 public bool IsThisAssigned (EmitContext ec)
1226 if (VariableInfo == null)
1227 throw new Exception ();
1229 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1232 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, ec.loc);
1235 public bool IsAssigned (EmitContext ec)
1237 if (VariableInfo == null)
1238 throw new Exception ();
1240 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1243 public bool Resolve (EmitContext ec)
1245 if (VariableType == null) {
1246 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1250 VariableType = texpr.Type;
1253 if (TypeManager.IsGenericParameter (VariableType))
1256 if (VariableType == TypeManager.void_type) {
1257 Expression.Error_VoidInvalidInTheContext (Location);
1261 if (VariableType.IsAbstract && VariableType.IsSealed) {
1262 FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
1266 if (VariableType.IsPointer && !ec.InUnsafe)
1267 Expression.UnsafeError (Location);
1272 public bool IsCaptured {
1273 get { return (flags & Flags.Captured) != 0; }
1274 set { flags |= Flags.Captured; }
1277 public bool IsConstant {
1278 get { return (flags & Flags.IsConstant) != 0; }
1279 set { flags |= Flags.IsConstant; }
1282 public bool AddressTaken {
1283 get { return (flags & Flags.AddressTaken) != 0; }
1284 set { flags |= Flags.AddressTaken; }
1287 public bool CompilerGenerated {
1288 get { return (flags & Flags.CompilerGenerated) != 0; }
1289 set { flags |= Flags.CompilerGenerated; }
1292 public override string ToString ()
1294 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1295 Name, Type, VariableInfo, Location);
1299 get { return (flags & Flags.Used) != 0; }
1300 set { flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used)); }
1303 public bool ReadOnly {
1304 get { return (flags & Flags.ReadOnly) != 0; }
1307 public void SetReadOnlyContext (ReadOnlyContext context)
1309 flags |= Flags.ReadOnly;
1310 ro_context = context;
1313 public string GetReadOnlyContext ()
1316 throw new InternalErrorException ("Variable is not readonly");
1318 switch (ro_context) {
1319 case ReadOnlyContext.Fixed:
1320 return "fixed variable";
1321 case ReadOnlyContext.Foreach:
1322 return "foreach iteration variable";
1323 case ReadOnlyContext.Using:
1324 return "using variable";
1326 throw new NotImplementedException ();
1330 // Whether the variable is pinned, if Pinned the variable has been
1331 // allocated in a pinned slot with DeclareLocal.
1333 public bool Pinned {
1334 get { return (flags & Flags.Pinned) != 0; }
1335 set { flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned); }
1338 public bool IsThis {
1339 get { return (flags & Flags.IsThis) != 0; }
1340 set { flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis); }
1343 Block IKnownVariable.Block {
1344 get { return Block; }
1347 Location IKnownVariable.Location {
1348 get { return Location; }
1351 protected class LocalVariable : Variable
1353 public readonly LocalInfo LocalInfo;
1354 LocalBuilder builder;
1356 public LocalVariable (LocalInfo local, LocalBuilder builder)
1358 this.LocalInfo = local;
1359 this.builder = builder;
1362 public override Type Type {
1363 get { return LocalInfo.VariableType; }
1366 public override bool HasInstance {
1367 get { return false; }
1370 public override bool NeedsTemporary {
1371 get { return false; }
1374 public override void EmitInstance (EmitContext ec)
1379 public override void Emit (EmitContext ec)
1381 ec.ig.Emit (OpCodes.Ldloc, builder);
1384 public override void EmitAssign (EmitContext ec)
1386 ec.ig.Emit (OpCodes.Stloc, builder);
1389 public override void EmitAddressOf (EmitContext ec)
1391 ec.ig.Emit (OpCodes.Ldloca, builder);
1395 public LocalInfo Clone (CloneContext clonectx)
1397 // Only this kind is created by the parser.
1398 return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
1403 /// Block represents a C# block.
1407 /// This class is used in a number of places: either to represent
1408 /// explicit blocks that the programmer places or implicit blocks.
1410 /// Implicit blocks are used as labels or to introduce variable
1413 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1414 /// they contain extra information that is not necessary on normal blocks.
1416 public class Block : Statement {
1417 public Block Parent;
1418 public readonly Location StartLocation;
1419 public Location EndLocation = Location.Null;
1421 public ExplicitBlock Explicit;
1422 public ToplevelBlock Toplevel;
1425 public enum Flags : byte {
1428 VariablesInitialized = 4,
1432 HasVarargs = 64, // Used in ToplevelBlock
1435 protected Flags flags;
1437 public bool Unchecked {
1438 get { return (flags & Flags.Unchecked) != 0; }
1439 set { flags |= Flags.Unchecked; }
1442 public bool Unsafe {
1443 get { return (flags & Flags.Unsafe) != 0; }
1444 set { flags |= Flags.Unsafe; }
1448 // The statements in this block
1450 protected ArrayList statements;
1451 protected int current_statement;
1455 // An array of Blocks. We keep track of children just
1456 // to generate the local variable declarations.
1458 // Statements and child statements are handled through the
1464 // Labels. (label, block) pairs.
1469 // Keeps track of (name, type) pairs
1471 IDictionary variables;
1474 // Keeps track of constants
1475 Hashtable constants;
1478 // Temporary variables.
1480 ArrayList temporary_variables;
1483 // If this is a switch section, the enclosing switch block.
1487 ExpressionStatement scope_init;
1489 ArrayList anonymous_children;
1491 protected static int id;
1495 public Block (Block parent)
1496 : this (parent, (Flags) 0, Location.Null, Location.Null)
1499 public Block (Block parent, Flags flags)
1500 : this (parent, flags, Location.Null, Location.Null)
1503 public Block (Block parent, Location start, Location end)
1504 : this (parent, (Flags) 0, start, end)
1507 public Block (Block parent, Flags flags, Location start, Location end)
1509 if (parent != null) {
1510 parent.AddChild (this);
1512 // the appropriate constructors will fixup these fields
1513 Toplevel = parent.Toplevel;
1514 Explicit = parent.Explicit;
1517 this.Parent = parent;
1519 this.StartLocation = start;
1520 this.EndLocation = end;
1523 statements = new ArrayList ();
1526 public Block CreateSwitchBlock (Location start)
1528 // FIXME: should this be implicit?
1529 Block new_block = new ExplicitBlock (this, start, start);
1530 new_block.switch_block = this;
1535 get { return this_id; }
1538 public IDictionary Variables {
1540 if (variables == null)
1541 variables = new ListDictionary ();
1546 void AddChild (Block b)
1548 if (children == null)
1549 children = new ArrayList ();
1554 public void SetEndLocation (Location loc)
1559 protected static void Error_158 (string name, Location loc)
1561 Report.Error (158, loc, "The label `{0}' shadows another label " +
1562 "by the same name in a contained scope", name);
1566 /// Adds a label to the current block.
1570 /// false if the name already exists in this block. true
1574 public bool AddLabel (LabeledStatement target)
1576 if (switch_block != null)
1577 return switch_block.AddLabel (target);
1579 string name = target.Name;
1582 while (cur != null) {
1583 LabeledStatement s = cur.DoLookupLabel (name);
1585 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
1586 Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1590 if (this == Explicit)
1596 while (cur != null) {
1597 if (cur.DoLookupLabel (name) != null) {
1598 Error_158 (name, target.loc);
1602 if (children != null) {
1603 foreach (Block b in children) {
1604 LabeledStatement s = b.DoLookupLabel (name);
1608 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
1609 Error_158 (name, target.loc);
1617 Toplevel.CheckError158 (name, target.loc);
1620 labels = new Hashtable ();
1622 labels.Add (name, target);
1626 public LabeledStatement LookupLabel (string name)
1628 LabeledStatement s = DoLookupLabel (name);
1632 if (children == null)
1635 foreach (Block child in children) {
1636 if (Explicit != child.Explicit)
1639 s = child.LookupLabel (name);
1647 LabeledStatement DoLookupLabel (string name)
1649 if (switch_block != null)
1650 return switch_block.LookupLabel (name);
1653 if (labels.Contains (name))
1654 return ((LabeledStatement) labels [name]);
1659 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1662 IKnownVariable kvi = b.Explicit.GetKnownVariable (name);
1663 while (kvi == null) {
1664 b = b.Explicit.Parent;
1667 kvi = b.Explicit.GetKnownVariable (name);
1673 // Is kvi.Block nested inside 'b'
1674 if (b.Explicit != kvi.Block.Explicit) {
1676 // If a variable by the same name it defined in a nested block of this
1677 // block, we violate the invariant meaning in a block.
1680 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1681 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1686 // It's ok if the definition is in a nested subblock of b, but not
1687 // nested inside this block -- a definition in a sibling block
1688 // should not affect us.
1694 // Block 'b' and kvi.Block are the same textual block.
1695 // However, different variables are extant.
1697 // Check if the variable is in scope in both blocks. We use
1698 // an indirect check that depends on AddVariable doing its
1699 // part in maintaining the invariant-meaning-in-block property.
1701 if (e is VariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1705 // Even though we detected the error when the name is used, we
1706 // treat it as if the variable declaration was in error.
1708 Report.SymbolRelatedToPreviousError (loc, name);
1709 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1713 public LocalInfo AddVariable (Expression type, string name, Location l)
1715 LocalInfo vi = GetLocalInfo (name);
1717 Report.SymbolRelatedToPreviousError (vi.Location, name);
1718 if (Explicit == vi.Block.Explicit)
1719 Report.Error (128, l,
1720 "A local variable named `{0}' is already defined in this scope", name);
1722 Error_AlreadyDeclared (l, name, "parent");
1726 ToplevelParameterInfo pi = Toplevel.GetParameterInfo (name);
1728 Report.SymbolRelatedToPreviousError (pi.Location, name);
1729 Error_AlreadyDeclared (loc, name,
1730 pi.Block == Toplevel ? "method argument" : "parent or current");
1733 IKnownVariable kvi = Explicit.GetKnownVariable (name);
1735 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1736 Error_AlreadyDeclared (l, name, "child");
1740 vi = new LocalInfo (type, name, this, l);
1741 Variables.Add (name, vi);
1742 Explicit.AddKnownVariable (name, vi);
1744 if ((flags & Flags.VariablesInitialized) != 0)
1745 throw new InternalErrorException ("block has already been resolved");
1750 protected static void Error_AlreadyDeclared (Location loc, string var, string reason)
1752 Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1753 "in this scope because it would give a different meaning " +
1754 "to `{0}', which is already used in a `{1}' scope " +
1755 "to denote something else", var, reason);
1758 public bool AddConstant (Expression type, string name, Expression value, Location l)
1760 if (AddVariable (type, name, l) == null)
1763 if (constants == null)
1764 constants = new Hashtable ();
1766 constants.Add (name, value);
1768 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1773 static int next_temp_id = 0;
1775 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1777 Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1779 if (temporary_variables == null)
1780 temporary_variables = new ArrayList ();
1782 int id = ++next_temp_id;
1783 string name = "$s_" + id.ToString ();
1785 LocalInfo li = new LocalInfo (te, name, this, loc);
1786 li.CompilerGenerated = true;
1787 temporary_variables.Add (li);
1791 public LocalInfo GetLocalInfo (string name)
1793 for (Block b = this; b != null; b = b.Parent) {
1794 if (b.variables != null) {
1795 LocalInfo ret = b.variables [name] as LocalInfo;
1803 public Expression GetVariableType (string name)
1805 LocalInfo vi = GetLocalInfo (name);
1806 return vi == null ? null : vi.Type;
1809 public Expression GetConstantExpression (string name)
1811 for (Block b = this; b != null; b = b.Parent) {
1812 if (b.constants != null) {
1813 Expression ret = b.constants [name] as Expression;
1821 public void AddStatement (Statement s)
1824 flags |= Flags.BlockUsed;
1827 public void InsertStatementAfterCurrent (Statement statement)
1829 statements.Insert (current_statement + 1, statement);
1830 flags |= Flags.BlockUsed;
1834 get { return (flags & Flags.BlockUsed) != 0; }
1839 flags |= Flags.BlockUsed;
1842 public bool HasRet {
1843 get { return (flags & Flags.HasRet) != 0; }
1846 public bool IsDestructor {
1847 get { return (flags & Flags.IsDestructor) != 0; }
1850 public void SetDestructor ()
1852 flags |= Flags.IsDestructor;
1855 int assignable_slots;
1856 public int AssignableSlots {
1858 if ((flags & Flags.VariablesInitialized) == 0)
1859 throw new Exception ("Variables have not been initialized yet");
1860 return assignable_slots;
1864 protected ScopeInfo scope_info;
1866 public ScopeInfo ScopeInfo {
1867 get { return scope_info; }
1870 public ScopeInfo CreateScopeInfo ()
1872 if (scope_info == null)
1873 scope_info = ScopeInfo.CreateScope (this);
1878 public ArrayList AnonymousChildren {
1879 get { return anonymous_children; }
1882 public void AddAnonymousChild (ToplevelBlock b)
1884 if (anonymous_children == null)
1885 anonymous_children = new ArrayList ();
1887 anonymous_children.Add (b);
1890 void DoResolveConstants (EmitContext ec)
1892 if (constants == null)
1895 if (variables == null)
1896 throw new InternalErrorException ("cannot happen");
1898 foreach (DictionaryEntry de in variables) {
1899 string name = (string) de.Key;
1900 LocalInfo vi = (LocalInfo) de.Value;
1901 Type variable_type = vi.VariableType;
1903 if (variable_type == null)
1906 Expression cv = (Expression) constants [name];
1910 // Don't let 'const int Foo = Foo;' succeed.
1911 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1912 // which in turn causes the 'must be constant' error to be triggered.
1913 constants.Remove (name);
1915 if (!Const.IsConstantTypeValid (variable_type)) {
1916 Const.Error_InvalidConstantType (variable_type, loc);
1920 ec.CurrentBlock = this;
1922 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1923 e = cv.Resolve (ec);
1928 Constant ce = e as Constant;
1930 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1934 e = ce.ConvertImplicitly (variable_type);
1936 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue)
1937 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1939 ce.Error_ValueCannotBeConverted (null, vi.Location, variable_type, false);
1943 constants.Add (name, e);
1944 vi.IsConstant = true;
1948 protected void ResolveMeta (EmitContext ec, int offset)
1950 Report.Debug (64, "BLOCK RESOLVE META", this, Parent);
1952 // If some parent block was unsafe, we remain unsafe even if this block
1953 // isn't explicitly marked as such.
1954 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1955 flags |= Flags.VariablesInitialized;
1957 if (variables != null) {
1958 foreach (LocalInfo li in variables.Values) {
1959 if (!li.Resolve (ec))
1961 li.VariableInfo = new VariableInfo (li, offset);
1962 offset += li.VariableInfo.Length;
1965 assignable_slots = offset;
1967 DoResolveConstants (ec);
1969 if (children == null)
1971 foreach (Block b in children)
1972 b.ResolveMeta (ec, offset);
1977 // Emits the local variable declarations for a block
1979 public virtual void EmitMeta (EmitContext ec)
1981 Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
1982 if (ScopeInfo != null) {
1983 scope_init = ScopeInfo.GetScopeInitializer (ec);
1984 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
1988 if (variables != null){
1989 foreach (LocalInfo vi in variables.Values)
1990 vi.ResolveVariable (ec);
1993 if (temporary_variables != null) {
1994 foreach (LocalInfo vi in temporary_variables)
1995 vi.ResolveVariable (ec);
1998 if (children != null){
1999 foreach (Block b in children)
2004 void UsageWarning (FlowBranching.UsageVector vector)
2008 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
2009 foreach (DictionaryEntry de in variables){
2010 LocalInfo vi = (LocalInfo) de.Value;
2015 name = (string) de.Key;
2017 // vi.VariableInfo can be null for 'catch' variables
2018 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2019 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2021 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2027 bool unreachable_shown;
2030 private void CheckPossibleMistakenEmptyStatement (Statement s)
2034 // Some statements are wrapped by a Block. Since
2035 // others' internal could be changed, here I treat
2036 // them as possibly wrapped by Block equally.
2037 Block b = s as Block;
2038 if (b != null && b.statements.Count == 1)
2039 s = (Statement) b.statements [0];
2042 body = ((Lock) s).Statement;
2044 body = ((For) s).Statement;
2045 else if (s is Foreach)
2046 body = ((Foreach) s).Statement;
2047 else if (s is While)
2048 body = ((While) s).Statement;
2049 else if (s is Using)
2050 body = ((Using) s).Statement;
2051 else if (s is Fixed)
2052 body = ((Fixed) s).Statement;
2056 if (body == null || body is EmptyStatement)
2057 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2060 public override bool Resolve (EmitContext ec)
2062 Block prev_block = ec.CurrentBlock;
2065 int errors = Report.Errors;
2067 ec.CurrentBlock = this;
2068 ec.StartFlowBranching (this);
2070 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2073 // This flag is used to notate nested statements as unreachable from the beginning of this block.
2074 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
2075 // from the beginning of the function. The outer Resolve() that detected the unreachability is
2076 // responsible for handling the situation.
2078 for (current_statement = 0; current_statement < statements.Count; current_statement++) {
2079 Statement s = (Statement) statements [current_statement];
2080 // Check possible empty statement (CS0642)
2081 if (RootContext.WarningLevel >= 3 &&
2082 current_statement + 1 < statements.Count &&
2083 statements [current_statement + 1] is Block)
2084 CheckPossibleMistakenEmptyStatement (s);
2087 // Warn if we detect unreachable code.
2090 if (s is EmptyStatement)
2094 ((Block) s).unreachable = true;
2096 if (!unreachable_shown && !(s is LabeledStatement)) {
2097 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2098 unreachable_shown = true;
2103 // Note that we're not using ResolveUnreachable() for unreachable
2104 // statements here. ResolveUnreachable() creates a temporary
2105 // flow branching and kills it afterwards. This leads to problems
2106 // if you have two unreachable statements where the first one
2107 // assigns a variable and the second one tries to access it.
2110 if (!s.Resolve (ec)) {
2112 statements [current_statement] = EmptyStatement.Value;
2116 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2117 statements [current_statement] = EmptyStatement.Value;
2119 num_statements = current_statement + 1;
2121 unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
2122 if (unreachable && s is LabeledStatement)
2123 throw new InternalErrorException ("should not happen");
2126 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2127 ec.CurrentBranching, statements.Count, num_statements);
2132 while (ec.CurrentBranching is FlowBranchingLabeled)
2133 ec.EndFlowBranching ();
2135 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2137 ec.CurrentBlock = prev_block;
2139 // If we're a non-static `struct' constructor which doesn't have an
2140 // initializer, then we must initialize all of the struct's fields.
2141 if (this == Toplevel && !Toplevel.IsThisAssigned (ec) && !vector.IsUnreachable)
2144 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2145 foreach (LabeledStatement label in labels.Values)
2146 if (!label.HasBeenReferenced)
2147 Report.Warning (164, 2, label.loc,
2148 "This label has not been referenced");
2151 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2153 if (vector.IsUnreachable)
2154 flags |= Flags.HasRet;
2156 if (ok && (errors == Report.Errors)) {
2157 if (RootContext.WarningLevel >= 3)
2158 UsageWarning (vector);
2164 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2166 unreachable_shown = true;
2170 Report.Warning (162, 2, loc, "Unreachable code detected");
2172 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2173 bool ok = Resolve (ec);
2174 ec.KillFlowBranching ();
2179 protected override void DoEmit (EmitContext ec)
2181 for (int ix = 0; ix < num_statements; ix++){
2182 Statement s = (Statement) statements [ix];
2187 public override void Emit (EmitContext ec)
2189 Block prev_block = ec.CurrentBlock;
2191 ec.CurrentBlock = this;
2193 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2194 bool is_lexical_block = this == Explicit && Parent != null;
2196 if (emit_debug_info) {
2197 if (is_lexical_block)
2200 ec.Mark (StartLocation, true);
2201 if (scope_init != null)
2202 scope_init.EmitStatement (ec);
2204 ec.Mark (EndLocation, true);
2206 if (emit_debug_info) {
2207 if (is_lexical_block)
2210 if (variables != null) {
2211 foreach (DictionaryEntry de in variables) {
2212 string name = (string) de.Key;
2213 LocalInfo vi = (LocalInfo) de.Value;
2215 vi.EmitSymbolInfo (ec, name);
2220 ec.CurrentBlock = prev_block;
2223 public override string ToString ()
2225 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2228 protected override void CloneTo (CloneContext clonectx, Statement t)
2230 Block target = (Block) t;
2232 clonectx.AddBlockMap (this, target);
2234 target.Toplevel = (ToplevelBlock) clonectx.LookupBlock (Toplevel);
2235 target.Explicit = (ExplicitBlock) clonectx.LookupBlock (Explicit);
2237 target.Parent = clonectx.LookupBlock (Parent);
2239 target.statements = new ArrayList ();
2240 if (target.children != null){
2241 target.children = new ArrayList ();
2242 foreach (Block b in children){
2243 Block newblock = (Block) b.Clone (clonectx);
2245 target.children.Add (newblock);
2250 foreach (Statement s in statements)
2251 target.statements.Add (s.Clone (clonectx));
2253 if (variables != null){
2254 target.variables = new Hashtable ();
2256 foreach (DictionaryEntry de in variables){
2257 LocalInfo newlocal = ((LocalInfo) de.Value).Clone (clonectx);
2258 target.variables [de.Key] = newlocal;
2259 clonectx.AddVariableMap ((LocalInfo) de.Value, newlocal);
2264 // TODO: labels, switch_block, constants (?), anonymous_children
2269 public class ExplicitBlock : Block {
2270 public ExplicitBlock (Block parent, Location start, Location end)
2271 : this (parent, (Flags) 0, start, end)
2275 public ExplicitBlock (Block parent, Flags flags, Location start, Location end)
2276 : base (parent, flags, start, end)
2278 this.Explicit = this;
2281 Hashtable known_variables;
2284 // Marks a variable with name @name as being used in this or a child block.
2285 // If a variable name has been used in a child block, it's illegal to
2286 // declare a variable with the same name in the current block.
2288 internal void AddKnownVariable (string name, IKnownVariable info)
2290 if (known_variables == null)
2291 known_variables = new Hashtable ();
2293 known_variables [name] = info;
2296 Parent.Explicit.AddKnownVariable (name, info);
2299 internal IKnownVariable GetKnownVariable (string name)
2301 return known_variables == null ? null : (IKnownVariable) known_variables [name];
2304 protected override void CloneTo (CloneContext clonectx, Statement t)
2306 ExplicitBlock target = (ExplicitBlock) t;
2307 target.known_variables = null;
2308 base.CloneTo (clonectx, t);
2312 public class ToplevelParameterInfo : IKnownVariable {
2313 public readonly ToplevelBlock Block;
2314 public readonly int Index;
2315 public VariableInfo VariableInfo;
2317 Block IKnownVariable.Block {
2318 get { return Block; }
2320 public Parameter Parameter {
2321 get { return Block.Parameters [Index]; }
2323 public Location Location {
2324 get { return Parameter.Location; }
2327 public ToplevelParameterInfo (ToplevelBlock block, int idx)
2335 // A toplevel block contains extra information, the split is done
2336 // only to separate information that would otherwise bloat the more
2337 // lightweight Block.
2339 // In particular, this was introduced when the support for Anonymous
2340 // Methods was implemented.
2342 public class ToplevelBlock : ExplicitBlock {
2343 GenericMethod generic;
2344 FlowBranchingToplevel top_level_branching;
2345 AnonymousContainer anonymous_container;
2346 RootScopeInfo root_scope;
2348 public bool HasVarargs {
2349 get { return (flags & Flags.HasVarargs) != 0; }
2350 set { flags |= Flags.HasVarargs; }
2353 public bool IsIterator {
2354 get { return (flags & Flags.IsIterator) != 0; }
2358 // The parameters for the block.
2360 Parameters parameters;
2361 public Parameters Parameters {
2362 get { return parameters; }
2365 public bool CompleteContexts (EmitContext ec)
2367 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this, Parent, root_scope);
2369 if (root_scope != null)
2370 root_scope.LinkScopes ();
2372 if (Parent == null && root_scope != null) {
2373 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this, root_scope);
2375 if (root_scope.DefineType () == null)
2377 if (!root_scope.ResolveType ())
2379 if (!root_scope.ResolveMembers ())
2381 if (!root_scope.DefineMembers ())
2388 public GenericMethod GenericMethod {
2389 get { return generic; }
2392 public ToplevelBlock Container {
2393 get { return Parent == null ? null : Parent.Toplevel; }
2396 public AnonymousContainer AnonymousContainer {
2397 get { return anonymous_container; }
2398 set { anonymous_container = value; }
2401 public ToplevelBlock (Block parent, Parameters parameters, Location start) :
2402 this (parent, (Flags) 0, parameters, start)
2406 public ToplevelBlock (Block parent, Parameters parameters, GenericMethod generic, Location start) :
2407 this (parent, parameters, start)
2409 this.generic = generic;
2412 public ToplevelBlock (Parameters parameters, Location start) :
2413 this (null, (Flags) 0, parameters, start)
2417 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2418 this (null, flags, parameters, start)
2422 // We use 'Parent' to hook up to the containing block, but don't want to register the current block as a child.
2423 // So, we use a two-stage setup -- first pass a null parent to the base constructor, and then override 'Parent'.
2424 public ToplevelBlock (Block parent, Flags flags, Parameters parameters, Location start) :
2425 base (null, flags, start, Location.Null)
2427 this.Toplevel = this;
2429 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2430 this.Parent = parent;
2432 parent.AddAnonymousChild (this);
2434 if (this.parameters.Count != 0)
2435 ProcessParameters ();
2438 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2442 protected override void CloneTo (CloneContext clonectx, Statement t)
2444 ToplevelBlock target = (ToplevelBlock) t;
2445 base.CloneTo (clonectx, t);
2447 if (parameters.Count != 0)
2448 target.parameter_info = new ToplevelParameterInfo [parameters.Count];
2449 for (int i = 0; i < parameters.Count; ++i)
2450 target.parameter_info [i] = new ToplevelParameterInfo (target, i);
2453 public bool CheckError158 (string name, Location loc)
2455 if (AnonymousChildren != null) {
2456 foreach (ToplevelBlock child in AnonymousChildren) {
2457 if (!child.CheckError158 (name, loc))
2462 for (ToplevelBlock c = Container; c != null; c = c.Container) {
2463 if (!c.DoCheckError158 (name, loc))
2470 ToplevelParameterInfo [] parameter_info;
2471 void ProcessParameters ()
2473 int n = parameters.Count;
2474 parameter_info = new ToplevelParameterInfo [n];
2475 for (int i = 0; i < n; ++i) {
2476 parameter_info [i] = new ToplevelParameterInfo (this, i);
2478 string name = parameters [i].Name;
2480 LocalInfo vi = GetLocalInfo (name);
2482 Report.SymbolRelatedToPreviousError (vi.Location, name);
2483 Error_AlreadyDeclared (loc, name, "parent or current");
2487 ToplevelParameterInfo pi = Parent == null ? null : Parent.Toplevel.GetParameterInfo (name);
2489 Report.SymbolRelatedToPreviousError (pi.Location, name);
2490 Error_AlreadyDeclared (loc, name, "parent or current");
2494 AddKnownVariable (name, parameter_info [i]);
2497 // mark this block as "used" so that we create local declarations in a sub-block
2498 // FIXME: This appears to uncover a lot of bugs
2502 bool DoCheckError158 (string name, Location loc)
2504 LabeledStatement s = LookupLabel (name);
2506 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
2507 Error_158 (name, loc);
2514 public RootScopeInfo CreateRootScope (TypeContainer host)
2516 if (root_scope != null)
2519 if (Container == null)
2520 root_scope = new RootScopeInfo (
2521 this, host, generic, StartLocation);
2523 if (scope_info != null)
2524 throw new InternalErrorException ();
2526 scope_info = root_scope;
2530 public void CreateIteratorHost (RootScopeInfo root)
2532 Report.Debug (64, "CREATE ITERATOR HOST", this, root, Parent, root_scope);
2534 if (Parent != null || root_scope != null)
2535 throw new InternalErrorException ();
2537 scope_info = root_scope = root;
2540 public RootScopeInfo RootScope {
2542 if (root_scope != null)
2544 else if (Container != null)
2545 return Container.RootScope;
2551 public FlowBranchingToplevel TopLevelBranching {
2552 get { return top_level_branching; }
2556 // This is used if anonymous methods are used inside an iterator
2557 // (see 2test-22.cs for an example).
2559 // The AnonymousMethod is created while parsing - at a time when we don't
2560 // know yet that we're inside an iterator, so it's `Container' is initially
2561 // null. Later on, when resolving the iterator, we need to move the
2562 // anonymous method into that iterator.
2564 public void ReParent (ToplevelBlock new_parent)
2566 if ((flags & Flags.VariablesInitialized) != 0)
2567 throw new InternalErrorException ("block has already been resolved");
2569 Parent = new_parent;
2573 // Returns a `ParameterReference' for the given name, or null if there
2574 // is no such parameter
2576 public ParameterReference GetParameterReference (string name, Location loc)
2578 ToplevelParameterInfo p = GetParameterInfo (name);
2579 return p == null ? null : new ParameterReference (this, p, loc);
2582 public ToplevelParameterInfo GetParameterInfo (string name)
2585 for (ToplevelBlock t = this; t != null; t = t.Container) {
2586 Parameter par = t.Parameters.GetParameterByName (name, out idx);
2588 return t.parameter_info [idx];
2594 // Whether the parameter named `name' is local to this block,
2595 // or false, if the parameter belongs to an encompassing block.
2597 public bool IsLocalParameter (string name)
2599 return Parameters.GetParameterByName (name) != null;
2603 // Whether the `name' is a parameter reference
2605 public bool IsParameterReference (string name)
2607 for (ToplevelBlock t = this; t != null; t = t.Container) {
2608 if (t.IsLocalParameter (name))
2614 LocalInfo this_variable = null;
2617 // Returns the "this" instance variable of this block.
2618 // See AddThisVariable() for more information.
2620 public LocalInfo ThisVariable {
2621 get { return this_variable; }
2626 // This is used by non-static `struct' constructors which do not have an
2627 // initializer - in this case, the constructor must initialize all of the
2628 // struct's fields. To do this, we add a "this" variable and use the flow
2629 // analysis code to ensure that it's been fully initialized before control
2630 // leaves the constructor.
2632 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2634 if (this_variable == null) {
2635 this_variable = new LocalInfo (ds, this, l);
2636 this_variable.Used = true;
2637 this_variable.IsThis = true;
2639 Variables.Add ("this", this_variable);
2642 return this_variable;
2645 public bool IsThisAssigned (EmitContext ec)
2647 return this_variable == null || this_variable.IsThisAssigned (ec);
2650 public bool ResolveMeta (EmitContext ec, Parameters ip)
2652 int errors = Report.Errors;
2653 int orig_count = parameters.Count;
2655 if (top_level_branching != null)
2661 // Assert: orig_count != parameter.Count => orig_count == 0
2662 if (orig_count != 0 && orig_count != parameters.Count)
2663 throw new InternalErrorException ("parameter information mismatch");
2665 int offset = Parent == null ? 0 : Parent.AssignableSlots;
2667 for (int i = 0; i < orig_count; ++i) {
2668 Parameter.Modifier mod = parameters.ParameterModifier (i);
2670 if ((mod & Parameter.Modifier.OUT) != Parameter.Modifier.OUT)
2673 VariableInfo vi = new VariableInfo (ip, i, offset);
2674 parameter_info [i].VariableInfo = vi;
2675 offset += vi.Length;
2678 ResolveMeta (ec, offset);
2680 top_level_branching = ec.StartFlowBranching (this);
2682 return Report.Errors == errors;
2686 // Check whether all `out' parameters have been assigned.
2688 public void CheckOutParameters (FlowBranching.UsageVector vector, Location loc)
2690 if (vector.IsUnreachable)
2693 int n = parameter_info == null ? 0 : parameter_info.Length;
2695 for (int i = 0; i < n; i++) {
2696 VariableInfo var = parameter_info [i].VariableInfo;
2701 if (vector.IsAssigned (var, false))
2704 Report.Error (177, loc, "The out parameter `{0}' must be assigned to before control leaves the current method",
2709 public override void EmitMeta (EmitContext ec)
2712 parameters.ResolveVariable (this);
2715 public void MakeIterator (Iterator iterator)
2717 flags |= Flags.IsIterator;
2719 Block block = new ExplicitBlock (this, StartLocation, EndLocation);
2720 foreach (Statement stmt in statements)
2721 block.AddStatement (stmt);
2722 statements = new ArrayList ();
2723 statements.Add (new MoveNextStatement (iterator, block));
2726 protected class MoveNextStatement : Statement {
2730 public MoveNextStatement (Iterator iterator, Block block)
2732 this.iterator = iterator;
2734 this.loc = iterator.Location;
2737 public override bool Resolve (EmitContext ec)
2739 return block.Resolve (ec);
2742 protected override void DoEmit (EmitContext ec)
2744 iterator.EmitMoveNext (ec, block);
2748 public override string ToString ()
2750 return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2751 root_scope, anonymous_container != null ?
2752 anonymous_container.Scope : null);
2756 public class SwitchLabel {
2763 Label il_label_code;
2764 bool il_label_code_set;
2766 public static readonly object NullStringCase = new object ();
2769 // if expr == null, then it is the default case.
2771 public SwitchLabel (Expression expr, Location l)
2777 public Expression Label {
2783 public object Converted {
2789 public Label GetILLabel (EmitContext ec)
2792 il_label = ec.ig.DefineLabel ();
2793 il_label_set = true;
2798 public Label GetILLabelCode (EmitContext ec)
2800 if (!il_label_code_set){
2801 il_label_code = ec.ig.DefineLabel ();
2802 il_label_code_set = true;
2804 return il_label_code;
2808 // Resolves the expression, reduces it to a literal if possible
2809 // and then converts it to the requested type.
2811 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2813 Expression e = label.Resolve (ec);
2818 Constant c = e as Constant;
2820 Report.Error (150, loc, "A constant value is expected");
2824 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2825 converted = NullStringCase;
2829 if (allow_nullable && c.GetValue () == null) {
2830 converted = NullStringCase;
2834 c = c.ImplicitConversionRequired (required_type, loc);
2838 converted = c.GetValue ();
2842 public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
2845 if (converted == null)
2847 else if (converted == NullStringCase)
2849 else if (TypeManager.IsEnumType (switchType))
2850 label = TypeManager.CSharpEnumValue (switchType, converted);
2852 label = converted.ToString ();
2854 Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
2855 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2858 public SwitchLabel Clone (CloneContext clonectx)
2860 return new SwitchLabel (label.Clone (clonectx), loc);
2864 public class SwitchSection {
2865 // An array of SwitchLabels.
2866 public readonly ArrayList Labels;
2867 public readonly Block Block;
2869 public SwitchSection (ArrayList labels, Block block)
2875 public SwitchSection Clone (CloneContext clonectx)
2877 ArrayList cloned_labels = new ArrayList ();
2879 foreach (SwitchLabel sl in cloned_labels)
2880 cloned_labels.Add (sl.Clone (clonectx));
2882 return new SwitchSection (cloned_labels, clonectx.LookupBlock (Block));
2886 public class Switch : Statement {
2887 public ArrayList Sections;
2888 public Expression Expr;
2891 /// Maps constants whose type type SwitchType to their SwitchLabels.
2893 public IDictionary Elements;
2896 /// The governing switch type
2898 public Type SwitchType;
2903 Label default_target;
2905 Expression new_expr;
2907 SwitchSection constant_section;
2908 SwitchSection default_section;
2912 // Nullable Types support for GMCS.
2914 Nullable.Unwrap unwrap;
2916 protected bool HaveUnwrap {
2917 get { return unwrap != null; }
2920 protected bool HaveUnwrap {
2921 get { return false; }
2926 // The types allowed to be implicitly cast from
2927 // on the governing type
2929 static Type [] allowed_types;
2931 public Switch (Expression e, ArrayList sects, Location l)
2938 public bool GotDefault {
2940 return default_section != null;
2944 public Label DefaultTarget {
2946 return default_target;
2951 // Determines the governing type for a switch. The returned
2952 // expression might be the expression from the switch, or an
2953 // expression that includes any potential conversions to the
2954 // integral types or to string.
2956 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2958 Type t = TypeManager.DropGenericTypeArguments (expr.Type);
2960 if (t == TypeManager.byte_type ||
2961 t == TypeManager.sbyte_type ||
2962 t == TypeManager.ushort_type ||
2963 t == TypeManager.short_type ||
2964 t == TypeManager.uint32_type ||
2965 t == TypeManager.int32_type ||
2966 t == TypeManager.uint64_type ||
2967 t == TypeManager.int64_type ||
2968 t == TypeManager.char_type ||
2969 t == TypeManager.string_type ||
2970 t == TypeManager.bool_type ||
2971 t.IsSubclassOf (TypeManager.enum_type))
2974 if (allowed_types == null){
2975 allowed_types = new Type [] {
2976 TypeManager.sbyte_type,
2977 TypeManager.byte_type,
2978 TypeManager.short_type,
2979 TypeManager.ushort_type,
2980 TypeManager.int32_type,
2981 TypeManager.uint32_type,
2982 TypeManager.int64_type,
2983 TypeManager.uint64_type,
2984 TypeManager.char_type,
2985 TypeManager.string_type,
2986 TypeManager.bool_type
2991 // Try to find a *user* defined implicit conversion.
2993 // If there is no implicit conversion, or if there are multiple
2994 // conversions, we have to report an error
2996 Expression converted = null;
2997 foreach (Type tt in allowed_types){
3000 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
3005 // Ignore over-worked ImplicitUserConversions that do
3006 // an implicit conversion in addition to the user conversion.
3008 if (!(e is UserCast))
3011 if (converted != null){
3012 Report.ExtraInformation (
3014 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
3015 TypeManager.CSharpName (expr.Type)));
3025 // Performs the basic sanity checks on the switch statement
3026 // (looks for duplicate keys and non-constant expressions).
3028 // It also returns a hashtable with the keys that we will later
3029 // use to compute the switch tables
3031 bool CheckSwitch (EmitContext ec)
3034 Elements = Sections.Count > 10 ?
3035 (IDictionary)new Hashtable () :
3036 (IDictionary)new ListDictionary ();
3038 foreach (SwitchSection ss in Sections){
3039 foreach (SwitchLabel sl in ss.Labels){
3040 if (sl.Label == null){
3041 if (default_section != null){
3042 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
3045 default_section = ss;
3049 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
3054 object key = sl.Converted;
3056 Elements.Add (key, sl);
3057 } catch (ArgumentException) {
3058 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
3066 void EmitObjectInteger (ILGenerator ig, object k)
3069 IntConstant.EmitInt (ig, (int) k);
3070 else if (k is Constant) {
3071 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3074 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3077 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3079 IntConstant.EmitInt (ig, (int) (long) k);
3080 ig.Emit (OpCodes.Conv_I8);
3083 LongConstant.EmitLong (ig, (long) k);
3085 else if (k is ulong)
3087 ulong ul = (ulong) k;
3090 IntConstant.EmitInt (ig, unchecked ((int) ul));
3091 ig.Emit (OpCodes.Conv_U8);
3095 LongConstant.EmitLong (ig, unchecked ((long) ul));
3099 IntConstant.EmitInt (ig, (int) ((char) k));
3100 else if (k is sbyte)
3101 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3103 IntConstant.EmitInt (ig, (int) ((byte) k));
3104 else if (k is short)
3105 IntConstant.EmitInt (ig, (int) ((short) k));
3106 else if (k is ushort)
3107 IntConstant.EmitInt (ig, (int) ((ushort) k));
3109 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3111 throw new Exception ("Unhandled case");
3114 // structure used to hold blocks of keys while calculating table switch
3115 class KeyBlock : IComparable
3117 public KeyBlock (long _nFirst)
3119 nFirst = nLast = _nFirst;
3123 public ArrayList rgKeys = null;
3124 // how many items are in the bucket
3125 public int Size = 1;
3128 get { return (int) (nLast - nFirst + 1); }
3130 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3132 return kbLast.nLast - kbFirst.nFirst + 1;
3134 public int CompareTo (object obj)
3136 KeyBlock kb = (KeyBlock) obj;
3137 int nLength = Length;
3138 int nLengthOther = kb.Length;
3139 if (nLengthOther == nLength)
3140 return (int) (kb.nFirst - nFirst);
3141 return nLength - nLengthOther;
3146 /// This method emits code for a lookup-based switch statement (non-string)
3147 /// Basically it groups the cases into blocks that are at least half full,
3148 /// and then spits out individual lookup opcodes for each block.
3149 /// It emits the longest blocks first, and short blocks are just
3150 /// handled with direct compares.
3152 /// <param name="ec"></param>
3153 /// <param name="val"></param>
3154 /// <returns></returns>
3155 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3157 int cElements = Elements.Count;
3158 object [] rgKeys = new object [cElements];
3159 Elements.Keys.CopyTo (rgKeys, 0);
3160 Array.Sort (rgKeys);
3162 // initialize the block list with one element per key
3163 ArrayList rgKeyBlocks = new ArrayList ();
3164 foreach (object key in rgKeys)
3165 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3168 // iteratively merge the blocks while they are at least half full
3169 // there's probably a really cool way to do this with a tree...
3170 while (rgKeyBlocks.Count > 1)
3172 ArrayList rgKeyBlocksNew = new ArrayList ();
3173 kbCurr = (KeyBlock) rgKeyBlocks [0];
3174 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3176 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3177 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3180 kbCurr.nLast = kb.nLast;
3181 kbCurr.Size += kb.Size;
3185 // start a new block
3186 rgKeyBlocksNew.Add (kbCurr);
3190 rgKeyBlocksNew.Add (kbCurr);
3191 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3193 rgKeyBlocks = rgKeyBlocksNew;
3196 // initialize the key lists
3197 foreach (KeyBlock kb in rgKeyBlocks)
3198 kb.rgKeys = new ArrayList ();
3200 // fill the key lists
3202 if (rgKeyBlocks.Count > 0) {
3203 kbCurr = (KeyBlock) rgKeyBlocks [0];
3204 foreach (object key in rgKeys)
3206 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3207 System.Convert.ToInt64 (key) > kbCurr.nLast;
3209 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3210 kbCurr.rgKeys.Add (key);
3214 // sort the blocks so we can tackle the largest ones first
3215 rgKeyBlocks.Sort ();
3217 // okay now we can start...
3218 ILGenerator ig = ec.ig;
3219 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3220 Label lblDefault = ig.DefineLabel ();
3222 Type typeKeys = null;
3223 if (rgKeys.Length > 0)
3224 typeKeys = rgKeys [0].GetType (); // used for conversions
3228 if (TypeManager.IsEnumType (SwitchType))
3229 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3231 compare_type = SwitchType;
3233 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3235 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3236 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3239 foreach (object key in kb.rgKeys)
3241 ig.Emit (OpCodes.Ldloc, val);
3242 EmitObjectInteger (ig, key);
3243 SwitchLabel sl = (SwitchLabel) Elements [key];
3244 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3249 // TODO: if all the keys in the block are the same and there are
3250 // no gaps/defaults then just use a range-check.
3251 if (compare_type == TypeManager.int64_type ||
3252 compare_type == TypeManager.uint64_type)
3254 // TODO: optimize constant/I4 cases
3256 // check block range (could be > 2^31)
3257 ig.Emit (OpCodes.Ldloc, val);
3258 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3259 ig.Emit (OpCodes.Blt, lblDefault);
3260 ig.Emit (OpCodes.Ldloc, val);
3261 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3262 ig.Emit (OpCodes.Bgt, lblDefault);
3265 ig.Emit (OpCodes.Ldloc, val);
3268 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3269 ig.Emit (OpCodes.Sub);
3271 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3276 ig.Emit (OpCodes.Ldloc, val);
3277 int nFirst = (int) kb.nFirst;
3280 IntConstant.EmitInt (ig, nFirst);
3281 ig.Emit (OpCodes.Sub);
3283 else if (nFirst < 0)
3285 IntConstant.EmitInt (ig, -nFirst);
3286 ig.Emit (OpCodes.Add);
3290 // first, build the list of labels for the switch
3292 int cJumps = kb.Length;
3293 Label [] rgLabels = new Label [cJumps];
3294 for (int iJump = 0; iJump < cJumps; iJump++)
3296 object key = kb.rgKeys [iKey];
3297 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3299 SwitchLabel sl = (SwitchLabel) Elements [key];
3300 rgLabels [iJump] = sl.GetILLabel (ec);
3304 rgLabels [iJump] = lblDefault;
3306 // emit the switch opcode
3307 ig.Emit (OpCodes.Switch, rgLabels);
3310 // mark the default for this block
3312 ig.MarkLabel (lblDefault);
3315 // TODO: find the default case and emit it here,
3316 // to prevent having to do the following jump.
3317 // make sure to mark other labels in the default section
3319 // the last default just goes to the end
3320 ig.Emit (OpCodes.Br, lblDefault);
3322 // now emit the code for the sections
3323 bool fFoundDefault = false;
3324 bool fFoundNull = false;
3325 foreach (SwitchSection ss in Sections)
3327 foreach (SwitchLabel sl in ss.Labels)
3328 if (sl.Converted == SwitchLabel.NullStringCase)
3332 foreach (SwitchSection ss in Sections)
3334 foreach (SwitchLabel sl in ss.Labels)
3336 ig.MarkLabel (sl.GetILLabel (ec));
3337 ig.MarkLabel (sl.GetILLabelCode (ec));
3338 if (sl.Converted == SwitchLabel.NullStringCase)
3339 ig.MarkLabel (null_target);
3340 else if (sl.Label == null) {
3341 ig.MarkLabel (lblDefault);
3342 fFoundDefault = true;
3344 ig.MarkLabel (null_target);
3350 if (!fFoundDefault) {
3351 ig.MarkLabel (lblDefault);
3353 ig.MarkLabel (lblEnd);
3356 // This simple emit switch works, but does not take advantage of the
3358 // TODO: remove non-string logic from here
3359 // TODO: binary search strings?
3361 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3363 ILGenerator ig = ec.ig;
3364 Label end_of_switch = ig.DefineLabel ();
3365 Label next_test = ig.DefineLabel ();
3366 bool first_test = true;
3367 bool pending_goto_end = false;
3368 bool null_marked = false;
3370 int section_count = Sections.Count;
3372 // TODO: implement switch optimization for string by using Hashtable
3373 //if (SwitchType == TypeManager.string_type && section_count > 7)
3374 // Console.WriteLine ("Switch optimization possible " + loc);
3376 ig.Emit (OpCodes.Ldloc, val);
3378 if (Elements.Contains (SwitchLabel.NullStringCase)){
3379 ig.Emit (OpCodes.Brfalse, null_target);
3381 ig.Emit (OpCodes.Brfalse, default_target);
3383 ig.Emit (OpCodes.Ldloc, val);
3384 ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
3385 ig.Emit (OpCodes.Stloc, val);
3387 for (int section = 0; section < section_count; section++){
3388 SwitchSection ss = (SwitchSection) Sections [section];
3390 if (ss == default_section)
3393 Label sec_begin = ig.DefineLabel ();
3395 ig.Emit (OpCodes.Nop);
3397 if (pending_goto_end)
3398 ig.Emit (OpCodes.Br, end_of_switch);
3400 int label_count = ss.Labels.Count;
3402 for (int label = 0; label < label_count; label++){
3403 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3404 ig.MarkLabel (sl.GetILLabel (ec));
3407 ig.MarkLabel (next_test);
3408 next_test = ig.DefineLabel ();
3411 // If we are the default target
3413 if (sl.Label != null){
3414 object lit = sl.Converted;
3416 if (lit == SwitchLabel.NullStringCase){
3418 if (label + 1 == label_count)
3419 ig.Emit (OpCodes.Br, next_test);
3423 ig.Emit (OpCodes.Ldloc, val);
3424 ig.Emit (OpCodes.Ldstr, (string)lit);
3425 if (label_count == 1)
3426 ig.Emit (OpCodes.Bne_Un, next_test);
3428 if (label+1 == label_count)
3429 ig.Emit (OpCodes.Bne_Un, next_test);
3431 ig.Emit (OpCodes.Beq, sec_begin);
3436 ig.MarkLabel (null_target);
3439 ig.MarkLabel (sec_begin);
3440 foreach (SwitchLabel sl in ss.Labels)
3441 ig.MarkLabel (sl.GetILLabelCode (ec));
3444 pending_goto_end = !ss.Block.HasRet;
3447 ig.MarkLabel (next_test);
3448 ig.MarkLabel (default_target);
3450 ig.MarkLabel (null_target);
3451 if (default_section != null)
3452 default_section.Block.Emit (ec);
3453 ig.MarkLabel (end_of_switch);
3456 SwitchSection FindSection (SwitchLabel label)
3458 foreach (SwitchSection ss in Sections){
3459 foreach (SwitchLabel sl in ss.Labels){
3468 public override bool Resolve (EmitContext ec)
3470 Expr = Expr.Resolve (ec);
3474 new_expr = SwitchGoverningType (ec, Expr);
3477 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3478 unwrap = Nullable.Unwrap.Create (Expr, ec);
3482 new_expr = SwitchGoverningType (ec, unwrap);
3486 if (new_expr == null){
3487 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3492 SwitchType = new_expr.Type;
3494 if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
3495 Report.FeatureIsNotISO1 (loc, "switch expression of boolean type");
3499 if (!CheckSwitch (ec))
3503 Elements.Remove (SwitchLabel.NullStringCase);
3505 Switch old_switch = ec.Switch;
3507 ec.Switch.SwitchType = SwitchType;
3509 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3510 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3512 is_constant = new_expr is Constant;
3514 object key = ((Constant) new_expr).GetValue ();
3515 SwitchLabel label = (SwitchLabel) Elements [key];
3517 constant_section = FindSection (label);
3518 if (constant_section == null)
3519 constant_section = default_section;
3523 foreach (SwitchSection ss in Sections){
3525 ec.CurrentBranching.CreateSibling (
3526 null, FlowBranching.SiblingType.SwitchSection);
3530 if (is_constant && (ss != constant_section)) {
3531 // If we're a constant switch, we're only emitting
3532 // one single section - mark all the others as
3534 ec.CurrentBranching.CurrentUsageVector.Goto ();
3535 if (!ss.Block.ResolveUnreachable (ec, true))
3538 if (!ss.Block.Resolve (ec))
3543 if (default_section == null)
3544 ec.CurrentBranching.CreateSibling (
3545 null, FlowBranching.SiblingType.SwitchSection);
3547 ec.EndFlowBranching ();
3548 ec.Switch = old_switch;
3550 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
3555 protected override void DoEmit (EmitContext ec)
3557 ILGenerator ig = ec.ig;
3559 default_target = ig.DefineLabel ();
3560 null_target = ig.DefineLabel ();
3562 // Store variable for comparission purposes
3565 value = ig.DeclareLocal (SwitchType);
3567 unwrap.EmitCheck (ec);
3568 ig.Emit (OpCodes.Brfalse, null_target);
3570 ig.Emit (OpCodes.Stloc, value);
3572 } else if (!is_constant) {
3573 value = ig.DeclareLocal (SwitchType);
3575 ig.Emit (OpCodes.Stloc, value);
3580 // Setup the codegen context
3582 Label old_end = ec.LoopEnd;
3583 Switch old_switch = ec.Switch;
3585 ec.LoopEnd = ig.DefineLabel ();
3590 if (constant_section != null)
3591 constant_section.Block.Emit (ec);
3592 } else if (SwitchType == TypeManager.string_type)
3593 SimpleSwitchEmit (ec, value);
3595 TableSwitchEmit (ec, value);
3597 // Restore context state.
3598 ig.MarkLabel (ec.LoopEnd);
3601 // Restore the previous context
3603 ec.LoopEnd = old_end;
3604 ec.Switch = old_switch;
3607 protected override void CloneTo (CloneContext clonectx, Statement t)
3609 Switch target = (Switch) t;
3611 target.Expr = Expr.Clone (clonectx);
3612 target.Sections = new ArrayList ();
3613 foreach (SwitchSection ss in Sections){
3614 target.Sections.Add (ss.Clone (clonectx));
3619 public abstract class ExceptionStatement : Statement
3621 public abstract void EmitFinally (EmitContext ec);
3623 protected bool emit_finally = true;
3624 ArrayList parent_vectors;
3626 protected void DoEmitFinally (EmitContext ec)
3629 ec.ig.BeginFinallyBlock ();
3630 else if (ec.InIterator)
3631 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3635 protected void ResolveFinally (FlowBranchingException branching)
3637 emit_finally = branching.EmitFinally;
3639 branching.Parent.StealFinallyClauses (ref parent_vectors);
3643 public class Lock : ExceptionStatement {
3645 public Statement Statement;
3646 TemporaryVariable temp;
3648 public Lock (Expression expr, Statement stmt, Location l)
3655 public override bool Resolve (EmitContext ec)
3657 expr = expr.Resolve (ec);
3661 if (expr.Type.IsValueType){
3662 Report.Error (185, loc,
3663 "`{0}' is not a reference type as required by the lock statement",
3664 TypeManager.CSharpName (expr.Type));
3668 FlowBranchingException branching = ec.StartFlowBranching (this);
3669 bool ok = Statement.Resolve (ec);
3671 ResolveFinally (branching);
3673 ec.EndFlowBranching ();
3675 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
3676 // So, ensure there's some IL code after the finally block.
3677 ec.NeedReturnLabel ();
3679 // Avoid creating libraries that reference the internal
3682 if (t == TypeManager.null_type)
3683 t = TypeManager.object_type;
3685 temp = new TemporaryVariable (t, loc);
3691 protected override void DoEmit (EmitContext ec)
3693 ILGenerator ig = ec.ig;
3695 temp.Store (ec, expr);
3697 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3701 ig.BeginExceptionBlock ();
3702 Statement.Emit (ec);
3707 ig.EndExceptionBlock ();
3710 public override void EmitFinally (EmitContext ec)
3713 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3716 protected override void CloneTo (CloneContext clonectx, Statement t)
3718 Lock target = (Lock) t;
3720 target.expr = expr.Clone (clonectx);
3721 target.Statement = Statement.Clone (clonectx);
3725 public class Unchecked : Statement {
3728 public Unchecked (Block b)
3734 public override bool Resolve (EmitContext ec)
3736 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3737 return Block.Resolve (ec);
3740 protected override void DoEmit (EmitContext ec)
3742 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3746 protected override void CloneTo (CloneContext clonectx, Statement t)
3748 Unchecked target = (Unchecked) t;
3750 target.Block = clonectx.LookupBlock (Block);
3754 public class Checked : Statement {
3757 public Checked (Block b)
3760 b.Unchecked = false;
3763 public override bool Resolve (EmitContext ec)
3765 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3766 return Block.Resolve (ec);
3769 protected override void DoEmit (EmitContext ec)
3771 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3775 protected override void CloneTo (CloneContext clonectx, Statement t)
3777 Checked target = (Checked) t;
3779 target.Block = clonectx.LookupBlock (Block);
3783 public class Unsafe : Statement {
3786 public Unsafe (Block b)
3789 Block.Unsafe = true;
3792 public override bool Resolve (EmitContext ec)
3794 using (ec.With (EmitContext.Flags.InUnsafe, true))
3795 return Block.Resolve (ec);
3798 protected override void DoEmit (EmitContext ec)
3800 using (ec.With (EmitContext.Flags.InUnsafe, true))
3803 protected override void CloneTo (CloneContext clonectx, Statement t)
3805 Unsafe target = (Unsafe) t;
3807 target.Block = clonectx.LookupBlock (Block);
3814 public class Fixed : Statement {
3816 ArrayList declarators;
3817 Statement statement;
3822 abstract class Emitter
3824 protected LocalInfo vi;
3825 protected Expression converted;
3827 protected Emitter (Expression expr, LocalInfo li)
3833 public abstract void Emit (EmitContext ec);
3834 public abstract void EmitExit (EmitContext ec);
3837 class ExpressionEmitter : Emitter {
3838 public ExpressionEmitter (Expression converted, LocalInfo li) :
3839 base (converted, li)
3843 public override void Emit (EmitContext ec) {
3845 // Store pointer in pinned location
3847 converted.Emit (ec);
3848 vi.Variable.EmitAssign (ec);
3851 public override void EmitExit (EmitContext ec)
3853 ec.ig.Emit (OpCodes.Ldc_I4_0);
3854 ec.ig.Emit (OpCodes.Conv_U);
3855 vi.Variable.EmitAssign (ec);
3859 class StringEmitter : Emitter {
3860 LocalBuilder pinned_string;
3863 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3869 public override void Emit (EmitContext ec)
3871 ILGenerator ig = ec.ig;
3872 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3874 converted.Emit (ec);
3875 ig.Emit (OpCodes.Stloc, pinned_string);
3877 Expression sptr = new StringPtr (pinned_string, loc);
3878 converted = Convert.ImplicitConversionRequired (
3879 ec, sptr, vi.VariableType, loc);
3881 if (converted == null)
3884 converted.Emit (ec);
3885 vi.Variable.EmitAssign (ec);
3888 public override void EmitExit (EmitContext ec)
3890 ec.ig.Emit (OpCodes.Ldnull);
3891 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3895 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3898 declarators = decls;
3903 public Statement Statement {
3904 get { return statement; }
3907 public override bool Resolve (EmitContext ec)
3910 Expression.UnsafeError (loc);
3914 TypeExpr texpr = null;
3915 if (type is VarExpr) {
3916 Unary u = ((Pair) declarators[0]).Second as Unary;
3920 Expression e = u.Expr.Resolve (ec);
3921 if (e == null || e.Type == null)
3924 Type t = TypeManager.GetPointerType (e.Type);
3925 texpr = new TypeExpression (t, loc);
3928 texpr = type.ResolveAsTypeTerminal (ec, false);
3933 expr_type = texpr.Type;
3935 data = new Emitter [declarators.Count];
3937 if (!expr_type.IsPointer){
3938 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3943 foreach (Pair p in declarators){
3944 LocalInfo vi = (LocalInfo) p.First;
3945 Expression e = (Expression) p.Second;
3947 if (type is VarExpr)
3948 vi.VariableType = expr_type;
3950 vi.VariableInfo.SetAssigned (ec);
3951 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3954 // The rules for the possible declarators are pretty wise,
3955 // but the production on the grammar is more concise.
3957 // So we have to enforce these rules here.
3959 // We do not resolve before doing the case 1 test,
3960 // because the grammar is explicit in that the token &
3961 // is present, so we need to test for this particular case.
3965 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3970 // Case 1: & object.
3972 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3973 Expression child = ((Unary) e).Expr;
3975 if (child is ParameterReference || child is LocalVariableReference){
3978 "No need to use fixed statement for parameters or " +
3979 "local variable declarations (address is already " +
3984 ec.InFixedInitializer = true;
3986 ec.InFixedInitializer = false;
3990 child = ((Unary) e).Expr;
3992 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3995 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
3996 e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
4000 data [i] = new ExpressionEmitter (e, vi);
4006 ec.InFixedInitializer = true;
4008 ec.InFixedInitializer = false;
4015 if (e.Type.IsArray){
4016 Type array_type = TypeManager.GetElementType (e.Type);
4019 // Provided that array_type is unmanaged,
4021 if (!TypeManager.VerifyUnManaged (array_type, loc))
4025 // and T* is implicitly convertible to the
4026 // pointer type given in the fixed statement.
4028 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
4030 Expression converted = Convert.ImplicitConversionRequired (
4031 ec, array_ptr, vi.VariableType, loc);
4032 if (converted == null)
4035 data [i] = new ExpressionEmitter (converted, vi);
4044 if (e.Type == TypeManager.string_type){
4045 data [i] = new StringEmitter (e, vi, loc);
4050 // Case 4: fixed buffer
4051 FieldExpr fe = e as FieldExpr;
4053 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
4055 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
4057 Expression converted = Convert.ImplicitConversionRequired (
4058 ec, fixed_buffer_ptr, vi.VariableType, loc);
4059 if (converted == null)
4062 data [i] = new ExpressionEmitter (converted, vi);
4070 // For other cases, flag a `this is already fixed expression'
4072 if (e is LocalVariableReference || e is ParameterReference ||
4073 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
4075 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
4079 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
4083 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
4084 bool ok = statement.Resolve (ec);
4085 bool flow_unreachable = ec.EndFlowBranching ();
4086 has_ret = flow_unreachable;
4091 protected override void DoEmit (EmitContext ec)
4093 for (int i = 0; i < data.Length; i++) {
4097 statement.Emit (ec);
4103 // Clear the pinned variable
4105 for (int i = 0; i < data.Length; i++) {
4106 data [i].EmitExit (ec);
4110 protected override void CloneTo (CloneContext clonectx, Statement t)
4112 Fixed target = (Fixed) t;
4114 target.type = type.Clone (clonectx);
4115 target.declarators = new ArrayList ();
4116 foreach (LocalInfo var in declarators)
4117 target.declarators.Add (clonectx.LookupVariable (var));
4118 target.statement = statement.Clone (clonectx);
4122 public class Catch : Statement {
4123 public readonly string Name;
4125 public Block VarBlock;
4127 Expression type_expr;
4130 public Catch (Expression type, string name, Block block, Block var_block, Location l)
4135 VarBlock = var_block;
4139 public Type CatchType {
4145 public bool IsGeneral {
4147 return type_expr == null;
4151 protected override void DoEmit(EmitContext ec)
4153 ILGenerator ig = ec.ig;
4155 if (CatchType != null)
4156 ig.BeginCatchBlock (CatchType);
4158 ig.BeginCatchBlock (TypeManager.object_type);
4160 if (VarBlock != null)
4164 LocalInfo vi = Block.GetLocalInfo (Name);
4166 throw new Exception ("Variable does not exist in this block");
4168 if (vi.Variable.NeedsTemporary) {
4169 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
4170 ig.Emit (OpCodes.Stloc, e);
4172 vi.Variable.EmitInstance (ec);
4173 ig.Emit (OpCodes.Ldloc, e);
4174 vi.Variable.EmitAssign (ec);
4176 vi.Variable.EmitAssign (ec);
4178 ig.Emit (OpCodes.Pop);
4183 public override bool Resolve (EmitContext ec)
4185 using (ec.With (EmitContext.Flags.InCatch, true)) {
4186 if (type_expr != null) {
4187 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
4193 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4194 Error (155, "The type caught or thrown must be derived from System.Exception");
4200 if (!Block.Resolve (ec))
4203 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4204 // emit the "unused variable" warnings.
4205 if (VarBlock != null)
4206 return VarBlock.Resolve (ec);
4212 protected override void CloneTo (CloneContext clonectx, Statement t)
4214 Catch target = (Catch) t;
4216 target.type_expr = type_expr.Clone (clonectx);
4217 target.Block = clonectx.LookupBlock (Block);
4218 target.VarBlock = clonectx.LookupBlock (VarBlock);
4222 public class Try : ExceptionStatement {
4223 public Block Fini, Block;
4224 public ArrayList Specific;
4225 public Catch General;
4227 bool need_exc_block;
4230 // specific, general and fini might all be null.
4232 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4234 if (specific == null && general == null){
4235 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4239 this.Specific = specific;
4240 this.General = general;
4245 public override bool Resolve (EmitContext ec)
4249 FlowBranchingException branching = ec.StartFlowBranching (this);
4251 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4253 if (!Block.Resolve (ec))
4256 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4258 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4260 Type[] prevCatches = new Type [Specific.Count];
4262 foreach (Catch c in Specific){
4263 ec.CurrentBranching.CreateSibling (
4264 c.Block, FlowBranching.SiblingType.Catch);
4266 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4268 if (c.Name != null) {
4269 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4271 throw new Exception ();
4273 vi.VariableInfo = null;
4276 if (!c.Resolve (ec))
4279 Type resolvedType = c.CatchType;
4280 for (int ii = 0; ii < last_index; ++ii) {
4281 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4282 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4287 prevCatches [last_index++] = resolvedType;
4288 need_exc_block = true;
4291 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4293 if (General != null){
4294 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4295 foreach (Catch c in Specific){
4296 if (c.CatchType == TypeManager.exception_type) {
4297 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'");
4302 ec.CurrentBranching.CreateSibling (
4303 General.Block, FlowBranching.SiblingType.Catch);
4305 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4307 if (!General.Resolve (ec))
4310 need_exc_block = true;
4313 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4317 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4319 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4320 using (ec.With (EmitContext.Flags.InFinally, true)) {
4321 if (!Fini.Resolve (ec))
4326 need_exc_block = true;
4329 if (ec.InIterator) {
4330 ResolveFinally (branching);
4331 need_exc_block |= emit_finally;
4333 emit_finally = Fini != null;
4335 ec.EndFlowBranching ();
4337 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4338 // So, ensure there's some IL code after the finally block.
4339 ec.NeedReturnLabel ();
4341 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4343 Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
4348 protected override void DoEmit (EmitContext ec)
4350 ILGenerator ig = ec.ig;
4353 ig.BeginExceptionBlock ();
4356 foreach (Catch c in Specific)
4359 if (General != null)
4364 ig.EndExceptionBlock ();
4367 public override void EmitFinally (EmitContext ec)
4373 public bool HasCatch
4376 return General != null || Specific.Count > 0;
4380 protected override void CloneTo (CloneContext clonectx, Statement t)
4382 Try target = (Try) t;
4384 target.Block = clonectx.LookupBlock (Block);
4386 target.Fini = clonectx.LookupBlock (Fini);
4387 if (General != null)
4388 target.General = (Catch) General.Clone (clonectx);
4389 if (Specific != null){
4390 target.Specific = new ArrayList ();
4391 foreach (Catch c in Specific)
4392 target.Specific.Add (c.Clone (clonectx));
4397 public class Using : ExceptionStatement {
4398 object expression_or_block;
4399 public Statement Statement;
4403 Expression [] resolved_vars;
4404 Expression [] converted_vars;
4405 ExpressionStatement [] assign;
4406 TemporaryVariable local_copy;
4408 public Using (object expression_or_block, Statement stmt, Location l)
4410 this.expression_or_block = expression_or_block;
4416 // Resolves for the case of using using a local variable declaration.
4418 bool ResolveLocalVariableDecls (EmitContext ec)
4422 TypeExpr texpr = null;
4424 if (expr is VarExpr) {
4425 Expression e = ((Expression)((DictionaryEntry)var_list[0]).Value).Resolve (ec);
4426 if (e == null || e.Type == null)
4428 texpr = new TypeExpression (e.Type, loc);
4431 texpr = expr.ResolveAsTypeTerminal (ec, false);
4436 expr_type = texpr.Type;
4439 // The type must be an IDisposable or an implicit conversion
4442 converted_vars = new Expression [var_list.Count];
4443 resolved_vars = new Expression [var_list.Count];
4444 assign = new ExpressionStatement [var_list.Count];
4446 bool need_conv = !TypeManager.ImplementsInterface (
4447 expr_type, TypeManager.idisposable_type);
4449 foreach (DictionaryEntry e in var_list){
4450 Expression var = (Expression) e.Key;
4452 if (expr is VarExpr) {
4453 LocalVariableReference l = var as LocalVariableReference;
4454 ((LocalInfo)l.Block.Variables[l.Name]).VariableType = expr_type;
4455 ((VarExpr)expr).Handled = true;
4458 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
4462 resolved_vars [i] = var;
4469 converted_vars [i] = Convert.ImplicitConversion (
4470 ec, var, TypeManager.idisposable_type, loc);
4472 if (converted_vars [i] == null) {
4473 Error_IsNotConvertibleToIDisposable ();
4481 foreach (DictionaryEntry e in var_list){
4482 Expression var = resolved_vars [i];
4483 Expression new_expr = (Expression) e.Value;
4486 a = new Assign (var, new_expr, loc);
4492 converted_vars [i] = var;
4493 assign [i] = (ExpressionStatement) a;
4500 void Error_IsNotConvertibleToIDisposable ()
4502 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4503 TypeManager.CSharpName (expr_type));
4506 bool ResolveExpression (EmitContext ec)
4508 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4509 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4510 Error_IsNotConvertibleToIDisposable ();
4515 local_copy = new TemporaryVariable (expr_type, loc);
4516 local_copy.Resolve (ec);
4522 // Emits the code for the case of using using a local variable declaration.
4524 void EmitLocalVariableDecls (EmitContext ec)
4526 ILGenerator ig = ec.ig;
4529 for (i = 0; i < assign.Length; i++) {
4530 assign [i].EmitStatement (ec);
4533 ig.BeginExceptionBlock ();
4535 Statement.Emit (ec);
4537 var_list.Reverse ();
4542 void EmitLocalVariableDeclFinally (EmitContext ec)
4544 ILGenerator ig = ec.ig;
4546 int i = assign.Length;
4547 for (int ii = 0; ii < var_list.Count; ++ii){
4548 Expression var = resolved_vars [--i];
4549 Label skip = ig.DefineLabel ();
4552 ig.BeginFinallyBlock ();
4554 if (!var.Type.IsValueType) {
4556 ig.Emit (OpCodes.Brfalse, skip);
4557 converted_vars [i].Emit (ec);
4558 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4560 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4562 if (!(ml is MethodGroupExpr)) {
4564 ig.Emit (OpCodes.Box, var.Type);
4565 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4567 MethodInfo mi = null;
4569 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4570 if (TypeManager.GetParameterData (mk).Count == 0) {
4577 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4581 IMemoryLocation mloc = (IMemoryLocation) var;
4583 mloc.AddressOf (ec, AddressOp.Load);
4584 ig.Emit (OpCodes.Call, mi);
4588 ig.MarkLabel (skip);
4591 ig.EndExceptionBlock ();
4593 ig.BeginFinallyBlock ();
4598 void EmitExpression (EmitContext ec)
4601 // Make a copy of the expression and operate on that.
4603 ILGenerator ig = ec.ig;
4605 local_copy.Store (ec, expr);
4608 ig.BeginExceptionBlock ();
4610 Statement.Emit (ec);
4614 ig.EndExceptionBlock ();
4617 void EmitExpressionFinally (EmitContext ec)
4619 ILGenerator ig = ec.ig;
4620 if (!expr_type.IsValueType) {
4621 Label skip = ig.DefineLabel ();
4622 local_copy.Emit (ec);
4623 ig.Emit (OpCodes.Brfalse, skip);
4624 local_copy.Emit (ec);
4625 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4626 ig.MarkLabel (skip);
4628 Expression ml = Expression.MemberLookup (
4629 ec.ContainerType, TypeManager.idisposable_type, expr_type,
4630 "Dispose", Location.Null);
4632 if (!(ml is MethodGroupExpr)) {
4633 local_copy.Emit (ec);
4634 ig.Emit (OpCodes.Box, expr_type);
4635 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4637 MethodInfo mi = null;
4639 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4640 if (TypeManager.GetParameterData (mk).Count == 0) {
4647 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4651 local_copy.AddressOf (ec, AddressOp.Load);
4652 ig.Emit (OpCodes.Call, mi);
4657 public override bool Resolve (EmitContext ec)
4659 if (expression_or_block is DictionaryEntry){
4660 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4661 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4663 if (!ResolveLocalVariableDecls (ec))
4666 } else if (expression_or_block is Expression){
4667 expr = (Expression) expression_or_block;
4669 expr = expr.Resolve (ec);
4673 expr_type = expr.Type;
4675 if (!ResolveExpression (ec))
4679 FlowBranchingException branching = ec.StartFlowBranching (this);
4681 bool ok = Statement.Resolve (ec);
4683 ResolveFinally (branching);
4685 ec.EndFlowBranching ();
4687 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4688 // So, ensure there's some IL code after the finally block.
4689 ec.NeedReturnLabel ();
4694 protected override void DoEmit (EmitContext ec)
4696 if (expression_or_block is DictionaryEntry)
4697 EmitLocalVariableDecls (ec);
4698 else if (expression_or_block is Expression)
4699 EmitExpression (ec);
4702 public override void EmitFinally (EmitContext ec)
4704 if (expression_or_block is DictionaryEntry)
4705 EmitLocalVariableDeclFinally (ec);
4706 else if (expression_or_block is Expression)
4707 EmitExpressionFinally (ec);
4710 protected override void CloneTo (CloneContext clonectx, Statement t)
4712 Using target = (Using) t;
4714 if (expression_or_block is Expression)
4715 target.expression_or_block = ((Expression) expression_or_block).Clone (clonectx);
4717 target.expression_or_block = ((Statement) expression_or_block).Clone (clonectx);
4719 target.Statement = Statement.Clone (clonectx);
4724 /// Implementation of the foreach C# statement
4726 public class Foreach : Statement {
4728 Expression variable;
4730 Statement statement;
4732 CollectionForeach collection;
4734 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4735 Statement stmt, Location l)
4738 this.variable = var;
4744 public Statement Statement {
4745 get { return statement; }
4748 public override bool Resolve (EmitContext ec)
4750 expr = expr.Resolve (ec);
4754 if (type is VarExpr) {
4755 Type element_type = null;
4756 if (TypeManager.HasElementType (expr.Type))
4757 element_type = TypeManager.GetElementType (expr.Type);
4759 MethodGroupExpr mg = Expression.MemberLookup (
4760 ec.ContainerType, expr.Type, "GetEnumerator", MemberTypes.Method,
4761 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4766 MethodInfo get_enumerator = null;
4767 foreach (MethodInfo mi in mg.Methods) {
4768 if (TypeManager.GetParameterData (mi).Count != 0)
4770 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4772 if (CollectionForeach.IsOverride (mi))
4774 get_enumerator = mi;
4777 if (get_enumerator == null)
4780 PropertyInfo pi = TypeManager.GetProperty (get_enumerator.ReturnType, "Current");
4785 element_type = pi.PropertyType;
4788 type = new TypeLookupExpression (element_type.AssemblyQualifiedName);
4790 LocalVariableReference lv = variable as LocalVariableReference;
4791 ((LocalInfo)lv.Block.Variables[lv.Name]).VariableType = element_type;
4794 Constant c = expr as Constant;
4795 if (c != null && c.GetValue () == null) {
4796 Report.Error (186, loc, "Use of null is not valid in this context");
4800 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4804 Type var_type = texpr.Type;
4806 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4807 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4808 expr.ExprClassName);
4813 // We need an instance variable. Not sure this is the best
4814 // way of doing this.
4816 // FIXME: When we implement propertyaccess, will those turn
4817 // out to return values in ExprClass? I think they should.
4819 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4820 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4821 collection.Error_Enumerator ();
4825 if (expr.Type.IsArray) {
4826 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4827 return array.Resolve (ec);
4829 collection = new CollectionForeach (
4830 var_type, variable, expr, statement, loc);
4831 return collection.Resolve (ec);
4835 protected override void DoEmit (EmitContext ec)
4837 ILGenerator ig = ec.ig;
4839 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4840 ec.LoopBegin = ig.DefineLabel ();
4841 ec.LoopEnd = ig.DefineLabel ();
4843 if (collection != null)
4844 collection.Emit (ec);
4848 ec.LoopBegin = old_begin;
4849 ec.LoopEnd = old_end;
4852 protected class ArrayCounter : TemporaryVariable
4854 public ArrayCounter (Location loc)
4855 : base (TypeManager.int32_type, loc)
4858 public void Initialize (EmitContext ec)
4861 ec.ig.Emit (OpCodes.Ldc_I4_0);
4865 public void Increment (EmitContext ec)
4869 ec.ig.Emit (OpCodes.Ldc_I4_1);
4870 ec.ig.Emit (OpCodes.Add);
4875 protected class ArrayForeach : Statement
4877 Expression variable, expr, conv;
4878 Statement statement;
4881 TemporaryVariable[] lengths;
4882 ArrayCounter[] counter;
4885 TemporaryVariable copy;
4888 public ArrayForeach (Type var_type, Expression var,
4889 Expression expr, Statement stmt, Location l)
4891 this.var_type = var_type;
4892 this.variable = var;
4898 public override bool Resolve (EmitContext ec)
4900 array_type = expr.Type;
4901 rank = array_type.GetArrayRank ();
4903 copy = new TemporaryVariable (array_type, loc);
4906 counter = new ArrayCounter [rank];
4907 lengths = new TemporaryVariable [rank];
4909 ArrayList list = new ArrayList ();
4910 for (int i = 0; i < rank; i++) {
4911 counter [i] = new ArrayCounter (loc);
4912 counter [i].Resolve (ec);
4914 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4915 lengths [i].Resolve (ec);
4917 list.Add (counter [i]);
4920 access = new ElementAccess (copy, list).Resolve (ec);
4924 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4930 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4931 ec.CurrentBranching.CreateSibling ();
4933 variable = variable.ResolveLValue (ec, conv, loc);
4934 if (variable == null)
4937 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4938 if (!statement.Resolve (ec))
4940 ec.EndFlowBranching ();
4942 // There's no direct control flow from the end of the embedded statement to the end of the loop
4943 ec.CurrentBranching.CurrentUsageVector.Goto ();
4945 ec.EndFlowBranching ();
4950 protected override void DoEmit (EmitContext ec)
4952 ILGenerator ig = ec.ig;
4954 copy.Store (ec, expr);
4956 Label[] test = new Label [rank];
4957 Label[] loop = new Label [rank];
4959 for (int i = 0; i < rank; i++) {
4960 test [i] = ig.DefineLabel ();
4961 loop [i] = ig.DefineLabel ();
4963 lengths [i].EmitThis (ec);
4964 ((ArrayAccess) access).EmitGetLength (ec, i);
4965 lengths [i].EmitStore (ec);
4968 for (int i = 0; i < rank; i++) {
4969 counter [i].Initialize (ec);
4971 ig.Emit (OpCodes.Br, test [i]);
4972 ig.MarkLabel (loop [i]);
4975 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4977 statement.Emit (ec);
4979 ig.MarkLabel (ec.LoopBegin);
4981 for (int i = rank - 1; i >= 0; i--){
4982 counter [i].Increment (ec);
4984 ig.MarkLabel (test [i]);
4985 counter [i].Emit (ec);
4986 lengths [i].Emit (ec);
4987 ig.Emit (OpCodes.Blt, loop [i]);
4990 ig.MarkLabel (ec.LoopEnd);
4994 protected class CollectionForeach : ExceptionStatement
4996 Expression variable, expr;
4997 Statement statement;
4999 TemporaryVariable enumerator;
5003 MethodGroupExpr get_enumerator;
5004 PropertyExpr get_current;
5005 MethodInfo move_next;
5006 Type var_type, enumerator_type;
5008 bool enumerator_found;
5010 public CollectionForeach (Type var_type, Expression var,
5011 Expression expr, Statement stmt, Location l)
5013 this.var_type = var_type;
5014 this.variable = var;
5020 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
5022 Type return_type = mi.ReturnType;
5024 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
5026 // Apply the same optimization as MS: skip the GetEnumerator
5027 // returning an IEnumerator, and use the one returning a
5028 // CharEnumerator instead. This allows us to avoid the
5029 // try-finally block and the boxing.
5034 // Ok, we can access it, now make sure that we can do something
5035 // with this `GetEnumerator'
5038 if (return_type == TypeManager.ienumerator_type ||
5039 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
5040 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
5042 // If it is not an interface, lets try to find the methods ourselves.
5043 // For example, if we have:
5044 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
5045 // We can avoid the iface call. This is a runtime perf boost.
5046 // even bigger if we have a ValueType, because we avoid the cost
5049 // We have to make sure that both methods exist for us to take
5050 // this path. If one of the methods does not exist, we will just
5051 // use the interface. Sadly, this complex if statement is the only
5052 // way I could do this without a goto
5057 // Prefer a generic enumerator over a non-generic one.
5059 if (return_type.IsInterface && return_type.IsGenericType) {
5060 enumerator_type = return_type;
5061 if (!FetchGetCurrent (ec, return_type))
5062 get_current = new PropertyExpr (
5063 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5064 if (!FetchMoveNext (return_type))
5065 move_next = TypeManager.bool_movenext_void;
5070 if (return_type.IsInterface ||
5071 !FetchMoveNext (return_type) ||
5072 !FetchGetCurrent (ec, return_type)) {
5073 enumerator_type = return_type;
5074 move_next = TypeManager.bool_movenext_void;
5075 get_current = new PropertyExpr (
5076 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5081 // Ok, so they dont return an IEnumerable, we will have to
5082 // find if they support the GetEnumerator pattern.
5085 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
5086 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",
5087 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
5092 enumerator_type = return_type;
5093 is_disposable = !enumerator_type.IsSealed ||
5094 TypeManager.ImplementsInterface (
5095 enumerator_type, TypeManager.idisposable_type);
5101 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5103 bool FetchMoveNext (Type t)
5105 MemberList move_next_list;
5107 move_next_list = TypeContainer.FindMembers (
5108 t, MemberTypes.Method,
5109 BindingFlags.Public | BindingFlags.Instance,
5110 Type.FilterName, "MoveNext");
5111 if (move_next_list.Count == 0)
5114 foreach (MemberInfo m in move_next_list){
5115 MethodInfo mi = (MethodInfo) m;
5117 if ((TypeManager.GetParameterData (mi).Count == 0) &&
5118 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
5128 // Retrieves a `public T get_Current ()' method from the Type `t'
5130 bool FetchGetCurrent (EmitContext ec, Type t)
5132 PropertyExpr pe = Expression.MemberLookup (
5133 ec.ContainerType, t, "Current", MemberTypes.Property,
5134 Expression.AllBindingFlags, loc) as PropertyExpr;
5143 // Retrieves a `public void Dispose ()' method from the Type `t'
5145 static MethodInfo FetchMethodDispose (Type t)
5147 MemberList dispose_list;
5149 dispose_list = TypeContainer.FindMembers (
5150 t, MemberTypes.Method,
5151 BindingFlags.Public | BindingFlags.Instance,
5152 Type.FilterName, "Dispose");
5153 if (dispose_list.Count == 0)
5156 foreach (MemberInfo m in dispose_list){
5157 MethodInfo mi = (MethodInfo) m;
5159 if (TypeManager.GetParameterData (mi).Count == 0){
5160 if (mi.ReturnType == TypeManager.void_type)
5167 public void Error_Enumerator ()
5169 if (enumerator_found) {
5173 Report.Error (1579, loc,
5174 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
5175 TypeManager.CSharpName (expr.Type));
5178 public static bool IsOverride (MethodInfo m)
5180 m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
5182 if (!m.IsVirtual || ((m.Attributes & MethodAttributes.NewSlot) != 0))
5184 if (m is MethodBuilder)
5187 MethodInfo base_method = m.GetBaseDefinition ();
5188 return base_method != m;
5191 bool TryType (EmitContext ec, Type t)
5193 MethodGroupExpr mg = Expression.MemberLookup (
5194 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
5195 Expression.AllBindingFlags, loc) as MethodGroupExpr;
5199 MethodInfo result = null;
5200 MethodInfo tmp_move_next = null;
5201 PropertyExpr tmp_get_cur = null;
5202 Type tmp_enumerator_type = enumerator_type;
5203 foreach (MethodInfo mi in mg.Methods) {
5204 if (TypeManager.GetParameterData (mi).Count != 0)
5207 // Check whether GetEnumerator is public
5208 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
5211 if (IsOverride (mi))
5214 enumerator_found = true;
5216 if (!GetEnumeratorFilter (ec, mi))
5219 if (result != null) {
5220 if (TypeManager.IsGenericType (result.ReturnType)) {
5221 if (!TypeManager.IsGenericType (mi.ReturnType))
5224 MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
5225 Report.SymbolRelatedToPreviousError (t);
5226 Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
5227 "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
5228 TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
5232 // Always prefer generics enumerators
5233 if (!TypeManager.IsGenericType (mi.ReturnType)) {
5234 if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
5235 TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
5238 Report.SymbolRelatedToPreviousError (result);
5239 Report.SymbolRelatedToPreviousError (mi);
5240 Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
5241 TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
5246 tmp_move_next = move_next;
5247 tmp_get_cur = get_current;
5248 tmp_enumerator_type = enumerator_type;
5249 if (mi.DeclaringType == t)
5253 if (result != null) {
5254 move_next = tmp_move_next;
5255 get_current = tmp_get_cur;
5256 enumerator_type = tmp_enumerator_type;
5257 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
5258 get_enumerator = new MethodGroupExpr (mi, loc);
5260 if (t != expr.Type) {
5261 expr = Convert.ExplicitConversion (
5264 throw new InternalErrorException ();
5267 get_enumerator.InstanceExpression = expr;
5268 get_enumerator.IsBase = t != expr.Type;
5276 bool ProbeCollectionType (EmitContext ec, Type t)
5278 int errors = Report.Errors;
5279 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
5280 if (TryType (ec, tt))
5285 if (Report.Errors > errors)
5289 // Now try to find the method in the interfaces
5291 Type [] ifaces = TypeManager.GetInterfaces (t);
5292 foreach (Type i in ifaces){
5293 if (TryType (ec, i))
5300 public override bool Resolve (EmitContext ec)
5302 enumerator_type = TypeManager.ienumerator_type;
5303 is_disposable = true;
5305 if (!ProbeCollectionType (ec, expr.Type)) {
5306 Error_Enumerator ();
5310 enumerator = new TemporaryVariable (enumerator_type, loc);
5311 enumerator.Resolve (ec);
5313 init = new Invocation (get_enumerator, new ArrayList ());
5314 init = init.Resolve (ec);
5318 Expression move_next_expr;
5320 MemberInfo[] mi = new MemberInfo[] { move_next };
5321 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5322 mg.InstanceExpression = enumerator;
5324 move_next_expr = new Invocation (mg, new ArrayList ());
5327 get_current.InstanceExpression = enumerator;
5329 Statement block = new CollectionForeachStatement (
5330 var_type, variable, get_current, statement, loc);
5332 loop = new While (move_next_expr, block, loc);
5336 FlowBranchingException branching = null;
5338 branching = ec.StartFlowBranching (this);
5340 if (!loop.Resolve (ec))
5343 if (is_disposable) {
5344 ResolveFinally (branching);
5345 ec.EndFlowBranching ();
5347 emit_finally = true;
5352 protected override void DoEmit (EmitContext ec)
5354 ILGenerator ig = ec.ig;
5356 enumerator.Store (ec, init);
5359 // Protect the code in a try/finalize block, so that
5360 // if the beast implement IDisposable, we get rid of it
5362 if (is_disposable && emit_finally)
5363 ig.BeginExceptionBlock ();
5368 // Now the finally block
5370 if (is_disposable) {
5373 ig.EndExceptionBlock ();
5378 public override void EmitFinally (EmitContext ec)
5380 ILGenerator ig = ec.ig;
5382 if (enumerator_type.IsValueType) {
5383 MethodInfo mi = FetchMethodDispose (enumerator_type);
5385 enumerator.EmitLoadAddress (ec);
5386 ig.Emit (OpCodes.Call, mi);
5388 enumerator.Emit (ec);
5389 ig.Emit (OpCodes.Box, enumerator_type);
5390 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5393 Label call_dispose = ig.DefineLabel ();
5395 enumerator.Emit (ec);
5396 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5397 ig.Emit (OpCodes.Dup);
5398 ig.Emit (OpCodes.Brtrue_S, call_dispose);
5399 ig.Emit (OpCodes.Pop);
5401 Label end_finally = ig.DefineLabel ();
5402 ig.Emit (OpCodes.Br, end_finally);
5404 ig.MarkLabel (call_dispose);
5405 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5406 ig.MarkLabel (end_finally);
5411 protected class CollectionForeachStatement : Statement
5414 Expression variable, current, conv;
5415 Statement statement;
5418 public CollectionForeachStatement (Type type, Expression variable,
5419 Expression current, Statement statement,
5423 this.variable = variable;
5424 this.current = current;
5425 this.statement = statement;
5429 public override bool Resolve (EmitContext ec)
5431 current = current.Resolve (ec);
5432 if (current == null)
5435 conv = Convert.ExplicitConversion (ec, current, type, loc);
5439 assign = new Assign (variable, conv, loc);
5440 if (assign.Resolve (ec) == null)
5443 if (!statement.Resolve (ec))
5449 protected override void DoEmit (EmitContext ec)
5451 assign.EmitStatement (ec);
5452 statement.Emit (ec);
5456 protected override void CloneTo (CloneContext clonectx, Statement t)
5458 Foreach target = (Foreach) t;
5460 target.type = type.Clone (clonectx);
5461 target.variable = variable.Clone (clonectx);
5462 target.expr = expr.Clone (clonectx);
5463 target.statement = statement.Clone (clonectx);