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 InternalErrorException ("{0} does not implement Statement.CloneTo", 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;
147 /// Remaps block to cloned copy if one exists.
149 public Block RemapBlockCopy (Block from)
151 Block mapped_to = (Block)block_map[from];
152 if (mapped_to == null)
158 public void AddVariableMap (LocalInfo from, LocalInfo to)
160 if (variable_map == null)
161 variable_map = new Hashtable ();
163 if (variable_map.Contains (from))
165 variable_map [from] = to;
168 public LocalInfo LookupVariable (LocalInfo from)
170 LocalInfo result = (LocalInfo) variable_map [from];
173 throw new Exception ("LookupVariable: looking up a variable that has not been registered yet");
179 public sealed class EmptyStatement : Statement {
181 private EmptyStatement () {}
183 public static readonly EmptyStatement Value = new EmptyStatement ();
185 public override bool Resolve (EmitContext ec)
190 public override bool ResolveUnreachable (EmitContext ec, bool warn)
195 protected override void DoEmit (EmitContext ec)
200 public class If : Statement {
202 public Statement TrueStatement;
203 public Statement FalseStatement;
207 public If (Expression expr, Statement trueStatement, Location l)
210 TrueStatement = trueStatement;
214 public If (Expression expr,
215 Statement trueStatement,
216 Statement falseStatement,
220 TrueStatement = trueStatement;
221 FalseStatement = falseStatement;
225 public override bool Resolve (EmitContext ec)
229 Report.Debug (1, "START IF BLOCK", loc);
231 expr = Expression.ResolveBoolean (ec, expr, loc);
237 Assign ass = expr as Assign;
238 if (ass != null && ass.Source is Constant) {
239 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
243 // Dead code elimination
245 if (expr is BoolConstant){
246 bool take = ((BoolConstant) expr).Value;
249 if (!TrueStatement.Resolve (ec))
252 if ((FalseStatement != null) &&
253 !FalseStatement.ResolveUnreachable (ec, true))
255 FalseStatement = null;
257 if (!TrueStatement.ResolveUnreachable (ec, true))
259 TrueStatement = null;
261 if ((FalseStatement != null) &&
262 !FalseStatement.Resolve (ec))
269 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
271 ok &= TrueStatement.Resolve (ec);
273 is_true_ret = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
275 ec.CurrentBranching.CreateSibling ();
277 if (FalseStatement != null)
278 ok &= FalseStatement.Resolve (ec);
280 ec.EndFlowBranching ();
282 Report.Debug (1, "END IF BLOCK", loc);
287 protected override void DoEmit (EmitContext ec)
289 ILGenerator ig = ec.ig;
290 Label false_target = ig.DefineLabel ();
294 // If we're a boolean expression, Resolve() already
295 // eliminated dead code for us.
297 if (expr is BoolConstant){
298 bool take = ((BoolConstant) expr).Value;
301 TrueStatement.Emit (ec);
302 else if (FalseStatement != null)
303 FalseStatement.Emit (ec);
308 expr.EmitBranchable (ec, false_target, false);
310 TrueStatement.Emit (ec);
312 if (FalseStatement != null){
313 bool branch_emitted = false;
315 end = ig.DefineLabel ();
317 ig.Emit (OpCodes.Br, end);
318 branch_emitted = true;
321 ig.MarkLabel (false_target);
322 FalseStatement.Emit (ec);
327 ig.MarkLabel (false_target);
331 protected override void CloneTo (CloneContext clonectx, Statement t)
335 target.expr = expr.Clone (clonectx);
336 target.TrueStatement = TrueStatement.Clone (clonectx);
337 if (FalseStatement != null)
338 target.FalseStatement = FalseStatement.Clone (clonectx);
342 public class Do : Statement {
343 public Expression expr;
344 public Statement EmbeddedStatement;
347 public Do (Statement statement, Expression boolExpr, Location l)
350 EmbeddedStatement = statement;
354 public override bool Resolve (EmitContext ec)
358 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
360 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
362 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
363 if (!EmbeddedStatement.Resolve (ec))
365 ec.EndFlowBranching ();
367 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable && !was_unreachable)
368 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
370 expr = Expression.ResolveBoolean (ec, expr, loc);
373 else if (expr is BoolConstant){
374 bool res = ((BoolConstant) expr).Value;
380 ec.CurrentBranching.CurrentUsageVector.Goto ();
382 ec.EndFlowBranching ();
387 protected override void DoEmit (EmitContext ec)
389 ILGenerator ig = ec.ig;
390 Label loop = ig.DefineLabel ();
391 Label old_begin = ec.LoopBegin;
392 Label old_end = ec.LoopEnd;
394 ec.LoopBegin = ig.DefineLabel ();
395 ec.LoopEnd = ig.DefineLabel ();
398 EmbeddedStatement.Emit (ec);
399 ig.MarkLabel (ec.LoopBegin);
402 // Dead code elimination
404 if (expr is BoolConstant){
405 bool res = ((BoolConstant) expr).Value;
408 ec.ig.Emit (OpCodes.Br, loop);
410 expr.EmitBranchable (ec, loop, true);
412 ig.MarkLabel (ec.LoopEnd);
414 ec.LoopBegin = old_begin;
415 ec.LoopEnd = old_end;
418 protected override void CloneTo (CloneContext clonectx, Statement t)
422 target.EmbeddedStatement = EmbeddedStatement.Clone (clonectx);
423 target.expr = expr.Clone (clonectx);
427 public class While : Statement {
428 public Expression expr;
429 public Statement Statement;
430 bool infinite, empty;
432 public While (Expression boolExpr, Statement statement, Location l)
434 this.expr = boolExpr;
435 Statement = statement;
439 public override bool Resolve (EmitContext ec)
443 expr = Expression.ResolveBoolean (ec, expr, loc);
448 // Inform whether we are infinite or not
450 if (expr is BoolConstant){
451 BoolConstant bc = (BoolConstant) expr;
453 if (bc.Value == false){
454 if (!Statement.ResolveUnreachable (ec, true))
462 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
464 ec.CurrentBranching.CreateSibling ();
466 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
467 if (!Statement.Resolve (ec))
469 ec.EndFlowBranching ();
471 // There's no direct control flow from the end of the embedded statement to the end of the loop
472 ec.CurrentBranching.CurrentUsageVector.Goto ();
474 ec.EndFlowBranching ();
479 protected override void DoEmit (EmitContext ec)
484 ILGenerator ig = ec.ig;
485 Label old_begin = ec.LoopBegin;
486 Label old_end = ec.LoopEnd;
488 ec.LoopBegin = ig.DefineLabel ();
489 ec.LoopEnd = ig.DefineLabel ();
492 // Inform whether we are infinite or not
494 if (expr is BoolConstant){
495 ig.MarkLabel (ec.LoopBegin);
497 ig.Emit (OpCodes.Br, ec.LoopBegin);
500 // Inform that we are infinite (ie, `we return'), only
501 // if we do not `break' inside the code.
503 ig.MarkLabel (ec.LoopEnd);
505 Label while_loop = ig.DefineLabel ();
507 ig.Emit (OpCodes.Br, ec.LoopBegin);
508 ig.MarkLabel (while_loop);
512 ig.MarkLabel (ec.LoopBegin);
514 expr.EmitBranchable (ec, while_loop, true);
516 ig.MarkLabel (ec.LoopEnd);
519 ec.LoopBegin = old_begin;
520 ec.LoopEnd = old_end;
523 protected override void CloneTo (CloneContext clonectx, Statement t)
525 While target = (While) t;
527 target.expr = expr.Clone (clonectx);
528 target.Statement = Statement.Clone (clonectx);
532 public class For : Statement {
534 Statement InitStatement;
536 public Statement Statement;
537 bool infinite, empty;
539 public For (Statement initStatement,
545 InitStatement = initStatement;
547 Increment = increment;
548 Statement = statement;
552 public override bool Resolve (EmitContext ec)
556 if (InitStatement != null){
557 if (!InitStatement.Resolve (ec))
562 Test = Expression.ResolveBoolean (ec, Test, loc);
565 else if (Test is BoolConstant){
566 BoolConstant bc = (BoolConstant) Test;
568 if (bc.Value == false){
569 if (!Statement.ResolveUnreachable (ec, true))
571 if ((Increment != null) &&
572 !Increment.ResolveUnreachable (ec, false))
582 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
584 ec.CurrentBranching.CreateSibling ();
586 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
588 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
589 if (!Statement.Resolve (ec))
591 ec.EndFlowBranching ();
593 if (Increment != null){
594 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable) {
595 if (!Increment.ResolveUnreachable (ec, !was_unreachable))
598 if (!Increment.Resolve (ec))
603 // There's no direct control flow from the end of the embedded statement to the end of the loop
604 ec.CurrentBranching.CurrentUsageVector.Goto ();
606 ec.EndFlowBranching ();
611 protected override void DoEmit (EmitContext ec)
616 ILGenerator ig = ec.ig;
617 Label old_begin = ec.LoopBegin;
618 Label old_end = ec.LoopEnd;
619 Label loop = ig.DefineLabel ();
620 Label test = ig.DefineLabel ();
622 if (InitStatement != null && InitStatement != EmptyStatement.Value)
623 InitStatement.Emit (ec);
625 ec.LoopBegin = ig.DefineLabel ();
626 ec.LoopEnd = ig.DefineLabel ();
628 ig.Emit (OpCodes.Br, test);
632 ig.MarkLabel (ec.LoopBegin);
633 if (Increment != EmptyStatement.Value)
638 // If test is null, there is no test, and we are just
643 // The Resolve code already catches the case for
644 // Test == BoolConstant (false) so we know that
647 if (Test is BoolConstant)
648 ig.Emit (OpCodes.Br, loop);
650 Test.EmitBranchable (ec, loop, true);
653 ig.Emit (OpCodes.Br, loop);
654 ig.MarkLabel (ec.LoopEnd);
656 ec.LoopBegin = old_begin;
657 ec.LoopEnd = old_end;
660 protected override void CloneTo (CloneContext clonectx, Statement t)
662 For target = (For) t;
664 if (InitStatement != null)
665 target.InitStatement = InitStatement.Clone (clonectx);
667 target.Test = Test.Clone (clonectx);
668 if (Increment != null)
669 target.Increment = Increment.Clone (clonectx);
670 target.Statement = Statement.Clone (clonectx);
674 public class StatementExpression : Statement {
675 ExpressionStatement expr;
677 public StatementExpression (ExpressionStatement expr)
683 public override bool Resolve (EmitContext ec)
686 expr = expr.ResolveStatement (ec);
690 protected override void DoEmit (EmitContext ec)
692 expr.EmitStatement (ec);
695 public override string ToString ()
697 return "StatementExpression (" + expr + ")";
700 protected override void CloneTo (CloneContext clonectx, Statement t)
702 StatementExpression target = (StatementExpression) t;
704 target.expr = (ExpressionStatement) expr.Clone (clonectx);
709 /// Implements the return statement
711 public class Return : Statement {
715 public Return (Expression expr, Location l)
721 bool DoResolve (EmitContext ec)
724 if (ec.ReturnType == TypeManager.void_type)
727 Error (126, "An object of a type convertible to `{0}' is required " +
728 "for the return statement",
729 TypeManager.CSharpName (ec.ReturnType));
733 AnonymousContainer am = ec.CurrentAnonymousMethod;
734 if ((am != null) && am.IsIterator && ec.InIterator) {
735 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
736 "statement to return a value, or yield break to end the iteration");
739 if (am == null && ec.ReturnType == TypeManager.void_type) {
740 MemberCore mc = ec.ResolveContext as MemberCore;
741 Report.Error (127, loc, "`{0}': A return keyword must not be followed by any expression when method returns void",
742 mc.GetSignatureForError ());
745 Expr = Expr.Resolve (ec);
749 if (Expr.Type != ec.ReturnType) {
750 if (ec.InferReturnType) {
751 ec.ReturnType = Expr.Type;
753 Expr = Convert.ImplicitConversionRequired (
754 ec, Expr, ec.ReturnType, loc);
758 Report.Error (1662, loc,
759 "Cannot convert `{0}' to delegate type `D' because some of the return types in the block are not implicitly convertible to the delegate return type",
760 am.ContainerType, am.GetSignatureForError ());
770 public override bool Resolve (EmitContext ec)
775 unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
777 ec.NeedReturnLabel ();
778 ec.CurrentBranching.CurrentUsageVector.Goto ();
782 protected override void DoEmit (EmitContext ec)
788 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
792 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
794 ec.ig.Emit (OpCodes.Ret);
797 protected override void CloneTo (CloneContext clonectx, Statement t)
799 Return target = (Return) t;
801 target.Expr = Expr.Clone (clonectx);
805 public class Goto : Statement {
807 LabeledStatement label;
810 public override bool Resolve (EmitContext ec)
812 int errors = Report.Errors;
813 unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
814 ec.CurrentBranching.CurrentUsageVector.Goto ();
815 return errors == Report.Errors;
818 public Goto (string label, Location l)
824 public string Target {
825 get { return target; }
828 public void SetResolvedTarget (LabeledStatement label)
831 label.AddReference ();
834 protected override void DoEmit (EmitContext ec)
837 throw new InternalErrorException ("goto emitted before target resolved");
838 Label l = label.LabelTarget (ec);
839 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
843 public class LabeledStatement : Statement {
850 FlowBranching.UsageVector vectors;
852 public LabeledStatement (string name, Location l)
858 public Label LabelTarget (EmitContext ec)
863 label = ec.ig.DefineLabel ();
873 public bool IsDefined {
874 get { return defined; }
877 public bool HasBeenReferenced {
878 get { return referenced; }
881 public FlowBranching.UsageVector JumpOrigins {
882 get { return vectors; }
885 public void AddUsageVector (FlowBranching.UsageVector vector)
887 vector = vector.Clone ();
888 vector.Next = vectors;
892 public override bool Resolve (EmitContext ec)
894 // this flow-branching will be terminated when the surrounding block ends
895 ec.StartFlowBranching (this);
899 protected override void DoEmit (EmitContext ec)
901 if (ig != null && ig != ec.ig)
902 throw new InternalErrorException ("cannot happen");
904 ec.ig.MarkLabel (label);
907 public void AddReference ()
915 /// `goto default' statement
917 public class GotoDefault : Statement {
919 public GotoDefault (Location l)
924 public override bool Resolve (EmitContext ec)
926 ec.CurrentBranching.CurrentUsageVector.Goto ();
930 protected override void DoEmit (EmitContext ec)
932 if (ec.Switch == null){
933 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
937 if (!ec.Switch.GotDefault){
938 FlowBranchingBlock.Error_UnknownLabel (loc, "default");
941 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
946 /// `goto case' statement
948 public class GotoCase : Statement {
952 public GotoCase (Expression e, Location l)
958 public override bool Resolve (EmitContext ec)
960 if (ec.Switch == null){
961 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
965 expr = expr.Resolve (ec);
969 Constant c = expr as Constant;
971 Error (150, "A constant value is expected");
975 Type type = ec.Switch.SwitchType;
976 if (!Convert.ImplicitStandardConversionExists (c, type))
977 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
978 "convertible to type `{0}'", TypeManager.CSharpName (type));
981 object val = c.GetValue ();
982 if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
983 val = TypeManager.ChangeType (val, type, out fail);
986 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
987 c.GetSignatureForError (), TypeManager.CSharpName (type));
992 val = SwitchLabel.NullStringCase;
994 sl = (SwitchLabel) ec.Switch.Elements [val];
997 FlowBranchingBlock.Error_UnknownLabel (loc, "case " +
998 (c.GetValue () == null ? "null" : val.ToString ()));
1002 ec.CurrentBranching.CurrentUsageVector.Goto ();
1006 protected override void DoEmit (EmitContext ec)
1008 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
1011 protected override void CloneTo (CloneContext clonectx, Statement t)
1013 GotoCase target = (GotoCase) t;
1015 target.expr = expr.Clone (clonectx);
1016 target.sl = sl.Clone (clonectx);
1020 public class Throw : Statement {
1023 public Throw (Expression expr, Location l)
1029 public override bool Resolve (EmitContext ec)
1031 ec.CurrentBranching.CurrentUsageVector.Goto ();
1034 expr = expr.Resolve (ec);
1038 ExprClass eclass = expr.eclass;
1040 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1041 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1042 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
1048 if ((t != TypeManager.exception_type) &&
1049 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
1050 !(expr is NullLiteral)) {
1052 "The type caught or thrown must be derived " +
1053 "from System.Exception");
1060 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
1065 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1071 protected override void DoEmit (EmitContext ec)
1074 ec.ig.Emit (OpCodes.Rethrow);
1078 ec.ig.Emit (OpCodes.Throw);
1082 protected override void CloneTo (CloneContext clonectx, Statement t)
1084 Throw target = (Throw) t;
1086 target.expr = expr.Clone (clonectx);
1090 public class Break : Statement {
1092 public Break (Location l)
1097 bool unwind_protect;
1099 public override bool Resolve (EmitContext ec)
1101 int errors = Report.Errors;
1102 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1103 ec.CurrentBranching.CurrentUsageVector.Goto ();
1104 return errors == Report.Errors;
1107 protected override void DoEmit (EmitContext ec)
1109 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
1113 public class Continue : Statement {
1115 public Continue (Location l)
1120 bool unwind_protect;
1122 public override bool Resolve (EmitContext ec)
1124 int errors = Report.Errors;
1125 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1126 ec.CurrentBranching.CurrentUsageVector.Goto ();
1127 return errors == Report.Errors;
1130 protected override void DoEmit (EmitContext ec)
1132 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
1136 public abstract class Variable
1138 public abstract Type Type {
1142 public abstract bool HasInstance {
1146 public abstract bool NeedsTemporary {
1150 public abstract void EmitInstance (EmitContext ec);
1152 public abstract void Emit (EmitContext ec);
1154 public abstract void EmitAssign (EmitContext ec);
1156 public abstract void EmitAddressOf (EmitContext ec);
1159 public interface IKnownVariable {
1160 Block Block { get; }
1161 Location Location { get; }
1165 // The information about a user-perceived local variable
1167 public class LocalInfo : IKnownVariable {
1168 public Expression Type;
1170 public Type VariableType;
1171 public readonly string Name;
1172 public readonly Location Location;
1173 public readonly Block Block;
1175 public VariableInfo VariableInfo;
1178 public Variable Variable {
1190 CompilerGenerated = 64,
1194 public enum ReadOnlyContext: byte {
1201 ReadOnlyContext ro_context;
1202 LocalBuilder builder;
1204 public LocalInfo (Expression type, string name, Block block, Location l)
1212 public LocalInfo (DeclSpace ds, Block block, Location l)
1214 VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
1219 public void ResolveVariable (EmitContext ec)
1221 Block theblock = Block;
1222 if (theblock.ScopeInfo != null)
1223 var = theblock.ScopeInfo.GetCapturedVariable (this);
1228 // This is needed to compile on both .NET 1.x and .NET 2.x
1229 // the later introduced `DeclareLocal (Type t, bool pinned)'
1231 builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1233 builder = ec.ig.DeclareLocal (VariableType);
1235 var = new LocalVariable (this, builder);
1239 public void EmitSymbolInfo (EmitContext ec, string name)
1241 if (builder != null)
1242 ec.DefineLocalVariable (name, builder);
1245 public bool IsThisAssigned (EmitContext ec)
1247 if (VariableInfo == null)
1248 throw new Exception ();
1250 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1253 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, ec.loc);
1256 public bool IsAssigned (EmitContext ec)
1258 if (VariableInfo == null)
1259 throw new Exception ();
1261 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1264 public bool Resolve (EmitContext ec)
1266 if (VariableType == null) {
1267 TypeExpr texpr = Type.ResolveAsContextualType (ec, false);
1271 VariableType = texpr.Type;
1274 if (TypeManager.IsGenericParameter (VariableType))
1277 if (VariableType == TypeManager.void_type) {
1278 Expression.Error_VoidInvalidInTheContext (Location);
1282 if (VariableType.IsAbstract && VariableType.IsSealed) {
1283 FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
1287 if (VariableType.IsPointer && !ec.InUnsafe)
1288 Expression.UnsafeError (Location);
1293 public bool IsCaptured {
1294 get { return (flags & Flags.Captured) != 0; }
1295 set { flags |= Flags.Captured; }
1298 public bool IsConstant {
1299 get { return (flags & Flags.IsConstant) != 0; }
1300 set { flags |= Flags.IsConstant; }
1303 public bool AddressTaken {
1304 get { return (flags & Flags.AddressTaken) != 0; }
1305 set { flags |= Flags.AddressTaken; }
1308 public bool CompilerGenerated {
1309 get { return (flags & Flags.CompilerGenerated) != 0; }
1310 set { flags |= Flags.CompilerGenerated; }
1313 public override string ToString ()
1315 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1316 Name, Type, VariableInfo, Location);
1320 get { return (flags & Flags.Used) != 0; }
1321 set { flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used)); }
1324 public bool ReadOnly {
1325 get { return (flags & Flags.ReadOnly) != 0; }
1328 public void SetReadOnlyContext (ReadOnlyContext context)
1330 flags |= Flags.ReadOnly;
1331 ro_context = context;
1334 public string GetReadOnlyContext ()
1337 throw new InternalErrorException ("Variable is not readonly");
1339 switch (ro_context) {
1340 case ReadOnlyContext.Fixed:
1341 return "fixed variable";
1342 case ReadOnlyContext.Foreach:
1343 return "foreach iteration variable";
1344 case ReadOnlyContext.Using:
1345 return "using variable";
1347 throw new NotImplementedException ();
1351 // Whether the variable is pinned, if Pinned the variable has been
1352 // allocated in a pinned slot with DeclareLocal.
1354 public bool Pinned {
1355 get { return (flags & Flags.Pinned) != 0; }
1356 set { flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned); }
1359 public bool IsThis {
1360 get { return (flags & Flags.IsThis) != 0; }
1361 set { flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis); }
1364 Block IKnownVariable.Block {
1365 get { return Block; }
1368 Location IKnownVariable.Location {
1369 get { return Location; }
1372 protected class LocalVariable : Variable
1374 public readonly LocalInfo LocalInfo;
1375 LocalBuilder builder;
1377 public LocalVariable (LocalInfo local, LocalBuilder builder)
1379 this.LocalInfo = local;
1380 this.builder = builder;
1383 public override Type Type {
1384 get { return LocalInfo.VariableType; }
1387 public override bool HasInstance {
1388 get { return false; }
1391 public override bool NeedsTemporary {
1392 get { return false; }
1395 public override void EmitInstance (EmitContext ec)
1400 public override void Emit (EmitContext ec)
1402 ec.ig.Emit (OpCodes.Ldloc, builder);
1405 public override void EmitAssign (EmitContext ec)
1407 ec.ig.Emit (OpCodes.Stloc, builder);
1410 public override void EmitAddressOf (EmitContext ec)
1412 ec.ig.Emit (OpCodes.Ldloca, builder);
1416 public LocalInfo Clone (CloneContext clonectx)
1418 // Only this kind is created by the parser.
1419 return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
1424 /// Block represents a C# block.
1428 /// This class is used in a number of places: either to represent
1429 /// explicit blocks that the programmer places or implicit blocks.
1431 /// Implicit blocks are used as labels or to introduce variable
1434 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1435 /// they contain extra information that is not necessary on normal blocks.
1437 public class Block : Statement {
1438 public Block Parent;
1439 public readonly Location StartLocation;
1440 public Location EndLocation = Location.Null;
1442 public ExplicitBlock Explicit;
1443 public ToplevelBlock Toplevel;
1446 public enum Flags : byte {
1449 VariablesInitialized = 4,
1453 HasVarargs = 64, // Used in ToplevelBlock
1456 protected Flags flags;
1458 public bool Unchecked {
1459 get { return (flags & Flags.Unchecked) != 0; }
1460 set { flags |= Flags.Unchecked; }
1463 public bool Unsafe {
1464 get { return (flags & Flags.Unsafe) != 0; }
1465 set { flags |= Flags.Unsafe; }
1469 // The statements in this block
1471 protected ArrayList statements;
1472 protected int current_statement;
1476 // An array of Blocks. We keep track of children just
1477 // to generate the local variable declarations.
1479 // Statements and child statements are handled through the
1485 // Labels. (label, block) pairs.
1490 // Keeps track of (name, type) pairs
1492 IDictionary variables;
1495 // Keeps track of constants
1496 Hashtable constants;
1499 // Temporary variables.
1501 ArrayList temporary_variables;
1504 // If this is a switch section, the enclosing switch block.
1508 ExpressionStatement scope_init;
1510 ArrayList anonymous_children;
1512 protected static int id;
1516 int assignable_slots;
1517 protected ScopeInfo scope_info;
1518 bool unreachable_shown;
1521 public Block (Block parent)
1522 : this (parent, (Flags) 0, Location.Null, Location.Null)
1525 public Block (Block parent, Flags flags)
1526 : this (parent, flags, Location.Null, Location.Null)
1529 public Block (Block parent, Location start, Location end)
1530 : this (parent, (Flags) 0, start, end)
1533 public Block (Block parent, Flags flags, Location start, Location end)
1535 if (parent != null) {
1536 parent.AddChild (this);
1538 // the appropriate constructors will fixup these fields
1539 Toplevel = parent.Toplevel;
1540 Explicit = parent.Explicit;
1543 this.Parent = parent;
1545 this.StartLocation = start;
1546 this.EndLocation = end;
1549 statements = new ArrayList ();
1552 public Block CreateSwitchBlock (Location start)
1554 // FIXME: should this be implicit?
1555 Block new_block = new ExplicitBlock (this, start, start);
1556 new_block.switch_block = this;
1561 get { return this_id; }
1564 public IDictionary Variables {
1566 if (variables == null)
1567 variables = new ListDictionary ();
1572 void AddChild (Block b)
1574 if (children == null)
1575 children = new ArrayList ();
1580 public void SetEndLocation (Location loc)
1585 protected static void Error_158 (string name, Location loc)
1587 Report.Error (158, loc, "The label `{0}' shadows another label " +
1588 "by the same name in a contained scope", name);
1592 /// Adds a label to the current block.
1596 /// false if the name already exists in this block. true
1600 public bool AddLabel (LabeledStatement target)
1602 if (switch_block != null)
1603 return switch_block.AddLabel (target);
1605 string name = target.Name;
1608 while (cur != null) {
1609 LabeledStatement s = cur.DoLookupLabel (name);
1611 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
1612 Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1616 if (this == Explicit)
1622 while (cur != null) {
1623 if (cur.DoLookupLabel (name) != null) {
1624 Error_158 (name, target.loc);
1628 if (children != null) {
1629 foreach (Block b in children) {
1630 LabeledStatement s = b.DoLookupLabel (name);
1634 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
1635 Error_158 (name, target.loc);
1643 Toplevel.CheckError158 (name, target.loc);
1646 labels = new Hashtable ();
1648 labels.Add (name, target);
1652 public LabeledStatement LookupLabel (string name)
1654 LabeledStatement s = DoLookupLabel (name);
1658 if (children == null)
1661 foreach (Block child in children) {
1662 if (Explicit != child.Explicit)
1665 s = child.LookupLabel (name);
1673 LabeledStatement DoLookupLabel (string name)
1675 if (switch_block != null)
1676 return switch_block.LookupLabel (name);
1679 if (labels.Contains (name))
1680 return ((LabeledStatement) labels [name]);
1685 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1688 IKnownVariable kvi = b.Explicit.GetKnownVariable (name);
1689 while (kvi == null) {
1690 b = b.Explicit.Parent;
1693 kvi = b.Explicit.GetKnownVariable (name);
1699 // Is kvi.Block nested inside 'b'
1700 if (b.Explicit != kvi.Block.Explicit) {
1702 // If a variable by the same name it defined in a nested block of this
1703 // block, we violate the invariant meaning in a block.
1706 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1707 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1712 // It's ok if the definition is in a nested subblock of b, but not
1713 // nested inside this block -- a definition in a sibling block
1714 // should not affect us.
1720 // Block 'b' and kvi.Block are the same textual block.
1721 // However, different variables are extant.
1723 // Check if the variable is in scope in both blocks. We use
1724 // an indirect check that depends on AddVariable doing its
1725 // part in maintaining the invariant-meaning-in-block property.
1727 if (e is VariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1731 // Even though we detected the error when the name is used, we
1732 // treat it as if the variable declaration was in error.
1734 Report.SymbolRelatedToPreviousError (loc, name);
1735 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1739 public LocalInfo AddVariable (Expression type, string name, Location l)
1741 LocalInfo vi = GetLocalInfo (name);
1743 Report.SymbolRelatedToPreviousError (vi.Location, name);
1744 if (Explicit == vi.Block.Explicit)
1745 Report.Error (128, l,
1746 "A local variable named `{0}' is already defined in this scope", name);
1748 Error_AlreadyDeclared (l, name, "parent");
1752 ToplevelParameterInfo pi = Toplevel.GetParameterInfo (name);
1754 Report.SymbolRelatedToPreviousError (pi.Location, name);
1755 Error_AlreadyDeclared (loc, name,
1756 pi.Block == Toplevel ? "method argument" : "parent or current");
1759 IKnownVariable kvi = Explicit.GetKnownVariable (name);
1761 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1762 Error_AlreadyDeclared (l, name, "child");
1766 vi = new LocalInfo (type, name, this, l);
1767 Variables.Add (name, vi);
1768 Explicit.AddKnownVariable (name, vi);
1770 if ((flags & Flags.VariablesInitialized) != 0)
1771 throw new InternalErrorException ("block has already been resolved");
1776 protected static void Error_AlreadyDeclared (Location loc, string var, string reason)
1778 Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1779 "in this scope because it would give a different meaning " +
1780 "to `{0}', which is already used in a `{1}' scope " +
1781 "to denote something else", var, reason);
1784 public bool AddConstant (Expression type, string name, Expression value, Location l)
1786 if (AddVariable (type, name, l) == null)
1789 if (constants == null)
1790 constants = new Hashtable ();
1792 constants.Add (name, value);
1794 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1799 static int next_temp_id = 0;
1801 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1803 Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1805 if (temporary_variables == null)
1806 temporary_variables = new ArrayList ();
1808 int id = ++next_temp_id;
1809 string name = "$s_" + id.ToString ();
1811 LocalInfo li = new LocalInfo (te, name, this, loc);
1812 li.CompilerGenerated = true;
1813 temporary_variables.Add (li);
1817 public LocalInfo GetLocalInfo (string name)
1819 for (Block b = this; b != null; b = b.Parent) {
1820 if (b.variables != null) {
1821 LocalInfo ret = b.variables [name] as LocalInfo;
1829 public Expression GetVariableType (string name)
1831 LocalInfo vi = GetLocalInfo (name);
1832 return vi == null ? null : vi.Type;
1835 public Expression GetConstantExpression (string name)
1837 for (Block b = this; b != null; b = b.Parent) {
1838 if (b.constants != null) {
1839 Expression ret = b.constants [name] as Expression;
1847 public void AddStatement (Statement s)
1850 flags |= Flags.BlockUsed;
1853 public void InsertStatementAfterCurrent (Statement statement)
1855 statements.Insert (current_statement + 1, statement);
1856 flags |= Flags.BlockUsed;
1860 get { return (flags & Flags.BlockUsed) != 0; }
1865 flags |= Flags.BlockUsed;
1868 public bool HasRet {
1869 get { return (flags & Flags.HasRet) != 0; }
1872 public bool IsDestructor {
1873 get { return (flags & Flags.IsDestructor) != 0; }
1876 public void SetDestructor ()
1878 flags |= Flags.IsDestructor;
1881 public int AssignableSlots {
1883 if ((flags & Flags.VariablesInitialized) == 0)
1884 throw new Exception ("Variables have not been initialized yet");
1885 return assignable_slots;
1889 public ScopeInfo ScopeInfo {
1890 get { return scope_info; }
1893 public ScopeInfo CreateScopeInfo ()
1895 if (scope_info == null)
1896 scope_info = ScopeInfo.CreateScope (this);
1901 public ArrayList AnonymousChildren {
1902 get { return anonymous_children; }
1905 public void AddAnonymousChild (ToplevelBlock b)
1907 if (anonymous_children == null)
1908 anonymous_children = new ArrayList ();
1910 anonymous_children.Add (b);
1913 void DoResolveConstants (EmitContext ec)
1915 if (constants == null)
1918 if (variables == null)
1919 throw new InternalErrorException ("cannot happen");
1921 foreach (DictionaryEntry de in variables) {
1922 string name = (string) de.Key;
1923 LocalInfo vi = (LocalInfo) de.Value;
1924 Type variable_type = vi.VariableType;
1926 if (variable_type == null)
1929 Expression cv = (Expression) constants [name];
1933 // Don't let 'const int Foo = Foo;' succeed.
1934 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
1935 // which in turn causes the 'must be constant' error to be triggered.
1936 constants.Remove (name);
1938 if (!Const.IsConstantTypeValid (variable_type)) {
1939 Const.Error_InvalidConstantType (variable_type, loc);
1943 ec.CurrentBlock = this;
1945 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
1946 e = cv.Resolve (ec);
1951 Constant ce = e as Constant;
1953 Const.Error_ExpressionMustBeConstant (vi.Location, name);
1957 e = ce.ConvertImplicitly (variable_type);
1959 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue)
1960 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
1962 ce.Error_ValueCannotBeConverted (null, vi.Location, variable_type, false);
1966 constants.Add (name, e);
1967 vi.IsConstant = true;
1971 protected void ResolveMeta (EmitContext ec, int offset)
1973 Report.Debug (64, "BLOCK RESOLVE META", this, Parent);
1975 // If some parent block was unsafe, we remain unsafe even if this block
1976 // isn't explicitly marked as such.
1977 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
1978 flags |= Flags.VariablesInitialized;
1980 if (variables != null) {
1981 foreach (LocalInfo li in variables.Values) {
1982 if (!li.Resolve (ec))
1984 li.VariableInfo = new VariableInfo (li, offset);
1985 offset += li.VariableInfo.Length;
1988 assignable_slots = offset;
1990 DoResolveConstants (ec);
1992 if (children == null)
1994 foreach (Block b in children)
1995 b.ResolveMeta (ec, offset);
2000 // Emits the local variable declarations for a block
2002 public virtual void EmitMeta (EmitContext ec)
2004 Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
2005 if (ScopeInfo != null) {
2006 scope_init = ScopeInfo.GetScopeInitializer (ec);
2007 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
2011 if (variables != null){
2012 foreach (LocalInfo vi in variables.Values)
2013 vi.ResolveVariable (ec);
2016 if (temporary_variables != null) {
2017 foreach (LocalInfo vi in temporary_variables)
2018 vi.ResolveVariable (ec);
2021 if (children != null){
2022 foreach (Block b in children)
2027 void UsageWarning (FlowBranching.UsageVector vector)
2031 if ((variables != null) && (Report.WarningLevel >= 3)) {
2032 foreach (DictionaryEntry de in variables){
2033 LocalInfo vi = (LocalInfo) de.Value;
2038 name = (string) de.Key;
2040 // vi.VariableInfo can be null for 'catch' variables
2041 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2042 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2044 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2050 private void CheckPossibleMistakenEmptyStatement (Statement s)
2054 // Some statements are wrapped by a Block. Since
2055 // others' internal could be changed, here I treat
2056 // them as possibly wrapped by Block equally.
2057 Block b = s as Block;
2058 if (b != null && b.statements.Count == 1)
2059 s = (Statement) b.statements [0];
2062 body = ((Lock) s).Statement;
2064 body = ((For) s).Statement;
2065 else if (s is Foreach)
2066 body = ((Foreach) s).Statement;
2067 else if (s is While)
2068 body = ((While) s).Statement;
2069 else if (s is Using)
2070 body = ((Using) s).Statement;
2071 else if (s is Fixed)
2072 body = ((Fixed) s).Statement;
2076 if (body == null || body is EmptyStatement)
2077 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2080 public override bool Resolve (EmitContext ec)
2082 Block prev_block = ec.CurrentBlock;
2085 int errors = Report.Errors;
2087 ec.CurrentBlock = this;
2088 ec.StartFlowBranching (this);
2090 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2093 // This flag is used to notate nested statements as unreachable from the beginning of this block.
2094 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
2095 // from the beginning of the function. The outer Resolve() that detected the unreachability is
2096 // responsible for handling the situation.
2098 for (current_statement = 0; current_statement < statements.Count; current_statement++) {
2099 Statement s = (Statement) statements [current_statement];
2100 // Check possible empty statement (CS0642)
2101 if (Report.WarningLevel >= 3 &&
2102 current_statement + 1 < statements.Count &&
2103 statements [current_statement + 1] is Block)
2104 CheckPossibleMistakenEmptyStatement (s);
2107 // Warn if we detect unreachable code.
2110 if (s is EmptyStatement)
2114 ((Block) s).unreachable = true;
2116 if (!unreachable_shown && !(s is LabeledStatement)) {
2117 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2118 unreachable_shown = true;
2123 // Note that we're not using ResolveUnreachable() for unreachable
2124 // statements here. ResolveUnreachable() creates a temporary
2125 // flow branching and kills it afterwards. This leads to problems
2126 // if you have two unreachable statements where the first one
2127 // assigns a variable and the second one tries to access it.
2130 if (!s.Resolve (ec)) {
2131 if (ec.IsInProbingMode)
2135 statements [current_statement] = EmptyStatement.Value;
2139 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2140 statements [current_statement] = EmptyStatement.Value;
2142 num_statements = current_statement + 1;
2144 unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
2145 if (unreachable && s is LabeledStatement)
2146 throw new InternalErrorException ("should not happen");
2149 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2150 ec.CurrentBranching, statements.Count, num_statements);
2155 while (ec.CurrentBranching is FlowBranchingLabeled)
2156 ec.EndFlowBranching ();
2158 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2160 ec.CurrentBlock = prev_block;
2162 // If we're a non-static `struct' constructor which doesn't have an
2163 // initializer, then we must initialize all of the struct's fields.
2164 if (this == Toplevel && !Toplevel.IsThisAssigned (ec) && !vector.IsUnreachable)
2167 if ((labels != null) && (Report.WarningLevel >= 2)) {
2168 foreach (LabeledStatement label in labels.Values)
2169 if (!label.HasBeenReferenced)
2170 Report.Warning (164, 2, label.loc,
2171 "This label has not been referenced");
2174 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2176 if (vector.IsUnreachable)
2177 flags |= Flags.HasRet;
2179 if (ok && (errors == Report.Errors)) {
2180 UsageWarning (vector);
2186 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2188 unreachable_shown = true;
2192 Report.Warning (162, 2, loc, "Unreachable code detected");
2194 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2195 bool ok = Resolve (ec);
2196 ec.KillFlowBranching ();
2201 protected override void DoEmit (EmitContext ec)
2203 for (int ix = 0; ix < num_statements; ix++){
2204 Statement s = (Statement) statements [ix];
2209 public override void Emit (EmitContext ec)
2211 Block prev_block = ec.CurrentBlock;
2213 ec.CurrentBlock = this;
2215 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2216 bool is_lexical_block = this == Explicit && Parent != null;
2218 if (emit_debug_info) {
2219 if (is_lexical_block)
2222 ec.Mark (StartLocation, true);
2223 if (scope_init != null)
2224 scope_init.EmitStatement (ec);
2226 ec.Mark (EndLocation, true);
2228 if (emit_debug_info) {
2229 if (is_lexical_block)
2232 if (variables != null) {
2233 foreach (DictionaryEntry de in variables) {
2234 string name = (string) de.Key;
2235 LocalInfo vi = (LocalInfo) de.Value;
2237 vi.EmitSymbolInfo (ec, name);
2242 ec.CurrentBlock = prev_block;
2245 public override string ToString ()
2247 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2250 protected override void CloneTo (CloneContext clonectx, Statement t)
2252 Block target = (Block) t;
2254 clonectx.AddBlockMap (this, target);
2256 //target.Toplevel = (ToplevelBlock) clonectx.LookupBlock (Toplevel);
2257 target.Explicit = (ExplicitBlock) clonectx.LookupBlock (Explicit);
2259 target.Parent = clonectx.RemapBlockCopy (Parent);
2261 target.statements = new ArrayList (statements.Count);
2262 if (target.children != null){
2263 target.children = new ArrayList ();
2264 foreach (Block b in children){
2265 Block newblock = (Block) b.Clone (clonectx);
2267 target.children.Add (newblock);
2272 foreach (Statement s in statements)
2273 target.statements.Add (s.Clone (clonectx));
2275 if (variables != null){
2276 target.variables = new Hashtable ();
2278 foreach (DictionaryEntry de in variables){
2279 LocalInfo newlocal = ((LocalInfo) de.Value).Clone (clonectx);
2280 target.variables [de.Key] = newlocal;
2281 clonectx.AddVariableMap ((LocalInfo) de.Value, newlocal);
2286 // TODO: labels, switch_block, constants (?), anonymous_children
2291 public class ExplicitBlock : Block {
2292 public ExplicitBlock (Block parent, Location start, Location end)
2293 : this (parent, (Flags) 0, start, end)
2297 public ExplicitBlock (Block parent, Flags flags, Location start, Location end)
2298 : base (parent, flags, start, end)
2300 this.Explicit = this;
2303 Hashtable known_variables;
2306 // Marks a variable with name @name as being used in this or a child block.
2307 // If a variable name has been used in a child block, it's illegal to
2308 // declare a variable with the same name in the current block.
2310 internal void AddKnownVariable (string name, IKnownVariable info)
2312 if (known_variables == null)
2313 known_variables = new Hashtable ();
2315 known_variables [name] = info;
2318 Parent.Explicit.AddKnownVariable (name, info);
2321 internal IKnownVariable GetKnownVariable (string name)
2323 return known_variables == null ? null : (IKnownVariable) known_variables [name];
2326 protected override void CloneTo (CloneContext clonectx, Statement t)
2328 ExplicitBlock target = (ExplicitBlock) t;
2329 target.known_variables = null;
2330 base.CloneTo (clonectx, t);
2334 public class ToplevelParameterInfo : IKnownVariable {
2335 public readonly ToplevelBlock Block;
2336 public readonly int Index;
2337 public VariableInfo VariableInfo;
2339 Block IKnownVariable.Block {
2340 get { return Block; }
2342 public Parameter Parameter {
2343 get { return Block.Parameters [Index]; }
2345 public Location Location {
2346 get { return Parameter.Location; }
2349 public ToplevelParameterInfo (ToplevelBlock block, int idx)
2357 // A toplevel block contains extra information, the split is done
2358 // only to separate information that would otherwise bloat the more
2359 // lightweight Block.
2361 // In particular, this was introduced when the support for Anonymous
2362 // Methods was implemented.
2364 public class ToplevelBlock : ExplicitBlock {
2365 GenericMethod generic;
2366 FlowBranchingToplevel top_level_branching;
2367 AnonymousContainer anonymous_container;
2368 RootScopeInfo root_scope;
2369 Parameters parameters;
2370 ToplevelParameterInfo[] parameter_info;
2372 public bool HasVarargs {
2373 get { return (flags & Flags.HasVarargs) != 0; }
2374 set { flags |= Flags.HasVarargs; }
2377 public bool IsIterator {
2378 get { return (flags & Flags.IsIterator) != 0; }
2382 // The parameters for the block.
2384 public Parameters Parameters {
2385 get { return parameters; }
2388 public bool CompleteContexts (EmitContext ec)
2390 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this, Parent, root_scope);
2392 if (root_scope != null)
2393 root_scope.LinkScopes ();
2395 if (Parent == null && root_scope != null) {
2396 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this, root_scope);
2398 if (root_scope.DefineType () == null)
2400 if (!root_scope.ResolveType ())
2402 if (!root_scope.ResolveMembers ())
2404 if (!root_scope.DefineMembers ())
2411 public GenericMethod GenericMethod {
2412 get { return generic; }
2415 public ToplevelBlock Container {
2416 get { return Parent == null ? null : Parent.Toplevel; }
2419 public AnonymousContainer AnonymousContainer {
2420 get { return anonymous_container; }
2421 set { anonymous_container = value; }
2424 public ToplevelBlock (Block parent, Parameters parameters, Location start) :
2425 this (parent, (Flags) 0, parameters, start)
2429 public ToplevelBlock (Block parent, Parameters parameters, GenericMethod generic, Location start) :
2430 this (parent, parameters, start)
2432 this.generic = generic;
2435 public ToplevelBlock (Parameters parameters, Location start) :
2436 this (null, (Flags) 0, parameters, start)
2440 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2441 this (null, flags, parameters, start)
2445 // We use 'Parent' to hook up to the containing block, but don't want to register the current block as a child.
2446 // So, we use a two-stage setup -- first pass a null parent to the base constructor, and then override 'Parent'.
2447 public ToplevelBlock (Block parent, Flags flags, Parameters parameters, Location start) :
2448 base (null, flags, start, Location.Null)
2450 this.Toplevel = this;
2452 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2453 this.Parent = parent;
2455 parent.AddAnonymousChild (this);
2457 if (this.parameters.Count != 0)
2458 ProcessParameters ();
2461 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2465 protected override void CloneTo (CloneContext clonectx, Statement t)
2467 ToplevelBlock target = (ToplevelBlock) t;
2468 base.CloneTo (clonectx, t);
2470 if (parameters.Count != 0)
2471 target.parameter_info = new ToplevelParameterInfo [parameters.Count];
2472 for (int i = 0; i < parameters.Count; ++i)
2473 target.parameter_info [i] = new ToplevelParameterInfo (target, i);
2476 public bool CheckError158 (string name, Location loc)
2478 if (AnonymousChildren != null) {
2479 foreach (ToplevelBlock child in AnonymousChildren) {
2480 if (!child.CheckError158 (name, loc))
2485 for (ToplevelBlock c = Container; c != null; c = c.Container) {
2486 if (!c.DoCheckError158 (name, loc))
2493 void ProcessParameters ()
2495 int n = parameters.Count;
2496 parameter_info = new ToplevelParameterInfo [n];
2497 for (int i = 0; i < n; ++i) {
2498 parameter_info [i] = new ToplevelParameterInfo (this, i);
2500 string name = parameters [i].Name;
2502 LocalInfo vi = GetLocalInfo (name);
2504 Report.SymbolRelatedToPreviousError (vi.Location, name);
2505 Error_AlreadyDeclared (loc, name, "parent or current");
2509 ToplevelParameterInfo pi = Parent == null ? null : Parent.Toplevel.GetParameterInfo (name);
2511 Report.SymbolRelatedToPreviousError (pi.Location, name);
2512 Error_AlreadyDeclared (loc, name, "parent or current");
2516 AddKnownVariable (name, parameter_info [i]);
2519 // mark this block as "used" so that we create local declarations in a sub-block
2520 // FIXME: This appears to uncover a lot of bugs
2524 bool DoCheckError158 (string name, Location loc)
2526 LabeledStatement s = LookupLabel (name);
2528 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
2529 Error_158 (name, loc);
2536 public RootScopeInfo CreateRootScope (TypeContainer host)
2538 if (root_scope != null)
2541 if (Container == null)
2542 root_scope = new RootScopeInfo (
2543 this, host, generic, StartLocation);
2545 if (scope_info != null)
2546 throw new InternalErrorException ();
2548 scope_info = root_scope;
2552 public void CreateIteratorHost (RootScopeInfo root)
2554 Report.Debug (64, "CREATE ITERATOR HOST", this, root, Parent, root_scope);
2556 if (Parent != null || root_scope != null)
2557 throw new InternalErrorException ();
2559 scope_info = root_scope = root;
2562 public RootScopeInfo RootScope {
2564 if (root_scope != null)
2566 else if (Container != null)
2567 return Container.RootScope;
2573 public FlowBranchingToplevel TopLevelBranching {
2574 get { return top_level_branching; }
2578 // This is used if anonymous methods are used inside an iterator
2579 // (see 2test-22.cs for an example).
2581 // The AnonymousMethod is created while parsing - at a time when we don't
2582 // know yet that we're inside an iterator, so it's `Container' is initially
2583 // null. Later on, when resolving the iterator, we need to move the
2584 // anonymous method into that iterator.
2586 public void ReParent (ToplevelBlock new_parent)
2588 if ((flags & Flags.VariablesInitialized) != 0)
2589 throw new InternalErrorException ("block has already been resolved");
2591 Parent = new_parent;
2595 // Returns a `ParameterReference' for the given name, or null if there
2596 // is no such parameter
2598 public ParameterReference GetParameterReference (string name, Location loc)
2600 ToplevelParameterInfo p = GetParameterInfo (name);
2601 return p == null ? null : new ParameterReference (this, p, loc);
2604 public ToplevelParameterInfo GetParameterInfo (string name)
2607 for (ToplevelBlock t = this; t != null; t = t.Container) {
2608 Parameter par = t.Parameters.GetParameterByName (name, out idx);
2610 return t.parameter_info [idx];
2616 // Whether the parameter named `name' is local to this block,
2617 // or false, if the parameter belongs to an encompassing block.
2619 public bool IsLocalParameter (string name)
2621 return Parameters.GetParameterByName (name) != null;
2625 // Whether the `name' is a parameter reference
2627 public bool IsParameterReference (string name)
2629 for (ToplevelBlock t = this; t != null; t = t.Container) {
2630 if (t.IsLocalParameter (name))
2636 LocalInfo this_variable = null;
2639 // Returns the "this" instance variable of this block.
2640 // See AddThisVariable() for more information.
2642 public LocalInfo ThisVariable {
2643 get { return this_variable; }
2648 // This is used by non-static `struct' constructors which do not have an
2649 // initializer - in this case, the constructor must initialize all of the
2650 // struct's fields. To do this, we add a "this" variable and use the flow
2651 // analysis code to ensure that it's been fully initialized before control
2652 // leaves the constructor.
2654 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2656 if (this_variable == null) {
2657 this_variable = new LocalInfo (ds, this, l);
2658 this_variable.Used = true;
2659 this_variable.IsThis = true;
2661 Variables.Add ("this", this_variable);
2664 return this_variable;
2667 public bool IsThisAssigned (EmitContext ec)
2669 return this_variable == null || this_variable.IsThisAssigned (ec);
2672 public bool ResolveMeta (EmitContext ec, Parameters ip)
2674 int errors = Report.Errors;
2675 int orig_count = parameters.Count;
2677 if (top_level_branching != null)
2683 // Assert: orig_count != parameter.Count => orig_count == 0
2684 if (orig_count != 0 && orig_count != parameters.Count)
2685 throw new InternalErrorException ("parameter information mismatch");
2687 int offset = Parent == null ? 0 : Parent.AssignableSlots;
2689 for (int i = 0; i < orig_count; ++i) {
2690 Parameter.Modifier mod = parameters.ParameterModifier (i);
2692 if ((mod & Parameter.Modifier.OUT) != Parameter.Modifier.OUT)
2695 VariableInfo vi = new VariableInfo (ip, i, offset);
2696 parameter_info [i].VariableInfo = vi;
2697 offset += vi.Length;
2700 ResolveMeta (ec, offset);
2702 top_level_branching = ec.StartFlowBranching (this);
2704 return Report.Errors == errors;
2708 // Check whether all `out' parameters have been assigned.
2710 public void CheckOutParameters (FlowBranching.UsageVector vector, Location loc)
2712 if (vector.IsUnreachable)
2715 int n = parameter_info == null ? 0 : parameter_info.Length;
2717 for (int i = 0; i < n; i++) {
2718 VariableInfo var = parameter_info [i].VariableInfo;
2723 if (vector.IsAssigned (var, false))
2726 Report.Error (177, loc, "The out parameter `{0}' must be assigned to before control leaves the current method",
2731 public override void EmitMeta (EmitContext ec)
2734 parameters.ResolveVariable (this);
2737 public void MakeIterator (Iterator iterator)
2739 flags |= Flags.IsIterator;
2741 Block block = new ExplicitBlock (this, StartLocation, EndLocation);
2742 foreach (Statement stmt in statements)
2743 block.AddStatement (stmt);
2744 statements.Clear ();
2745 statements.Add (new MoveNextStatement (iterator, block));
2748 protected class MoveNextStatement : Statement {
2752 public MoveNextStatement (Iterator iterator, Block block)
2754 this.iterator = iterator;
2756 this.loc = iterator.Location;
2759 public override bool Resolve (EmitContext ec)
2761 return block.Resolve (ec);
2764 protected override void DoEmit (EmitContext ec)
2766 iterator.EmitMoveNext (ec, block);
2770 public override string ToString ()
2772 return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2773 root_scope, anonymous_container != null ?
2774 anonymous_container.Scope : null);
2778 public class SwitchLabel {
2785 Label il_label_code;
2786 bool il_label_code_set;
2788 public static readonly object NullStringCase = new object ();
2791 // if expr == null, then it is the default case.
2793 public SwitchLabel (Expression expr, Location l)
2799 public Expression Label {
2805 public object Converted {
2811 public Label GetILLabel (EmitContext ec)
2814 il_label = ec.ig.DefineLabel ();
2815 il_label_set = true;
2820 public Label GetILLabelCode (EmitContext ec)
2822 if (!il_label_code_set){
2823 il_label_code = ec.ig.DefineLabel ();
2824 il_label_code_set = true;
2826 return il_label_code;
2830 // Resolves the expression, reduces it to a literal if possible
2831 // and then converts it to the requested type.
2833 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2835 Expression e = label.Resolve (ec);
2840 Constant c = e as Constant;
2842 Report.Error (150, loc, "A constant value is expected");
2846 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2847 converted = NullStringCase;
2851 if (allow_nullable && c.GetValue () == null) {
2852 converted = NullStringCase;
2856 c = c.ImplicitConversionRequired (required_type, loc);
2860 converted = c.GetValue ();
2864 public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
2867 if (converted == null)
2869 else if (converted == NullStringCase)
2871 else if (TypeManager.IsEnumType (switchType))
2872 label = TypeManager.CSharpEnumValue (switchType, converted);
2874 label = converted.ToString ();
2876 Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
2877 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2880 public SwitchLabel Clone (CloneContext clonectx)
2882 return new SwitchLabel (label.Clone (clonectx), loc);
2886 public class SwitchSection {
2887 // An array of SwitchLabels.
2888 public readonly ArrayList Labels;
2889 public readonly Block Block;
2891 public SwitchSection (ArrayList labels, Block block)
2897 public SwitchSection Clone (CloneContext clonectx)
2899 ArrayList cloned_labels = new ArrayList ();
2901 foreach (SwitchLabel sl in cloned_labels)
2902 cloned_labels.Add (sl.Clone (clonectx));
2904 return new SwitchSection (cloned_labels, clonectx.LookupBlock (Block));
2908 public class Switch : Statement {
2909 public ArrayList Sections;
2910 public Expression Expr;
2913 /// Maps constants whose type type SwitchType to their SwitchLabels.
2915 public IDictionary Elements;
2918 /// The governing switch type
2920 public Type SwitchType;
2925 Label default_target;
2927 Expression new_expr;
2929 SwitchSection constant_section;
2930 SwitchSection default_section;
2934 // Nullable Types support for GMCS.
2936 Nullable.Unwrap unwrap;
2938 protected bool HaveUnwrap {
2939 get { return unwrap != null; }
2942 protected bool HaveUnwrap {
2943 get { return false; }
2948 // The types allowed to be implicitly cast from
2949 // on the governing type
2951 static Type [] allowed_types;
2953 public Switch (Expression e, ArrayList sects, Location l)
2960 public bool GotDefault {
2962 return default_section != null;
2966 public Label DefaultTarget {
2968 return default_target;
2973 // Determines the governing type for a switch. The returned
2974 // expression might be the expression from the switch, or an
2975 // expression that includes any potential conversions to the
2976 // integral types or to string.
2978 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2980 Type t = TypeManager.DropGenericTypeArguments (expr.Type);
2982 if (t == TypeManager.byte_type ||
2983 t == TypeManager.sbyte_type ||
2984 t == TypeManager.ushort_type ||
2985 t == TypeManager.short_type ||
2986 t == TypeManager.uint32_type ||
2987 t == TypeManager.int32_type ||
2988 t == TypeManager.uint64_type ||
2989 t == TypeManager.int64_type ||
2990 t == TypeManager.char_type ||
2991 t == TypeManager.string_type ||
2992 t == TypeManager.bool_type ||
2993 t.IsSubclassOf (TypeManager.enum_type))
2996 if (allowed_types == null){
2997 allowed_types = new Type [] {
2998 TypeManager.sbyte_type,
2999 TypeManager.byte_type,
3000 TypeManager.short_type,
3001 TypeManager.ushort_type,
3002 TypeManager.int32_type,
3003 TypeManager.uint32_type,
3004 TypeManager.int64_type,
3005 TypeManager.uint64_type,
3006 TypeManager.char_type,
3007 TypeManager.string_type,
3008 TypeManager.bool_type
3013 // Try to find a *user* defined implicit conversion.
3015 // If there is no implicit conversion, or if there are multiple
3016 // conversions, we have to report an error
3018 Expression converted = null;
3019 foreach (Type tt in allowed_types){
3022 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
3027 // Ignore over-worked ImplicitUserConversions that do
3028 // an implicit conversion in addition to the user conversion.
3030 if (!(e is UserCast))
3033 if (converted != null){
3034 Report.ExtraInformation (
3036 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
3037 TypeManager.CSharpName (expr.Type)));
3047 // Performs the basic sanity checks on the switch statement
3048 // (looks for duplicate keys and non-constant expressions).
3050 // It also returns a hashtable with the keys that we will later
3051 // use to compute the switch tables
3053 bool CheckSwitch (EmitContext ec)
3056 Elements = Sections.Count > 10 ?
3057 (IDictionary)new Hashtable () :
3058 (IDictionary)new ListDictionary ();
3060 foreach (SwitchSection ss in Sections){
3061 foreach (SwitchLabel sl in ss.Labels){
3062 if (sl.Label == null){
3063 if (default_section != null){
3064 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
3067 default_section = ss;
3071 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
3076 object key = sl.Converted;
3078 Elements.Add (key, sl);
3079 } catch (ArgumentException) {
3080 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
3088 void EmitObjectInteger (ILGenerator ig, object k)
3091 IntConstant.EmitInt (ig, (int) k);
3092 else if (k is Constant) {
3093 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3096 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3099 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3101 IntConstant.EmitInt (ig, (int) (long) k);
3102 ig.Emit (OpCodes.Conv_I8);
3105 LongConstant.EmitLong (ig, (long) k);
3107 else if (k is ulong)
3109 ulong ul = (ulong) k;
3112 IntConstant.EmitInt (ig, unchecked ((int) ul));
3113 ig.Emit (OpCodes.Conv_U8);
3117 LongConstant.EmitLong (ig, unchecked ((long) ul));
3121 IntConstant.EmitInt (ig, (int) ((char) k));
3122 else if (k is sbyte)
3123 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3125 IntConstant.EmitInt (ig, (int) ((byte) k));
3126 else if (k is short)
3127 IntConstant.EmitInt (ig, (int) ((short) k));
3128 else if (k is ushort)
3129 IntConstant.EmitInt (ig, (int) ((ushort) k));
3131 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3133 throw new Exception ("Unhandled case");
3136 // structure used to hold blocks of keys while calculating table switch
3137 class KeyBlock : IComparable
3139 public KeyBlock (long _nFirst)
3141 nFirst = nLast = _nFirst;
3145 public ArrayList rgKeys = null;
3146 // how many items are in the bucket
3147 public int Size = 1;
3150 get { return (int) (nLast - nFirst + 1); }
3152 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3154 return kbLast.nLast - kbFirst.nFirst + 1;
3156 public int CompareTo (object obj)
3158 KeyBlock kb = (KeyBlock) obj;
3159 int nLength = Length;
3160 int nLengthOther = kb.Length;
3161 if (nLengthOther == nLength)
3162 return (int) (kb.nFirst - nFirst);
3163 return nLength - nLengthOther;
3168 /// This method emits code for a lookup-based switch statement (non-string)
3169 /// Basically it groups the cases into blocks that are at least half full,
3170 /// and then spits out individual lookup opcodes for each block.
3171 /// It emits the longest blocks first, and short blocks are just
3172 /// handled with direct compares.
3174 /// <param name="ec"></param>
3175 /// <param name="val"></param>
3176 /// <returns></returns>
3177 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3179 int cElements = Elements.Count;
3180 object [] rgKeys = new object [cElements];
3181 Elements.Keys.CopyTo (rgKeys, 0);
3182 Array.Sort (rgKeys);
3184 // initialize the block list with one element per key
3185 ArrayList rgKeyBlocks = new ArrayList ();
3186 foreach (object key in rgKeys)
3187 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3190 // iteratively merge the blocks while they are at least half full
3191 // there's probably a really cool way to do this with a tree...
3192 while (rgKeyBlocks.Count > 1)
3194 ArrayList rgKeyBlocksNew = new ArrayList ();
3195 kbCurr = (KeyBlock) rgKeyBlocks [0];
3196 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3198 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3199 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3202 kbCurr.nLast = kb.nLast;
3203 kbCurr.Size += kb.Size;
3207 // start a new block
3208 rgKeyBlocksNew.Add (kbCurr);
3212 rgKeyBlocksNew.Add (kbCurr);
3213 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3215 rgKeyBlocks = rgKeyBlocksNew;
3218 // initialize the key lists
3219 foreach (KeyBlock kb in rgKeyBlocks)
3220 kb.rgKeys = new ArrayList ();
3222 // fill the key lists
3224 if (rgKeyBlocks.Count > 0) {
3225 kbCurr = (KeyBlock) rgKeyBlocks [0];
3226 foreach (object key in rgKeys)
3228 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3229 System.Convert.ToInt64 (key) > kbCurr.nLast;
3231 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3232 kbCurr.rgKeys.Add (key);
3236 // sort the blocks so we can tackle the largest ones first
3237 rgKeyBlocks.Sort ();
3239 // okay now we can start...
3240 ILGenerator ig = ec.ig;
3241 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3242 Label lblDefault = ig.DefineLabel ();
3244 Type typeKeys = null;
3245 if (rgKeys.Length > 0)
3246 typeKeys = rgKeys [0].GetType (); // used for conversions
3250 if (TypeManager.IsEnumType (SwitchType))
3251 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3253 compare_type = SwitchType;
3255 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3257 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3258 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3261 foreach (object key in kb.rgKeys)
3263 ig.Emit (OpCodes.Ldloc, val);
3264 EmitObjectInteger (ig, key);
3265 SwitchLabel sl = (SwitchLabel) Elements [key];
3266 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3271 // TODO: if all the keys in the block are the same and there are
3272 // no gaps/defaults then just use a range-check.
3273 if (compare_type == TypeManager.int64_type ||
3274 compare_type == TypeManager.uint64_type)
3276 // TODO: optimize constant/I4 cases
3278 // check block range (could be > 2^31)
3279 ig.Emit (OpCodes.Ldloc, val);
3280 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3281 ig.Emit (OpCodes.Blt, lblDefault);
3282 ig.Emit (OpCodes.Ldloc, val);
3283 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3284 ig.Emit (OpCodes.Bgt, lblDefault);
3287 ig.Emit (OpCodes.Ldloc, val);
3290 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3291 ig.Emit (OpCodes.Sub);
3293 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3298 ig.Emit (OpCodes.Ldloc, val);
3299 int nFirst = (int) kb.nFirst;
3302 IntConstant.EmitInt (ig, nFirst);
3303 ig.Emit (OpCodes.Sub);
3305 else if (nFirst < 0)
3307 IntConstant.EmitInt (ig, -nFirst);
3308 ig.Emit (OpCodes.Add);
3312 // first, build the list of labels for the switch
3314 int cJumps = kb.Length;
3315 Label [] rgLabels = new Label [cJumps];
3316 for (int iJump = 0; iJump < cJumps; iJump++)
3318 object key = kb.rgKeys [iKey];
3319 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3321 SwitchLabel sl = (SwitchLabel) Elements [key];
3322 rgLabels [iJump] = sl.GetILLabel (ec);
3326 rgLabels [iJump] = lblDefault;
3328 // emit the switch opcode
3329 ig.Emit (OpCodes.Switch, rgLabels);
3332 // mark the default for this block
3334 ig.MarkLabel (lblDefault);
3337 // TODO: find the default case and emit it here,
3338 // to prevent having to do the following jump.
3339 // make sure to mark other labels in the default section
3341 // the last default just goes to the end
3342 ig.Emit (OpCodes.Br, lblDefault);
3344 // now emit the code for the sections
3345 bool fFoundDefault = false;
3346 bool fFoundNull = false;
3347 foreach (SwitchSection ss in Sections)
3349 foreach (SwitchLabel sl in ss.Labels)
3350 if (sl.Converted == SwitchLabel.NullStringCase)
3354 foreach (SwitchSection ss in Sections)
3356 foreach (SwitchLabel sl in ss.Labels)
3358 ig.MarkLabel (sl.GetILLabel (ec));
3359 ig.MarkLabel (sl.GetILLabelCode (ec));
3360 if (sl.Converted == SwitchLabel.NullStringCase)
3361 ig.MarkLabel (null_target);
3362 else if (sl.Label == null) {
3363 ig.MarkLabel (lblDefault);
3364 fFoundDefault = true;
3366 ig.MarkLabel (null_target);
3372 if (!fFoundDefault) {
3373 ig.MarkLabel (lblDefault);
3374 if (HaveUnwrap && !fFoundNull) {
3375 ig.MarkLabel (null_target);
3379 ig.MarkLabel (lblEnd);
3382 // This simple emit switch works, but does not take advantage of the
3384 // TODO: remove non-string logic from here
3385 // TODO: binary search strings?
3387 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3389 ILGenerator ig = ec.ig;
3390 Label end_of_switch = ig.DefineLabel ();
3391 Label next_test = ig.DefineLabel ();
3392 bool first_test = true;
3393 bool pending_goto_end = false;
3394 bool null_marked = false;
3396 int section_count = Sections.Count;
3398 // TODO: implement switch optimization for string by using Hashtable
3399 //if (SwitchType == TypeManager.string_type && section_count > 7)
3400 // Console.WriteLine ("Switch optimization possible " + loc);
3402 ig.Emit (OpCodes.Ldloc, val);
3404 if (Elements.Contains (SwitchLabel.NullStringCase)){
3405 ig.Emit (OpCodes.Brfalse, null_target);
3407 ig.Emit (OpCodes.Brfalse, default_target);
3409 ig.Emit (OpCodes.Ldloc, val);
3410 ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
3411 ig.Emit (OpCodes.Stloc, val);
3413 for (int section = 0; section < section_count; section++){
3414 SwitchSection ss = (SwitchSection) Sections [section];
3416 if (ss == default_section)
3419 Label sec_begin = ig.DefineLabel ();
3421 ig.Emit (OpCodes.Nop);
3423 if (pending_goto_end)
3424 ig.Emit (OpCodes.Br, end_of_switch);
3426 int label_count = ss.Labels.Count;
3428 for (int label = 0; label < label_count; label++){
3429 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3430 ig.MarkLabel (sl.GetILLabel (ec));
3433 ig.MarkLabel (next_test);
3434 next_test = ig.DefineLabel ();
3437 // If we are the default target
3439 if (sl.Label != null){
3440 object lit = sl.Converted;
3442 if (lit == SwitchLabel.NullStringCase){
3444 if (label + 1 == label_count)
3445 ig.Emit (OpCodes.Br, next_test);
3449 ig.Emit (OpCodes.Ldloc, val);
3450 ig.Emit (OpCodes.Ldstr, (string)lit);
3451 if (label_count == 1)
3452 ig.Emit (OpCodes.Bne_Un, next_test);
3454 if (label+1 == label_count)
3455 ig.Emit (OpCodes.Bne_Un, next_test);
3457 ig.Emit (OpCodes.Beq, sec_begin);
3462 ig.MarkLabel (null_target);
3465 ig.MarkLabel (sec_begin);
3466 foreach (SwitchLabel sl in ss.Labels)
3467 ig.MarkLabel (sl.GetILLabelCode (ec));
3470 pending_goto_end = !ss.Block.HasRet;
3473 ig.MarkLabel (next_test);
3474 ig.MarkLabel (default_target);
3476 ig.MarkLabel (null_target);
3477 if (default_section != null)
3478 default_section.Block.Emit (ec);
3479 ig.MarkLabel (end_of_switch);
3482 SwitchSection FindSection (SwitchLabel label)
3484 foreach (SwitchSection ss in Sections){
3485 foreach (SwitchLabel sl in ss.Labels){
3494 public override bool Resolve (EmitContext ec)
3496 Expr = Expr.Resolve (ec);
3500 new_expr = SwitchGoverningType (ec, Expr);
3503 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3504 unwrap = Nullable.Unwrap.Create (Expr, ec);
3508 new_expr = SwitchGoverningType (ec, unwrap);
3512 if (new_expr == null){
3513 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3518 SwitchType = new_expr.Type;
3520 if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
3521 Report.FeatureIsNotISO1 (loc, "switch expression of boolean type");
3525 if (!CheckSwitch (ec))
3529 Elements.Remove (SwitchLabel.NullStringCase);
3531 Switch old_switch = ec.Switch;
3533 ec.Switch.SwitchType = SwitchType;
3535 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3536 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3538 is_constant = new_expr is Constant;
3540 object key = ((Constant) new_expr).GetValue ();
3541 SwitchLabel label = (SwitchLabel) Elements [key];
3543 constant_section = FindSection (label);
3544 if (constant_section == null)
3545 constant_section = default_section;
3549 foreach (SwitchSection ss in Sections){
3551 ec.CurrentBranching.CreateSibling (
3552 null, FlowBranching.SiblingType.SwitchSection);
3556 if (is_constant && (ss != constant_section)) {
3557 // If we're a constant switch, we're only emitting
3558 // one single section - mark all the others as
3560 ec.CurrentBranching.CurrentUsageVector.Goto ();
3561 if (!ss.Block.ResolveUnreachable (ec, true))
3564 if (!ss.Block.Resolve (ec))
3569 if (default_section == null)
3570 ec.CurrentBranching.CreateSibling (
3571 null, FlowBranching.SiblingType.SwitchSection);
3573 ec.EndFlowBranching ();
3574 ec.Switch = old_switch;
3576 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
3581 protected override void DoEmit (EmitContext ec)
3583 ILGenerator ig = ec.ig;
3585 default_target = ig.DefineLabel ();
3586 null_target = ig.DefineLabel ();
3588 // Store variable for comparission purposes
3591 value = ig.DeclareLocal (SwitchType);
3593 unwrap.EmitCheck (ec);
3594 ig.Emit (OpCodes.Brfalse, null_target);
3596 ig.Emit (OpCodes.Stloc, value);
3598 } else if (!is_constant) {
3599 value = ig.DeclareLocal (SwitchType);
3601 ig.Emit (OpCodes.Stloc, value);
3606 // Setup the codegen context
3608 Label old_end = ec.LoopEnd;
3609 Switch old_switch = ec.Switch;
3611 ec.LoopEnd = ig.DefineLabel ();
3616 if (constant_section != null)
3617 constant_section.Block.Emit (ec);
3618 } else if (SwitchType == TypeManager.string_type)
3619 SimpleSwitchEmit (ec, value);
3621 TableSwitchEmit (ec, value);
3623 // Restore context state.
3624 ig.MarkLabel (ec.LoopEnd);
3627 // Restore the previous context
3629 ec.LoopEnd = old_end;
3630 ec.Switch = old_switch;
3633 protected override void CloneTo (CloneContext clonectx, Statement t)
3635 Switch target = (Switch) t;
3637 target.Expr = Expr.Clone (clonectx);
3638 target.Sections = new ArrayList ();
3639 foreach (SwitchSection ss in Sections){
3640 target.Sections.Add (ss.Clone (clonectx));
3645 public abstract class ExceptionStatement : Statement
3647 public abstract void EmitFinally (EmitContext ec);
3649 protected bool emit_finally = true;
3650 ArrayList parent_vectors;
3652 protected void DoEmitFinally (EmitContext ec)
3655 ec.ig.BeginFinallyBlock ();
3656 else if (ec.InIterator)
3657 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3661 protected void ResolveFinally (FlowBranchingException branching)
3663 emit_finally = branching.EmitFinally;
3665 branching.Parent.StealFinallyClauses (ref parent_vectors);
3669 public class Lock : ExceptionStatement {
3671 public Statement Statement;
3672 TemporaryVariable temp;
3674 public Lock (Expression expr, Statement stmt, Location l)
3681 public override bool Resolve (EmitContext ec)
3683 expr = expr.Resolve (ec);
3687 if (expr.Type.IsValueType){
3688 Report.Error (185, loc,
3689 "`{0}' is not a reference type as required by the lock statement",
3690 TypeManager.CSharpName (expr.Type));
3694 FlowBranchingException branching = ec.StartFlowBranching (this);
3695 bool ok = Statement.Resolve (ec);
3697 ResolveFinally (branching);
3699 ec.EndFlowBranching ();
3701 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
3702 // So, ensure there's some IL code after the finally block.
3703 ec.NeedReturnLabel ();
3705 // Avoid creating libraries that reference the internal
3708 if (t == TypeManager.null_type)
3709 t = TypeManager.object_type;
3711 temp = new TemporaryVariable (t, loc);
3717 protected override void DoEmit (EmitContext ec)
3719 ILGenerator ig = ec.ig;
3721 temp.Store (ec, expr);
3723 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3727 ig.BeginExceptionBlock ();
3728 Statement.Emit (ec);
3733 ig.EndExceptionBlock ();
3736 public override void EmitFinally (EmitContext ec)
3739 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3742 protected override void CloneTo (CloneContext clonectx, Statement t)
3744 Lock target = (Lock) t;
3746 target.expr = expr.Clone (clonectx);
3747 target.Statement = Statement.Clone (clonectx);
3751 public class Unchecked : Statement {
3754 public Unchecked (Block b)
3760 public override bool Resolve (EmitContext ec)
3762 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3763 return Block.Resolve (ec);
3766 protected override void DoEmit (EmitContext ec)
3768 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3772 protected override void CloneTo (CloneContext clonectx, Statement t)
3774 Unchecked target = (Unchecked) t;
3776 target.Block = clonectx.LookupBlock (Block);
3780 public class Checked : Statement {
3783 public Checked (Block b)
3786 b.Unchecked = false;
3789 public override bool Resolve (EmitContext ec)
3791 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3792 return Block.Resolve (ec);
3795 protected override void DoEmit (EmitContext ec)
3797 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3801 protected override void CloneTo (CloneContext clonectx, Statement t)
3803 Checked target = (Checked) t;
3805 target.Block = clonectx.LookupBlock (Block);
3809 public class Unsafe : Statement {
3812 public Unsafe (Block b)
3815 Block.Unsafe = true;
3818 public override bool Resolve (EmitContext ec)
3820 using (ec.With (EmitContext.Flags.InUnsafe, true))
3821 return Block.Resolve (ec);
3824 protected override void DoEmit (EmitContext ec)
3826 using (ec.With (EmitContext.Flags.InUnsafe, true))
3829 protected override void CloneTo (CloneContext clonectx, Statement t)
3831 Unsafe target = (Unsafe) t;
3833 target.Block = clonectx.LookupBlock (Block);
3840 public class Fixed : Statement {
3842 ArrayList declarators;
3843 Statement statement;
3848 abstract class Emitter
3850 protected LocalInfo vi;
3851 protected Expression converted;
3853 protected Emitter (Expression expr, LocalInfo li)
3859 public abstract void Emit (EmitContext ec);
3860 public abstract void EmitExit (EmitContext ec);
3863 class ExpressionEmitter : Emitter {
3864 public ExpressionEmitter (Expression converted, LocalInfo li) :
3865 base (converted, li)
3869 public override void Emit (EmitContext ec) {
3871 // Store pointer in pinned location
3873 converted.Emit (ec);
3874 vi.Variable.EmitAssign (ec);
3877 public override void EmitExit (EmitContext ec)
3879 ec.ig.Emit (OpCodes.Ldc_I4_0);
3880 ec.ig.Emit (OpCodes.Conv_U);
3881 vi.Variable.EmitAssign (ec);
3885 class StringEmitter : Emitter {
3886 LocalBuilder pinned_string;
3889 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3895 public override void Emit (EmitContext ec)
3897 ILGenerator ig = ec.ig;
3898 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3900 converted.Emit (ec);
3901 ig.Emit (OpCodes.Stloc, pinned_string);
3903 Expression sptr = new StringPtr (pinned_string, loc);
3904 converted = Convert.ImplicitConversionRequired (
3905 ec, sptr, vi.VariableType, loc);
3907 if (converted == null)
3910 converted.Emit (ec);
3911 vi.Variable.EmitAssign (ec);
3914 public override void EmitExit (EmitContext ec)
3916 ec.ig.Emit (OpCodes.Ldnull);
3917 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3921 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3924 declarators = decls;
3929 public Statement Statement {
3930 get { return statement; }
3933 public override bool Resolve (EmitContext ec)
3936 Expression.UnsafeError (loc);
3940 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3944 expr_type = texpr.Type;
3946 data = new Emitter [declarators.Count];
3948 if (!expr_type.IsPointer){
3949 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3954 foreach (Pair p in declarators){
3955 LocalInfo vi = (LocalInfo) p.First;
3956 Expression e = (Expression) p.Second;
3958 vi.VariableInfo.SetAssigned (ec);
3959 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3962 // The rules for the possible declarators are pretty wise,
3963 // but the production on the grammar is more concise.
3965 // So we have to enforce these rules here.
3967 // We do not resolve before doing the case 1 test,
3968 // because the grammar is explicit in that the token &
3969 // is present, so we need to test for this particular case.
3973 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
3978 // Case 1: & object.
3980 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3981 Expression child = ((Unary) e).Expr;
3983 if (child is ParameterReference || child is LocalVariableReference){
3986 "No need to use fixed statement for parameters or " +
3987 "local variable declarations (address is already " +
3992 ec.InFixedInitializer = true;
3994 ec.InFixedInitializer = false;
3998 child = ((Unary) e).Expr;
4000 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4003 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
4004 e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
4008 data [i] = new ExpressionEmitter (e, vi);
4014 ec.InFixedInitializer = true;
4016 ec.InFixedInitializer = false;
4023 if (e.Type.IsArray){
4024 Type array_type = TypeManager.GetElementType (e.Type);
4027 // Provided that array_type is unmanaged,
4029 if (!TypeManager.VerifyUnManaged (array_type, loc))
4033 // and T* is implicitly convertible to the
4034 // pointer type given in the fixed statement.
4036 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
4038 Expression converted = Convert.ImplicitConversionRequired (
4039 ec, array_ptr, vi.VariableType, loc);
4040 if (converted == null)
4043 data [i] = new ExpressionEmitter (converted, vi);
4052 if (e.Type == TypeManager.string_type){
4053 data [i] = new StringEmitter (e, vi, loc);
4058 // Case 4: fixed buffer
4059 FixedBufferPtr fixed_buffer_ptr = e as FixedBufferPtr;
4060 if (fixed_buffer_ptr != null) {
4061 data [i++] = new ExpressionEmitter (fixed_buffer_ptr, vi);
4066 // For other cases, flag a `this is already fixed expression'
4068 if (e is LocalVariableReference || e is ParameterReference ||
4069 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
4071 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
4075 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
4079 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
4080 bool ok = statement.Resolve (ec);
4081 bool flow_unreachable = ec.EndFlowBranching ();
4082 has_ret = flow_unreachable;
4087 protected override void DoEmit (EmitContext ec)
4089 for (int i = 0; i < data.Length; i++) {
4093 statement.Emit (ec);
4099 // Clear the pinned variable
4101 for (int i = 0; i < data.Length; i++) {
4102 data [i].EmitExit (ec);
4106 protected override void CloneTo (CloneContext clonectx, Statement t)
4108 Fixed target = (Fixed) t;
4110 target.type = type.Clone (clonectx);
4111 target.declarators = new ArrayList ();
4112 foreach (LocalInfo var in declarators)
4113 target.declarators.Add (clonectx.LookupVariable (var));
4114 target.statement = statement.Clone (clonectx);
4118 public class Catch : Statement {
4119 public readonly string Name;
4121 public Block VarBlock;
4123 Expression type_expr;
4126 public Catch (Expression type, string name, Block block, Block var_block, Location l)
4131 VarBlock = var_block;
4135 public Type CatchType {
4141 public bool IsGeneral {
4143 return type_expr == null;
4147 protected override void DoEmit(EmitContext ec)
4149 ILGenerator ig = ec.ig;
4151 if (CatchType != null)
4152 ig.BeginCatchBlock (CatchType);
4154 ig.BeginCatchBlock (TypeManager.object_type);
4156 if (VarBlock != null)
4160 LocalInfo vi = Block.GetLocalInfo (Name);
4162 throw new Exception ("Variable does not exist in this block");
4164 if (vi.Variable.NeedsTemporary) {
4165 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
4166 ig.Emit (OpCodes.Stloc, e);
4168 vi.Variable.EmitInstance (ec);
4169 ig.Emit (OpCodes.Ldloc, e);
4170 vi.Variable.EmitAssign (ec);
4172 vi.Variable.EmitAssign (ec);
4174 ig.Emit (OpCodes.Pop);
4179 public override bool Resolve (EmitContext ec)
4181 using (ec.With (EmitContext.Flags.InCatch, true)) {
4182 if (type_expr != null) {
4183 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
4189 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4190 Error (155, "The type caught or thrown must be derived from System.Exception");
4196 if (!Block.Resolve (ec))
4199 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4200 // emit the "unused variable" warnings.
4201 if (VarBlock != null)
4202 return VarBlock.Resolve (ec);
4208 protected override void CloneTo (CloneContext clonectx, Statement t)
4210 Catch target = (Catch) t;
4212 target.type_expr = type_expr.Clone (clonectx);
4213 target.Block = clonectx.LookupBlock (Block);
4214 target.VarBlock = clonectx.LookupBlock (VarBlock);
4218 public class Try : ExceptionStatement {
4219 public Block Fini, Block;
4220 public ArrayList Specific;
4221 public Catch General;
4223 bool need_exc_block;
4226 // specific, general and fini might all be null.
4228 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4230 if (specific == null && general == null){
4231 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4235 this.Specific = specific;
4236 this.General = general;
4241 public override bool Resolve (EmitContext ec)
4245 FlowBranchingException branching = ec.StartFlowBranching (this);
4247 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4249 if (!Block.Resolve (ec))
4252 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4254 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4256 Type[] prevCatches = new Type [Specific.Count];
4258 foreach (Catch c in Specific){
4259 ec.CurrentBranching.CreateSibling (
4260 c.Block, FlowBranching.SiblingType.Catch);
4262 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4264 if (c.Name != null) {
4265 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4267 throw new Exception ();
4269 vi.VariableInfo = null;
4272 if (!c.Resolve (ec))
4275 Type resolvedType = c.CatchType;
4276 for (int ii = 0; ii < last_index; ++ii) {
4277 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4278 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4283 prevCatches [last_index++] = resolvedType;
4284 need_exc_block = true;
4287 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4289 if (General != null){
4290 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4291 foreach (Catch c in Specific){
4292 if (c.CatchType == TypeManager.exception_type) {
4293 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'");
4298 ec.CurrentBranching.CreateSibling (
4299 General.Block, FlowBranching.SiblingType.Catch);
4301 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4303 if (!General.Resolve (ec))
4306 need_exc_block = true;
4309 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4313 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4315 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4316 using (ec.With (EmitContext.Flags.InFinally, true)) {
4317 if (!Fini.Resolve (ec))
4322 need_exc_block = true;
4325 if (ec.InIterator) {
4326 ResolveFinally (branching);
4327 need_exc_block |= emit_finally;
4329 emit_finally = Fini != null;
4331 ec.EndFlowBranching ();
4333 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4334 // So, ensure there's some IL code after the finally block.
4335 ec.NeedReturnLabel ();
4337 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4339 Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
4344 protected override void DoEmit (EmitContext ec)
4346 ILGenerator ig = ec.ig;
4349 ig.BeginExceptionBlock ();
4352 foreach (Catch c in Specific)
4355 if (General != null)
4360 ig.EndExceptionBlock ();
4363 public override void EmitFinally (EmitContext ec)
4369 public bool HasCatch
4372 return General != null || Specific.Count > 0;
4376 protected override void CloneTo (CloneContext clonectx, Statement t)
4378 Try target = (Try) t;
4380 target.Block = clonectx.LookupBlock (Block);
4382 target.Fini = clonectx.LookupBlock (Fini);
4383 if (General != null)
4384 target.General = (Catch) General.Clone (clonectx);
4385 if (Specific != null){
4386 target.Specific = new ArrayList ();
4387 foreach (Catch c in Specific)
4388 target.Specific.Add (c.Clone (clonectx));
4393 public class Using : ExceptionStatement {
4394 object expression_or_block;
4395 public Statement Statement;
4399 Expression [] resolved_vars;
4400 Expression [] converted_vars;
4401 Expression [] assign;
4402 TemporaryVariable local_copy;
4404 public Using (object expression_or_block, Statement stmt, Location l)
4406 this.expression_or_block = expression_or_block;
4412 // Resolves for the case of using using a local variable declaration.
4414 bool ResolveLocalVariableDecls (EmitContext ec)
4416 resolved_vars = new Expression[var_list.Count];
4417 assign = new Expression [var_list.Count];
4418 converted_vars = new Expression[var_list.Count];
4420 for (int i = 0; i < assign.Length; ++i) {
4421 DictionaryEntry e = (DictionaryEntry) var_list [i];
4422 Expression var = (Expression) e.Key;
4423 Expression new_expr = (Expression) e.Value;
4425 Expression a = new Assign (var, new_expr, loc);
4430 resolved_vars [i] = var;
4433 if (TypeManager.ImplementsInterface (a.Type, TypeManager.idisposable_type)) {
4434 converted_vars [i] = var;
4438 a = Convert.ImplicitConversion (ec, a, TypeManager.idisposable_type, var.Location);
4440 Error_IsNotConvertibleToIDisposable (var);
4444 converted_vars [i] = a;
4450 static void Error_IsNotConvertibleToIDisposable (Expression expr)
4452 Report.SymbolRelatedToPreviousError (expr.Type);
4453 Report.Error (1674, expr.Location, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4454 expr.GetSignatureForError ());
4457 bool ResolveExpression (EmitContext ec)
4459 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4460 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4461 Error_IsNotConvertibleToIDisposable (expr);
4466 local_copy = new TemporaryVariable (expr_type, loc);
4467 local_copy.Resolve (ec);
4473 // Emits the code for the case of using using a local variable declaration.
4475 void EmitLocalVariableDecls (EmitContext ec)
4477 ILGenerator ig = ec.ig;
4480 for (i = 0; i < assign.Length; i++) {
4481 ExpressionStatement es = assign [i] as ExpressionStatement;
4484 es.EmitStatement (ec);
4486 assign [i].Emit (ec);
4487 ig.Emit (OpCodes.Pop);
4491 ig.BeginExceptionBlock ();
4493 Statement.Emit (ec);
4495 var_list.Reverse ();
4500 void EmitLocalVariableDeclFinally (EmitContext ec)
4502 ILGenerator ig = ec.ig;
4504 int i = assign.Length;
4505 for (int ii = 0; ii < var_list.Count; ++ii){
4506 Expression var = resolved_vars [--i];
4507 Label skip = ig.DefineLabel ();
4510 ig.BeginFinallyBlock ();
4512 if (!var.Type.IsValueType) {
4514 ig.Emit (OpCodes.Brfalse, skip);
4515 converted_vars [i].Emit (ec);
4516 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4518 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4520 if (!(ml is MethodGroupExpr)) {
4522 ig.Emit (OpCodes.Box, var.Type);
4523 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4525 MethodInfo mi = null;
4527 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4528 if (TypeManager.GetParameterData (mk).Count == 0) {
4535 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4539 IMemoryLocation mloc = (IMemoryLocation) var;
4541 mloc.AddressOf (ec, AddressOp.Load);
4542 ig.Emit (OpCodes.Call, mi);
4546 ig.MarkLabel (skip);
4549 ig.EndExceptionBlock ();
4551 ig.BeginFinallyBlock ();
4556 void EmitExpression (EmitContext ec)
4559 // Make a copy of the expression and operate on that.
4561 ILGenerator ig = ec.ig;
4563 local_copy.Store (ec, expr);
4566 ig.BeginExceptionBlock ();
4568 Statement.Emit (ec);
4572 ig.EndExceptionBlock ();
4575 void EmitExpressionFinally (EmitContext ec)
4577 ILGenerator ig = ec.ig;
4578 if (!expr_type.IsValueType) {
4579 Label skip = ig.DefineLabel ();
4580 local_copy.Emit (ec);
4581 ig.Emit (OpCodes.Brfalse, skip);
4582 local_copy.Emit (ec);
4583 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4584 ig.MarkLabel (skip);
4586 Expression ml = Expression.MemberLookup (
4587 ec.ContainerType, TypeManager.idisposable_type, expr_type,
4588 "Dispose", Location.Null);
4590 if (!(ml is MethodGroupExpr)) {
4591 local_copy.Emit (ec);
4592 ig.Emit (OpCodes.Box, expr_type);
4593 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4595 MethodInfo mi = null;
4597 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4598 if (TypeManager.GetParameterData (mk).Count == 0) {
4605 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4609 local_copy.AddressOf (ec, AddressOp.Load);
4610 ig.Emit (OpCodes.Call, mi);
4615 public override bool Resolve (EmitContext ec)
4617 if (expression_or_block is DictionaryEntry){
4618 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4619 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4621 if (!ResolveLocalVariableDecls (ec))
4624 } else if (expression_or_block is Expression){
4625 expr = (Expression) expression_or_block;
4627 expr = expr.Resolve (ec);
4631 expr_type = expr.Type;
4633 if (!ResolveExpression (ec))
4637 FlowBranchingException branching = ec.StartFlowBranching (this);
4639 bool ok = Statement.Resolve (ec);
4641 ResolveFinally (branching);
4643 ec.EndFlowBranching ();
4645 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4646 // So, ensure there's some IL code after the finally block.
4647 ec.NeedReturnLabel ();
4652 protected override void DoEmit (EmitContext ec)
4654 if (expression_or_block is DictionaryEntry)
4655 EmitLocalVariableDecls (ec);
4656 else if (expression_or_block is Expression)
4657 EmitExpression (ec);
4660 public override void EmitFinally (EmitContext ec)
4662 if (expression_or_block is DictionaryEntry)
4663 EmitLocalVariableDeclFinally (ec);
4664 else if (expression_or_block is Expression)
4665 EmitExpressionFinally (ec);
4668 protected override void CloneTo (CloneContext clonectx, Statement t)
4670 Using target = (Using) t;
4672 if (expression_or_block is Expression)
4673 target.expression_or_block = ((Expression) expression_or_block).Clone (clonectx);
4675 target.expression_or_block = ((Statement) expression_or_block).Clone (clonectx);
4677 target.Statement = Statement.Clone (clonectx);
4682 /// Implementation of the foreach C# statement
4684 public class Foreach : Statement {
4686 Expression variable;
4688 Statement statement;
4690 CollectionForeach collection;
4692 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4693 Statement stmt, Location l)
4696 this.variable = var;
4702 public Statement Statement {
4703 get { return statement; }
4706 public override bool Resolve (EmitContext ec)
4708 expr = expr.Resolve (ec);
4712 if (expr.Type == TypeManager.null_type) {
4713 Report.Error (186, loc, "Use of null is not valid in this context");
4717 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4718 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4719 expr.ExprClassName);
4724 // We need an instance variable. Not sure this is the best
4725 // way of doing this.
4727 // FIXME: When we implement propertyaccess, will those turn
4728 // out to return values in ExprClass? I think they should.
4730 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4731 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4732 collection.Error_Enumerator ();
4736 if (expr.Type.IsArray) {
4737 array = new ArrayForeach (type, variable, expr, statement, loc);
4738 return array.Resolve (ec);
4741 collection = new CollectionForeach (type, variable, expr, statement, loc);
4742 return collection.Resolve (ec);
4745 protected override void DoEmit (EmitContext ec)
4747 ILGenerator ig = ec.ig;
4749 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4750 ec.LoopBegin = ig.DefineLabel ();
4751 ec.LoopEnd = ig.DefineLabel ();
4753 if (collection != null)
4754 collection.Emit (ec);
4758 ec.LoopBegin = old_begin;
4759 ec.LoopEnd = old_end;
4762 protected class ArrayCounter : TemporaryVariable
4764 public ArrayCounter (Location loc)
4765 : base (TypeManager.int32_type, loc)
4768 public void Initialize (EmitContext ec)
4771 ec.ig.Emit (OpCodes.Ldc_I4_0);
4775 public void Increment (EmitContext ec)
4779 ec.ig.Emit (OpCodes.Ldc_I4_1);
4780 ec.ig.Emit (OpCodes.Add);
4785 protected class ArrayForeach : Statement
4787 Expression variable, expr, conv;
4788 Statement statement;
4790 Expression var_type;
4791 TemporaryVariable[] lengths;
4792 ArrayCounter[] counter;
4795 TemporaryVariable copy;
4798 public ArrayForeach (Expression var_type, Expression var,
4799 Expression expr, Statement stmt, Location l)
4801 this.var_type = var_type;
4802 this.variable = var;
4808 public override bool Resolve (EmitContext ec)
4810 array_type = expr.Type;
4811 rank = array_type.GetArrayRank ();
4813 copy = new TemporaryVariable (array_type, loc);
4816 counter = new ArrayCounter [rank];
4817 lengths = new TemporaryVariable [rank];
4819 ArrayList list = new ArrayList ();
4820 for (int i = 0; i < rank; i++) {
4821 counter [i] = new ArrayCounter (loc);
4822 counter [i].Resolve (ec);
4824 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4825 lengths [i].Resolve (ec);
4827 list.Add (counter [i]);
4830 access = new ElementAccess (copy, list).Resolve (ec);
4834 VarExpr ve = var_type as VarExpr;
4836 // Infer implicitly typed local variable from foreach array type
4837 var_type = new TypeExpression (access.Type, ve.Location);
4840 var_type = var_type.ResolveAsTypeTerminal (ec, false);
4841 if (var_type == null)
4844 conv = Convert.ExplicitConversion (ec, access, var_type.Type, loc);
4850 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4851 ec.CurrentBranching.CreateSibling ();
4853 variable = variable.ResolveLValue (ec, conv, loc);
4854 if (variable == null)
4857 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4858 if (!statement.Resolve (ec))
4860 ec.EndFlowBranching ();
4862 // There's no direct control flow from the end of the embedded statement to the end of the loop
4863 ec.CurrentBranching.CurrentUsageVector.Goto ();
4865 ec.EndFlowBranching ();
4870 protected override void DoEmit (EmitContext ec)
4872 ILGenerator ig = ec.ig;
4874 copy.Store (ec, expr);
4876 Label[] test = new Label [rank];
4877 Label[] loop = new Label [rank];
4879 for (int i = 0; i < rank; i++) {
4880 test [i] = ig.DefineLabel ();
4881 loop [i] = ig.DefineLabel ();
4883 lengths [i].EmitThis (ec);
4884 ((ArrayAccess) access).EmitGetLength (ec, i);
4885 lengths [i].EmitStore (ec);
4888 for (int i = 0; i < rank; i++) {
4889 counter [i].Initialize (ec);
4891 ig.Emit (OpCodes.Br, test [i]);
4892 ig.MarkLabel (loop [i]);
4895 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
4897 statement.Emit (ec);
4899 ig.MarkLabel (ec.LoopBegin);
4901 for (int i = rank - 1; i >= 0; i--){
4902 counter [i].Increment (ec);
4904 ig.MarkLabel (test [i]);
4905 counter [i].Emit (ec);
4906 lengths [i].Emit (ec);
4907 ig.Emit (OpCodes.Blt, loop [i]);
4910 ig.MarkLabel (ec.LoopEnd);
4914 protected class CollectionForeach : ExceptionStatement
4916 Expression variable, expr;
4917 Statement statement;
4919 TemporaryVariable enumerator;
4923 MethodGroupExpr get_enumerator;
4924 PropertyExpr get_current;
4925 MethodInfo move_next;
4926 Expression var_type;
4927 Type enumerator_type;
4929 bool enumerator_found;
4931 public CollectionForeach (Expression var_type, Expression var,
4932 Expression expr, Statement stmt, Location l)
4934 this.var_type = var_type;
4935 this.variable = var;
4941 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
4943 Type return_type = mi.ReturnType;
4945 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4947 // Apply the same optimization as MS: skip the GetEnumerator
4948 // returning an IEnumerator, and use the one returning a
4949 // CharEnumerator instead. This allows us to avoid the
4950 // try-finally block and the boxing.
4955 // Ok, we can access it, now make sure that we can do something
4956 // with this `GetEnumerator'
4959 if (return_type == TypeManager.ienumerator_type ||
4960 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4961 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4963 // If it is not an interface, lets try to find the methods ourselves.
4964 // For example, if we have:
4965 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4966 // We can avoid the iface call. This is a runtime perf boost.
4967 // even bigger if we have a ValueType, because we avoid the cost
4970 // We have to make sure that both methods exist for us to take
4971 // this path. If one of the methods does not exist, we will just
4972 // use the interface. Sadly, this complex if statement is the only
4973 // way I could do this without a goto
4978 // Prefer a generic enumerator over a non-generic one.
4980 if (return_type.IsInterface && return_type.IsGenericType) {
4981 enumerator_type = return_type;
4982 if (!FetchGetCurrent (ec, return_type))
4983 get_current = new PropertyExpr (
4984 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
4985 if (!FetchMoveNext (return_type))
4986 move_next = TypeManager.bool_movenext_void;
4991 if (return_type.IsInterface ||
4992 !FetchMoveNext (return_type) ||
4993 !FetchGetCurrent (ec, return_type)) {
4994 enumerator_type = return_type;
4995 move_next = TypeManager.bool_movenext_void;
4996 get_current = new PropertyExpr (
4997 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5002 // Ok, so they dont return an IEnumerable, we will have to
5003 // find if they support the GetEnumerator pattern.
5006 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
5007 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",
5008 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
5013 enumerator_type = return_type;
5014 is_disposable = !enumerator_type.IsSealed ||
5015 TypeManager.ImplementsInterface (
5016 enumerator_type, TypeManager.idisposable_type);
5022 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5024 bool FetchMoveNext (Type t)
5026 MemberList move_next_list;
5028 move_next_list = TypeContainer.FindMembers (
5029 t, MemberTypes.Method,
5030 BindingFlags.Public | BindingFlags.Instance,
5031 Type.FilterName, "MoveNext");
5032 if (move_next_list.Count == 0)
5035 foreach (MemberInfo m in move_next_list){
5036 MethodInfo mi = (MethodInfo) m;
5038 if ((TypeManager.GetParameterData (mi).Count == 0) &&
5039 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
5049 // Retrieves a `public T get_Current ()' method from the Type `t'
5051 bool FetchGetCurrent (EmitContext ec, Type t)
5053 PropertyExpr pe = Expression.MemberLookup (
5054 ec.ContainerType, t, "Current", MemberTypes.Property,
5055 Expression.AllBindingFlags, loc) as PropertyExpr;
5064 // Retrieves a `public void Dispose ()' method from the Type `t'
5066 static MethodInfo FetchMethodDispose (Type t)
5068 MemberList dispose_list;
5070 dispose_list = TypeContainer.FindMembers (
5071 t, MemberTypes.Method,
5072 BindingFlags.Public | BindingFlags.Instance,
5073 Type.FilterName, "Dispose");
5074 if (dispose_list.Count == 0)
5077 foreach (MemberInfo m in dispose_list){
5078 MethodInfo mi = (MethodInfo) m;
5080 if (TypeManager.GetParameterData (mi).Count == 0){
5081 if (mi.ReturnType == TypeManager.void_type)
5088 public void Error_Enumerator ()
5090 if (enumerator_found) {
5094 Report.Error (1579, loc,
5095 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
5096 TypeManager.CSharpName (expr.Type));
5099 public static bool IsOverride (MethodInfo m)
5101 m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
5103 if (!m.IsVirtual || ((m.Attributes & MethodAttributes.NewSlot) != 0))
5105 if (m is MethodBuilder)
5108 MethodInfo base_method = m.GetBaseDefinition ();
5109 return base_method != m;
5112 bool TryType (EmitContext ec, Type t)
5114 MethodGroupExpr mg = Expression.MemberLookup (
5115 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
5116 Expression.AllBindingFlags, loc) as MethodGroupExpr;
5120 MethodInfo result = null;
5121 MethodInfo tmp_move_next = null;
5122 PropertyExpr tmp_get_cur = null;
5123 Type tmp_enumerator_type = enumerator_type;
5124 foreach (MethodInfo mi in mg.Methods) {
5125 if (TypeManager.GetParameterData (mi).Count != 0)
5128 // Check whether GetEnumerator is public
5129 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
5132 if (IsOverride (mi))
5135 enumerator_found = true;
5137 if (!GetEnumeratorFilter (ec, mi))
5140 if (result != null) {
5141 if (TypeManager.IsGenericType (result.ReturnType)) {
5142 if (!TypeManager.IsGenericType (mi.ReturnType))
5145 MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
5146 Report.SymbolRelatedToPreviousError (t);
5147 Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
5148 "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
5149 TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
5153 // Always prefer generics enumerators
5154 if (!TypeManager.IsGenericType (mi.ReturnType)) {
5155 if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
5156 TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
5159 Report.SymbolRelatedToPreviousError (result);
5160 Report.SymbolRelatedToPreviousError (mi);
5161 Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
5162 TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
5167 tmp_move_next = move_next;
5168 tmp_get_cur = get_current;
5169 tmp_enumerator_type = enumerator_type;
5170 if (mi.DeclaringType == t)
5174 if (result != null) {
5175 move_next = tmp_move_next;
5176 get_current = tmp_get_cur;
5177 enumerator_type = tmp_enumerator_type;
5178 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
5179 get_enumerator = new MethodGroupExpr (mi, loc);
5181 if (t != expr.Type) {
5182 expr = Convert.ExplicitConversion (
5185 throw new InternalErrorException ();
5188 get_enumerator.InstanceExpression = expr;
5189 get_enumerator.IsBase = t != expr.Type;
5197 bool ProbeCollectionType (EmitContext ec, Type t)
5199 int errors = Report.Errors;
5200 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
5201 if (TryType (ec, tt))
5206 if (Report.Errors > errors)
5210 // Now try to find the method in the interfaces
5212 Type [] ifaces = TypeManager.GetInterfaces (t);
5213 foreach (Type i in ifaces){
5214 if (TryType (ec, i))
5221 public override bool Resolve (EmitContext ec)
5223 enumerator_type = TypeManager.ienumerator_type;
5224 is_disposable = true;
5226 if (!ProbeCollectionType (ec, expr.Type)) {
5227 Error_Enumerator ();
5231 VarExpr ve = var_type as VarExpr;
5233 // Infer implicitly typed local variable from foreach enumerable type
5234 var_type = new TypeExpression (get_current.PropertyInfo.PropertyType, var_type.Location);
5237 var_type = var_type.ResolveAsTypeTerminal (ec, false);
5238 if (var_type == null)
5241 enumerator = new TemporaryVariable (enumerator_type, loc);
5242 enumerator.Resolve (ec);
5244 init = new Invocation (get_enumerator, null);
5245 init = init.Resolve (ec);
5249 Expression move_next_expr;
5251 MemberInfo[] mi = new MemberInfo[] { move_next };
5252 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5253 mg.InstanceExpression = enumerator;
5255 move_next_expr = new Invocation (mg, null);
5258 get_current.InstanceExpression = enumerator;
5260 Statement block = new CollectionForeachStatement (
5261 var_type.Type, variable, get_current, statement, loc);
5263 loop = new While (move_next_expr, block, loc);
5267 FlowBranchingException branching = null;
5269 branching = ec.StartFlowBranching (this);
5271 if (!loop.Resolve (ec))
5274 if (is_disposable) {
5275 ResolveFinally (branching);
5276 ec.EndFlowBranching ();
5278 emit_finally = true;
5283 protected override void DoEmit (EmitContext ec)
5285 ILGenerator ig = ec.ig;
5287 enumerator.Store (ec, init);
5290 // Protect the code in a try/finalize block, so that
5291 // if the beast implement IDisposable, we get rid of it
5293 if (is_disposable && emit_finally)
5294 ig.BeginExceptionBlock ();
5299 // Now the finally block
5301 if (is_disposable) {
5304 ig.EndExceptionBlock ();
5309 public override void EmitFinally (EmitContext ec)
5311 ILGenerator ig = ec.ig;
5313 if (enumerator_type.IsValueType) {
5314 MethodInfo mi = FetchMethodDispose (enumerator_type);
5316 enumerator.EmitLoadAddress (ec);
5317 ig.Emit (OpCodes.Call, mi);
5319 enumerator.Emit (ec);
5320 ig.Emit (OpCodes.Box, enumerator_type);
5321 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5324 Label call_dispose = ig.DefineLabel ();
5326 enumerator.Emit (ec);
5327 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5328 ig.Emit (OpCodes.Dup);
5329 ig.Emit (OpCodes.Brtrue_S, call_dispose);
5330 ig.Emit (OpCodes.Pop);
5332 Label end_finally = ig.DefineLabel ();
5333 ig.Emit (OpCodes.Br, end_finally);
5335 ig.MarkLabel (call_dispose);
5336 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5337 ig.MarkLabel (end_finally);
5342 protected class CollectionForeachStatement : Statement
5345 Expression variable, current, conv;
5346 Statement statement;
5349 public CollectionForeachStatement (Type type, Expression variable,
5350 Expression current, Statement statement,
5354 this.variable = variable;
5355 this.current = current;
5356 this.statement = statement;
5360 public override bool Resolve (EmitContext ec)
5362 current = current.Resolve (ec);
5363 if (current == null)
5366 conv = Convert.ExplicitConversion (ec, current, type, loc);
5370 assign = new Assign (variable, conv, loc);
5371 if (assign.Resolve (ec) == null)
5374 if (!statement.Resolve (ec))
5380 protected override void DoEmit (EmitContext ec)
5382 assign.EmitStatement (ec);
5383 statement.Emit (ec);
5387 protected override void CloneTo (CloneContext clonectx, Statement t)
5389 Foreach target = (Foreach) t;
5391 target.type = type.Clone (clonectx);
5392 target.variable = variable.Clone (clonectx);
5393 target.expr = expr.Clone (clonectx);
5394 target.statement = statement.Clone (clonectx);