2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
7 // Marek Safar (marek.safar@seznam.cz)
9 // (C) 2001, 2002, 2003 Ximian, Inc.
10 // (C) 2003, 2004 Novell, Inc.
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Diagnostics;
18 using System.Collections;
19 using System.Collections.Specialized;
21 namespace Mono.CSharp {
23 public abstract class Statement {
27 /// Resolves the statement, true means that all sub-statements
30 public virtual bool Resolve (EmitContext ec)
36 /// We already know that the statement is unreachable, but we still
37 /// need to resolve it to catch errors.
39 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
42 // This conflicts with csc's way of doing this, but IMHO it's
43 // the right thing to do.
45 // If something is unreachable, we still check whether it's
46 // correct. This means that you cannot use unassigned variables
47 // in unreachable code, for instance.
51 Report.Warning (162, 2, loc, "Unreachable code detected");
53 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
54 bool ok = Resolve (ec);
55 ec.KillFlowBranching ();
61 /// Return value indicates whether all code paths emitted return.
63 protected abstract void DoEmit (EmitContext ec);
66 /// Utility wrapper routine for Error, just to beautify the code
68 public void Error (int error, string format, params object[] args)
70 Error (error, String.Format (format, args));
73 public void Error (int error, string s)
76 Report.Error (error, loc, s);
78 Report.Error (error, s);
82 /// Return value indicates whether all code paths emitted return.
84 public virtual void Emit (EmitContext ec)
91 // This routine must be overrided in derived classes and make copies
92 // of all the data that might be modified if resolved
94 protected virtual void CloneTo (CloneContext clonectx, Statement target)
96 throw new Exception (String.Format ("Statement.CloneTo not implemented for {0}", this.GetType ()));
99 public Statement Clone (CloneContext clonectx)
101 Statement s = (Statement) this.MemberwiseClone ();
103 clonectx.AddBlockMap ((Block) this, (Block) s);
105 CloneTo (clonectx, s);
109 public Statement PerformClone ()
111 CloneContext clonectx = new CloneContext ();
113 return Clone (clonectx);
119 // This class is used during the Statement.Clone operation
120 // to remap objects that have been cloned.
122 // Since blocks are cloned by Block.Clone, we need a way for
123 // expressions that must reference the block to be cloned
124 // pointing to the new cloned block.
126 public class CloneContext {
127 Hashtable block_map = new Hashtable ();
128 Hashtable variable_map;
130 public void AddBlockMap (Block from, Block to)
132 if (block_map.Contains (from))
134 block_map [from] = to;
137 public Block LookupBlock (Block from)
139 Block result = (Block) block_map [from];
142 result = (Block) from.Clone (this);
143 block_map [from] = result;
149 public void AddVariableMap (LocalInfo from, LocalInfo to)
151 if (variable_map == null)
152 variable_map = new Hashtable ();
154 if (variable_map.Contains (from))
156 variable_map [from] = to;
159 public LocalInfo LookupVariable (LocalInfo from)
161 LocalInfo result = (LocalInfo) variable_map [from];
164 throw new Exception ("LookupVariable: looking up a variable that has not been registered yet");
170 public sealed class EmptyStatement : Statement {
172 private EmptyStatement () {}
174 public static readonly EmptyStatement Value = new EmptyStatement ();
176 public override bool Resolve (EmitContext ec)
181 public override bool ResolveUnreachable (EmitContext ec, bool warn)
186 protected override void DoEmit (EmitContext ec)
191 public class If : Statement {
193 public Statement TrueStatement;
194 public Statement FalseStatement;
198 public If (Expression expr, Statement trueStatement, Location l)
201 TrueStatement = trueStatement;
205 public If (Expression expr,
206 Statement trueStatement,
207 Statement falseStatement,
211 TrueStatement = trueStatement;
212 FalseStatement = falseStatement;
216 public override bool Resolve (EmitContext ec)
220 Report.Debug (1, "START IF BLOCK", loc);
222 expr = Expression.ResolveBoolean (ec, expr, loc);
228 Assign ass = expr as Assign;
229 if (ass != null && ass.Source is Constant) {
230 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
234 // Dead code elimination
236 if (expr is BoolConstant){
237 bool take = ((BoolConstant) expr).Value;
240 if (!TrueStatement.Resolve (ec))
243 if ((FalseStatement != null) &&
244 !FalseStatement.ResolveUnreachable (ec, true))
246 FalseStatement = null;
248 if (!TrueStatement.ResolveUnreachable (ec, true))
250 TrueStatement = null;
252 if ((FalseStatement != null) &&
253 !FalseStatement.Resolve (ec))
260 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
262 ok &= TrueStatement.Resolve (ec);
264 is_true_ret = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
266 ec.CurrentBranching.CreateSibling ();
268 if (FalseStatement != null)
269 ok &= FalseStatement.Resolve (ec);
271 ec.EndFlowBranching ();
273 Report.Debug (1, "END IF BLOCK", loc);
278 protected override void DoEmit (EmitContext ec)
280 ILGenerator ig = ec.ig;
281 Label false_target = ig.DefineLabel ();
285 // If we're a boolean expression, Resolve() already
286 // eliminated dead code for us.
288 if (expr is BoolConstant){
289 bool take = ((BoolConstant) expr).Value;
292 TrueStatement.Emit (ec);
293 else if (FalseStatement != null)
294 FalseStatement.Emit (ec);
299 expr.EmitBranchable (ec, false_target, false);
301 TrueStatement.Emit (ec);
303 if (FalseStatement != null){
304 bool branch_emitted = false;
306 end = ig.DefineLabel ();
308 ig.Emit (OpCodes.Br, end);
309 branch_emitted = true;
312 ig.MarkLabel (false_target);
313 FalseStatement.Emit (ec);
318 ig.MarkLabel (false_target);
322 protected override void CloneTo (CloneContext clonectx, Statement t)
326 target.expr = expr.Clone (clonectx);
327 target.TrueStatement = TrueStatement.Clone (clonectx);
328 if (FalseStatement != null)
329 target.FalseStatement = FalseStatement.Clone (clonectx);
333 public class Do : Statement {
334 public Expression expr;
335 public Statement EmbeddedStatement;
338 public Do (Statement statement, Expression boolExpr, Location l)
341 EmbeddedStatement = statement;
345 public override bool Resolve (EmitContext ec)
349 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
351 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
353 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
354 if (!EmbeddedStatement.Resolve (ec))
356 ec.EndFlowBranching ();
358 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable && !was_unreachable)
359 Report.Warning (162, 2, expr.Location, "Unreachable code detected");
361 expr = Expression.ResolveBoolean (ec, expr, loc);
364 else if (expr is BoolConstant){
365 bool res = ((BoolConstant) expr).Value;
371 ec.CurrentBranching.CurrentUsageVector.Goto ();
373 ec.EndFlowBranching ();
378 protected override void DoEmit (EmitContext ec)
380 ILGenerator ig = ec.ig;
381 Label loop = ig.DefineLabel ();
382 Label old_begin = ec.LoopBegin;
383 Label old_end = ec.LoopEnd;
385 ec.LoopBegin = ig.DefineLabel ();
386 ec.LoopEnd = ig.DefineLabel ();
389 EmbeddedStatement.Emit (ec);
390 ig.MarkLabel (ec.LoopBegin);
393 // Dead code elimination
395 if (expr is BoolConstant){
396 bool res = ((BoolConstant) expr).Value;
399 ec.ig.Emit (OpCodes.Br, loop);
401 expr.EmitBranchable (ec, loop, true);
403 ig.MarkLabel (ec.LoopEnd);
405 ec.LoopBegin = old_begin;
406 ec.LoopEnd = old_end;
409 protected override void CloneTo (CloneContext clonectx, Statement t)
413 target.EmbeddedStatement = EmbeddedStatement.Clone (clonectx);
414 target.expr = expr.Clone (clonectx);
418 public class While : Statement {
419 public Expression expr;
420 public Statement Statement;
421 bool infinite, empty;
423 public While (Expression boolExpr, Statement statement, Location l)
425 this.expr = boolExpr;
426 Statement = statement;
430 public override bool Resolve (EmitContext ec)
434 expr = Expression.ResolveBoolean (ec, expr, loc);
439 // Inform whether we are infinite or not
441 if (expr is BoolConstant){
442 BoolConstant bc = (BoolConstant) expr;
444 if (bc.Value == false){
445 if (!Statement.ResolveUnreachable (ec, true))
453 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
455 ec.CurrentBranching.CreateSibling ();
457 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
458 if (!Statement.Resolve (ec))
460 ec.EndFlowBranching ();
462 // There's no direct control flow from the end of the embedded statement to the end of the loop
463 ec.CurrentBranching.CurrentUsageVector.Goto ();
465 ec.EndFlowBranching ();
470 protected override void DoEmit (EmitContext ec)
475 ILGenerator ig = ec.ig;
476 Label old_begin = ec.LoopBegin;
477 Label old_end = ec.LoopEnd;
479 ec.LoopBegin = ig.DefineLabel ();
480 ec.LoopEnd = ig.DefineLabel ();
483 // Inform whether we are infinite or not
485 if (expr is BoolConstant){
486 ig.MarkLabel (ec.LoopBegin);
488 ig.Emit (OpCodes.Br, ec.LoopBegin);
491 // Inform that we are infinite (ie, `we return'), only
492 // if we do not `break' inside the code.
494 ig.MarkLabel (ec.LoopEnd);
496 Label while_loop = ig.DefineLabel ();
498 ig.Emit (OpCodes.Br, ec.LoopBegin);
499 ig.MarkLabel (while_loop);
503 ig.MarkLabel (ec.LoopBegin);
505 expr.EmitBranchable (ec, while_loop, true);
507 ig.MarkLabel (ec.LoopEnd);
510 ec.LoopBegin = old_begin;
511 ec.LoopEnd = old_end;
514 protected override void CloneTo (CloneContext clonectx, Statement t)
516 While target = (While) t;
518 target.expr = expr.Clone (clonectx);
519 target.Statement = Statement.Clone (clonectx);
523 public class For : Statement {
525 Statement InitStatement;
527 public Statement Statement;
528 bool infinite, empty;
530 public For (Statement initStatement,
536 InitStatement = initStatement;
538 Increment = increment;
539 Statement = statement;
543 public override bool Resolve (EmitContext ec)
547 if (InitStatement != null){
548 if (!InitStatement.Resolve (ec))
553 Test = Expression.ResolveBoolean (ec, Test, loc);
556 else if (Test is BoolConstant){
557 BoolConstant bc = (BoolConstant) Test;
559 if (bc.Value == false){
560 if (!Statement.ResolveUnreachable (ec, true))
562 if ((Increment != null) &&
563 !Increment.ResolveUnreachable (ec, false))
573 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
575 ec.CurrentBranching.CreateSibling ();
577 bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
579 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
580 if (!Statement.Resolve (ec))
582 ec.EndFlowBranching ();
584 if (Increment != null){
585 if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable) {
586 if (!Increment.ResolveUnreachable (ec, !was_unreachable))
589 if (!Increment.Resolve (ec))
594 // There's no direct control flow from the end of the embedded statement to the end of the loop
595 ec.CurrentBranching.CurrentUsageVector.Goto ();
597 ec.EndFlowBranching ();
602 protected override void DoEmit (EmitContext ec)
607 ILGenerator ig = ec.ig;
608 Label old_begin = ec.LoopBegin;
609 Label old_end = ec.LoopEnd;
610 Label loop = ig.DefineLabel ();
611 Label test = ig.DefineLabel ();
613 if (InitStatement != null && InitStatement != EmptyStatement.Value)
614 InitStatement.Emit (ec);
616 ec.LoopBegin = ig.DefineLabel ();
617 ec.LoopEnd = ig.DefineLabel ();
619 ig.Emit (OpCodes.Br, test);
623 ig.MarkLabel (ec.LoopBegin);
624 if (Increment != EmptyStatement.Value)
629 // If test is null, there is no test, and we are just
634 // The Resolve code already catches the case for
635 // Test == BoolConstant (false) so we know that
638 if (Test is BoolConstant)
639 ig.Emit (OpCodes.Br, loop);
641 Test.EmitBranchable (ec, loop, true);
644 ig.Emit (OpCodes.Br, loop);
645 ig.MarkLabel (ec.LoopEnd);
647 ec.LoopBegin = old_begin;
648 ec.LoopEnd = old_end;
651 protected override void CloneTo (CloneContext clonectx, Statement t)
653 For target = (For) t;
655 if (InitStatement != null)
656 target.InitStatement = InitStatement.Clone (clonectx);
658 target.Test = Test.Clone (clonectx);
659 if (Increment != null)
660 target.Increment = Increment.Clone (clonectx);
661 target.Statement = Statement.Clone (clonectx);
665 public class StatementExpression : Statement {
666 ExpressionStatement expr;
668 public StatementExpression (ExpressionStatement expr)
674 public override bool Resolve (EmitContext ec)
677 expr = expr.ResolveStatement (ec);
681 protected override void DoEmit (EmitContext ec)
683 expr.EmitStatement (ec);
686 public override string ToString ()
688 return "StatementExpression (" + expr + ")";
691 protected override void CloneTo (CloneContext clonectx, Statement t)
693 StatementExpression target = (StatementExpression) t;
695 target.expr = (ExpressionStatement) expr.Clone (clonectx);
700 /// Implements the return statement
702 public class Return : Statement {
703 public Expression Expr;
705 public Return (Expression expr, Location l)
713 public override bool Resolve (EmitContext ec)
715 AnonymousContainer am = ec.CurrentAnonymousMethod;
716 if ((am != null) && am.IsIterator && ec.InIterator) {
717 Report.Error (1622, loc, "Cannot return a value from iterators. Use the yield return " +
718 "statement to return a value, or yield break to end the iteration");
722 if (ec.ReturnType == null){
725 Report.Error (1662, loc,
726 "Cannot convert anonymous method block to delegate type `{0}' because some of the return types in the block are not implicitly convertible to the delegate return type",
727 am.GetSignatureForError ());
729 Error (127, "A return keyword must not be followed by any expression when method returns void");
734 Error (126, "An object of a type convertible to `{0}' is required " +
735 "for the return statement",
736 TypeManager.CSharpName (ec.ReturnType));
740 Expr = Expr.Resolve (ec);
744 if (Expr.Type != ec.ReturnType) {
745 if (ec.InferReturnType) {
746 ec.ReturnType = Expr.Type;
748 Expr = Convert.ImplicitConversionRequired (
749 ec, Expr, ec.ReturnType, loc);
756 int errors = Report.Errors;
757 unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
759 ec.NeedReturnLabel ();
760 ec.CurrentBranching.CurrentUsageVector.Goto ();
761 return errors == Report.Errors;
764 protected override void DoEmit (EmitContext ec)
770 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
774 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
776 ec.ig.Emit (OpCodes.Ret);
779 protected override void CloneTo (CloneContext clonectx, Statement t)
781 Return target = (Return) t;
783 target.Expr = Expr.Clone (clonectx);
787 public class Goto : Statement {
789 LabeledStatement label;
792 public override bool Resolve (EmitContext ec)
794 int errors = Report.Errors;
795 unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
796 ec.CurrentBranching.CurrentUsageVector.Goto ();
797 return errors == Report.Errors;
800 public Goto (string label, Location l)
806 public string Target {
807 get { return target; }
810 public void SetResolvedTarget (LabeledStatement label)
813 label.AddReference ();
816 protected override void DoEmit (EmitContext ec)
819 throw new InternalErrorException ("goto emitted before target resolved");
820 Label l = label.LabelTarget (ec);
821 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
825 public class LabeledStatement : Statement {
832 FlowBranching.UsageVector vectors;
834 public LabeledStatement (string name, Location l)
840 public Label LabelTarget (EmitContext ec)
845 label = ec.ig.DefineLabel ();
855 public bool IsDefined {
856 get { return defined; }
859 public bool HasBeenReferenced {
860 get { return referenced; }
863 public FlowBranching.UsageVector JumpOrigins {
864 get { return vectors; }
867 public void AddUsageVector (FlowBranching.UsageVector vector)
869 vector = vector.Clone ();
870 vector.Next = vectors;
874 public override bool Resolve (EmitContext ec)
876 // this flow-branching will be terminated when the surrounding block ends
877 ec.StartFlowBranching (this);
881 protected override void DoEmit (EmitContext ec)
883 if (ig != null && ig != ec.ig)
884 throw new InternalErrorException ("cannot happen");
886 ec.ig.MarkLabel (label);
889 public void AddReference ()
897 /// `goto default' statement
899 public class GotoDefault : Statement {
901 public GotoDefault (Location l)
906 public override bool Resolve (EmitContext ec)
908 ec.CurrentBranching.CurrentUsageVector.Goto ();
912 protected override void DoEmit (EmitContext ec)
914 if (ec.Switch == null){
915 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
919 if (!ec.Switch.GotDefault){
920 FlowBranchingBlock.Error_UnknownLabel (loc, "default");
923 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
928 /// `goto case' statement
930 public class GotoCase : Statement {
934 public GotoCase (Expression e, Location l)
940 public override bool Resolve (EmitContext ec)
942 if (ec.Switch == null){
943 Report.Error (153, loc, "A goto case is only valid inside a switch statement");
947 expr = expr.Resolve (ec);
951 Constant c = expr as Constant;
953 Error (150, "A constant value is expected");
957 Type type = ec.Switch.SwitchType;
958 if (!Convert.ImplicitStandardConversionExists (c, type))
959 Report.Warning (469, 2, loc, "The `goto case' value is not implicitly " +
960 "convertible to type `{0}'", TypeManager.CSharpName (type));
963 object val = c.GetValue ();
964 if ((val != null) && (c.Type != type) && (c.Type != TypeManager.object_type))
965 val = TypeManager.ChangeType (val, type, out fail);
968 Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
969 c.GetSignatureForError (), TypeManager.CSharpName (type));
974 val = SwitchLabel.NullStringCase;
976 sl = (SwitchLabel) ec.Switch.Elements [val];
979 FlowBranchingBlock.Error_UnknownLabel (loc, "case " +
980 (c.GetValue () == null ? "null" : val.ToString ()));
984 ec.CurrentBranching.CurrentUsageVector.Goto ();
988 protected override void DoEmit (EmitContext ec)
990 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
993 protected override void CloneTo (CloneContext clonectx, Statement t)
995 GotoCase target = (GotoCase) t;
997 target.expr = expr.Clone (clonectx);
998 target.sl = sl.Clone (clonectx);
1002 public class Throw : Statement {
1005 public Throw (Expression expr, Location l)
1011 public override bool Resolve (EmitContext ec)
1013 ec.CurrentBranching.CurrentUsageVector.Goto ();
1016 expr = expr.Resolve (ec);
1020 ExprClass eclass = expr.eclass;
1022 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1023 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1024 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
1030 if ((t != TypeManager.exception_type) &&
1031 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
1032 !(expr is NullLiteral)) {
1034 "The type caught or thrown must be derived " +
1035 "from System.Exception");
1042 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
1047 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1053 protected override void DoEmit (EmitContext ec)
1056 ec.ig.Emit (OpCodes.Rethrow);
1060 ec.ig.Emit (OpCodes.Throw);
1064 protected override void CloneTo (CloneContext clonectx, Statement t)
1066 Throw target = (Throw) t;
1068 target.expr = expr.Clone (clonectx);
1072 public class Break : Statement {
1074 public Break (Location l)
1079 bool unwind_protect;
1081 public override bool Resolve (EmitContext ec)
1083 int errors = Report.Errors;
1084 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1085 ec.CurrentBranching.CurrentUsageVector.Goto ();
1086 return errors == Report.Errors;
1089 protected override void DoEmit (EmitContext ec)
1091 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
1095 public class Continue : Statement {
1097 public Continue (Location l)
1102 bool unwind_protect;
1104 public override bool Resolve (EmitContext ec)
1106 int errors = Report.Errors;
1107 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1108 ec.CurrentBranching.CurrentUsageVector.Goto ();
1109 return errors == Report.Errors;
1112 protected override void DoEmit (EmitContext ec)
1114 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
1118 public abstract class Variable
1120 public abstract Type Type {
1124 public abstract bool HasInstance {
1128 public abstract bool NeedsTemporary {
1132 public abstract void EmitInstance (EmitContext ec);
1134 public abstract void Emit (EmitContext ec);
1136 public abstract void EmitAssign (EmitContext ec);
1138 public abstract void EmitAddressOf (EmitContext ec);
1142 // The information about a user-perceived local variable
1144 public class LocalInfo {
1145 public Expression Type;
1147 public Type VariableType;
1148 public readonly string Name;
1149 public readonly Location Location;
1150 public readonly Block Block;
1152 public VariableInfo VariableInfo;
1155 public Variable Variable {
1167 CompilerGenerated = 64,
1171 public enum ReadOnlyContext: byte {
1178 ReadOnlyContext ro_context;
1179 LocalBuilder builder;
1181 public LocalInfo (Expression type, string name, Block block, Location l)
1189 public LocalInfo (DeclSpace ds, Block block, Location l)
1191 VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
1196 public void ResolveVariable (EmitContext ec)
1198 Block theblock = Block;
1199 if (theblock.ScopeInfo != null)
1200 var = theblock.ScopeInfo.GetCapturedVariable (this);
1205 // This is needed to compile on both .NET 1.x and .NET 2.x
1206 // the later introduced `DeclareLocal (Type t, bool pinned)'
1208 builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1210 builder = ec.ig.DeclareLocal (VariableType);
1212 var = new LocalVariable (this, builder);
1216 public void EmitSymbolInfo (EmitContext ec, string name)
1218 if (builder != null)
1219 ec.DefineLocalVariable (name, builder);
1222 public bool IsThisAssigned (EmitContext ec)
1224 if (VariableInfo == null)
1225 throw new Exception ();
1227 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1230 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, ec.loc);
1233 public bool IsAssigned (EmitContext ec)
1235 if (VariableInfo == null)
1236 throw new Exception ();
1238 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1241 public bool Resolve (EmitContext ec)
1243 if (VariableType == null) {
1244 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1248 VariableType = texpr.Type;
1251 if (TypeManager.IsGenericParameter (VariableType))
1254 if (VariableType == TypeManager.void_type) {
1255 Expression.Error_VoidInvalidInTheContext (Location);
1259 if (VariableType.IsAbstract && VariableType.IsSealed) {
1260 FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
1264 if (VariableType.IsPointer && !ec.InUnsafe)
1265 Expression.UnsafeError (Location);
1270 public bool IsCaptured {
1272 return (flags & Flags.Captured) != 0;
1276 flags |= Flags.Captured;
1280 public bool IsConstant {
1282 return (flags & Flags.IsConstant) != 0;
1285 flags |= Flags.IsConstant;
1289 public bool AddressTaken {
1291 return (flags & Flags.AddressTaken) != 0;
1295 flags |= Flags.AddressTaken;
1299 public bool CompilerGenerated {
1301 return (flags & Flags.CompilerGenerated) != 0;
1305 flags |= Flags.CompilerGenerated;
1309 public override string ToString ()
1311 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1312 Name, Type, VariableInfo, Location);
1317 return (flags & Flags.Used) != 0;
1320 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1324 public bool ReadOnly {
1326 return (flags & Flags.ReadOnly) != 0;
1330 public void SetReadOnlyContext (ReadOnlyContext context)
1332 flags |= Flags.ReadOnly;
1333 ro_context = context;
1336 public string GetReadOnlyContext ()
1339 throw new InternalErrorException ("Variable is not readonly");
1341 switch (ro_context) {
1342 case ReadOnlyContext.Fixed:
1343 return "fixed variable";
1344 case ReadOnlyContext.Foreach:
1345 return "foreach iteration variable";
1346 case ReadOnlyContext.Using:
1347 return "using variable";
1349 throw new NotImplementedException ();
1353 // Whether the variable is pinned, if Pinned the variable has been
1354 // allocated in a pinned slot with DeclareLocal.
1356 public bool Pinned {
1358 return (flags & Flags.Pinned) != 0;
1361 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1365 public bool IsThis {
1367 return (flags & Flags.IsThis) != 0;
1370 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1374 protected class LocalVariable : Variable
1376 public readonly LocalInfo LocalInfo;
1377 LocalBuilder builder;
1379 public LocalVariable (LocalInfo local, LocalBuilder builder)
1381 this.LocalInfo = local;
1382 this.builder = builder;
1385 public override Type Type {
1386 get { return LocalInfo.VariableType; }
1389 public override bool HasInstance {
1390 get { return false; }
1393 public override bool NeedsTemporary {
1394 get { return false; }
1397 public override void EmitInstance (EmitContext ec)
1402 public override void Emit (EmitContext ec)
1404 ec.ig.Emit (OpCodes.Ldloc, builder);
1407 public override void EmitAssign (EmitContext ec)
1409 ec.ig.Emit (OpCodes.Stloc, builder);
1412 public override void EmitAddressOf (EmitContext ec)
1414 ec.ig.Emit (OpCodes.Ldloca, builder);
1418 public LocalInfo Clone (CloneContext clonectx)
1420 // Only this kind is created by the parser.
1421 return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
1426 /// Block represents a C# block.
1430 /// This class is used in a number of places: either to represent
1431 /// explicit blocks that the programmer places or implicit blocks.
1433 /// Implicit blocks are used as labels or to introduce variable
1436 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1437 /// they contain extra information that is not necessary on normal blocks.
1439 public class Block : Statement {
1440 public Block Parent;
1441 public readonly Location StartLocation;
1442 public Location EndLocation = Location.Null;
1444 public readonly ToplevelBlock Toplevel;
1447 public enum Flags : ushort {
1451 VariablesInitialized = 8,
1456 HasVarargs = 256, // Used in ToplevelBlock
1460 protected Flags flags;
1462 public bool Implicit {
1463 get { return (flags & Flags.Implicit) != 0; }
1466 public bool Unchecked {
1467 get { return (flags & Flags.Unchecked) != 0; }
1468 set { flags |= Flags.Unchecked; }
1471 public bool Unsafe {
1472 get { return (flags & Flags.Unsafe) != 0; }
1473 set { flags |= Flags.Unsafe; }
1477 // The statements in this block
1479 protected ArrayList statements;
1480 protected int current_statement;
1484 // An array of Blocks. We keep track of children just
1485 // to generate the local variable declarations.
1487 // Statements and child statements are handled through the
1493 // Labels. (label, block) pairs.
1498 // Keeps track of (name, type) pairs
1500 IDictionary variables;
1503 // Keeps track of constants
1504 Hashtable constants;
1507 // Temporary variables.
1509 ArrayList temporary_variables;
1511 ExpressionStatement scope_init;
1513 ArrayList anonymous_children;
1515 protected static int id;
1519 public Block (Block parent)
1520 : this (parent, (Flags) 0, Location.Null, Location.Null)
1523 public Block (Block parent, Flags flags)
1524 : this (parent, flags, Location.Null, Location.Null)
1527 public Block (Block parent, Location start, Location end)
1528 : this (parent, (Flags) 0, start, end)
1531 public Block (Block parent, Flags flags, Location start, Location end)
1534 parent.AddChild (this);
1536 this.Parent = parent;
1538 this.StartLocation = start;
1539 this.EndLocation = end;
1542 statements = new ArrayList ();
1544 if ((flags & Flags.IsToplevel) != 0)
1545 Toplevel = (ToplevelBlock) this;
1547 Toplevel = parent.Toplevel;
1549 if (parent != null && Implicit) {
1550 if (parent.known_variables == null)
1551 parent.known_variables = new Hashtable ();
1552 // share with parent
1553 known_variables = parent.known_variables;
1557 public Block CreateSwitchBlock (Location start)
1559 return new Block (this, start, start);
1563 get { return this_id; }
1566 public IDictionary Variables {
1568 if (variables == null)
1569 variables = new ListDictionary ();
1574 void AddChild (Block b)
1576 if (children == null)
1577 children = new ArrayList ();
1582 public void SetEndLocation (Location loc)
1587 protected static void Error_158 (string name, Location loc)
1589 Report.Error (158, loc, "The label `{0}' shadows another label " +
1590 "by the same name in a contained scope", name);
1594 /// Adds a label to the current block.
1598 /// false if the name already exists in this block. true
1602 public bool AddLabel (LabeledStatement target)
1604 string name = target.Name;
1607 while (cur != null) {
1608 LabeledStatement s = cur.DoLookupLabel (name);
1610 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
1611 Report.Error (140, target.loc, "The label `{0}' is a duplicate", name);
1621 if (Toplevel.children != null) {
1622 foreach (Block b in Toplevel.children) {
1623 LabeledStatement s = b.LookupLabel (name);
1627 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
1628 Error_158 (name, target.loc);
1633 Toplevel.CheckError158 (name, target.loc);
1636 labels = new Hashtable ();
1638 labels.Add (name, target);
1642 public LabeledStatement LookupLabel (string name)
1644 LabeledStatement s = DoLookupLabel (name);
1648 if (children == null)
1651 foreach (Block child in children) {
1652 //if (!child.Implicit)
1655 s = child.LookupLabel (name);
1663 LabeledStatement DoLookupLabel (string name)
1668 return ((LabeledStatement) labels [name]);
1671 Hashtable known_variables;
1674 // Marks a variable with name @name as being used in this or a child block.
1675 // If a variable name has been used in a child block, it's illegal to
1676 // declare a variable with the same name in the current block.
1678 void AddKnownVariable (string name, LocalInfo info)
1680 if (known_variables == null)
1681 known_variables = new Hashtable ();
1683 known_variables [name] = info;
1686 LocalInfo GetKnownVariableInfo (string name, bool recurse)
1688 if (known_variables != null) {
1689 LocalInfo vi = (LocalInfo) known_variables [name];
1694 if (!recurse || (children == null))
1697 foreach (Block block in children) {
1698 LocalInfo vi = block.GetKnownVariableInfo (name, true);
1706 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1709 LocalInfo kvi = b.GetKnownVariableInfo (name, true);
1710 while (kvi == null) {
1716 kvi = b.GetKnownVariableInfo (name, false);
1722 // Is kvi.Block nested inside 'b'
1723 if (b.known_variables != kvi.Block.known_variables) {
1725 // If a variable by the same name it defined in a nested block of this
1726 // block, we violate the invariant meaning in a block.
1729 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1730 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1735 // It's ok if the definition is in a nested subblock of b, but not
1736 // nested inside this block -- a definition in a sibling block
1737 // should not affect us.
1743 // Block 'b' and kvi.Block are the same textual block.
1744 // However, different variables are extant.
1746 // Check if the variable is in scope in both blocks. We use
1747 // an indirect check that depends on AddVariable doing its
1748 // part in maintaining the invariant-meaning-in-block property.
1750 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1754 // Even though we detected the error when the name is used, we
1755 // treat it as if the variable declaration was in error.
1757 Report.SymbolRelatedToPreviousError (loc, name);
1758 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1762 public bool CheckError136_InParents (string name, Location loc)
1764 for (Block b = Parent; b != null; b = b.Parent) {
1765 if (!b.DoCheckError136 (name, "parent or current", loc))
1769 for (Block b = Toplevel.ContainerBlock; b != null; b = b.Toplevel.ContainerBlock) {
1770 if (!b.CheckError136_InParents (name, loc))
1777 public bool CheckError136_InChildren (string name, Location loc)
1779 if (!DoCheckError136_InChildren (name, loc))
1783 while (b.Implicit) {
1784 if (!b.Parent.DoCheckError136_InChildren (name, loc))
1792 protected bool DoCheckError136_InChildren (string name, Location loc)
1794 if (!DoCheckError136 (name, "child", loc))
1797 if (AnonymousChildren != null) {
1798 foreach (ToplevelBlock child in AnonymousChildren) {
1799 if (!child.DoCheckError136_InChildren (name, loc))
1804 if (children != null) {
1805 foreach (Block child in children) {
1806 if (!child.DoCheckError136_InChildren (name, loc))
1814 public bool CheckError136 (string name, string scope, bool check_parents,
1815 bool check_children, Location loc)
1817 if (!DoCheckError136 (name, scope, loc))
1820 if (check_parents) {
1821 if (!CheckError136_InParents (name, loc))
1825 if (check_children) {
1826 if (!CheckError136_InChildren (name, loc))
1830 for (Block c = Toplevel.ContainerBlock; c != null; c = c.Toplevel.ContainerBlock) {
1831 if (!c.DoCheckError136 (name, "parent or current", loc))
1838 protected bool DoCheckError136 (string name, string scope, Location loc)
1840 LocalInfo vi = GetKnownVariableInfo (name, false);
1842 Report.SymbolRelatedToPreviousError (vi.Location, name);
1843 Error_AlreadyDeclared (loc, name, scope != null ? scope : "child");
1848 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1850 Report.SymbolRelatedToPreviousError (p.Location, name);
1851 Error_AlreadyDeclared (
1852 loc, name, scope != null ? scope : "method argument");
1859 public LocalInfo AddVariable (Expression type, string name, Location l)
1861 LocalInfo vi = GetLocalInfo (name);
1863 Report.SymbolRelatedToPreviousError (vi.Location, name);
1864 if (known_variables == vi.Block.known_variables)
1865 Report.Error (128, l,
1866 "A local variable named `{0}' is already defined in this scope", name);
1868 Error_AlreadyDeclared (l, name, "parent");
1872 if (!CheckError136 (name, null, true, true, l))
1875 vi = new LocalInfo (type, name, this, l);
1876 Variables.Add (name, vi);
1877 AddKnownVariable (name, vi);
1879 if ((flags & Flags.VariablesInitialized) != 0)
1880 throw new InternalErrorException ("block has already been resolved");
1885 void Error_AlreadyDeclared (Location loc, string var, string reason)
1887 Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1888 "in this scope because it would give a different meaning " +
1889 "to `{0}', which is already used in a `{1}' scope " +
1890 "to denote something else", var, reason);
1893 public bool AddConstant (Expression type, string name, Expression value, Location l)
1895 if (AddVariable (type, name, l) == null)
1898 if (constants == null)
1899 constants = new Hashtable ();
1901 constants.Add (name, value);
1903 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1908 static int next_temp_id = 0;
1910 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1912 Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1914 if (temporary_variables == null)
1915 temporary_variables = new ArrayList ();
1917 int id = ++next_temp_id;
1918 string name = "$s_" + id.ToString ();
1920 LocalInfo li = new LocalInfo (te, name, this, loc);
1921 li.CompilerGenerated = true;
1922 temporary_variables.Add (li);
1926 public LocalInfo GetLocalInfo (string name)
1928 for (Block b = this; b != null; b = b.Parent) {
1929 if (b.variables != null) {
1930 LocalInfo ret = b.variables [name] as LocalInfo;
1938 public Expression GetVariableType (string name)
1940 LocalInfo vi = GetLocalInfo (name);
1941 return vi == null ? null : vi.Type;
1944 public Expression GetConstantExpression (string name)
1946 for (Block b = this; b != null; b = b.Parent) {
1947 if (b.constants != null) {
1948 Expression ret = b.constants [name] as Expression;
1956 public void AddStatement (Statement s)
1959 flags |= Flags.BlockUsed;
1962 public void InsertStatementAfterCurrent (Statement statement)
1964 statements.Insert (current_statement + 1, statement);
1965 flags |= Flags.BlockUsed;
1969 get { return (flags & Flags.BlockUsed) != 0; }
1974 flags |= Flags.BlockUsed;
1977 public bool HasRet {
1978 get { return (flags & Flags.HasRet) != 0; }
1981 public bool IsDestructor {
1982 get { return (flags & Flags.IsDestructor) != 0; }
1985 public void SetDestructor ()
1987 flags |= Flags.IsDestructor;
1990 VariableMap param_map;
1992 public VariableMap ParameterMap {
1994 if ((flags & Flags.VariablesInitialized) == 0){
1995 throw new Exception ("Variables have not been initialized yet");
2002 int assignable_slots;
2003 public int AssignableSlots {
2005 if ((flags & Flags.VariablesInitialized) == 0){
2006 throw new Exception ("Variables have not been initialized yet");
2008 return assignable_slots;
2012 protected ScopeInfo scope_info;
2014 public ScopeInfo ScopeInfo {
2015 get { return scope_info; }
2018 public ScopeInfo CreateScopeInfo ()
2020 if (scope_info == null)
2021 scope_info = ScopeInfo.CreateScope (this);
2026 public ArrayList AnonymousChildren {
2027 get { return anonymous_children; }
2030 public void AddAnonymousChild (ToplevelBlock b)
2032 if (anonymous_children == null)
2033 anonymous_children = new ArrayList ();
2035 anonymous_children.Add (b);
2038 void DoResolveConstants (EmitContext ec)
2040 if (constants == null)
2043 if (variables == null)
2044 throw new InternalErrorException ("cannot happen");
2046 foreach (DictionaryEntry de in variables) {
2047 string name = (string) de.Key;
2048 LocalInfo vi = (LocalInfo) de.Value;
2049 Type variable_type = vi.VariableType;
2051 if (variable_type == null)
2054 Expression cv = (Expression) constants [name];
2058 // Don't let 'const int Foo = Foo;' succeed.
2059 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
2060 // which in turn causes the 'must be constant' error to be triggered.
2061 constants.Remove (name);
2063 if (!Const.IsConstantTypeValid (variable_type)) {
2064 Const.Error_InvalidConstantType (variable_type, loc);
2068 ec.CurrentBlock = this;
2070 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
2071 e = cv.Resolve (ec);
2076 Constant ce = e as Constant;
2078 Const.Error_ExpressionMustBeConstant (vi.Location, name);
2082 e = ce.ConvertImplicitly (variable_type);
2084 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue)
2085 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
2087 ce.Error_ValueCannotBeConverted (null, vi.Location, variable_type, false);
2091 constants.Add (name, e);
2092 vi.IsConstant = true;
2096 protected void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
2098 Report.Debug (64, "BLOCK RESOLVE META", this, Parent, toplevel);
2100 // If some parent block was unsafe, we remain unsafe even if this block
2101 // isn't explicitly marked as such.
2102 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
2103 param_map = new VariableMap (ip);
2104 flags |= Flags.VariablesInitialized;
2106 int offset = Parent == null ? 0 : Parent.AssignableSlots;
2107 if (variables != null) {
2108 foreach (LocalInfo li in variables.Values) {
2109 if (li.Resolve (ec)) {
2110 li.VariableInfo = new VariableInfo (li, offset);
2111 offset += li.VariableInfo.Length;
2115 assignable_slots = offset;
2117 DoResolveConstants (ec);
2119 if (children != null) {
2120 foreach (Block b in children)
2121 b.ResolveMeta (toplevel, ec, ip);
2127 // Emits the local variable declarations for a block
2129 public virtual void EmitMeta (EmitContext ec)
2131 Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
2132 if (ScopeInfo != null) {
2133 scope_init = ScopeInfo.GetScopeInitializer (ec);
2134 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
2138 if (variables != null){
2139 foreach (LocalInfo vi in variables.Values)
2140 vi.ResolveVariable (ec);
2143 if (temporary_variables != null) {
2144 foreach (LocalInfo vi in temporary_variables)
2145 vi.ResolveVariable (ec);
2148 if (children != null){
2149 foreach (Block b in children)
2154 void UsageWarning (FlowBranching.UsageVector vector)
2158 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
2159 foreach (DictionaryEntry de in variables){
2160 LocalInfo vi = (LocalInfo) de.Value;
2165 name = (string) de.Key;
2167 // vi.VariableInfo can be null for 'catch' variables
2168 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2169 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2171 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2177 bool unreachable_shown;
2180 private void CheckPossibleMistakenEmptyStatement (Statement s)
2184 // Some statements are wrapped by a Block. Since
2185 // others' internal could be changed, here I treat
2186 // them as possibly wrapped by Block equally.
2187 Block b = s as Block;
2188 if (b != null && b.statements.Count == 1)
2189 s = (Statement) b.statements [0];
2192 body = ((Lock) s).Statement;
2194 body = ((For) s).Statement;
2195 else if (s is Foreach)
2196 body = ((Foreach) s).Statement;
2197 else if (s is While)
2198 body = ((While) s).Statement;
2199 else if (s is Using)
2200 body = ((Using) s).Statement;
2201 else if (s is Fixed)
2202 body = ((Fixed) s).Statement;
2206 if (body == null || body is EmptyStatement)
2207 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2210 public override bool Resolve (EmitContext ec)
2212 Block prev_block = ec.CurrentBlock;
2215 int errors = Report.Errors;
2217 ec.CurrentBlock = this;
2218 ec.StartFlowBranching (this);
2220 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2223 // This flag is used to notate nested statements as unreachable from the beginning of this block.
2224 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
2225 // from the beginning of the function. The outer Resolve() that detected the unreachability is
2226 // responsible for handling the situation.
2228 for (current_statement = 0; current_statement < statements.Count; current_statement++) {
2229 Statement s = (Statement) statements [current_statement];
2230 // Check possible empty statement (CS0642)
2231 if (RootContext.WarningLevel >= 3 &&
2232 current_statement + 1 < statements.Count &&
2233 statements [current_statement + 1] is Block)
2234 CheckPossibleMistakenEmptyStatement (s);
2237 // Warn if we detect unreachable code.
2240 if (s is EmptyStatement)
2244 ((Block) s).unreachable = true;
2246 if (!unreachable_shown && !(s is LabeledStatement)) {
2247 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2248 unreachable_shown = true;
2253 // Note that we're not using ResolveUnreachable() for unreachable
2254 // statements here. ResolveUnreachable() creates a temporary
2255 // flow branching and kills it afterwards. This leads to problems
2256 // if you have two unreachable statements where the first one
2257 // assigns a variable and the second one tries to access it.
2260 if (!s.Resolve (ec)) {
2262 statements [current_statement] = EmptyStatement.Value;
2266 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2267 statements [current_statement] = EmptyStatement.Value;
2269 num_statements = current_statement + 1;
2271 unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
2272 if (unreachable && s is LabeledStatement)
2273 throw new InternalErrorException ("should not happen");
2276 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2277 ec.CurrentBranching, statements.Count, num_statements);
2282 while (ec.CurrentBranching is FlowBranchingLabeled)
2283 ec.EndFlowBranching ();
2285 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2287 ec.CurrentBlock = prev_block;
2289 // If we're a non-static `struct' constructor which doesn't have an
2290 // initializer, then we must initialize all of the struct's fields.
2291 if ((flags & Flags.IsToplevel) != 0 &&
2292 !Toplevel.IsThisAssigned (ec) &&
2293 !vector.IsUnreachable)
2296 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2297 foreach (LabeledStatement label in labels.Values)
2298 if (!label.HasBeenReferenced)
2299 Report.Warning (164, 2, label.loc,
2300 "This label has not been referenced");
2303 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2305 if (vector.IsUnreachable)
2306 flags |= Flags.HasRet;
2308 if (ok && (errors == Report.Errors)) {
2309 if (RootContext.WarningLevel >= 3)
2310 UsageWarning (vector);
2316 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2318 unreachable_shown = true;
2322 Report.Warning (162, 2, loc, "Unreachable code detected");
2324 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2325 bool ok = Resolve (ec);
2326 ec.KillFlowBranching ();
2331 protected override void DoEmit (EmitContext ec)
2333 for (int ix = 0; ix < num_statements; ix++){
2334 Statement s = (Statement) statements [ix];
2336 // Check whether we are the last statement in a
2339 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2340 ec.IsLastStatement = true;
2342 ec.IsLastStatement = false;
2348 public override void Emit (EmitContext ec)
2350 Block prev_block = ec.CurrentBlock;
2352 ec.CurrentBlock = this;
2354 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2355 bool is_lexical_block = !Implicit && (Parent != null);
2357 if (emit_debug_info) {
2358 if (is_lexical_block)
2361 ec.Mark (StartLocation, true);
2362 if (scope_init != null)
2363 scope_init.EmitStatement (ec);
2365 ec.Mark (EndLocation, true);
2367 if (emit_debug_info) {
2368 if (is_lexical_block)
2371 if (variables != null) {
2372 foreach (DictionaryEntry de in variables) {
2373 string name = (string) de.Key;
2374 LocalInfo vi = (LocalInfo) de.Value;
2376 vi.EmitSymbolInfo (ec, name);
2381 ec.CurrentBlock = prev_block;
2385 // Returns true if we ar ea child of `b'.
2387 public bool IsChildOf (Block b)
2389 Block current = this;
2392 if (current.Parent == b)
2394 current = current.Parent;
2395 } while (current != null);
2399 public override string ToString ()
2401 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2404 protected override void CloneTo (CloneContext clonectx, Statement t)
2406 Block target = (Block) t;
2409 target.Parent = clonectx.LookupBlock (Parent);
2411 target.statements = new ArrayList ();
2412 if (target.children != null){
2413 target.children = new ArrayList ();
2414 foreach (Block b in children){
2415 Block newblock = (Block) b.Clone (clonectx);
2417 target.children.Add (newblock);
2422 foreach (Statement s in statements)
2423 target.statements.Add (s.Clone (clonectx));
2425 if (variables != null){
2426 target.variables = new Hashtable ();
2428 foreach (DictionaryEntry de in variables){
2429 LocalInfo newlocal = ((LocalInfo) de.Value).Clone (clonectx);
2430 target.variables [de.Key] = newlocal;
2431 clonectx.AddVariableMap ((LocalInfo) de.Value, newlocal);
2436 // TODO: labels, switch_block, constants (?), anonymous_children
2442 // A toplevel block contains extra information, the split is done
2443 // only to separate information that would otherwise bloat the more
2444 // lightweight Block.
2446 // In particular, this was introduced when the support for Anonymous
2447 // Methods was implemented.
2449 public class ToplevelBlock : Block {
2451 // Pointer to the host of this anonymous method, or null
2452 // if we are the topmost block
2455 GenericMethod generic;
2456 FlowBranchingToplevel top_level_branching;
2457 AnonymousContainer anonymous_container;
2458 RootScopeInfo root_scope;
2460 public bool HasVarargs {
2461 get { return (flags & Flags.HasVarargs) != 0; }
2462 set { flags |= Flags.HasVarargs; }
2465 public bool IsIterator {
2466 get { return (flags & Flags.IsIterator) != 0; }
2470 // The parameters for the block.
2472 Parameters parameters;
2473 public Parameters Parameters {
2474 get { return parameters; }
2477 public bool CompleteContexts (EmitContext ec)
2479 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this,
2480 container, root_scope);
2482 if (root_scope != null)
2483 root_scope.LinkScopes ();
2485 if ((container == null) && (root_scope != null)) {
2486 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this,
2489 if (root_scope.DefineType () == null)
2491 if (!root_scope.ResolveType ())
2493 if (!root_scope.ResolveMembers ())
2495 if (!root_scope.DefineMembers ())
2502 public GenericMethod GenericMethod {
2503 get { return generic; }
2506 public ToplevelBlock Container {
2507 get { return container != null ? container.Toplevel : null; }
2510 public Block ContainerBlock {
2511 get { return container; }
2514 public AnonymousContainer AnonymousContainer {
2515 get { return anonymous_container; }
2516 set { anonymous_container = value; }
2520 // Parent is only used by anonymous blocks to link back to their
2523 public ToplevelBlock (Block container, Parameters parameters, Location start) :
2524 this (container, (Flags) 0, parameters, start)
2528 public ToplevelBlock (Block container, Parameters parameters, GenericMethod generic,
2530 this (container, parameters, start)
2532 this.generic = generic;
2535 public ToplevelBlock (Parameters parameters, Location start) :
2536 this (null, (Flags) 0, parameters, start)
2540 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2541 this (null, flags, parameters, start)
2545 public ToplevelBlock (Block container, Flags flags, Parameters parameters, Location start) :
2546 base (null, flags | Flags.IsToplevel, start, Location.Null)
2548 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2549 this.container = container;
2552 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2556 public bool CheckError158 (string name, Location loc)
2558 if (AnonymousChildren != null) {
2559 foreach (ToplevelBlock child in AnonymousChildren) {
2560 if (!child.CheckError158 (name, loc))
2565 for (ToplevelBlock c = Container; c != null; c = c.Container) {
2566 if (!c.DoCheckError158 (name, loc))
2570 return DoCheckError158 (name, loc);
2573 bool DoCheckError158 (string name, Location loc)
2575 LabeledStatement s = LookupLabel (name);
2577 Report.SymbolRelatedToPreviousError (s.loc, s.Name);
2578 Error_158 (name, loc);
2585 public RootScopeInfo CreateRootScope (TypeContainer host)
2587 if (root_scope != null)
2590 if (Container == null)
2591 root_scope = new RootScopeInfo (
2592 this, host, generic, StartLocation);
2594 if (scope_info != null)
2595 throw new InternalErrorException ();
2597 scope_info = root_scope;
2601 public void CreateIteratorHost (RootScopeInfo root)
2603 Report.Debug (64, "CREATE ITERATOR HOST", this, root,
2604 container, root_scope);
2606 if ((container != null) || (root_scope != null))
2607 throw new InternalErrorException ();
2609 scope_info = root_scope = root;
2612 public RootScopeInfo RootScope {
2614 if (root_scope != null)
2616 else if (Container != null)
2617 return Container.RootScope;
2623 public FlowBranchingToplevel TopLevelBranching {
2624 get { return top_level_branching; }
2628 // This is used if anonymous methods are used inside an iterator
2629 // (see 2test-22.cs for an example).
2631 // The AnonymousMethod is created while parsing - at a time when we don't
2632 // know yet that we're inside an iterator, so it's `Container' is initially
2633 // null. Later on, when resolving the iterator, we need to move the
2634 // anonymous method into that iterator.
2636 public void ReParent (ToplevelBlock new_parent)
2638 if ((flags & Flags.VariablesInitialized) != 0)
2639 throw new InternalErrorException ("block has already been resolved");
2641 container = new_parent;
2642 Parent = new_parent;
2646 // Returns a `ParameterReference' for the given name, or null if there
2647 // is no such parameter
2649 public ParameterReference GetParameterReference (string name, Location loc)
2654 for (ToplevelBlock t = this; t != null; t = t.Container) {
2655 Parameters pars = t.Parameters;
2656 par = pars.GetParameterByName (name, out idx);
2658 return new ParameterReference (par, this, idx, loc);
2664 // Whether the parameter named `name' is local to this block,
2665 // or false, if the parameter belongs to an encompassing block.
2667 public bool IsLocalParameter (string name)
2669 return Parameters.GetParameterByName (name) != null;
2673 // Whether the `name' is a parameter reference
2675 public bool IsParameterReference (string name)
2677 for (ToplevelBlock t = this; t != null; t = t.Container) {
2678 if (t.IsLocalParameter (name))
2684 LocalInfo this_variable = null;
2687 // Returns the "this" instance variable of this block.
2688 // See AddThisVariable() for more information.
2690 public LocalInfo ThisVariable {
2691 get { return this_variable; }
2696 // This is used by non-static `struct' constructors which do not have an
2697 // initializer - in this case, the constructor must initialize all of the
2698 // struct's fields. To do this, we add a "this" variable and use the flow
2699 // analysis code to ensure that it's been fully initialized before control
2700 // leaves the constructor.
2702 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2704 if (this_variable == null) {
2705 this_variable = new LocalInfo (ds, this, l);
2706 this_variable.Used = true;
2707 this_variable.IsThis = true;
2709 Variables.Add ("this", this_variable);
2712 return this_variable;
2715 public bool IsThisAssigned (EmitContext ec)
2717 return this_variable == null || this_variable.IsThisAssigned (ec);
2720 public bool ResolveMeta (EmitContext ec, Parameters ip)
2722 int errors = Report.Errors;
2724 if (top_level_branching != null)
2730 if (!IsIterator && (container != null) && (parameters != null)) {
2731 foreach (Parameter p in parameters.FixedParameters) {
2732 if (!CheckError136_InParents (p.Name, loc))
2737 ResolveMeta (this, ec, ip);
2739 top_level_branching = ec.StartFlowBranching (this);
2741 return Report.Errors == errors;
2744 public override void EmitMeta (EmitContext ec)
2747 parameters.ResolveVariable (this);
2750 public void MakeIterator (Iterator iterator)
2752 flags |= Flags.IsIterator;
2754 Block block = new Block (this);
2755 foreach (Statement stmt in statements)
2756 block.AddStatement (stmt);
2757 statements = new ArrayList ();
2758 statements.Add (new MoveNextStatement (iterator, block));
2761 protected class MoveNextStatement : Statement {
2765 public MoveNextStatement (Iterator iterator, Block block)
2767 this.iterator = iterator;
2769 this.loc = iterator.Location;
2772 public override bool Resolve (EmitContext ec)
2774 return block.Resolve (ec);
2777 protected override void DoEmit (EmitContext ec)
2779 iterator.EmitMoveNext (ec, block);
2783 public override string ToString ()
2785 return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2786 root_scope, anonymous_container != null ?
2787 anonymous_container.Scope : null);
2791 public class SwitchLabel {
2798 Label il_label_code;
2799 bool il_label_code_set;
2801 public static readonly object NullStringCase = new object ();
2804 // if expr == null, then it is the default case.
2806 public SwitchLabel (Expression expr, Location l)
2812 public Expression Label {
2818 public object Converted {
2824 public Label GetILLabel (EmitContext ec)
2827 il_label = ec.ig.DefineLabel ();
2828 il_label_set = true;
2833 public Label GetILLabelCode (EmitContext ec)
2835 if (!il_label_code_set){
2836 il_label_code = ec.ig.DefineLabel ();
2837 il_label_code_set = true;
2839 return il_label_code;
2843 // Resolves the expression, reduces it to a literal if possible
2844 // and then converts it to the requested type.
2846 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2848 Expression e = label.Resolve (ec);
2853 Constant c = e as Constant;
2855 Report.Error (150, loc, "A constant value is expected");
2859 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2860 converted = NullStringCase;
2864 if (allow_nullable && c.GetValue () == null) {
2865 converted = NullStringCase;
2869 c = c.ImplicitConversionRequired (required_type, loc);
2873 converted = c.GetValue ();
2877 public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
2880 if (converted == null)
2882 else if (converted == NullStringCase)
2884 else if (TypeManager.IsEnumType (switchType))
2885 label = TypeManager.CSharpEnumValue (switchType, converted);
2887 label = converted.ToString ();
2889 Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
2890 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2893 public SwitchLabel Clone (CloneContext clonectx)
2895 return new SwitchLabel (label.Clone (clonectx), loc);
2899 public class SwitchSection {
2900 // An array of SwitchLabels.
2901 public readonly ArrayList Labels;
2902 public readonly Block Block;
2904 public SwitchSection (ArrayList labels, Block block)
2910 public SwitchSection Clone (CloneContext clonectx)
2912 ArrayList cloned_labels = new ArrayList ();
2914 foreach (SwitchLabel sl in cloned_labels)
2915 cloned_labels.Add (sl.Clone (clonectx));
2917 return new SwitchSection (cloned_labels, clonectx.LookupBlock (Block));
2921 public class Switch : Statement {
2922 public ArrayList Sections;
2923 public Expression Expr;
2926 /// Maps constants whose type type SwitchType to their SwitchLabels.
2928 public IDictionary Elements;
2931 /// The governing switch type
2933 public Type SwitchType;
2938 Label default_target;
2940 Expression new_expr;
2942 SwitchSection constant_section;
2943 SwitchSection default_section;
2947 // Nullable Types support for GMCS.
2949 Nullable.Unwrap unwrap;
2951 protected bool HaveUnwrap {
2952 get { return unwrap != null; }
2955 protected bool HaveUnwrap {
2956 get { return false; }
2961 // The types allowed to be implicitly cast from
2962 // on the governing type
2964 static Type [] allowed_types;
2966 public Switch (Expression e, ArrayList sects, Location l)
2973 public bool GotDefault {
2975 return default_section != null;
2979 public Label DefaultTarget {
2981 return default_target;
2986 // Determines the governing type for a switch. The returned
2987 // expression might be the expression from the switch, or an
2988 // expression that includes any potential conversions to the
2989 // integral types or to string.
2991 Expression SwitchGoverningType (EmitContext ec, Expression expr)
2993 Type t = TypeManager.DropGenericTypeArguments (expr.Type);
2995 if (t == TypeManager.byte_type ||
2996 t == TypeManager.sbyte_type ||
2997 t == TypeManager.ushort_type ||
2998 t == TypeManager.short_type ||
2999 t == TypeManager.uint32_type ||
3000 t == TypeManager.int32_type ||
3001 t == TypeManager.uint64_type ||
3002 t == TypeManager.int64_type ||
3003 t == TypeManager.char_type ||
3004 t == TypeManager.string_type ||
3005 t == TypeManager.bool_type ||
3006 t.IsSubclassOf (TypeManager.enum_type))
3009 if (allowed_types == null){
3010 allowed_types = new Type [] {
3011 TypeManager.sbyte_type,
3012 TypeManager.byte_type,
3013 TypeManager.short_type,
3014 TypeManager.ushort_type,
3015 TypeManager.int32_type,
3016 TypeManager.uint32_type,
3017 TypeManager.int64_type,
3018 TypeManager.uint64_type,
3019 TypeManager.char_type,
3020 TypeManager.string_type,
3021 TypeManager.bool_type
3026 // Try to find a *user* defined implicit conversion.
3028 // If there is no implicit conversion, or if there are multiple
3029 // conversions, we have to report an error
3031 Expression converted = null;
3032 foreach (Type tt in allowed_types){
3035 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
3040 // Ignore over-worked ImplicitUserConversions that do
3041 // an implicit conversion in addition to the user conversion.
3043 if (!(e is UserCast))
3046 if (converted != null){
3047 Report.ExtraInformation (
3049 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
3050 TypeManager.CSharpName (expr.Type)));
3060 // Performs the basic sanity checks on the switch statement
3061 // (looks for duplicate keys and non-constant expressions).
3063 // It also returns a hashtable with the keys that we will later
3064 // use to compute the switch tables
3066 bool CheckSwitch (EmitContext ec)
3069 Elements = Sections.Count > 10 ?
3070 (IDictionary)new Hashtable () :
3071 (IDictionary)new ListDictionary ();
3073 foreach (SwitchSection ss in Sections){
3074 foreach (SwitchLabel sl in ss.Labels){
3075 if (sl.Label == null){
3076 if (default_section != null){
3077 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
3080 default_section = ss;
3084 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
3089 object key = sl.Converted;
3091 Elements.Add (key, sl);
3092 } catch (ArgumentException) {
3093 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
3101 void EmitObjectInteger (ILGenerator ig, object k)
3104 IntConstant.EmitInt (ig, (int) k);
3105 else if (k is Constant) {
3106 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3109 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3112 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3114 IntConstant.EmitInt (ig, (int) (long) k);
3115 ig.Emit (OpCodes.Conv_I8);
3118 LongConstant.EmitLong (ig, (long) k);
3120 else if (k is ulong)
3122 ulong ul = (ulong) k;
3125 IntConstant.EmitInt (ig, unchecked ((int) ul));
3126 ig.Emit (OpCodes.Conv_U8);
3130 LongConstant.EmitLong (ig, unchecked ((long) ul));
3134 IntConstant.EmitInt (ig, (int) ((char) k));
3135 else if (k is sbyte)
3136 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3138 IntConstant.EmitInt (ig, (int) ((byte) k));
3139 else if (k is short)
3140 IntConstant.EmitInt (ig, (int) ((short) k));
3141 else if (k is ushort)
3142 IntConstant.EmitInt (ig, (int) ((ushort) k));
3144 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3146 throw new Exception ("Unhandled case");
3149 // structure used to hold blocks of keys while calculating table switch
3150 class KeyBlock : IComparable
3152 public KeyBlock (long _nFirst)
3154 nFirst = nLast = _nFirst;
3158 public ArrayList rgKeys = null;
3159 // how many items are in the bucket
3160 public int Size = 1;
3163 get { return (int) (nLast - nFirst + 1); }
3165 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3167 return kbLast.nLast - kbFirst.nFirst + 1;
3169 public int CompareTo (object obj)
3171 KeyBlock kb = (KeyBlock) obj;
3172 int nLength = Length;
3173 int nLengthOther = kb.Length;
3174 if (nLengthOther == nLength)
3175 return (int) (kb.nFirst - nFirst);
3176 return nLength - nLengthOther;
3181 /// This method emits code for a lookup-based switch statement (non-string)
3182 /// Basically it groups the cases into blocks that are at least half full,
3183 /// and then spits out individual lookup opcodes for each block.
3184 /// It emits the longest blocks first, and short blocks are just
3185 /// handled with direct compares.
3187 /// <param name="ec"></param>
3188 /// <param name="val"></param>
3189 /// <returns></returns>
3190 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3192 int cElements = Elements.Count;
3193 object [] rgKeys = new object [cElements];
3194 Elements.Keys.CopyTo (rgKeys, 0);
3195 Array.Sort (rgKeys);
3197 // initialize the block list with one element per key
3198 ArrayList rgKeyBlocks = new ArrayList ();
3199 foreach (object key in rgKeys)
3200 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3203 // iteratively merge the blocks while they are at least half full
3204 // there's probably a really cool way to do this with a tree...
3205 while (rgKeyBlocks.Count > 1)
3207 ArrayList rgKeyBlocksNew = new ArrayList ();
3208 kbCurr = (KeyBlock) rgKeyBlocks [0];
3209 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3211 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3212 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3215 kbCurr.nLast = kb.nLast;
3216 kbCurr.Size += kb.Size;
3220 // start a new block
3221 rgKeyBlocksNew.Add (kbCurr);
3225 rgKeyBlocksNew.Add (kbCurr);
3226 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3228 rgKeyBlocks = rgKeyBlocksNew;
3231 // initialize the key lists
3232 foreach (KeyBlock kb in rgKeyBlocks)
3233 kb.rgKeys = new ArrayList ();
3235 // fill the key lists
3237 if (rgKeyBlocks.Count > 0) {
3238 kbCurr = (KeyBlock) rgKeyBlocks [0];
3239 foreach (object key in rgKeys)
3241 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3242 System.Convert.ToInt64 (key) > kbCurr.nLast;
3244 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3245 kbCurr.rgKeys.Add (key);
3249 // sort the blocks so we can tackle the largest ones first
3250 rgKeyBlocks.Sort ();
3252 // okay now we can start...
3253 ILGenerator ig = ec.ig;
3254 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3255 Label lblDefault = ig.DefineLabel ();
3257 Type typeKeys = null;
3258 if (rgKeys.Length > 0)
3259 typeKeys = rgKeys [0].GetType (); // used for conversions
3263 if (TypeManager.IsEnumType (SwitchType))
3264 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3266 compare_type = SwitchType;
3268 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3270 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3271 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3274 foreach (object key in kb.rgKeys)
3276 ig.Emit (OpCodes.Ldloc, val);
3277 EmitObjectInteger (ig, key);
3278 SwitchLabel sl = (SwitchLabel) Elements [key];
3279 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3284 // TODO: if all the keys in the block are the same and there are
3285 // no gaps/defaults then just use a range-check.
3286 if (compare_type == TypeManager.int64_type ||
3287 compare_type == TypeManager.uint64_type)
3289 // TODO: optimize constant/I4 cases
3291 // check block range (could be > 2^31)
3292 ig.Emit (OpCodes.Ldloc, val);
3293 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3294 ig.Emit (OpCodes.Blt, lblDefault);
3295 ig.Emit (OpCodes.Ldloc, val);
3296 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3297 ig.Emit (OpCodes.Bgt, lblDefault);
3300 ig.Emit (OpCodes.Ldloc, val);
3303 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3304 ig.Emit (OpCodes.Sub);
3306 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3311 ig.Emit (OpCodes.Ldloc, val);
3312 int nFirst = (int) kb.nFirst;
3315 IntConstant.EmitInt (ig, nFirst);
3316 ig.Emit (OpCodes.Sub);
3318 else if (nFirst < 0)
3320 IntConstant.EmitInt (ig, -nFirst);
3321 ig.Emit (OpCodes.Add);
3325 // first, build the list of labels for the switch
3327 int cJumps = kb.Length;
3328 Label [] rgLabels = new Label [cJumps];
3329 for (int iJump = 0; iJump < cJumps; iJump++)
3331 object key = kb.rgKeys [iKey];
3332 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3334 SwitchLabel sl = (SwitchLabel) Elements [key];
3335 rgLabels [iJump] = sl.GetILLabel (ec);
3339 rgLabels [iJump] = lblDefault;
3341 // emit the switch opcode
3342 ig.Emit (OpCodes.Switch, rgLabels);
3345 // mark the default for this block
3347 ig.MarkLabel (lblDefault);
3350 // TODO: find the default case and emit it here,
3351 // to prevent having to do the following jump.
3352 // make sure to mark other labels in the default section
3354 // the last default just goes to the end
3355 ig.Emit (OpCodes.Br, lblDefault);
3357 // now emit the code for the sections
3358 bool fFoundDefault = false;
3359 bool fFoundNull = false;
3360 foreach (SwitchSection ss in Sections)
3362 foreach (SwitchLabel sl in ss.Labels)
3363 if (sl.Converted == SwitchLabel.NullStringCase)
3367 foreach (SwitchSection ss in Sections)
3369 foreach (SwitchLabel sl in ss.Labels)
3371 ig.MarkLabel (sl.GetILLabel (ec));
3372 ig.MarkLabel (sl.GetILLabelCode (ec));
3373 if (sl.Converted == SwitchLabel.NullStringCase)
3374 ig.MarkLabel (null_target);
3375 else if (sl.Label == null) {
3376 ig.MarkLabel (lblDefault);
3377 fFoundDefault = true;
3379 ig.MarkLabel (null_target);
3385 if (!fFoundDefault) {
3386 ig.MarkLabel (lblDefault);
3388 ig.MarkLabel (lblEnd);
3391 // This simple emit switch works, but does not take advantage of the
3393 // TODO: remove non-string logic from here
3394 // TODO: binary search strings?
3396 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3398 ILGenerator ig = ec.ig;
3399 Label end_of_switch = ig.DefineLabel ();
3400 Label next_test = ig.DefineLabel ();
3401 bool first_test = true;
3402 bool pending_goto_end = false;
3403 bool null_marked = false;
3405 int section_count = Sections.Count;
3407 // TODO: implement switch optimization for string by using Hashtable
3408 //if (SwitchType == TypeManager.string_type && section_count > 7)
3409 // Console.WriteLine ("Switch optimization possible " + loc);
3411 ig.Emit (OpCodes.Ldloc, val);
3413 if (Elements.Contains (SwitchLabel.NullStringCase)){
3414 ig.Emit (OpCodes.Brfalse, null_target);
3416 ig.Emit (OpCodes.Brfalse, default_target);
3418 ig.Emit (OpCodes.Ldloc, val);
3419 ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
3420 ig.Emit (OpCodes.Stloc, val);
3422 for (int section = 0; section < section_count; section++){
3423 SwitchSection ss = (SwitchSection) Sections [section];
3425 if (ss == default_section)
3428 Label sec_begin = ig.DefineLabel ();
3430 ig.Emit (OpCodes.Nop);
3432 if (pending_goto_end)
3433 ig.Emit (OpCodes.Br, end_of_switch);
3435 int label_count = ss.Labels.Count;
3437 for (int label = 0; label < label_count; label++){
3438 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3439 ig.MarkLabel (sl.GetILLabel (ec));
3442 ig.MarkLabel (next_test);
3443 next_test = ig.DefineLabel ();
3446 // If we are the default target
3448 if (sl.Label != null){
3449 object lit = sl.Converted;
3451 if (lit == SwitchLabel.NullStringCase){
3453 if (label + 1 == label_count)
3454 ig.Emit (OpCodes.Br, next_test);
3458 ig.Emit (OpCodes.Ldloc, val);
3459 ig.Emit (OpCodes.Ldstr, (string)lit);
3460 if (label_count == 1)
3461 ig.Emit (OpCodes.Bne_Un, next_test);
3463 if (label+1 == label_count)
3464 ig.Emit (OpCodes.Bne_Un, next_test);
3466 ig.Emit (OpCodes.Beq, sec_begin);
3471 ig.MarkLabel (null_target);
3474 ig.MarkLabel (sec_begin);
3475 foreach (SwitchLabel sl in ss.Labels)
3476 ig.MarkLabel (sl.GetILLabelCode (ec));
3479 pending_goto_end = !ss.Block.HasRet;
3482 ig.MarkLabel (next_test);
3483 ig.MarkLabel (default_target);
3485 ig.MarkLabel (null_target);
3486 if (default_section != null)
3487 default_section.Block.Emit (ec);
3488 ig.MarkLabel (end_of_switch);
3491 SwitchSection FindSection (SwitchLabel label)
3493 foreach (SwitchSection ss in Sections){
3494 foreach (SwitchLabel sl in ss.Labels){
3503 public override bool Resolve (EmitContext ec)
3505 Expr = Expr.Resolve (ec);
3509 new_expr = SwitchGoverningType (ec, Expr);
3512 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3513 unwrap = Nullable.Unwrap.Create (Expr, ec);
3517 new_expr = SwitchGoverningType (ec, unwrap);
3521 if (new_expr == null){
3522 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3527 SwitchType = new_expr.Type;
3529 if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
3530 Report.FeatureIsNotISO1 (loc, "switch expression of boolean type");
3534 if (!CheckSwitch (ec))
3538 Elements.Remove (SwitchLabel.NullStringCase);
3540 Switch old_switch = ec.Switch;
3542 ec.Switch.SwitchType = SwitchType;
3544 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3545 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3547 is_constant = new_expr is Constant;
3549 object key = ((Constant) new_expr).GetValue ();
3550 SwitchLabel label = (SwitchLabel) Elements [key];
3552 constant_section = FindSection (label);
3553 if (constant_section == null)
3554 constant_section = default_section;
3558 foreach (SwitchSection ss in Sections){
3560 ec.CurrentBranching.CreateSibling (
3561 null, FlowBranching.SiblingType.SwitchSection);
3565 if (is_constant && (ss != constant_section)) {
3566 // If we're a constant switch, we're only emitting
3567 // one single section - mark all the others as
3569 ec.CurrentBranching.CurrentUsageVector.Goto ();
3570 if (!ss.Block.ResolveUnreachable (ec, true))
3573 if (!ss.Block.Resolve (ec))
3578 if (default_section == null)
3579 ec.CurrentBranching.CreateSibling (
3580 null, FlowBranching.SiblingType.SwitchSection);
3582 ec.EndFlowBranching ();
3583 ec.Switch = old_switch;
3585 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
3590 protected override void DoEmit (EmitContext ec)
3592 ILGenerator ig = ec.ig;
3594 default_target = ig.DefineLabel ();
3595 null_target = ig.DefineLabel ();
3597 // Store variable for comparission purposes
3600 value = ig.DeclareLocal (SwitchType);
3602 unwrap.EmitCheck (ec);
3603 ig.Emit (OpCodes.Brfalse, null_target);
3605 ig.Emit (OpCodes.Stloc, value);
3607 } else if (!is_constant) {
3608 value = ig.DeclareLocal (SwitchType);
3610 ig.Emit (OpCodes.Stloc, value);
3615 // Setup the codegen context
3617 Label old_end = ec.LoopEnd;
3618 Switch old_switch = ec.Switch;
3620 ec.LoopEnd = ig.DefineLabel ();
3625 if (constant_section != null)
3626 constant_section.Block.Emit (ec);
3627 } else if (SwitchType == TypeManager.string_type)
3628 SimpleSwitchEmit (ec, value);
3630 TableSwitchEmit (ec, value);
3632 // Restore context state.
3633 ig.MarkLabel (ec.LoopEnd);
3636 // Restore the previous context
3638 ec.LoopEnd = old_end;
3639 ec.Switch = old_switch;
3642 protected override void CloneTo (CloneContext clonectx, Statement t)
3644 Switch target = (Switch) t;
3646 target.Expr = Expr.Clone (clonectx);
3647 target.Sections = new ArrayList ();
3648 foreach (SwitchSection ss in Sections){
3649 target.Sections.Add (ss.Clone (clonectx));
3654 public abstract class ExceptionStatement : Statement
3656 public abstract void EmitFinally (EmitContext ec);
3658 protected bool emit_finally = true;
3659 ArrayList parent_vectors;
3661 protected void DoEmitFinally (EmitContext ec)
3664 ec.ig.BeginFinallyBlock ();
3665 else if (ec.InIterator)
3666 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3670 protected void ResolveFinally (FlowBranchingException branching)
3672 emit_finally = branching.EmitFinally;
3674 branching.Parent.StealFinallyClauses (ref parent_vectors);
3678 public class Lock : ExceptionStatement {
3680 public Statement Statement;
3681 TemporaryVariable temp;
3683 public Lock (Expression expr, Statement stmt, Location l)
3690 public override bool Resolve (EmitContext ec)
3692 expr = expr.Resolve (ec);
3696 if (expr.Type.IsValueType){
3697 Report.Error (185, loc,
3698 "`{0}' is not a reference type as required by the lock statement",
3699 TypeManager.CSharpName (expr.Type));
3703 FlowBranchingException branching = ec.StartFlowBranching (this);
3704 bool ok = Statement.Resolve (ec);
3706 ResolveFinally (branching);
3708 ec.EndFlowBranching ();
3710 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
3711 // So, ensure there's some IL code after the finally block.
3712 ec.NeedReturnLabel ();
3714 // Avoid creating libraries that reference the internal
3717 if (t == TypeManager.null_type)
3718 t = TypeManager.object_type;
3720 temp = new TemporaryVariable (t, loc);
3726 protected override void DoEmit (EmitContext ec)
3728 ILGenerator ig = ec.ig;
3730 temp.Store (ec, expr);
3732 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3736 ig.BeginExceptionBlock ();
3737 Statement.Emit (ec);
3742 ig.EndExceptionBlock ();
3745 public override void EmitFinally (EmitContext ec)
3748 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3751 protected override void CloneTo (CloneContext clonectx, Statement t)
3753 Lock target = (Lock) t;
3755 target.expr = expr.Clone (clonectx);
3756 target.Statement = Statement.Clone (clonectx);
3760 public class Unchecked : Statement {
3763 public Unchecked (Block b)
3769 public override bool Resolve (EmitContext ec)
3771 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3772 return Block.Resolve (ec);
3775 protected override void DoEmit (EmitContext ec)
3777 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3781 protected override void CloneTo (CloneContext clonectx, Statement t)
3783 Unchecked target = (Unchecked) t;
3785 target.Block = clonectx.LookupBlock (Block);
3789 public class Checked : Statement {
3792 public Checked (Block b)
3795 b.Unchecked = false;
3798 public override bool Resolve (EmitContext ec)
3800 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3801 return Block.Resolve (ec);
3804 protected override void DoEmit (EmitContext ec)
3806 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3810 protected override void CloneTo (CloneContext clonectx, Statement t)
3812 Checked target = (Checked) t;
3814 target.Block = clonectx.LookupBlock (Block);
3818 public class Unsafe : Statement {
3821 public Unsafe (Block b)
3824 Block.Unsafe = true;
3827 public override bool Resolve (EmitContext ec)
3829 using (ec.With (EmitContext.Flags.InUnsafe, true))
3830 return Block.Resolve (ec);
3833 protected override void DoEmit (EmitContext ec)
3835 using (ec.With (EmitContext.Flags.InUnsafe, true))
3838 protected override void CloneTo (CloneContext clonectx, Statement t)
3840 Unsafe target = (Unsafe) t;
3842 target.Block = clonectx.LookupBlock (Block);
3849 public class Fixed : Statement {
3851 ArrayList declarators;
3852 Statement statement;
3857 abstract class Emitter
3859 protected LocalInfo vi;
3860 protected Expression converted;
3862 protected Emitter (Expression expr, LocalInfo li)
3868 public abstract void Emit (EmitContext ec);
3869 public abstract void EmitExit (EmitContext ec);
3872 class ExpressionEmitter : Emitter {
3873 public ExpressionEmitter (Expression converted, LocalInfo li) :
3874 base (converted, li)
3878 public override void Emit (EmitContext ec) {
3880 // Store pointer in pinned location
3882 converted.Emit (ec);
3883 vi.Variable.EmitAssign (ec);
3886 public override void EmitExit (EmitContext ec)
3888 ec.ig.Emit (OpCodes.Ldc_I4_0);
3889 ec.ig.Emit (OpCodes.Conv_U);
3890 vi.Variable.EmitAssign (ec);
3894 class StringEmitter : Emitter {
3895 LocalBuilder pinned_string;
3898 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3904 public override void Emit (EmitContext ec)
3906 ILGenerator ig = ec.ig;
3907 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3909 converted.Emit (ec);
3910 ig.Emit (OpCodes.Stloc, pinned_string);
3912 Expression sptr = new StringPtr (pinned_string, loc);
3913 converted = Convert.ImplicitConversionRequired (
3914 ec, sptr, vi.VariableType, loc);
3916 if (converted == null)
3919 converted.Emit (ec);
3920 vi.Variable.EmitAssign (ec);
3923 public override void EmitExit (EmitContext ec)
3925 ec.ig.Emit (OpCodes.Ldnull);
3926 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3930 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3933 declarators = decls;
3938 public Statement Statement {
3939 get { return statement; }
3942 public override bool Resolve (EmitContext ec)
3945 Expression.UnsafeError (loc);
3949 TypeExpr texpr = null;
3950 if (type is VarExpr) {
3951 Unary u = ((Pair) declarators[0]).Second as Unary;
3955 Expression e = u.Expr.Resolve (ec);
3956 if (e == null || e.Type == null)
3959 Type t = TypeManager.GetPointerType (e.Type);
3960 texpr = new TypeExpression (t, loc);
3963 texpr = type.ResolveAsTypeTerminal (ec, false);
3968 expr_type = texpr.Type;
3970 data = new Emitter [declarators.Count];
3972 if (!expr_type.IsPointer){
3973 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
3978 foreach (Pair p in declarators){
3979 LocalInfo vi = (LocalInfo) p.First;
3980 Expression e = (Expression) p.Second;
3982 if (type is VarExpr)
3983 vi.VariableType = expr_type;
3985 vi.VariableInfo.SetAssigned (ec);
3986 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
3989 // The rules for the possible declarators are pretty wise,
3990 // but the production on the grammar is more concise.
3992 // So we have to enforce these rules here.
3994 // We do not resolve before doing the case 1 test,
3995 // because the grammar is explicit in that the token &
3996 // is present, so we need to test for this particular case.
4000 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
4005 // Case 1: & object.
4007 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4008 Expression child = ((Unary) e).Expr;
4010 if (child is ParameterReference || child is LocalVariableReference){
4013 "No need to use fixed statement for parameters or " +
4014 "local variable declarations (address is already " +
4019 ec.InFixedInitializer = true;
4021 ec.InFixedInitializer = false;
4025 child = ((Unary) e).Expr;
4027 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4030 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
4031 e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
4035 data [i] = new ExpressionEmitter (e, vi);
4041 ec.InFixedInitializer = true;
4043 ec.InFixedInitializer = false;
4050 if (e.Type.IsArray){
4051 Type array_type = TypeManager.GetElementType (e.Type);
4054 // Provided that array_type is unmanaged,
4056 if (!TypeManager.VerifyUnManaged (array_type, loc))
4060 // and T* is implicitly convertible to the
4061 // pointer type given in the fixed statement.
4063 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
4065 Expression converted = Convert.ImplicitConversionRequired (
4066 ec, array_ptr, vi.VariableType, loc);
4067 if (converted == null)
4070 data [i] = new ExpressionEmitter (converted, vi);
4079 if (e.Type == TypeManager.string_type){
4080 data [i] = new StringEmitter (e, vi, loc);
4085 // Case 4: fixed buffer
4086 FieldExpr fe = e as FieldExpr;
4088 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
4090 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
4092 Expression converted = Convert.ImplicitConversionRequired (
4093 ec, fixed_buffer_ptr, vi.VariableType, loc);
4094 if (converted == null)
4097 data [i] = new ExpressionEmitter (converted, vi);
4105 // For other cases, flag a `this is already fixed expression'
4107 if (e is LocalVariableReference || e is ParameterReference ||
4108 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
4110 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
4114 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
4118 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
4119 bool ok = statement.Resolve (ec);
4120 bool flow_unreachable = ec.EndFlowBranching ();
4121 has_ret = flow_unreachable;
4126 protected override void DoEmit (EmitContext ec)
4128 for (int i = 0; i < data.Length; i++) {
4132 statement.Emit (ec);
4138 // Clear the pinned variable
4140 for (int i = 0; i < data.Length; i++) {
4141 data [i].EmitExit (ec);
4145 protected override void CloneTo (CloneContext clonectx, Statement t)
4147 Fixed target = (Fixed) t;
4149 target.type = type.Clone (clonectx);
4150 target.declarators = new ArrayList ();
4151 foreach (LocalInfo var in declarators)
4152 target.declarators.Add (clonectx.LookupVariable (var));
4153 target.statement = statement.Clone (clonectx);
4157 public class Catch : Statement {
4158 public readonly string Name;
4160 public Block VarBlock;
4162 Expression type_expr;
4165 public Catch (Expression type, string name, Block block, Block var_block, Location l)
4170 VarBlock = var_block;
4174 public Type CatchType {
4180 public bool IsGeneral {
4182 return type_expr == null;
4186 protected override void DoEmit(EmitContext ec)
4188 ILGenerator ig = ec.ig;
4190 if (CatchType != null)
4191 ig.BeginCatchBlock (CatchType);
4193 ig.BeginCatchBlock (TypeManager.object_type);
4195 if (VarBlock != null)
4199 LocalInfo vi = Block.GetLocalInfo (Name);
4201 throw new Exception ("Variable does not exist in this block");
4203 if (vi.Variable.NeedsTemporary) {
4204 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
4205 ig.Emit (OpCodes.Stloc, e);
4207 vi.Variable.EmitInstance (ec);
4208 ig.Emit (OpCodes.Ldloc, e);
4209 vi.Variable.EmitAssign (ec);
4211 vi.Variable.EmitAssign (ec);
4213 ig.Emit (OpCodes.Pop);
4218 public override bool Resolve (EmitContext ec)
4220 using (ec.With (EmitContext.Flags.InCatch, true)) {
4221 if (type_expr != null) {
4222 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
4228 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4229 Error (155, "The type caught or thrown must be derived from System.Exception");
4235 if (!Block.Resolve (ec))
4238 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4239 // emit the "unused variable" warnings.
4240 if (VarBlock != null)
4241 return VarBlock.Resolve (ec);
4247 protected override void CloneTo (CloneContext clonectx, Statement t)
4249 Catch target = (Catch) t;
4251 target.type_expr = type_expr.Clone (clonectx);
4252 target.Block = clonectx.LookupBlock (Block);
4253 target.VarBlock = clonectx.LookupBlock (VarBlock);
4257 public class Try : ExceptionStatement {
4258 public Block Fini, Block;
4259 public ArrayList Specific;
4260 public Catch General;
4262 bool need_exc_block;
4265 // specific, general and fini might all be null.
4267 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4269 if (specific == null && general == null){
4270 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4274 this.Specific = specific;
4275 this.General = general;
4280 public override bool Resolve (EmitContext ec)
4284 FlowBranchingException branching = ec.StartFlowBranching (this);
4286 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4288 if (!Block.Resolve (ec))
4291 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4293 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4295 Type[] prevCatches = new Type [Specific.Count];
4297 foreach (Catch c in Specific){
4298 ec.CurrentBranching.CreateSibling (
4299 c.Block, FlowBranching.SiblingType.Catch);
4301 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4303 if (c.Name != null) {
4304 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4306 throw new Exception ();
4308 vi.VariableInfo = null;
4311 if (!c.Resolve (ec))
4314 Type resolvedType = c.CatchType;
4315 for (int ii = 0; ii < last_index; ++ii) {
4316 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4317 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4322 prevCatches [last_index++] = resolvedType;
4323 need_exc_block = true;
4326 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4328 if (General != null){
4329 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4330 foreach (Catch c in Specific){
4331 if (c.CatchType == TypeManager.exception_type) {
4332 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'");
4337 ec.CurrentBranching.CreateSibling (
4338 General.Block, FlowBranching.SiblingType.Catch);
4340 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4342 if (!General.Resolve (ec))
4345 need_exc_block = true;
4348 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4352 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4354 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4355 using (ec.With (EmitContext.Flags.InFinally, true)) {
4356 if (!Fini.Resolve (ec))
4361 need_exc_block = true;
4364 if (ec.InIterator) {
4365 ResolveFinally (branching);
4366 need_exc_block |= emit_finally;
4368 emit_finally = Fini != null;
4370 ec.EndFlowBranching ();
4372 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4373 // So, ensure there's some IL code after the finally block.
4374 ec.NeedReturnLabel ();
4376 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4378 Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
4383 protected override void DoEmit (EmitContext ec)
4385 ILGenerator ig = ec.ig;
4388 ig.BeginExceptionBlock ();
4391 foreach (Catch c in Specific)
4394 if (General != null)
4399 ig.EndExceptionBlock ();
4402 public override void EmitFinally (EmitContext ec)
4408 public bool HasCatch
4411 return General != null || Specific.Count > 0;
4415 protected override void CloneTo (CloneContext clonectx, Statement t)
4417 Try target = (Try) t;
4419 target.Block = clonectx.LookupBlock (Block);
4421 target.Fini = clonectx.LookupBlock (Fini);
4422 if (General != null)
4423 target.General = (Catch) General.Clone (clonectx);
4424 if (Specific != null){
4425 target.Specific = new ArrayList ();
4426 foreach (Catch c in Specific)
4427 target.Specific.Add (c.Clone (clonectx));
4432 public class Using : ExceptionStatement {
4433 object expression_or_block;
4434 public Statement Statement;
4438 Expression [] resolved_vars;
4439 Expression [] converted_vars;
4440 ExpressionStatement [] assign;
4441 TemporaryVariable local_copy;
4443 public Using (object expression_or_block, Statement stmt, Location l)
4445 this.expression_or_block = expression_or_block;
4451 // Resolves for the case of using using a local variable declaration.
4453 bool ResolveLocalVariableDecls (EmitContext ec)
4457 TypeExpr texpr = null;
4459 if (expr is VarExpr) {
4460 Expression e = ((Expression)((DictionaryEntry)var_list[0]).Value).Resolve (ec);
4461 if (e == null || e.Type == null)
4463 texpr = new TypeExpression (e.Type, loc);
4466 texpr = expr.ResolveAsTypeTerminal (ec, false);
4471 expr_type = texpr.Type;
4474 // The type must be an IDisposable or an implicit conversion
4477 converted_vars = new Expression [var_list.Count];
4478 resolved_vars = new Expression [var_list.Count];
4479 assign = new ExpressionStatement [var_list.Count];
4481 bool need_conv = !TypeManager.ImplementsInterface (
4482 expr_type, TypeManager.idisposable_type);
4484 foreach (DictionaryEntry e in var_list){
4485 Expression var = (Expression) e.Key;
4487 if (expr is VarExpr) {
4488 LocalVariableReference l = var as LocalVariableReference;
4489 ((LocalInfo)l.Block.Variables[l.Name]).VariableType = expr_type;
4490 ((VarExpr)expr).Handled = true;
4493 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
4497 resolved_vars [i] = var;
4504 converted_vars [i] = Convert.ImplicitConversion (
4505 ec, var, TypeManager.idisposable_type, loc);
4507 if (converted_vars [i] == null) {
4508 Error_IsNotConvertibleToIDisposable ();
4516 foreach (DictionaryEntry e in var_list){
4517 Expression var = resolved_vars [i];
4518 Expression new_expr = (Expression) e.Value;
4521 a = new Assign (var, new_expr, loc);
4527 converted_vars [i] = var;
4528 assign [i] = (ExpressionStatement) a;
4535 void Error_IsNotConvertibleToIDisposable ()
4537 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4538 TypeManager.CSharpName (expr_type));
4541 bool ResolveExpression (EmitContext ec)
4543 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4544 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4545 Error_IsNotConvertibleToIDisposable ();
4550 local_copy = new TemporaryVariable (expr_type, loc);
4551 local_copy.Resolve (ec);
4557 // Emits the code for the case of using using a local variable declaration.
4559 void EmitLocalVariableDecls (EmitContext ec)
4561 ILGenerator ig = ec.ig;
4564 for (i = 0; i < assign.Length; i++) {
4565 assign [i].EmitStatement (ec);
4568 ig.BeginExceptionBlock ();
4570 Statement.Emit (ec);
4572 var_list.Reverse ();
4577 void EmitLocalVariableDeclFinally (EmitContext ec)
4579 ILGenerator ig = ec.ig;
4581 int i = assign.Length;
4582 for (int ii = 0; ii < var_list.Count; ++ii){
4583 Expression var = resolved_vars [--i];
4584 Label skip = ig.DefineLabel ();
4587 ig.BeginFinallyBlock ();
4589 if (!var.Type.IsValueType) {
4591 ig.Emit (OpCodes.Brfalse, skip);
4592 converted_vars [i].Emit (ec);
4593 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4595 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4597 if (!(ml is MethodGroupExpr)) {
4599 ig.Emit (OpCodes.Box, var.Type);
4600 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4602 MethodInfo mi = null;
4604 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4605 if (TypeManager.GetParameterData (mk).Count == 0) {
4612 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4616 IMemoryLocation mloc = (IMemoryLocation) var;
4618 mloc.AddressOf (ec, AddressOp.Load);
4619 ig.Emit (OpCodes.Call, mi);
4623 ig.MarkLabel (skip);
4626 ig.EndExceptionBlock ();
4628 ig.BeginFinallyBlock ();
4633 void EmitExpression (EmitContext ec)
4636 // Make a copy of the expression and operate on that.
4638 ILGenerator ig = ec.ig;
4640 local_copy.Store (ec, expr);
4643 ig.BeginExceptionBlock ();
4645 Statement.Emit (ec);
4649 ig.EndExceptionBlock ();
4652 void EmitExpressionFinally (EmitContext ec)
4654 ILGenerator ig = ec.ig;
4655 if (!expr_type.IsValueType) {
4656 Label skip = ig.DefineLabel ();
4657 local_copy.Emit (ec);
4658 ig.Emit (OpCodes.Brfalse, skip);
4659 local_copy.Emit (ec);
4660 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4661 ig.MarkLabel (skip);
4663 Expression ml = Expression.MemberLookup (
4664 ec.ContainerType, TypeManager.idisposable_type, expr_type,
4665 "Dispose", Location.Null);
4667 if (!(ml is MethodGroupExpr)) {
4668 local_copy.Emit (ec);
4669 ig.Emit (OpCodes.Box, expr_type);
4670 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4672 MethodInfo mi = null;
4674 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4675 if (TypeManager.GetParameterData (mk).Count == 0) {
4682 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4686 local_copy.AddressOf (ec, AddressOp.Load);
4687 ig.Emit (OpCodes.Call, mi);
4692 public override bool Resolve (EmitContext ec)
4694 if (expression_or_block is DictionaryEntry){
4695 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4696 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4698 if (!ResolveLocalVariableDecls (ec))
4701 } else if (expression_or_block is Expression){
4702 expr = (Expression) expression_or_block;
4704 expr = expr.Resolve (ec);
4708 expr_type = expr.Type;
4710 if (!ResolveExpression (ec))
4714 FlowBranchingException branching = ec.StartFlowBranching (this);
4716 bool ok = Statement.Resolve (ec);
4718 ResolveFinally (branching);
4720 ec.EndFlowBranching ();
4722 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4723 // So, ensure there's some IL code after the finally block.
4724 ec.NeedReturnLabel ();
4729 protected override void DoEmit (EmitContext ec)
4731 if (expression_or_block is DictionaryEntry)
4732 EmitLocalVariableDecls (ec);
4733 else if (expression_or_block is Expression)
4734 EmitExpression (ec);
4737 public override void EmitFinally (EmitContext ec)
4739 if (expression_or_block is DictionaryEntry)
4740 EmitLocalVariableDeclFinally (ec);
4741 else if (expression_or_block is Expression)
4742 EmitExpressionFinally (ec);
4745 protected override void CloneTo (CloneContext clonectx, Statement t)
4747 Using target = (Using) t;
4749 if (expression_or_block is Expression)
4750 target.expression_or_block = ((Expression) expression_or_block).Clone (clonectx);
4752 target.expression_or_block = ((Statement) expression_or_block).Clone (clonectx);
4754 target.Statement = Statement.Clone (clonectx);
4759 /// Implementation of the foreach C# statement
4761 public class Foreach : Statement {
4763 Expression variable;
4765 Statement statement;
4767 CollectionForeach collection;
4769 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4770 Statement stmt, Location l)
4773 this.variable = var;
4779 public Statement Statement {
4780 get { return statement; }
4783 public override bool Resolve (EmitContext ec)
4785 expr = expr.Resolve (ec);
4789 if (type is VarExpr) {
4790 Type element_type = null;
4791 if (TypeManager.HasElementType (expr.Type))
4792 element_type = TypeManager.GetElementType (expr.Type);
4794 MethodGroupExpr mg = Expression.MemberLookup (
4795 ec.ContainerType, expr.Type, "GetEnumerator", MemberTypes.Method,
4796 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4801 MethodInfo get_enumerator = null;
4802 foreach (MethodInfo mi in mg.Methods) {
4803 if (TypeManager.GetParameterData (mi).Count != 0)
4805 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4807 if (CollectionForeach.IsOverride (mi))
4809 get_enumerator = mi;
4812 if (get_enumerator == null)
4815 PropertyInfo pi = TypeManager.GetProperty (get_enumerator.ReturnType, "Current");
4820 element_type = pi.PropertyType;
4823 type = new TypeLookupExpression (element_type.AssemblyQualifiedName);
4825 LocalVariableReference lv = variable as LocalVariableReference;
4826 ((LocalInfo)lv.Block.Variables[lv.Name]).VariableType = element_type;
4829 Constant c = expr as Constant;
4830 if (c != null && c.GetValue () == null) {
4831 Report.Error (186, loc, "Use of null is not valid in this context");
4835 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4839 Type var_type = texpr.Type;
4841 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4842 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4843 expr.ExprClassName);
4848 // We need an instance variable. Not sure this is the best
4849 // way of doing this.
4851 // FIXME: When we implement propertyaccess, will those turn
4852 // out to return values in ExprClass? I think they should.
4854 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4855 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4856 collection.Error_Enumerator ();
4860 if (expr.Type.IsArray) {
4861 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4862 return array.Resolve (ec);
4864 collection = new CollectionForeach (
4865 var_type, variable, expr, statement, loc);
4866 return collection.Resolve (ec);
4870 protected override void DoEmit (EmitContext ec)
4872 ILGenerator ig = ec.ig;
4874 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4875 ec.LoopBegin = ig.DefineLabel ();
4876 ec.LoopEnd = ig.DefineLabel ();
4878 if (collection != null)
4879 collection.Emit (ec);
4883 ec.LoopBegin = old_begin;
4884 ec.LoopEnd = old_end;
4887 protected class ArrayCounter : TemporaryVariable
4889 public ArrayCounter (Location loc)
4890 : base (TypeManager.int32_type, loc)
4893 public void Initialize (EmitContext ec)
4896 ec.ig.Emit (OpCodes.Ldc_I4_0);
4900 public void Increment (EmitContext ec)
4904 ec.ig.Emit (OpCodes.Ldc_I4_1);
4905 ec.ig.Emit (OpCodes.Add);
4910 protected class ArrayForeach : Statement
4912 Expression variable, expr, conv;
4913 Statement statement;
4916 TemporaryVariable[] lengths;
4917 ArrayCounter[] counter;
4920 TemporaryVariable copy;
4923 public ArrayForeach (Type var_type, Expression var,
4924 Expression expr, Statement stmt, Location l)
4926 this.var_type = var_type;
4927 this.variable = var;
4933 public override bool Resolve (EmitContext ec)
4935 array_type = expr.Type;
4936 rank = array_type.GetArrayRank ();
4938 copy = new TemporaryVariable (array_type, loc);
4941 counter = new ArrayCounter [rank];
4942 lengths = new TemporaryVariable [rank];
4944 ArrayList list = new ArrayList ();
4945 for (int i = 0; i < rank; i++) {
4946 counter [i] = new ArrayCounter (loc);
4947 counter [i].Resolve (ec);
4949 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4950 lengths [i].Resolve (ec);
4952 list.Add (counter [i]);
4955 access = new ElementAccess (copy, list).Resolve (ec);
4959 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
4965 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4966 ec.CurrentBranching.CreateSibling ();
4968 variable = variable.ResolveLValue (ec, conv, loc);
4969 if (variable == null)
4972 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
4973 if (!statement.Resolve (ec))
4975 ec.EndFlowBranching ();
4977 // There's no direct control flow from the end of the embedded statement to the end of the loop
4978 ec.CurrentBranching.CurrentUsageVector.Goto ();
4980 ec.EndFlowBranching ();
4985 protected override void DoEmit (EmitContext ec)
4987 ILGenerator ig = ec.ig;
4989 copy.Store (ec, expr);
4991 Label[] test = new Label [rank];
4992 Label[] loop = new Label [rank];
4994 for (int i = 0; i < rank; i++) {
4995 test [i] = ig.DefineLabel ();
4996 loop [i] = ig.DefineLabel ();
4998 lengths [i].EmitThis (ec);
4999 ((ArrayAccess) access).EmitGetLength (ec, i);
5000 lengths [i].EmitStore (ec);
5003 for (int i = 0; i < rank; i++) {
5004 counter [i].Initialize (ec);
5006 ig.Emit (OpCodes.Br, test [i]);
5007 ig.MarkLabel (loop [i]);
5010 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
5012 statement.Emit (ec);
5014 ig.MarkLabel (ec.LoopBegin);
5016 for (int i = rank - 1; i >= 0; i--){
5017 counter [i].Increment (ec);
5019 ig.MarkLabel (test [i]);
5020 counter [i].Emit (ec);
5021 lengths [i].Emit (ec);
5022 ig.Emit (OpCodes.Blt, loop [i]);
5025 ig.MarkLabel (ec.LoopEnd);
5029 protected class CollectionForeach : ExceptionStatement
5031 Expression variable, expr;
5032 Statement statement;
5034 TemporaryVariable enumerator;
5038 MethodGroupExpr get_enumerator;
5039 PropertyExpr get_current;
5040 MethodInfo move_next;
5041 Type var_type, enumerator_type;
5043 bool enumerator_found;
5045 public CollectionForeach (Type var_type, Expression var,
5046 Expression expr, Statement stmt, Location l)
5048 this.var_type = var_type;
5049 this.variable = var;
5055 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
5057 Type return_type = mi.ReturnType;
5059 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
5061 // Apply the same optimization as MS: skip the GetEnumerator
5062 // returning an IEnumerator, and use the one returning a
5063 // CharEnumerator instead. This allows us to avoid the
5064 // try-finally block and the boxing.
5069 // Ok, we can access it, now make sure that we can do something
5070 // with this `GetEnumerator'
5073 if (return_type == TypeManager.ienumerator_type ||
5074 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
5075 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
5077 // If it is not an interface, lets try to find the methods ourselves.
5078 // For example, if we have:
5079 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
5080 // We can avoid the iface call. This is a runtime perf boost.
5081 // even bigger if we have a ValueType, because we avoid the cost
5084 // We have to make sure that both methods exist for us to take
5085 // this path. If one of the methods does not exist, we will just
5086 // use the interface. Sadly, this complex if statement is the only
5087 // way I could do this without a goto
5092 // Prefer a generic enumerator over a non-generic one.
5094 if (return_type.IsInterface && return_type.IsGenericType) {
5095 enumerator_type = return_type;
5096 if (!FetchGetCurrent (ec, return_type))
5097 get_current = new PropertyExpr (
5098 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5099 if (!FetchMoveNext (return_type))
5100 move_next = TypeManager.bool_movenext_void;
5105 if (return_type.IsInterface ||
5106 !FetchMoveNext (return_type) ||
5107 !FetchGetCurrent (ec, return_type)) {
5108 enumerator_type = return_type;
5109 move_next = TypeManager.bool_movenext_void;
5110 get_current = new PropertyExpr (
5111 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5116 // Ok, so they dont return an IEnumerable, we will have to
5117 // find if they support the GetEnumerator pattern.
5120 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
5121 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",
5122 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
5127 enumerator_type = return_type;
5128 is_disposable = !enumerator_type.IsSealed ||
5129 TypeManager.ImplementsInterface (
5130 enumerator_type, TypeManager.idisposable_type);
5136 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5138 bool FetchMoveNext (Type t)
5140 MemberList move_next_list;
5142 move_next_list = TypeContainer.FindMembers (
5143 t, MemberTypes.Method,
5144 BindingFlags.Public | BindingFlags.Instance,
5145 Type.FilterName, "MoveNext");
5146 if (move_next_list.Count == 0)
5149 foreach (MemberInfo m in move_next_list){
5150 MethodInfo mi = (MethodInfo) m;
5152 if ((TypeManager.GetParameterData (mi).Count == 0) &&
5153 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
5163 // Retrieves a `public T get_Current ()' method from the Type `t'
5165 bool FetchGetCurrent (EmitContext ec, Type t)
5167 PropertyExpr pe = Expression.MemberLookup (
5168 ec.ContainerType, t, "Current", MemberTypes.Property,
5169 Expression.AllBindingFlags, loc) as PropertyExpr;
5178 // Retrieves a `public void Dispose ()' method from the Type `t'
5180 static MethodInfo FetchMethodDispose (Type t)
5182 MemberList dispose_list;
5184 dispose_list = TypeContainer.FindMembers (
5185 t, MemberTypes.Method,
5186 BindingFlags.Public | BindingFlags.Instance,
5187 Type.FilterName, "Dispose");
5188 if (dispose_list.Count == 0)
5191 foreach (MemberInfo m in dispose_list){
5192 MethodInfo mi = (MethodInfo) m;
5194 if (TypeManager.GetParameterData (mi).Count == 0){
5195 if (mi.ReturnType == TypeManager.void_type)
5202 public void Error_Enumerator ()
5204 if (enumerator_found) {
5208 Report.Error (1579, loc,
5209 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
5210 TypeManager.CSharpName (expr.Type));
5213 public static bool IsOverride (MethodInfo m)
5215 m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
5217 if (!m.IsVirtual || ((m.Attributes & MethodAttributes.NewSlot) != 0))
5219 if (m is MethodBuilder)
5222 MethodInfo base_method = m.GetBaseDefinition ();
5223 return base_method != m;
5226 bool TryType (EmitContext ec, Type t)
5228 MethodGroupExpr mg = Expression.MemberLookup (
5229 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
5230 Expression.AllBindingFlags, loc) as MethodGroupExpr;
5234 MethodInfo result = null;
5235 MethodInfo tmp_move_next = null;
5236 PropertyExpr tmp_get_cur = null;
5237 Type tmp_enumerator_type = enumerator_type;
5238 foreach (MethodInfo mi in mg.Methods) {
5239 if (TypeManager.GetParameterData (mi).Count != 0)
5242 // Check whether GetEnumerator is public
5243 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
5246 if (IsOverride (mi))
5249 enumerator_found = true;
5251 if (!GetEnumeratorFilter (ec, mi))
5254 if (result != null) {
5255 if (TypeManager.IsGenericType (result.ReturnType)) {
5256 if (!TypeManager.IsGenericType (mi.ReturnType))
5259 MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
5260 Report.SymbolRelatedToPreviousError (t);
5261 Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
5262 "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
5263 TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
5267 // Always prefer generics enumerators
5268 if (!TypeManager.IsGenericType (mi.ReturnType)) {
5269 if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
5270 TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
5273 Report.SymbolRelatedToPreviousError (result);
5274 Report.SymbolRelatedToPreviousError (mi);
5275 Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
5276 TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
5281 tmp_move_next = move_next;
5282 tmp_get_cur = get_current;
5283 tmp_enumerator_type = enumerator_type;
5284 if (mi.DeclaringType == t)
5288 if (result != null) {
5289 move_next = tmp_move_next;
5290 get_current = tmp_get_cur;
5291 enumerator_type = tmp_enumerator_type;
5292 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
5293 get_enumerator = new MethodGroupExpr (mi, loc);
5295 if (t != expr.Type) {
5296 expr = Convert.ExplicitConversion (
5299 throw new InternalErrorException ();
5302 get_enumerator.InstanceExpression = expr;
5303 get_enumerator.IsBase = t != expr.Type;
5311 bool ProbeCollectionType (EmitContext ec, Type t)
5313 int errors = Report.Errors;
5314 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
5315 if (TryType (ec, tt))
5320 if (Report.Errors > errors)
5324 // Now try to find the method in the interfaces
5326 Type [] ifaces = TypeManager.GetInterfaces (t);
5327 foreach (Type i in ifaces){
5328 if (TryType (ec, i))
5335 public override bool Resolve (EmitContext ec)
5337 enumerator_type = TypeManager.ienumerator_type;
5338 is_disposable = true;
5340 if (!ProbeCollectionType (ec, expr.Type)) {
5341 Error_Enumerator ();
5345 enumerator = new TemporaryVariable (enumerator_type, loc);
5346 enumerator.Resolve (ec);
5348 init = new Invocation (get_enumerator, new ArrayList ());
5349 init = init.Resolve (ec);
5353 Expression move_next_expr;
5355 MemberInfo[] mi = new MemberInfo[] { move_next };
5356 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5357 mg.InstanceExpression = enumerator;
5359 move_next_expr = new Invocation (mg, new ArrayList ());
5362 get_current.InstanceExpression = enumerator;
5364 Statement block = new CollectionForeachStatement (
5365 var_type, variable, get_current, statement, loc);
5367 loop = new While (move_next_expr, block, loc);
5371 FlowBranchingException branching = null;
5373 branching = ec.StartFlowBranching (this);
5375 if (!loop.Resolve (ec))
5378 if (is_disposable) {
5379 ResolveFinally (branching);
5380 ec.EndFlowBranching ();
5382 emit_finally = true;
5387 protected override void DoEmit (EmitContext ec)
5389 ILGenerator ig = ec.ig;
5391 enumerator.Store (ec, init);
5394 // Protect the code in a try/finalize block, so that
5395 // if the beast implement IDisposable, we get rid of it
5397 if (is_disposable && emit_finally)
5398 ig.BeginExceptionBlock ();
5403 // Now the finally block
5405 if (is_disposable) {
5408 ig.EndExceptionBlock ();
5413 public override void EmitFinally (EmitContext ec)
5415 ILGenerator ig = ec.ig;
5417 if (enumerator_type.IsValueType) {
5418 MethodInfo mi = FetchMethodDispose (enumerator_type);
5420 enumerator.EmitLoadAddress (ec);
5421 ig.Emit (OpCodes.Call, mi);
5423 enumerator.Emit (ec);
5424 ig.Emit (OpCodes.Box, enumerator_type);
5425 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5428 Label call_dispose = ig.DefineLabel ();
5430 enumerator.Emit (ec);
5431 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5432 ig.Emit (OpCodes.Dup);
5433 ig.Emit (OpCodes.Brtrue_S, call_dispose);
5434 ig.Emit (OpCodes.Pop);
5436 Label end_finally = ig.DefineLabel ();
5437 ig.Emit (OpCodes.Br, end_finally);
5439 ig.MarkLabel (call_dispose);
5440 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5441 ig.MarkLabel (end_finally);
5446 protected class CollectionForeachStatement : Statement
5449 Expression variable, current, conv;
5450 Statement statement;
5453 public CollectionForeachStatement (Type type, Expression variable,
5454 Expression current, Statement statement,
5458 this.variable = variable;
5459 this.current = current;
5460 this.statement = statement;
5464 public override bool Resolve (EmitContext ec)
5466 current = current.Resolve (ec);
5467 if (current == null)
5470 conv = Convert.ExplicitConversion (ec, current, type, loc);
5474 assign = new Assign (variable, conv, loc);
5475 if (assign.Resolve (ec) == null)
5478 if (!statement.Resolve (ec))
5484 protected override void DoEmit (EmitContext ec)
5486 assign.EmitStatement (ec);
5487 statement.Emit (ec);
5491 protected override void CloneTo (CloneContext clonectx, Statement t)
5493 Foreach target = (Foreach) t;
5495 target.type = type.Clone (clonectx);
5496 target.variable = variable.Clone (clonectx);
5497 target.expr = expr.Clone (clonectx);
5498 target.statement = statement.Clone (clonectx);