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 Report.Error (159, loc, "No such label `default:' within the scope of the goto statement");
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 Report.Error (159, loc, "No such label `case {0}:' within the scope of the goto statement", c.GetValue () == null ? "null" : val.ToString ());
983 ec.CurrentBranching.CurrentUsageVector.Goto ();
987 protected override void DoEmit (EmitContext ec)
989 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
992 protected override void CloneTo (CloneContext clonectx, Statement t)
994 GotoCase target = (GotoCase) t;
996 target.expr = expr.Clone (clonectx);
997 target.sl = sl.Clone (clonectx);
1001 public class Throw : Statement {
1004 public Throw (Expression expr, Location l)
1010 public override bool Resolve (EmitContext ec)
1012 ec.CurrentBranching.CurrentUsageVector.Goto ();
1015 expr = expr.Resolve (ec);
1019 ExprClass eclass = expr.eclass;
1021 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
1022 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
1023 expr.Error_UnexpectedKind (ec.DeclContainer, "value, variable, property or indexer access ", loc);
1029 if ((t != TypeManager.exception_type) &&
1030 !TypeManager.IsSubclassOf (t, TypeManager.exception_type) &&
1031 !(expr is NullLiteral)) {
1033 "The type caught or thrown must be derived " +
1034 "from System.Exception");
1041 Error (156, "A throw statement with no arguments is not allowed outside of a catch clause");
1046 Error (724, "A throw statement with no arguments is not allowed inside of a finally clause nested inside of the innermost catch clause");
1052 protected override void DoEmit (EmitContext ec)
1055 ec.ig.Emit (OpCodes.Rethrow);
1059 ec.ig.Emit (OpCodes.Throw);
1063 protected override void CloneTo (CloneContext clonectx, Statement t)
1065 Throw target = (Throw) t;
1067 target.expr = expr.Clone (clonectx);
1071 public class Break : Statement {
1073 public Break (Location l)
1078 bool unwind_protect;
1080 public override bool Resolve (EmitContext ec)
1082 int errors = Report.Errors;
1083 unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1084 ec.CurrentBranching.CurrentUsageVector.Goto ();
1085 return errors == Report.Errors;
1088 protected override void DoEmit (EmitContext ec)
1090 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
1094 public class Continue : Statement {
1096 public Continue (Location l)
1101 bool unwind_protect;
1103 public override bool Resolve (EmitContext ec)
1105 int errors = Report.Errors;
1106 unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
1107 ec.CurrentBranching.CurrentUsageVector.Goto ();
1108 return errors == Report.Errors;
1111 protected override void DoEmit (EmitContext ec)
1113 ec.ig.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
1117 public abstract class Variable
1119 public abstract Type Type {
1123 public abstract bool HasInstance {
1127 public abstract bool NeedsTemporary {
1131 public abstract void EmitInstance (EmitContext ec);
1133 public abstract void Emit (EmitContext ec);
1135 public abstract void EmitAssign (EmitContext ec);
1137 public abstract void EmitAddressOf (EmitContext ec);
1141 // The information about a user-perceived local variable
1143 public class LocalInfo {
1144 public Expression Type;
1146 public Type VariableType;
1147 public readonly string Name;
1148 public readonly Location Location;
1149 public readonly Block Block;
1151 public VariableInfo VariableInfo;
1154 public Variable Variable {
1166 CompilerGenerated = 64,
1170 public enum ReadOnlyContext: byte {
1177 ReadOnlyContext ro_context;
1178 LocalBuilder builder;
1180 public LocalInfo (Expression type, string name, Block block, Location l)
1188 public LocalInfo (DeclSpace ds, Block block, Location l)
1190 VariableType = ds.IsGeneric ? ds.CurrentType : ds.TypeBuilder;
1195 public void ResolveVariable (EmitContext ec)
1197 Block theblock = Block;
1198 if (theblock.ScopeInfo != null)
1199 var = theblock.ScopeInfo.GetCapturedVariable (this);
1204 // This is needed to compile on both .NET 1.x and .NET 2.x
1205 // the later introduced `DeclareLocal (Type t, bool pinned)'
1207 builder = TypeManager.DeclareLocalPinned (ec.ig, VariableType);
1209 builder = ec.ig.DeclareLocal (VariableType);
1211 var = new LocalVariable (this, builder);
1215 public void EmitSymbolInfo (EmitContext ec, string name)
1217 if (builder != null)
1218 ec.DefineLocalVariable (name, builder);
1221 public bool IsThisAssigned (EmitContext ec)
1223 if (VariableInfo == null)
1224 throw new Exception ();
1226 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1229 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, ec.loc);
1232 public bool IsAssigned (EmitContext ec)
1234 if (VariableInfo == null)
1235 throw new Exception ();
1237 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1240 public bool Resolve (EmitContext ec)
1242 if (VariableType == null) {
1243 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1247 VariableType = texpr.Type;
1250 if (TypeManager.IsGenericParameter (VariableType))
1253 if (VariableType == TypeManager.void_type) {
1254 Expression.Error_VoidInvalidInTheContext (Location);
1258 if (VariableType.IsAbstract && VariableType.IsSealed) {
1259 FieldBase.Error_VariableOfStaticClass (Location, Name, VariableType);
1263 if (VariableType.IsPointer && !ec.InUnsafe)
1264 Expression.UnsafeError (Location);
1269 public bool IsCaptured {
1271 return (flags & Flags.Captured) != 0;
1275 flags |= Flags.Captured;
1279 public bool IsConstant {
1281 return (flags & Flags.IsConstant) != 0;
1284 flags |= Flags.IsConstant;
1288 public bool AddressTaken {
1290 return (flags & Flags.AddressTaken) != 0;
1294 flags |= Flags.AddressTaken;
1298 public bool CompilerGenerated {
1300 return (flags & Flags.CompilerGenerated) != 0;
1304 flags |= Flags.CompilerGenerated;
1308 public override string ToString ()
1310 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1311 Name, Type, VariableInfo, Location);
1316 return (flags & Flags.Used) != 0;
1319 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1323 public bool ReadOnly {
1325 return (flags & Flags.ReadOnly) != 0;
1329 public void SetReadOnlyContext (ReadOnlyContext context)
1331 flags |= Flags.ReadOnly;
1332 ro_context = context;
1335 public string GetReadOnlyContext ()
1338 throw new InternalErrorException ("Variable is not readonly");
1340 switch (ro_context) {
1341 case ReadOnlyContext.Fixed:
1342 return "fixed variable";
1343 case ReadOnlyContext.Foreach:
1344 return "foreach iteration variable";
1345 case ReadOnlyContext.Using:
1346 return "using variable";
1348 throw new NotImplementedException ();
1352 // Whether the variable is pinned, if Pinned the variable has been
1353 // allocated in a pinned slot with DeclareLocal.
1355 public bool Pinned {
1357 return (flags & Flags.Pinned) != 0;
1360 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1364 public bool IsThis {
1366 return (flags & Flags.IsThis) != 0;
1369 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1373 protected class LocalVariable : Variable
1375 public readonly LocalInfo LocalInfo;
1376 LocalBuilder builder;
1378 public LocalVariable (LocalInfo local, LocalBuilder builder)
1380 this.LocalInfo = local;
1381 this.builder = builder;
1384 public override Type Type {
1385 get { return LocalInfo.VariableType; }
1388 public override bool HasInstance {
1389 get { return false; }
1392 public override bool NeedsTemporary {
1393 get { return false; }
1396 public override void EmitInstance (EmitContext ec)
1401 public override void Emit (EmitContext ec)
1403 ec.ig.Emit (OpCodes.Ldloc, builder);
1406 public override void EmitAssign (EmitContext ec)
1408 ec.ig.Emit (OpCodes.Stloc, builder);
1411 public override void EmitAddressOf (EmitContext ec)
1413 ec.ig.Emit (OpCodes.Ldloca, builder);
1417 public LocalInfo Clone (CloneContext clonectx)
1419 // Only this kind is created by the parser.
1420 return new LocalInfo (Type.Clone (clonectx), Name, clonectx.LookupBlock (Block), Location);
1425 /// Block represents a C# block.
1429 /// This class is used in a number of places: either to represent
1430 /// explicit blocks that the programmer places or implicit blocks.
1432 /// Implicit blocks are used as labels or to introduce variable
1435 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1436 /// they contain extra information that is not necessary on normal blocks.
1438 public class Block : Statement {
1439 public Block Parent;
1440 public readonly Location StartLocation;
1441 public Location EndLocation = Location.Null;
1443 public readonly ToplevelBlock Toplevel;
1446 public enum Flags : ushort {
1450 VariablesInitialized = 8,
1455 HasVarargs = 256, // Used in ToplevelBlock
1459 protected Flags flags;
1461 public bool Implicit {
1462 get { return (flags & Flags.Implicit) != 0; }
1465 public bool Unchecked {
1466 get { return (flags & Flags.Unchecked) != 0; }
1467 set { flags |= Flags.Unchecked; }
1470 public bool Unsafe {
1471 get { return (flags & Flags.Unsafe) != 0; }
1472 set { flags |= Flags.Unsafe; }
1476 // The statements in this block
1478 protected ArrayList statements;
1479 protected int current_statement;
1483 // An array of Blocks. We keep track of children just
1484 // to generate the local variable declarations.
1486 // Statements and child statements are handled through the
1492 // Labels. (label, block) pairs.
1497 // Keeps track of (name, type) pairs
1499 IDictionary variables;
1502 // Keeps track of constants
1503 Hashtable constants;
1506 // Temporary variables.
1508 ArrayList temporary_variables;
1511 // If this is a switch section, the enclosing switch block.
1515 ExpressionStatement scope_init;
1517 ArrayList anonymous_children;
1519 protected static int id;
1523 public Block (Block parent)
1524 : this (parent, (Flags) 0, Location.Null, Location.Null)
1527 public Block (Block parent, Flags flags)
1528 : this (parent, flags, Location.Null, Location.Null)
1531 public Block (Block parent, Location start, Location end)
1532 : this (parent, (Flags) 0, start, end)
1535 public Block (Block parent, Flags flags, Location start, Location end)
1538 parent.AddChild (this);
1540 this.Parent = parent;
1542 this.StartLocation = start;
1543 this.EndLocation = end;
1546 statements = new ArrayList ();
1548 if ((flags & Flags.IsToplevel) != 0)
1549 Toplevel = (ToplevelBlock) this;
1551 Toplevel = parent.Toplevel;
1553 if (parent != null && Implicit) {
1554 if (parent.known_variables == null)
1555 parent.known_variables = new Hashtable ();
1556 // share with parent
1557 known_variables = parent.known_variables;
1561 public Block CreateSwitchBlock (Location start)
1563 Block new_block = new Block (this, start, start);
1564 new_block.switch_block = this;
1569 get { return this_id; }
1572 public IDictionary Variables {
1574 if (variables == null)
1575 variables = new ListDictionary ();
1580 void AddChild (Block b)
1582 if (children == null)
1583 children = new ArrayList ();
1588 public void SetEndLocation (Location loc)
1593 protected static void Error_158 (string name, Location loc)
1595 Report.Error (158, loc, "The label `{0}' shadows another label " +
1596 "by the same name in a contained scope.", name);
1600 /// Adds a label to the current block.
1604 /// false if the name already exists in this block. true
1608 public bool AddLabel (LabeledStatement target)
1610 if (switch_block != null)
1611 return switch_block.AddLabel (target);
1613 string name = target.Name;
1616 while (cur != null) {
1617 if (cur.DoLookupLabel (name) != null) {
1618 Report.Error (140, target.loc,
1619 "The label `{0}' is a duplicate", name);
1629 while (cur != null) {
1630 if (cur.DoLookupLabel (name) != null) {
1631 Error_158 (name, target.loc);
1635 if (children != null) {
1636 foreach (Block b in children) {
1637 LabeledStatement s = b.DoLookupLabel (name);
1641 Error_158 (name, target.loc);
1649 Toplevel.CheckError158 (name, target.loc);
1652 labels = new Hashtable ();
1654 labels.Add (name, target);
1658 public LabeledStatement LookupLabel (string name)
1660 LabeledStatement s = DoLookupLabel (name);
1664 if (children == null)
1667 foreach (Block child in children) {
1668 if (!child.Implicit)
1671 s = child.LookupLabel (name);
1679 LabeledStatement DoLookupLabel (string name)
1681 if (switch_block != null)
1682 return switch_block.LookupLabel (name);
1685 if (labels.Contains (name))
1686 return ((LabeledStatement) labels [name]);
1691 Hashtable known_variables;
1694 // Marks a variable with name @name as being used in this or a child block.
1695 // If a variable name has been used in a child block, it's illegal to
1696 // declare a variable with the same name in the current block.
1698 void AddKnownVariable (string name, LocalInfo info)
1700 if (known_variables == null)
1701 known_variables = new Hashtable ();
1703 known_variables [name] = info;
1706 LocalInfo GetKnownVariableInfo (string name, bool recurse)
1708 if (known_variables != null) {
1709 LocalInfo vi = (LocalInfo) known_variables [name];
1714 if (!recurse || (children == null))
1717 foreach (Block block in children) {
1718 LocalInfo vi = block.GetKnownVariableInfo (name, true);
1726 public bool CheckInvariantMeaningInBlock (string name, Expression e, Location loc)
1729 LocalInfo kvi = b.GetKnownVariableInfo (name, true);
1730 while (kvi == null) {
1736 kvi = b.GetKnownVariableInfo (name, false);
1742 // Is kvi.Block nested inside 'b'
1743 if (b.known_variables != kvi.Block.known_variables) {
1745 // If a variable by the same name it defined in a nested block of this
1746 // block, we violate the invariant meaning in a block.
1749 Report.SymbolRelatedToPreviousError (kvi.Location, name);
1750 Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", name);
1755 // It's ok if the definition is in a nested subblock of b, but not
1756 // nested inside this block -- a definition in a sibling block
1757 // should not affect us.
1763 // Block 'b' and kvi.Block are the same textual block.
1764 // However, different variables are extant.
1766 // Check if the variable is in scope in both blocks. We use
1767 // an indirect check that depends on AddVariable doing its
1768 // part in maintaining the invariant-meaning-in-block property.
1770 if (e is LocalVariableReference || (e is Constant && b.GetLocalInfo (name) != null))
1774 // Even though we detected the error when the name is used, we
1775 // treat it as if the variable declaration was in error.
1777 Report.SymbolRelatedToPreviousError (loc, name);
1778 Error_AlreadyDeclared (kvi.Location, name, "parent or current");
1782 public bool CheckError136_InParents (string name, Location loc)
1784 for (Block b = Parent; b != null; b = b.Parent) {
1785 if (!b.DoCheckError136 (name, "parent or current", loc))
1789 for (Block b = Toplevel.ContainerBlock; b != null; b = b.Toplevel.ContainerBlock) {
1790 if (!b.CheckError136_InParents (name, loc))
1797 public bool CheckError136_InChildren (string name, Location loc)
1799 if (!DoCheckError136_InChildren (name, loc))
1803 while (b.Implicit) {
1804 if (!b.Parent.DoCheckError136_InChildren (name, loc))
1812 protected bool DoCheckError136_InChildren (string name, Location loc)
1814 if (!DoCheckError136 (name, "child", loc))
1817 if (AnonymousChildren != null) {
1818 foreach (ToplevelBlock child in AnonymousChildren) {
1819 if (!child.DoCheckError136_InChildren (name, loc))
1824 if (children != null) {
1825 foreach (Block child in children) {
1826 if (!child.DoCheckError136_InChildren (name, loc))
1834 public bool CheckError136 (string name, string scope, bool check_parents,
1835 bool check_children, Location loc)
1837 if (!DoCheckError136 (name, scope, loc))
1840 if (check_parents) {
1841 if (!CheckError136_InParents (name, loc))
1845 if (check_children) {
1846 if (!CheckError136_InChildren (name, loc))
1850 for (Block c = Toplevel.ContainerBlock; c != null; c = c.Toplevel.ContainerBlock) {
1851 if (!c.DoCheckError136 (name, "parent or current", loc))
1858 protected bool DoCheckError136 (string name, string scope, Location loc)
1860 LocalInfo vi = GetKnownVariableInfo (name, false);
1862 Report.SymbolRelatedToPreviousError (vi.Location, name);
1863 Error_AlreadyDeclared (loc, name, scope != null ? scope : "child");
1868 Parameter p = Toplevel.Parameters.GetParameterByName (name, out idx);
1870 Report.SymbolRelatedToPreviousError (p.Location, name);
1871 Error_AlreadyDeclared (
1872 loc, name, scope != null ? scope : "method argument");
1879 public LocalInfo AddVariable (Expression type, string name, Location l)
1881 LocalInfo vi = GetLocalInfo (name);
1883 Report.SymbolRelatedToPreviousError (vi.Location, name);
1884 if (known_variables == vi.Block.known_variables)
1885 Report.Error (128, l,
1886 "A local variable named `{0}' is already defined in this scope", name);
1888 Error_AlreadyDeclared (l, name, "parent");
1892 if (!CheckError136 (name, null, true, true, l))
1895 vi = new LocalInfo (type, name, this, l);
1896 Variables.Add (name, vi);
1897 AddKnownVariable (name, vi);
1899 if ((flags & Flags.VariablesInitialized) != 0)
1900 throw new Exception ();
1905 void Error_AlreadyDeclared (Location loc, string var, string reason)
1907 Report.Error (136, loc, "A local variable named `{0}' cannot be declared " +
1908 "in this scope because it would give a different meaning " +
1909 "to `{0}', which is already used in a `{1}' scope " +
1910 "to denote something else", var, reason);
1913 public bool AddConstant (Expression type, string name, Expression value, Location l)
1915 if (AddVariable (type, name, l) == null)
1918 if (constants == null)
1919 constants = new Hashtable ();
1921 constants.Add (name, value);
1923 // A block is considered used if we perform an initialization in a local declaration, even if it is constant.
1928 static int next_temp_id = 0;
1930 public LocalInfo AddTemporaryVariable (TypeExpr te, Location loc)
1932 Report.Debug (64, "ADD TEMPORARY", this, Toplevel, loc);
1934 if (temporary_variables == null)
1935 temporary_variables = new ArrayList ();
1937 int id = ++next_temp_id;
1938 string name = "$s_" + id.ToString ();
1940 LocalInfo li = new LocalInfo (te, name, this, loc);
1941 li.CompilerGenerated = true;
1942 temporary_variables.Add (li);
1946 public LocalInfo GetLocalInfo (string name)
1948 for (Block b = this; b != null; b = b.Parent) {
1949 if (b.variables != null) {
1950 LocalInfo ret = b.variables [name] as LocalInfo;
1958 public Expression GetVariableType (string name)
1960 LocalInfo vi = GetLocalInfo (name);
1961 return vi == null ? null : vi.Type;
1964 public Expression GetConstantExpression (string name)
1966 for (Block b = this; b != null; b = b.Parent) {
1967 if (b.constants != null) {
1968 Expression ret = b.constants [name] as Expression;
1976 public void AddStatement (Statement s)
1979 flags |= Flags.BlockUsed;
1982 public void InsertStatementAfterCurrent (Statement statement)
1984 statements.Insert (current_statement + 1, statement);
1985 flags |= Flags.BlockUsed;
1989 get { return (flags & Flags.BlockUsed) != 0; }
1994 flags |= Flags.BlockUsed;
1997 public bool HasRet {
1998 get { return (flags & Flags.HasRet) != 0; }
2001 public bool IsDestructor {
2002 get { return (flags & Flags.IsDestructor) != 0; }
2005 public void SetDestructor ()
2007 flags |= Flags.IsDestructor;
2010 VariableMap param_map, local_map;
2012 public VariableMap ParameterMap {
2014 if ((flags & Flags.VariablesInitialized) == 0){
2015 throw new Exception ("Variables have not been initialized yet");
2022 public VariableMap LocalMap {
2024 if ((flags & Flags.VariablesInitialized) == 0)
2025 throw new Exception ("Variables have not been initialized yet");
2031 protected ScopeInfo scope_info;
2033 public ScopeInfo ScopeInfo {
2034 get { return scope_info; }
2037 public ScopeInfo CreateScopeInfo ()
2039 if (scope_info == null)
2040 scope_info = ScopeInfo.CreateScope (this);
2045 public ArrayList AnonymousChildren {
2046 get { return anonymous_children; }
2049 public void AddAnonymousChild (ToplevelBlock b)
2051 if (anonymous_children == null)
2052 anonymous_children = new ArrayList ();
2054 anonymous_children.Add (b);
2058 /// Emits the variable declarations and labels.
2061 /// tc: is our typecontainer (to resolve type references)
2062 /// ig: is the code generator:
2064 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, Parameters ip)
2066 Report.Debug (64, "BLOCK RESOLVE META", this, Parent, toplevel);
2068 // If some parent block was unsafe, we remain unsafe even if this block
2069 // isn't explicitly marked as such.
2070 using (ec.With (EmitContext.Flags.InUnsafe, ec.InUnsafe | Unsafe)) {
2072 // Compute the VariableMap's.
2074 // Unfortunately, we don't know the type when adding variables with
2075 // AddVariable(), so we need to compute this info here.
2079 if (variables != null) {
2080 foreach (LocalInfo li in variables.Values)
2083 locals = new LocalInfo [variables.Count];
2084 variables.Values.CopyTo (locals, 0);
2086 locals = new LocalInfo [0];
2089 local_map = new VariableMap (Parent.LocalMap, locals);
2091 local_map = new VariableMap (locals);
2093 param_map = new VariableMap (ip);
2094 flags |= Flags.VariablesInitialized;
2097 // Process this block variables
2099 if (variables != null) {
2100 foreach (DictionaryEntry de in variables) {
2101 string name = (string) de.Key;
2102 LocalInfo vi = (LocalInfo) de.Value;
2103 Type variable_type = vi.VariableType;
2105 if (variable_type == null)
2108 if (variable_type.IsPointer) {
2110 // Am not really convinced that this test is required (Microsoft does it)
2111 // but the fact is that you would not be able to use the pointer variable
2114 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
2119 if (constants == null)
2122 Expression cv = (Expression) constants [name];
2126 // Don't let 'const int Foo = Foo;' succeed.
2127 // Removing the name from 'constants' ensures that we get a LocalVariableReference below,
2128 // which in turn causes the 'must be constant' error to be triggered.
2129 constants.Remove (name);
2131 if (!Const.IsConstantTypeValid (variable_type)) {
2132 Const.Error_InvalidConstantType (variable_type, loc);
2136 using (ec.With (EmitContext.Flags.ConstantCheckState, (flags & Flags.Unchecked) == 0)) {
2137 ec.CurrentBlock = this;
2138 Expression e = cv.Resolve (ec);
2142 Constant ce = e as Constant;
2144 Const.Error_ExpressionMustBeConstant (vi.Location, name);
2148 e = ce.ConvertImplicitly (variable_type);
2150 if (!variable_type.IsValueType && variable_type != TypeManager.string_type && !ce.IsDefaultValue)
2151 Const.Error_ConstantCanBeInitializedWithNullOnly (vi.Location, vi.Name);
2153 ce.Error_ValueCannotBeConverted (null, vi.Location, variable_type, false);
2157 constants.Add (name, e);
2158 vi.IsConstant = true;
2164 // Now, handle the children
2166 if (children != null) {
2167 foreach (Block b in children)
2168 b.ResolveMeta (toplevel, ec, ip);
2174 // Emits the local variable declarations for a block
2176 public virtual void EmitMeta (EmitContext ec)
2178 Report.Debug (64, "BLOCK EMIT META", this, Parent, Toplevel, ScopeInfo, ec);
2179 if (ScopeInfo != null) {
2180 scope_init = ScopeInfo.GetScopeInitializer (ec);
2181 Report.Debug (64, "BLOCK EMIT META #1", this, Toplevel, ScopeInfo,
2185 if (variables != null){
2186 foreach (LocalInfo vi in variables.Values)
2187 vi.ResolveVariable (ec);
2190 if (temporary_variables != null) {
2191 foreach (LocalInfo vi in temporary_variables)
2192 vi.ResolveVariable (ec);
2195 if (children != null){
2196 foreach (Block b in children)
2201 void UsageWarning (FlowBranching.UsageVector vector)
2205 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
2206 foreach (DictionaryEntry de in variables){
2207 LocalInfo vi = (LocalInfo) de.Value;
2212 name = (string) de.Key;
2214 // vi.VariableInfo can be null for 'catch' variables
2215 if (vi.VariableInfo != null && vector.IsAssigned (vi.VariableInfo, true)){
2216 Report.Warning (219, 3, vi.Location, "The variable `{0}' is assigned but its value is never used", name);
2218 Report.Warning (168, 3, vi.Location, "The variable `{0}' is declared but never used", name);
2224 bool unreachable_shown;
2227 private void CheckPossibleMistakenEmptyStatement (Statement s)
2231 // Some statements are wrapped by a Block. Since
2232 // others' internal could be changed, here I treat
2233 // them as possibly wrapped by Block equally.
2234 Block b = s as Block;
2235 if (b != null && b.statements.Count == 1)
2236 s = (Statement) b.statements [0];
2239 body = ((Lock) s).Statement;
2241 body = ((For) s).Statement;
2242 else if (s is Foreach)
2243 body = ((Foreach) s).Statement;
2244 else if (s is While)
2245 body = ((While) s).Statement;
2246 else if (s is Using)
2247 body = ((Using) s).Statement;
2248 else if (s is Fixed)
2249 body = ((Fixed) s).Statement;
2253 if (body == null || body is EmptyStatement)
2254 Report.Warning (642, 3, s.loc, "Possible mistaken empty statement");
2257 public override bool Resolve (EmitContext ec)
2259 Block prev_block = ec.CurrentBlock;
2262 int errors = Report.Errors;
2264 ec.CurrentBlock = this;
2265 ec.StartFlowBranching (this);
2267 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2270 // This flag is used to notate nested statements as unreachable from the beginning of this block.
2271 // For the purposes of this resolution, it doesn't matter that the whole block is unreachable
2272 // from the beginning of the function. The outer Resolve() that detected the unreachability is
2273 // responsible for handling the situation.
2275 for (current_statement = 0; current_statement < statements.Count; current_statement++) {
2276 Statement s = (Statement) statements [current_statement];
2277 // Check possible empty statement (CS0642)
2278 if (RootContext.WarningLevel >= 3 &&
2279 current_statement + 1 < statements.Count &&
2280 statements [current_statement + 1] is Block)
2281 CheckPossibleMistakenEmptyStatement (s);
2284 // Warn if we detect unreachable code.
2287 if (s is EmptyStatement)
2291 ((Block) s).unreachable = true;
2293 if (!unreachable_shown && !(s is LabeledStatement)) {
2294 Report.Warning (162, 2, s.loc, "Unreachable code detected");
2295 unreachable_shown = true;
2300 // Note that we're not using ResolveUnreachable() for unreachable
2301 // statements here. ResolveUnreachable() creates a temporary
2302 // flow branching and kills it afterwards. This leads to problems
2303 // if you have two unreachable statements where the first one
2304 // assigns a variable and the second one tries to access it.
2307 if (!s.Resolve (ec)) {
2309 statements [current_statement] = EmptyStatement.Value;
2313 if (unreachable && !(s is LabeledStatement) && !(s is Block))
2314 statements [current_statement] = EmptyStatement.Value;
2316 num_statements = current_statement + 1;
2318 unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
2319 if (unreachable && s is LabeledStatement)
2320 throw new InternalErrorException ("should not happen");
2323 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
2324 ec.CurrentBranching, statements.Count, num_statements);
2329 while (ec.CurrentBranching is FlowBranchingLabeled)
2330 ec.EndFlowBranching ();
2332 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
2334 ec.CurrentBlock = prev_block;
2336 // If we're a non-static `struct' constructor which doesn't have an
2337 // initializer, then we must initialize all of the struct's fields.
2338 if ((flags & Flags.IsToplevel) != 0 &&
2339 !Toplevel.IsThisAssigned (ec) &&
2340 !vector.IsUnreachable)
2343 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2344 foreach (LabeledStatement label in labels.Values)
2345 if (!label.HasBeenReferenced)
2346 Report.Warning (164, 2, label.loc,
2347 "This label has not been referenced");
2350 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2352 if (vector.IsUnreachable)
2353 flags |= Flags.HasRet;
2355 if (ok && (errors == Report.Errors)) {
2356 if (RootContext.WarningLevel >= 3)
2357 UsageWarning (vector);
2363 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2365 unreachable_shown = true;
2369 Report.Warning (162, 2, loc, "Unreachable code detected");
2371 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2372 bool ok = Resolve (ec);
2373 ec.KillFlowBranching ();
2378 protected override void DoEmit (EmitContext ec)
2380 for (int ix = 0; ix < num_statements; ix++){
2381 Statement s = (Statement) statements [ix];
2383 // Check whether we are the last statement in a
2386 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2387 ec.IsLastStatement = true;
2389 ec.IsLastStatement = false;
2395 public override void Emit (EmitContext ec)
2397 Block prev_block = ec.CurrentBlock;
2399 ec.CurrentBlock = this;
2401 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2402 bool is_lexical_block = !Implicit && (Parent != null);
2404 if (emit_debug_info) {
2405 if (is_lexical_block)
2408 ec.Mark (StartLocation, true);
2409 if (scope_init != null)
2410 scope_init.EmitStatement (ec);
2412 ec.Mark (EndLocation, true);
2414 if (emit_debug_info) {
2415 if (is_lexical_block)
2418 if (variables != null) {
2419 foreach (DictionaryEntry de in variables) {
2420 string name = (string) de.Key;
2421 LocalInfo vi = (LocalInfo) de.Value;
2423 vi.EmitSymbolInfo (ec, name);
2428 ec.CurrentBlock = prev_block;
2432 // Returns true if we ar ea child of `b'.
2434 public bool IsChildOf (Block b)
2436 Block current = this;
2439 if (current.Parent == b)
2441 current = current.Parent;
2442 } while (current != null);
2446 public override string ToString ()
2448 return String.Format ("{0} ({1}:{2})", GetType (),ID, StartLocation);
2451 protected override void CloneTo (CloneContext clonectx, Statement t)
2453 Block target = (Block) t;
2456 target.Parent = clonectx.LookupBlock (Parent);
2458 target.statements = new ArrayList ();
2459 if (target.children != null){
2460 target.children = new ArrayList ();
2461 foreach (Block b in children){
2462 Block newblock = (Block) b.Clone (clonectx);
2464 target.children.Add (newblock);
2469 foreach (Statement s in statements)
2470 target.statements.Add (s.Clone (clonectx));
2472 if (variables != null){
2473 target.variables = new Hashtable ();
2475 foreach (DictionaryEntry de in variables){
2476 LocalInfo newlocal = ((LocalInfo) de.Value).Clone (clonectx);
2477 target.variables [de.Key] = newlocal;
2478 clonectx.AddVariableMap ((LocalInfo) de.Value, newlocal);
2483 // TODO: labels, switch_block, constants (?), anonymous_children
2489 // A toplevel block contains extra information, the split is done
2490 // only to separate information that would otherwise bloat the more
2491 // lightweight Block.
2493 // In particular, this was introduced when the support for Anonymous
2494 // Methods was implemented.
2496 public class ToplevelBlock : Block {
2498 // Pointer to the host of this anonymous method, or null
2499 // if we are the topmost block
2502 ToplevelBlock child;
2503 GenericMethod generic;
2504 FlowBranchingToplevel top_level_branching;
2505 AnonymousContainer anonymous_container;
2506 RootScopeInfo root_scope;
2508 public bool HasVarargs {
2509 get { return (flags & Flags.HasVarargs) != 0; }
2510 set { flags |= Flags.HasVarargs; }
2513 public bool IsIterator {
2514 get { return (flags & Flags.IsIterator) != 0; }
2518 // The parameters for the block.
2520 Parameters parameters;
2521 public Parameters Parameters {
2522 get { return parameters; }
2525 public bool CompleteContexts (EmitContext ec)
2527 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS", this,
2528 container, root_scope);
2530 if (root_scope != null)
2531 root_scope.LinkScopes ();
2533 if ((container == null) && (root_scope != null)) {
2534 Report.Debug (64, "TOPLEVEL COMPLETE CONTEXTS #1", this,
2537 if (root_scope.DefineType () == null)
2539 if (!root_scope.ResolveType ())
2541 if (!root_scope.ResolveMembers ())
2543 if (!root_scope.DefineMembers ())
2550 public GenericMethod GenericMethod {
2551 get { return generic; }
2554 public ToplevelBlock Container {
2555 get { return container != null ? container.Toplevel : null; }
2558 public Block ContainerBlock {
2559 get { return container; }
2562 public AnonymousContainer AnonymousContainer {
2563 get { return anonymous_container; }
2564 set { anonymous_container = value; }
2568 // Parent is only used by anonymous blocks to link back to their
2571 public ToplevelBlock (Block container, Parameters parameters, Location start) :
2572 this (container, (Flags) 0, parameters, start)
2576 public ToplevelBlock (Block container, Parameters parameters, GenericMethod generic,
2578 this (container, parameters, start)
2580 this.generic = generic;
2583 public ToplevelBlock (Parameters parameters, Location start) :
2584 this (null, (Flags) 0, parameters, start)
2588 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2589 this (null, flags, parameters, start)
2593 public ToplevelBlock (Block container, Flags flags, Parameters parameters, Location start) :
2594 base (null, flags | Flags.IsToplevel, start, Location.Null)
2596 this.parameters = parameters == null ? Parameters.EmptyReadOnlyParameters : parameters;
2597 this.container = container;
2600 public ToplevelBlock (Location loc) : this (null, (Flags) 0, null, loc)
2604 public bool CheckError158 (string name, Location loc)
2606 if (AnonymousChildren != null) {
2607 foreach (ToplevelBlock child in AnonymousChildren) {
2608 if (!child.CheckError158 (name, loc))
2613 for (ToplevelBlock c = Container; c != null; c = c.Container) {
2614 if (!c.DoCheckError158 (name, loc))
2621 bool DoCheckError158 (string name, Location loc)
2623 LabeledStatement s = LookupLabel (name);
2625 Error_158 (name, loc);
2632 public RootScopeInfo CreateRootScope (TypeContainer host)
2634 if (root_scope != null)
2637 if (Container == null)
2638 root_scope = new RootScopeInfo (
2639 this, host, generic, StartLocation);
2641 if (scope_info != null)
2642 throw new InternalErrorException ();
2644 scope_info = root_scope;
2648 public void CreateIteratorHost (RootScopeInfo root)
2650 Report.Debug (64, "CREATE ITERATOR HOST", this, root,
2651 container, root_scope);
2653 if ((container != null) || (root_scope != null))
2654 throw new InternalErrorException ();
2656 scope_info = root_scope = root;
2659 public RootScopeInfo RootScope {
2661 if (root_scope != null)
2663 else if (Container != null)
2664 return Container.RootScope;
2670 public FlowBranchingToplevel TopLevelBranching {
2671 get { return top_level_branching; }
2675 // This is used if anonymous methods are used inside an iterator
2676 // (see 2test-22.cs for an example).
2678 // The AnonymousMethod is created while parsing - at a time when we don't
2679 // know yet that we're inside an iterator, so it's `Container' is initially
2680 // null. Later on, when resolving the iterator, we need to move the
2681 // anonymous method into that iterator.
2683 public void ReParent (ToplevelBlock new_parent)
2685 container = new_parent;
2686 Parent = new_parent;
2687 new_parent.child = this;
2691 // Returns a `ParameterReference' for the given name, or null if there
2692 // is no such parameter
2694 public ParameterReference GetParameterReference (string name, Location loc)
2699 for (ToplevelBlock t = this; t != null; t = t.Container) {
2700 Parameters pars = t.Parameters;
2701 par = pars.GetParameterByName (name, out idx);
2703 return new ParameterReference (par, this, idx, loc);
2709 // Whether the parameter named `name' is local to this block,
2710 // or false, if the parameter belongs to an encompassing block.
2712 public bool IsLocalParameter (string name)
2714 return Parameters.GetParameterByName (name) != null;
2718 // Whether the `name' is a parameter reference
2720 public bool IsParameterReference (string name)
2722 for (ToplevelBlock t = this; t != null; t = t.Container) {
2723 if (t.IsLocalParameter (name))
2729 LocalInfo this_variable = null;
2732 // Returns the "this" instance variable of this block.
2733 // See AddThisVariable() for more information.
2735 public LocalInfo ThisVariable {
2736 get { return this_variable; }
2741 // This is used by non-static `struct' constructors which do not have an
2742 // initializer - in this case, the constructor must initialize all of the
2743 // struct's fields. To do this, we add a "this" variable and use the flow
2744 // analysis code to ensure that it's been fully initialized before control
2745 // leaves the constructor.
2747 public LocalInfo AddThisVariable (DeclSpace ds, Location l)
2749 if (this_variable == null) {
2750 this_variable = new LocalInfo (ds, this, l);
2751 this_variable.Used = true;
2752 this_variable.IsThis = true;
2754 Variables.Add ("this", this_variable);
2757 return this_variable;
2760 public bool IsThisAssigned (EmitContext ec)
2762 return this_variable == null || this_variable.IsThisAssigned (ec);
2765 public bool ResolveMeta (EmitContext ec, Parameters ip)
2767 int errors = Report.Errors;
2769 if (top_level_branching != null)
2775 if (!IsIterator && (container != null) && (parameters != null)) {
2776 foreach (Parameter p in parameters.FixedParameters) {
2777 if (!CheckError136_InParents (p.Name, loc))
2782 ResolveMeta (this, ec, ip);
2785 child.ResolveMeta (this, ec, ip);
2787 top_level_branching = ec.StartFlowBranching (this);
2789 return Report.Errors == errors;
2792 public override void EmitMeta (EmitContext ec)
2795 parameters.ResolveVariable (this);
2798 public void MakeIterator (Iterator iterator)
2800 flags |= Flags.IsIterator;
2802 Block block = new Block (this);
2803 foreach (Statement stmt in statements)
2804 block.AddStatement (stmt);
2805 statements = new ArrayList ();
2806 statements.Add (new MoveNextStatement (iterator, block));
2809 protected class MoveNextStatement : Statement {
2813 public MoveNextStatement (Iterator iterator, Block block)
2815 this.iterator = iterator;
2817 this.loc = iterator.Location;
2820 public override bool Resolve (EmitContext ec)
2822 return block.Resolve (ec);
2825 protected override void DoEmit (EmitContext ec)
2827 iterator.EmitMoveNext (ec, block);
2831 public override string ToString ()
2833 return String.Format ("{0} ({1}:{2}{3}:{4})", GetType (), ID, StartLocation,
2834 root_scope, anonymous_container != null ?
2835 anonymous_container.Scope : null);
2839 public class SwitchLabel {
2846 Label il_label_code;
2847 bool il_label_code_set;
2849 public static readonly object NullStringCase = new object ();
2852 // if expr == null, then it is the default case.
2854 public SwitchLabel (Expression expr, Location l)
2860 public Expression Label {
2866 public object Converted {
2872 public Label GetILLabel (EmitContext ec)
2875 il_label = ec.ig.DefineLabel ();
2876 il_label_set = true;
2881 public Label GetILLabelCode (EmitContext ec)
2883 if (!il_label_code_set){
2884 il_label_code = ec.ig.DefineLabel ();
2885 il_label_code_set = true;
2887 return il_label_code;
2891 // Resolves the expression, reduces it to a literal if possible
2892 // and then converts it to the requested type.
2894 public bool ResolveAndReduce (EmitContext ec, Type required_type, bool allow_nullable)
2896 Expression e = label.Resolve (ec);
2901 Constant c = e as Constant;
2903 Report.Error (150, loc, "A constant value is expected");
2907 if (required_type == TypeManager.string_type && c.GetValue () == null) {
2908 converted = NullStringCase;
2912 if (allow_nullable && c.GetValue () == null) {
2913 converted = NullStringCase;
2917 c = c.ImplicitConversionRequired (required_type, loc);
2921 converted = c.GetValue ();
2925 public void Erorr_AlreadyOccurs (Type switchType, SwitchLabel collisionWith)
2928 if (converted == null)
2930 else if (converted == NullStringCase)
2932 else if (TypeManager.IsEnumType (switchType))
2933 label = TypeManager.CSharpEnumValue (switchType, converted);
2935 label = converted.ToString ();
2937 Report.SymbolRelatedToPreviousError (collisionWith.loc, null);
2938 Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
2941 public SwitchLabel Clone (CloneContext clonectx)
2943 return new SwitchLabel (label.Clone (clonectx), loc);
2947 public class SwitchSection {
2948 // An array of SwitchLabels.
2949 public readonly ArrayList Labels;
2950 public readonly Block Block;
2952 public SwitchSection (ArrayList labels, Block block)
2958 public SwitchSection Clone (CloneContext clonectx)
2960 ArrayList cloned_labels = new ArrayList ();
2962 foreach (SwitchLabel sl in cloned_labels)
2963 cloned_labels.Add (sl.Clone (clonectx));
2965 return new SwitchSection (cloned_labels, clonectx.LookupBlock (Block));
2969 public class Switch : Statement {
2970 public ArrayList Sections;
2971 public Expression Expr;
2974 /// Maps constants whose type type SwitchType to their SwitchLabels.
2976 public IDictionary Elements;
2979 /// The governing switch type
2981 public Type SwitchType;
2986 Label default_target;
2988 Expression new_expr;
2990 SwitchSection constant_section;
2991 SwitchSection default_section;
2995 // Nullable Types support for GMCS.
2997 Nullable.Unwrap unwrap;
2999 protected bool HaveUnwrap {
3000 get { return unwrap != null; }
3003 protected bool HaveUnwrap {
3004 get { return false; }
3009 // The types allowed to be implicitly cast from
3010 // on the governing type
3012 static Type [] allowed_types;
3014 public Switch (Expression e, ArrayList sects, Location l)
3021 public bool GotDefault {
3023 return default_section != null;
3027 public Label DefaultTarget {
3029 return default_target;
3034 // Determines the governing type for a switch. The returned
3035 // expression might be the expression from the switch, or an
3036 // expression that includes any potential conversions to the
3037 // integral types or to string.
3039 Expression SwitchGoverningType (EmitContext ec, Expression expr)
3041 Type t = TypeManager.DropGenericTypeArguments (expr.Type);
3043 if (t == TypeManager.byte_type ||
3044 t == TypeManager.sbyte_type ||
3045 t == TypeManager.ushort_type ||
3046 t == TypeManager.short_type ||
3047 t == TypeManager.uint32_type ||
3048 t == TypeManager.int32_type ||
3049 t == TypeManager.uint64_type ||
3050 t == TypeManager.int64_type ||
3051 t == TypeManager.char_type ||
3052 t == TypeManager.string_type ||
3053 t == TypeManager.bool_type ||
3054 t.IsSubclassOf (TypeManager.enum_type))
3057 if (allowed_types == null){
3058 allowed_types = new Type [] {
3059 TypeManager.sbyte_type,
3060 TypeManager.byte_type,
3061 TypeManager.short_type,
3062 TypeManager.ushort_type,
3063 TypeManager.int32_type,
3064 TypeManager.uint32_type,
3065 TypeManager.int64_type,
3066 TypeManager.uint64_type,
3067 TypeManager.char_type,
3068 TypeManager.string_type,
3069 TypeManager.bool_type
3074 // Try to find a *user* defined implicit conversion.
3076 // If there is no implicit conversion, or if there are multiple
3077 // conversions, we have to report an error
3079 Expression converted = null;
3080 foreach (Type tt in allowed_types){
3083 e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
3088 // Ignore over-worked ImplicitUserConversions that do
3089 // an implicit conversion in addition to the user conversion.
3091 if (!(e is UserCast))
3094 if (converted != null){
3095 Report.ExtraInformation (
3097 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
3098 TypeManager.CSharpName (expr.Type)));
3108 // Performs the basic sanity checks on the switch statement
3109 // (looks for duplicate keys and non-constant expressions).
3111 // It also returns a hashtable with the keys that we will later
3112 // use to compute the switch tables
3114 bool CheckSwitch (EmitContext ec)
3117 Elements = Sections.Count > 10 ?
3118 (IDictionary)new Hashtable () :
3119 (IDictionary)new ListDictionary ();
3121 foreach (SwitchSection ss in Sections){
3122 foreach (SwitchLabel sl in ss.Labels){
3123 if (sl.Label == null){
3124 if (default_section != null){
3125 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)default_section.Labels [0]);
3128 default_section = ss;
3132 if (!sl.ResolveAndReduce (ec, SwitchType, HaveUnwrap)) {
3137 object key = sl.Converted;
3139 Elements.Add (key, sl);
3140 } catch (ArgumentException) {
3141 sl.Erorr_AlreadyOccurs (SwitchType, (SwitchLabel)Elements [key]);
3149 void EmitObjectInteger (ILGenerator ig, object k)
3152 IntConstant.EmitInt (ig, (int) k);
3153 else if (k is Constant) {
3154 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3157 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3160 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3162 IntConstant.EmitInt (ig, (int) (long) k);
3163 ig.Emit (OpCodes.Conv_I8);
3166 LongConstant.EmitLong (ig, (long) k);
3168 else if (k is ulong)
3170 ulong ul = (ulong) k;
3173 IntConstant.EmitInt (ig, unchecked ((int) ul));
3174 ig.Emit (OpCodes.Conv_U8);
3178 LongConstant.EmitLong (ig, unchecked ((long) ul));
3182 IntConstant.EmitInt (ig, (int) ((char) k));
3183 else if (k is sbyte)
3184 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3186 IntConstant.EmitInt (ig, (int) ((byte) k));
3187 else if (k is short)
3188 IntConstant.EmitInt (ig, (int) ((short) k));
3189 else if (k is ushort)
3190 IntConstant.EmitInt (ig, (int) ((ushort) k));
3192 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3194 throw new Exception ("Unhandled case");
3197 // structure used to hold blocks of keys while calculating table switch
3198 class KeyBlock : IComparable
3200 public KeyBlock (long _nFirst)
3202 nFirst = nLast = _nFirst;
3206 public ArrayList rgKeys = null;
3207 // how many items are in the bucket
3208 public int Size = 1;
3211 get { return (int) (nLast - nFirst + 1); }
3213 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3215 return kbLast.nLast - kbFirst.nFirst + 1;
3217 public int CompareTo (object obj)
3219 KeyBlock kb = (KeyBlock) obj;
3220 int nLength = Length;
3221 int nLengthOther = kb.Length;
3222 if (nLengthOther == nLength)
3223 return (int) (kb.nFirst - nFirst);
3224 return nLength - nLengthOther;
3229 /// This method emits code for a lookup-based switch statement (non-string)
3230 /// Basically it groups the cases into blocks that are at least half full,
3231 /// and then spits out individual lookup opcodes for each block.
3232 /// It emits the longest blocks first, and short blocks are just
3233 /// handled with direct compares.
3235 /// <param name="ec"></param>
3236 /// <param name="val"></param>
3237 /// <returns></returns>
3238 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
3240 int cElements = Elements.Count;
3241 object [] rgKeys = new object [cElements];
3242 Elements.Keys.CopyTo (rgKeys, 0);
3243 Array.Sort (rgKeys);
3245 // initialize the block list with one element per key
3246 ArrayList rgKeyBlocks = new ArrayList ();
3247 foreach (object key in rgKeys)
3248 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
3251 // iteratively merge the blocks while they are at least half full
3252 // there's probably a really cool way to do this with a tree...
3253 while (rgKeyBlocks.Count > 1)
3255 ArrayList rgKeyBlocksNew = new ArrayList ();
3256 kbCurr = (KeyBlock) rgKeyBlocks [0];
3257 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3259 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3260 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3263 kbCurr.nLast = kb.nLast;
3264 kbCurr.Size += kb.Size;
3268 // start a new block
3269 rgKeyBlocksNew.Add (kbCurr);
3273 rgKeyBlocksNew.Add (kbCurr);
3274 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3276 rgKeyBlocks = rgKeyBlocksNew;
3279 // initialize the key lists
3280 foreach (KeyBlock kb in rgKeyBlocks)
3281 kb.rgKeys = new ArrayList ();
3283 // fill the key lists
3285 if (rgKeyBlocks.Count > 0) {
3286 kbCurr = (KeyBlock) rgKeyBlocks [0];
3287 foreach (object key in rgKeys)
3289 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
3290 System.Convert.ToInt64 (key) > kbCurr.nLast;
3292 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3293 kbCurr.rgKeys.Add (key);
3297 // sort the blocks so we can tackle the largest ones first
3298 rgKeyBlocks.Sort ();
3300 // okay now we can start...
3301 ILGenerator ig = ec.ig;
3302 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3303 Label lblDefault = ig.DefineLabel ();
3305 Type typeKeys = null;
3306 if (rgKeys.Length > 0)
3307 typeKeys = rgKeys [0].GetType (); // used for conversions
3311 if (TypeManager.IsEnumType (SwitchType))
3312 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3314 compare_type = SwitchType;
3316 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3318 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3319 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3322 foreach (object key in kb.rgKeys)
3324 ig.Emit (OpCodes.Ldloc, val);
3325 EmitObjectInteger (ig, key);
3326 SwitchLabel sl = (SwitchLabel) Elements [key];
3327 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
3332 // TODO: if all the keys in the block are the same and there are
3333 // no gaps/defaults then just use a range-check.
3334 if (compare_type == TypeManager.int64_type ||
3335 compare_type == TypeManager.uint64_type)
3337 // TODO: optimize constant/I4 cases
3339 // check block range (could be > 2^31)
3340 ig.Emit (OpCodes.Ldloc, val);
3341 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3342 ig.Emit (OpCodes.Blt, lblDefault);
3343 ig.Emit (OpCodes.Ldloc, val);
3344 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
3345 ig.Emit (OpCodes.Bgt, lblDefault);
3348 ig.Emit (OpCodes.Ldloc, val);
3351 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
3352 ig.Emit (OpCodes.Sub);
3354 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3359 ig.Emit (OpCodes.Ldloc, val);
3360 int nFirst = (int) kb.nFirst;
3363 IntConstant.EmitInt (ig, nFirst);
3364 ig.Emit (OpCodes.Sub);
3366 else if (nFirst < 0)
3368 IntConstant.EmitInt (ig, -nFirst);
3369 ig.Emit (OpCodes.Add);
3373 // first, build the list of labels for the switch
3375 int cJumps = kb.Length;
3376 Label [] rgLabels = new Label [cJumps];
3377 for (int iJump = 0; iJump < cJumps; iJump++)
3379 object key = kb.rgKeys [iKey];
3380 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
3382 SwitchLabel sl = (SwitchLabel) Elements [key];
3383 rgLabels [iJump] = sl.GetILLabel (ec);
3387 rgLabels [iJump] = lblDefault;
3389 // emit the switch opcode
3390 ig.Emit (OpCodes.Switch, rgLabels);
3393 // mark the default for this block
3395 ig.MarkLabel (lblDefault);
3398 // TODO: find the default case and emit it here,
3399 // to prevent having to do the following jump.
3400 // make sure to mark other labels in the default section
3402 // the last default just goes to the end
3403 ig.Emit (OpCodes.Br, lblDefault);
3405 // now emit the code for the sections
3406 bool fFoundDefault = false;
3407 bool fFoundNull = false;
3408 foreach (SwitchSection ss in Sections)
3410 foreach (SwitchLabel sl in ss.Labels)
3411 if (sl.Converted == SwitchLabel.NullStringCase)
3415 foreach (SwitchSection ss in Sections)
3417 foreach (SwitchLabel sl in ss.Labels)
3419 ig.MarkLabel (sl.GetILLabel (ec));
3420 ig.MarkLabel (sl.GetILLabelCode (ec));
3421 if (sl.Converted == SwitchLabel.NullStringCase)
3422 ig.MarkLabel (null_target);
3423 else if (sl.Label == null) {
3424 ig.MarkLabel (lblDefault);
3425 fFoundDefault = true;
3427 ig.MarkLabel (null_target);
3433 if (!fFoundDefault) {
3434 ig.MarkLabel (lblDefault);
3436 ig.MarkLabel (lblEnd);
3439 // This simple emit switch works, but does not take advantage of the
3441 // TODO: remove non-string logic from here
3442 // TODO: binary search strings?
3444 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3446 ILGenerator ig = ec.ig;
3447 Label end_of_switch = ig.DefineLabel ();
3448 Label next_test = ig.DefineLabel ();
3449 bool first_test = true;
3450 bool pending_goto_end = false;
3451 bool null_marked = false;
3453 int section_count = Sections.Count;
3455 // TODO: implement switch optimization for string by using Hashtable
3456 //if (SwitchType == TypeManager.string_type && section_count > 7)
3457 // Console.WriteLine ("Switch optimization possible " + loc);
3459 ig.Emit (OpCodes.Ldloc, val);
3461 if (Elements.Contains (SwitchLabel.NullStringCase)){
3462 ig.Emit (OpCodes.Brfalse, null_target);
3464 ig.Emit (OpCodes.Brfalse, default_target);
3466 ig.Emit (OpCodes.Ldloc, val);
3467 ig.Emit (OpCodes.Call, TypeManager.string_isinterned_string);
3468 ig.Emit (OpCodes.Stloc, val);
3470 for (int section = 0; section < section_count; section++){
3471 SwitchSection ss = (SwitchSection) Sections [section];
3473 if (ss == default_section)
3476 Label sec_begin = ig.DefineLabel ();
3478 ig.Emit (OpCodes.Nop);
3480 if (pending_goto_end)
3481 ig.Emit (OpCodes.Br, end_of_switch);
3483 int label_count = ss.Labels.Count;
3485 for (int label = 0; label < label_count; label++){
3486 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
3487 ig.MarkLabel (sl.GetILLabel (ec));
3490 ig.MarkLabel (next_test);
3491 next_test = ig.DefineLabel ();
3494 // If we are the default target
3496 if (sl.Label != null){
3497 object lit = sl.Converted;
3499 if (lit == SwitchLabel.NullStringCase){
3501 if (label + 1 == label_count)
3502 ig.Emit (OpCodes.Br, next_test);
3506 ig.Emit (OpCodes.Ldloc, val);
3507 ig.Emit (OpCodes.Ldstr, (string)lit);
3508 if (label_count == 1)
3509 ig.Emit (OpCodes.Bne_Un, next_test);
3511 if (label+1 == label_count)
3512 ig.Emit (OpCodes.Bne_Un, next_test);
3514 ig.Emit (OpCodes.Beq, sec_begin);
3519 ig.MarkLabel (null_target);
3522 ig.MarkLabel (sec_begin);
3523 foreach (SwitchLabel sl in ss.Labels)
3524 ig.MarkLabel (sl.GetILLabelCode (ec));
3527 pending_goto_end = !ss.Block.HasRet;
3530 ig.MarkLabel (next_test);
3531 ig.MarkLabel (default_target);
3533 ig.MarkLabel (null_target);
3534 if (default_section != null)
3535 default_section.Block.Emit (ec);
3536 ig.MarkLabel (end_of_switch);
3539 SwitchSection FindSection (SwitchLabel label)
3541 foreach (SwitchSection ss in Sections){
3542 foreach (SwitchLabel sl in ss.Labels){
3551 public override bool Resolve (EmitContext ec)
3553 Expr = Expr.Resolve (ec);
3557 new_expr = SwitchGoverningType (ec, Expr);
3560 if ((new_expr == null) && TypeManager.IsNullableType (Expr.Type)) {
3561 unwrap = Nullable.Unwrap.Create (Expr, ec);
3565 new_expr = SwitchGoverningType (ec, unwrap);
3569 if (new_expr == null){
3570 Report.Error (151, loc, "A value of an integral type or string expected for switch");
3575 SwitchType = new_expr.Type;
3577 if (RootContext.Version == LanguageVersion.ISO_1 && SwitchType == TypeManager.bool_type) {
3578 Report.FeatureIsNotISO1 (loc, "switch expression of boolean type");
3582 if (!CheckSwitch (ec))
3586 Elements.Remove (SwitchLabel.NullStringCase);
3588 Switch old_switch = ec.Switch;
3590 ec.Switch.SwitchType = SwitchType;
3592 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3593 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3595 is_constant = new_expr is Constant;
3597 object key = ((Constant) new_expr).GetValue ();
3598 SwitchLabel label = (SwitchLabel) Elements [key];
3600 constant_section = FindSection (label);
3601 if (constant_section == null)
3602 constant_section = default_section;
3606 foreach (SwitchSection ss in Sections){
3608 ec.CurrentBranching.CreateSibling (
3609 null, FlowBranching.SiblingType.SwitchSection);
3613 if (is_constant && (ss != constant_section)) {
3614 // If we're a constant switch, we're only emitting
3615 // one single section - mark all the others as
3617 ec.CurrentBranching.CurrentUsageVector.Goto ();
3618 if (!ss.Block.ResolveUnreachable (ec, true))
3621 if (!ss.Block.Resolve (ec))
3626 if (default_section == null)
3627 ec.CurrentBranching.CreateSibling (
3628 null, FlowBranching.SiblingType.SwitchSection);
3630 ec.EndFlowBranching ();
3631 ec.Switch = old_switch;
3633 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching);
3638 protected override void DoEmit (EmitContext ec)
3640 ILGenerator ig = ec.ig;
3642 default_target = ig.DefineLabel ();
3643 null_target = ig.DefineLabel ();
3645 // Store variable for comparission purposes
3648 value = ig.DeclareLocal (SwitchType);
3650 unwrap.EmitCheck (ec);
3651 ig.Emit (OpCodes.Brfalse, null_target);
3653 ig.Emit (OpCodes.Stloc, value);
3655 } else if (!is_constant) {
3656 value = ig.DeclareLocal (SwitchType);
3658 ig.Emit (OpCodes.Stloc, value);
3663 // Setup the codegen context
3665 Label old_end = ec.LoopEnd;
3666 Switch old_switch = ec.Switch;
3668 ec.LoopEnd = ig.DefineLabel ();
3673 if (constant_section != null)
3674 constant_section.Block.Emit (ec);
3675 } else if (SwitchType == TypeManager.string_type)
3676 SimpleSwitchEmit (ec, value);
3678 TableSwitchEmit (ec, value);
3680 // Restore context state.
3681 ig.MarkLabel (ec.LoopEnd);
3684 // Restore the previous context
3686 ec.LoopEnd = old_end;
3687 ec.Switch = old_switch;
3690 protected override void CloneTo (CloneContext clonectx, Statement t)
3692 Switch target = (Switch) t;
3694 target.Expr = Expr.Clone (clonectx);
3695 target.Sections = new ArrayList ();
3696 foreach (SwitchSection ss in Sections){
3697 target.Sections.Add (ss.Clone (clonectx));
3702 public abstract class ExceptionStatement : Statement
3704 public abstract void EmitFinally (EmitContext ec);
3706 protected bool emit_finally = true;
3707 ArrayList parent_vectors;
3709 protected void DoEmitFinally (EmitContext ec)
3712 ec.ig.BeginFinallyBlock ();
3713 else if (ec.InIterator)
3714 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3718 protected void ResolveFinally (FlowBranchingException branching)
3720 emit_finally = branching.EmitFinally;
3722 branching.Parent.StealFinallyClauses (ref parent_vectors);
3726 public class Lock : ExceptionStatement {
3728 public Statement Statement;
3729 TemporaryVariable temp;
3731 public Lock (Expression expr, Statement stmt, Location l)
3738 public override bool Resolve (EmitContext ec)
3740 expr = expr.Resolve (ec);
3744 if (expr.Type.IsValueType){
3745 Report.Error (185, loc,
3746 "`{0}' is not a reference type as required by the lock statement",
3747 TypeManager.CSharpName (expr.Type));
3751 FlowBranchingException branching = ec.StartFlowBranching (this);
3752 bool ok = Statement.Resolve (ec);
3754 ResolveFinally (branching);
3756 ec.EndFlowBranching ();
3758 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
3759 // So, ensure there's some IL code after the finally block.
3760 ec.NeedReturnLabel ();
3762 // Avoid creating libraries that reference the internal
3765 if (t == TypeManager.null_type)
3766 t = TypeManager.object_type;
3768 temp = new TemporaryVariable (t, loc);
3774 protected override void DoEmit (EmitContext ec)
3776 ILGenerator ig = ec.ig;
3778 temp.Store (ec, expr);
3780 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3784 ig.BeginExceptionBlock ();
3785 Statement.Emit (ec);
3790 ig.EndExceptionBlock ();
3793 public override void EmitFinally (EmitContext ec)
3796 ec.ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3799 protected override void CloneTo (CloneContext clonectx, Statement t)
3801 Lock target = (Lock) t;
3803 target.expr = expr.Clone (clonectx);
3804 target.Statement = Statement.Clone (clonectx);
3808 public class Unchecked : Statement {
3811 public Unchecked (Block b)
3817 public override bool Resolve (EmitContext ec)
3819 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3820 return Block.Resolve (ec);
3823 protected override void DoEmit (EmitContext ec)
3825 using (ec.With (EmitContext.Flags.AllCheckStateFlags, false))
3829 protected override void CloneTo (CloneContext clonectx, Statement t)
3831 Unchecked target = (Unchecked) t;
3833 target.Block = clonectx.LookupBlock (Block);
3837 public class Checked : Statement {
3840 public Checked (Block b)
3843 b.Unchecked = false;
3846 public override bool Resolve (EmitContext ec)
3848 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3849 return Block.Resolve (ec);
3852 protected override void DoEmit (EmitContext ec)
3854 using (ec.With (EmitContext.Flags.AllCheckStateFlags, true))
3858 protected override void CloneTo (CloneContext clonectx, Statement t)
3860 Checked target = (Checked) t;
3862 target.Block = clonectx.LookupBlock (Block);
3866 public class Unsafe : Statement {
3869 public Unsafe (Block b)
3872 Block.Unsafe = true;
3875 public override bool Resolve (EmitContext ec)
3877 using (ec.With (EmitContext.Flags.InUnsafe, true))
3878 return Block.Resolve (ec);
3881 protected override void DoEmit (EmitContext ec)
3883 using (ec.With (EmitContext.Flags.InUnsafe, true))
3886 protected override void CloneTo (CloneContext clonectx, Statement t)
3888 Unsafe target = (Unsafe) t;
3890 target.Block = clonectx.LookupBlock (Block);
3897 public class Fixed : Statement {
3899 ArrayList declarators;
3900 Statement statement;
3905 abstract class Emitter
3907 protected LocalInfo vi;
3908 protected Expression converted;
3910 protected Emitter (Expression expr, LocalInfo li)
3916 public abstract void Emit (EmitContext ec);
3917 public abstract void EmitExit (EmitContext ec);
3920 class ExpressionEmitter : Emitter {
3921 public ExpressionEmitter (Expression converted, LocalInfo li) :
3922 base (converted, li)
3926 public override void Emit (EmitContext ec) {
3928 // Store pointer in pinned location
3930 converted.Emit (ec);
3931 vi.Variable.EmitAssign (ec);
3934 public override void EmitExit (EmitContext ec)
3936 ec.ig.Emit (OpCodes.Ldc_I4_0);
3937 ec.ig.Emit (OpCodes.Conv_U);
3938 vi.Variable.EmitAssign (ec);
3942 class StringEmitter : Emitter {
3943 LocalBuilder pinned_string;
3946 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3952 public override void Emit (EmitContext ec)
3954 ILGenerator ig = ec.ig;
3955 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3957 converted.Emit (ec);
3958 ig.Emit (OpCodes.Stloc, pinned_string);
3960 Expression sptr = new StringPtr (pinned_string, loc);
3961 converted = Convert.ImplicitConversionRequired (
3962 ec, sptr, vi.VariableType, loc);
3964 if (converted == null)
3967 converted.Emit (ec);
3968 vi.Variable.EmitAssign (ec);
3971 public override void EmitExit (EmitContext ec)
3973 ec.ig.Emit (OpCodes.Ldnull);
3974 ec.ig.Emit (OpCodes.Stloc, pinned_string);
3978 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3981 declarators = decls;
3986 public Statement Statement {
3987 get { return statement; }
3990 public override bool Resolve (EmitContext ec)
3993 Expression.UnsafeError (loc);
3997 TypeExpr texpr = null;
3998 if (type is VarExpr) {
3999 Unary u = ((Pair) declarators[0]).Second as Unary;
4003 Expression e = u.Expr.Resolve (ec);
4004 if (e == null || e.Type == null)
4007 Type t = TypeManager.GetPointerType (e.Type);
4008 texpr = new TypeExpression (t, loc);
4011 texpr = type.ResolveAsTypeTerminal (ec, false);
4016 expr_type = texpr.Type;
4018 data = new Emitter [declarators.Count];
4020 if (!expr_type.IsPointer){
4021 Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
4026 foreach (Pair p in declarators){
4027 LocalInfo vi = (LocalInfo) p.First;
4028 Expression e = (Expression) p.Second;
4030 if (type is VarExpr)
4031 vi.VariableType = expr_type;
4033 vi.VariableInfo.SetAssigned (ec);
4034 vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);
4037 // The rules for the possible declarators are pretty wise,
4038 // but the production on the grammar is more concise.
4040 // So we have to enforce these rules here.
4042 // We do not resolve before doing the case 1 test,
4043 // because the grammar is explicit in that the token &
4044 // is present, so we need to test for this particular case.
4048 Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
4053 // Case 1: & object.
4055 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4056 Expression child = ((Unary) e).Expr;
4058 if (child is ParameterReference || child is LocalVariableReference){
4061 "No need to use fixed statement for parameters or " +
4062 "local variable declarations (address is already " +
4067 ec.InFixedInitializer = true;
4069 ec.InFixedInitializer = false;
4073 child = ((Unary) e).Expr;
4075 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4078 if (!Convert.ImplicitConversionExists (ec, e, expr_type)) {
4079 e.Error_ValueCannotBeConverted (ec, e.Location, expr_type, false);
4083 data [i] = new ExpressionEmitter (e, vi);
4089 ec.InFixedInitializer = true;
4091 ec.InFixedInitializer = false;
4098 if (e.Type.IsArray){
4099 Type array_type = TypeManager.GetElementType (e.Type);
4102 // Provided that array_type is unmanaged,
4104 if (!TypeManager.VerifyUnManaged (array_type, loc))
4108 // and T* is implicitly convertible to the
4109 // pointer type given in the fixed statement.
4111 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
4113 Expression converted = Convert.ImplicitConversionRequired (
4114 ec, array_ptr, vi.VariableType, loc);
4115 if (converted == null)
4118 data [i] = new ExpressionEmitter (converted, vi);
4127 if (e.Type == TypeManager.string_type){
4128 data [i] = new StringEmitter (e, vi, loc);
4133 // Case 4: fixed buffer
4134 FieldExpr fe = e as FieldExpr;
4136 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
4138 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
4140 Expression converted = Convert.ImplicitConversionRequired (
4141 ec, fixed_buffer_ptr, vi.VariableType, loc);
4142 if (converted == null)
4145 data [i] = new ExpressionEmitter (converted, vi);
4153 // For other cases, flag a `this is already fixed expression'
4155 if (e is LocalVariableReference || e is ParameterReference ||
4156 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
4158 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
4162 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
4166 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
4167 bool ok = statement.Resolve (ec);
4168 bool flow_unreachable = ec.EndFlowBranching ();
4169 has_ret = flow_unreachable;
4174 protected override void DoEmit (EmitContext ec)
4176 for (int i = 0; i < data.Length; i++) {
4180 statement.Emit (ec);
4186 // Clear the pinned variable
4188 for (int i = 0; i < data.Length; i++) {
4189 data [i].EmitExit (ec);
4193 protected override void CloneTo (CloneContext clonectx, Statement t)
4195 Fixed target = (Fixed) t;
4197 target.type = type.Clone (clonectx);
4198 target.declarators = new ArrayList ();
4199 foreach (LocalInfo var in declarators)
4200 target.declarators.Add (clonectx.LookupVariable (var));
4201 target.statement = statement.Clone (clonectx);
4205 public class Catch : Statement {
4206 public readonly string Name;
4208 public Block VarBlock;
4210 Expression type_expr;
4213 public Catch (Expression type, string name, Block block, Block var_block, Location l)
4218 VarBlock = var_block;
4222 public Type CatchType {
4228 public bool IsGeneral {
4230 return type_expr == null;
4234 protected override void DoEmit(EmitContext ec)
4236 ILGenerator ig = ec.ig;
4238 if (CatchType != null)
4239 ig.BeginCatchBlock (CatchType);
4241 ig.BeginCatchBlock (TypeManager.object_type);
4243 if (VarBlock != null)
4247 LocalInfo vi = Block.GetLocalInfo (Name);
4249 throw new Exception ("Variable does not exist in this block");
4251 if (vi.Variable.NeedsTemporary) {
4252 LocalBuilder e = ig.DeclareLocal (vi.VariableType);
4253 ig.Emit (OpCodes.Stloc, e);
4255 vi.Variable.EmitInstance (ec);
4256 ig.Emit (OpCodes.Ldloc, e);
4257 vi.Variable.EmitAssign (ec);
4259 vi.Variable.EmitAssign (ec);
4261 ig.Emit (OpCodes.Pop);
4266 public override bool Resolve (EmitContext ec)
4268 using (ec.With (EmitContext.Flags.InCatch, true)) {
4269 if (type_expr != null) {
4270 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
4276 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4277 Error (155, "The type caught or thrown must be derived from System.Exception");
4283 if (!Block.Resolve (ec))
4286 // Even though VarBlock surrounds 'Block' we resolve it later, so that we can correctly
4287 // emit the "unused variable" warnings.
4288 if (VarBlock != null)
4289 return VarBlock.Resolve (ec);
4295 protected override void CloneTo (CloneContext clonectx, Statement t)
4297 Catch target = (Catch) t;
4299 target.type_expr = type_expr.Clone (clonectx);
4300 target.Block = clonectx.LookupBlock (Block);
4301 target.VarBlock = clonectx.LookupBlock (VarBlock);
4305 public class Try : ExceptionStatement {
4306 public Block Fini, Block;
4307 public ArrayList Specific;
4308 public Catch General;
4310 bool need_exc_block;
4313 // specific, general and fini might all be null.
4315 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4317 if (specific == null && general == null){
4318 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4322 this.Specific = specific;
4323 this.General = general;
4328 public override bool Resolve (EmitContext ec)
4332 FlowBranchingException branching = ec.StartFlowBranching (this);
4334 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4336 if (!Block.Resolve (ec))
4339 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4341 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4343 Type[] prevCatches = new Type [Specific.Count];
4345 foreach (Catch c in Specific){
4346 ec.CurrentBranching.CreateSibling (
4347 c.Block, FlowBranching.SiblingType.Catch);
4349 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4351 if (c.Name != null) {
4352 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
4354 throw new Exception ();
4356 vi.VariableInfo = null;
4359 if (!c.Resolve (ec))
4362 Type resolvedType = c.CatchType;
4363 for (int ii = 0; ii < last_index; ++ii) {
4364 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
4365 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type `{0}'", prevCatches [ii].FullName);
4370 prevCatches [last_index++] = resolvedType;
4371 need_exc_block = true;
4374 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4376 if (General != null){
4377 if (CodeGen.Assembly.WrapNonExceptionThrows) {
4378 foreach (Catch c in Specific){
4379 if (c.CatchType == TypeManager.exception_type) {
4380 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'");
4385 ec.CurrentBranching.CreateSibling (
4386 General.Block, FlowBranching.SiblingType.Catch);
4388 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4390 if (!General.Resolve (ec))
4393 need_exc_block = true;
4396 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4400 ec.CurrentBranching.CreateSibling (Fini, FlowBranching.SiblingType.Finally);
4402 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4403 using (ec.With (EmitContext.Flags.InFinally, true)) {
4404 if (!Fini.Resolve (ec))
4409 need_exc_block = true;
4412 if (ec.InIterator) {
4413 ResolveFinally (branching);
4414 need_exc_block |= emit_finally;
4416 emit_finally = Fini != null;
4418 ec.EndFlowBranching ();
4420 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4421 // So, ensure there's some IL code after the finally block.
4422 ec.NeedReturnLabel ();
4424 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4426 Report.Debug (1, "END OF TRY", ec.CurrentBranching, vector, f_vector);
4431 protected override void DoEmit (EmitContext ec)
4433 ILGenerator ig = ec.ig;
4436 ig.BeginExceptionBlock ();
4439 foreach (Catch c in Specific)
4442 if (General != null)
4447 ig.EndExceptionBlock ();
4450 public override void EmitFinally (EmitContext ec)
4456 public bool HasCatch
4459 return General != null || Specific.Count > 0;
4463 protected override void CloneTo (CloneContext clonectx, Statement t)
4465 Try target = (Try) t;
4467 target.Block = clonectx.LookupBlock (Block);
4469 target.Fini = clonectx.LookupBlock (Fini);
4470 if (General != null)
4471 target.General = (Catch) General.Clone (clonectx);
4472 if (Specific != null){
4473 target.Specific = new ArrayList ();
4474 foreach (Catch c in Specific)
4475 target.Specific.Add (c.Clone (clonectx));
4480 public class Using : ExceptionStatement {
4481 object expression_or_block;
4482 public Statement Statement;
4486 Expression [] resolved_vars;
4487 Expression [] converted_vars;
4488 ExpressionStatement [] assign;
4489 TemporaryVariable local_copy;
4491 public Using (object expression_or_block, Statement stmt, Location l)
4493 this.expression_or_block = expression_or_block;
4499 // Resolves for the case of using using a local variable declaration.
4501 bool ResolveLocalVariableDecls (EmitContext ec)
4505 TypeExpr texpr = null;
4507 if (expr is VarExpr) {
4508 Expression e = ((Expression)((DictionaryEntry)var_list[0]).Value).Resolve (ec);
4509 if (e == null || e.Type == null)
4511 texpr = new TypeExpression (e.Type, loc);
4514 texpr = expr.ResolveAsTypeTerminal (ec, false);
4519 expr_type = texpr.Type;
4522 // The type must be an IDisposable or an implicit conversion
4525 converted_vars = new Expression [var_list.Count];
4526 resolved_vars = new Expression [var_list.Count];
4527 assign = new ExpressionStatement [var_list.Count];
4529 bool need_conv = !TypeManager.ImplementsInterface (
4530 expr_type, TypeManager.idisposable_type);
4532 foreach (DictionaryEntry e in var_list){
4533 Expression var = (Expression) e.Key;
4535 if (expr is VarExpr) {
4536 LocalVariableReference l = var as LocalVariableReference;
4537 ((LocalInfo)l.Block.Variables[l.Name]).VariableType = expr_type;
4538 ((VarExpr)expr).Handled = true;
4541 var = var.ResolveLValue (ec, new EmptyExpression (), loc);
4545 resolved_vars [i] = var;
4552 converted_vars [i] = Convert.ImplicitConversion (
4553 ec, var, TypeManager.idisposable_type, loc);
4555 if (converted_vars [i] == null) {
4556 Error_IsNotConvertibleToIDisposable ();
4564 foreach (DictionaryEntry e in var_list){
4565 Expression var = resolved_vars [i];
4566 Expression new_expr = (Expression) e.Value;
4569 a = new Assign (var, new_expr, loc);
4575 converted_vars [i] = var;
4576 assign [i] = (ExpressionStatement) a;
4583 void Error_IsNotConvertibleToIDisposable ()
4585 Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
4586 TypeManager.CSharpName (expr_type));
4589 bool ResolveExpression (EmitContext ec)
4591 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4592 if (Convert.ImplicitConversion (ec, expr, TypeManager.idisposable_type, loc) == null) {
4593 Error_IsNotConvertibleToIDisposable ();
4598 local_copy = new TemporaryVariable (expr_type, loc);
4599 local_copy.Resolve (ec);
4605 // Emits the code for the case of using using a local variable declaration.
4607 void EmitLocalVariableDecls (EmitContext ec)
4609 ILGenerator ig = ec.ig;
4612 for (i = 0; i < assign.Length; i++) {
4613 assign [i].EmitStatement (ec);
4616 ig.BeginExceptionBlock ();
4618 Statement.Emit (ec);
4620 var_list.Reverse ();
4625 void EmitLocalVariableDeclFinally (EmitContext ec)
4627 ILGenerator ig = ec.ig;
4629 int i = assign.Length;
4630 for (int ii = 0; ii < var_list.Count; ++ii){
4631 Expression var = resolved_vars [--i];
4632 Label skip = ig.DefineLabel ();
4635 ig.BeginFinallyBlock ();
4637 if (!var.Type.IsValueType) {
4639 ig.Emit (OpCodes.Brfalse, skip);
4640 converted_vars [i].Emit (ec);
4641 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4643 Expression ml = Expression.MemberLookup(ec.ContainerType, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
4645 if (!(ml is MethodGroupExpr)) {
4647 ig.Emit (OpCodes.Box, var.Type);
4648 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4650 MethodInfo mi = null;
4652 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4653 if (TypeManager.GetParameterData (mk).Count == 0) {
4660 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4664 IMemoryLocation mloc = (IMemoryLocation) var;
4666 mloc.AddressOf (ec, AddressOp.Load);
4667 ig.Emit (OpCodes.Call, mi);
4671 ig.MarkLabel (skip);
4674 ig.EndExceptionBlock ();
4676 ig.BeginFinallyBlock ();
4681 void EmitExpression (EmitContext ec)
4684 // Make a copy of the expression and operate on that.
4686 ILGenerator ig = ec.ig;
4688 local_copy.Store (ec, expr);
4691 ig.BeginExceptionBlock ();
4693 Statement.Emit (ec);
4697 ig.EndExceptionBlock ();
4700 void EmitExpressionFinally (EmitContext ec)
4702 ILGenerator ig = ec.ig;
4703 if (!expr_type.IsValueType) {
4704 Label skip = ig.DefineLabel ();
4705 local_copy.Emit (ec);
4706 ig.Emit (OpCodes.Brfalse, skip);
4707 local_copy.Emit (ec);
4708 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4709 ig.MarkLabel (skip);
4711 Expression ml = Expression.MemberLookup (
4712 ec.ContainerType, TypeManager.idisposable_type, expr_type,
4713 "Dispose", Location.Null);
4715 if (!(ml is MethodGroupExpr)) {
4716 local_copy.Emit (ec);
4717 ig.Emit (OpCodes.Box, expr_type);
4718 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4720 MethodInfo mi = null;
4722 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4723 if (TypeManager.GetParameterData (mk).Count == 0) {
4730 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4734 local_copy.AddressOf (ec, AddressOp.Load);
4735 ig.Emit (OpCodes.Call, mi);
4740 public override bool Resolve (EmitContext ec)
4742 if (expression_or_block is DictionaryEntry){
4743 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4744 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4746 if (!ResolveLocalVariableDecls (ec))
4749 } else if (expression_or_block is Expression){
4750 expr = (Expression) expression_or_block;
4752 expr = expr.Resolve (ec);
4756 expr_type = expr.Type;
4758 if (!ResolveExpression (ec))
4762 FlowBranchingException branching = ec.StartFlowBranching (this);
4764 bool ok = Statement.Resolve (ec);
4766 ResolveFinally (branching);
4768 ec.EndFlowBranching ();
4770 // System.Reflection.Emit automatically emits a 'leave' to the end of the finally block.
4771 // So, ensure there's some IL code after the finally block.
4772 ec.NeedReturnLabel ();
4777 protected override void DoEmit (EmitContext ec)
4779 if (expression_or_block is DictionaryEntry)
4780 EmitLocalVariableDecls (ec);
4781 else if (expression_or_block is Expression)
4782 EmitExpression (ec);
4785 public override void EmitFinally (EmitContext ec)
4787 if (expression_or_block is DictionaryEntry)
4788 EmitLocalVariableDeclFinally (ec);
4789 else if (expression_or_block is Expression)
4790 EmitExpressionFinally (ec);
4793 protected override void CloneTo (CloneContext clonectx, Statement t)
4795 Using target = (Using) t;
4797 if (expression_or_block is Expression)
4798 target.expression_or_block = ((Expression) expression_or_block).Clone (clonectx);
4800 target.expression_or_block = ((Statement) expression_or_block).Clone (clonectx);
4802 target.Statement = Statement.Clone (clonectx);
4807 /// Implementation of the foreach C# statement
4809 public class Foreach : Statement {
4811 Expression variable;
4813 Statement statement;
4815 CollectionForeach collection;
4817 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4818 Statement stmt, Location l)
4821 this.variable = var;
4827 public Statement Statement {
4828 get { return statement; }
4831 public override bool Resolve (EmitContext ec)
4833 expr = expr.Resolve (ec);
4837 if (type is VarExpr) {
4838 Type element_type = null;
4839 if (TypeManager.HasElementType (expr.Type))
4840 element_type = TypeManager.GetElementType (expr.Type);
4842 MethodGroupExpr mg = Expression.MemberLookup (
4843 ec.ContainerType, expr.Type, "GetEnumerator", MemberTypes.Method,
4844 Expression.AllBindingFlags, loc) as MethodGroupExpr;
4849 MethodInfo get_enumerator = null;
4850 foreach (MethodInfo mi in mg.Methods) {
4851 if (TypeManager.GetParameterData (mi).Count != 0)
4853 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4855 if (CollectionForeach.IsOverride (mi))
4857 get_enumerator = mi;
4860 if (get_enumerator == null)
4863 PropertyInfo pi = TypeManager.GetProperty (get_enumerator.ReturnType, "Current");
4868 element_type = pi.PropertyType;
4871 type = new TypeLookupExpression (element_type.AssemblyQualifiedName);
4873 LocalVariableReference lv = variable as LocalVariableReference;
4874 ((LocalInfo)lv.Block.Variables[lv.Name]).VariableType = element_type;
4877 Constant c = expr as Constant;
4878 if (c != null && c.GetValue () == null) {
4879 Report.Error (186, loc, "Use of null is not valid in this context");
4883 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4887 Type var_type = texpr.Type;
4889 if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
4890 Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
4891 expr.ExprClassName);
4896 // We need an instance variable. Not sure this is the best
4897 // way of doing this.
4899 // FIXME: When we implement propertyaccess, will those turn
4900 // out to return values in ExprClass? I think they should.
4902 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4903 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4904 collection.Error_Enumerator ();
4908 if (expr.Type.IsArray) {
4909 array = new ArrayForeach (var_type, variable, expr, statement, loc);
4910 return array.Resolve (ec);
4912 collection = new CollectionForeach (
4913 var_type, variable, expr, statement, loc);
4914 return collection.Resolve (ec);
4918 protected override void DoEmit (EmitContext ec)
4920 ILGenerator ig = ec.ig;
4922 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4923 ec.LoopBegin = ig.DefineLabel ();
4924 ec.LoopEnd = ig.DefineLabel ();
4926 if (collection != null)
4927 collection.Emit (ec);
4931 ec.LoopBegin = old_begin;
4932 ec.LoopEnd = old_end;
4935 protected class ArrayCounter : TemporaryVariable
4937 public ArrayCounter (Location loc)
4938 : base (TypeManager.int32_type, loc)
4941 public void Initialize (EmitContext ec)
4944 ec.ig.Emit (OpCodes.Ldc_I4_0);
4948 public void Increment (EmitContext ec)
4952 ec.ig.Emit (OpCodes.Ldc_I4_1);
4953 ec.ig.Emit (OpCodes.Add);
4958 protected class ArrayForeach : Statement
4960 Expression variable, expr, conv;
4961 Statement statement;
4964 TemporaryVariable[] lengths;
4965 ArrayCounter[] counter;
4968 TemporaryVariable copy;
4971 public ArrayForeach (Type var_type, Expression var,
4972 Expression expr, Statement stmt, Location l)
4974 this.var_type = var_type;
4975 this.variable = var;
4981 public override bool Resolve (EmitContext ec)
4983 array_type = expr.Type;
4984 rank = array_type.GetArrayRank ();
4986 copy = new TemporaryVariable (array_type, loc);
4989 counter = new ArrayCounter [rank];
4990 lengths = new TemporaryVariable [rank];
4992 ArrayList list = new ArrayList ();
4993 for (int i = 0; i < rank; i++) {
4994 counter [i] = new ArrayCounter (loc);
4995 counter [i].Resolve (ec);
4997 lengths [i] = new TemporaryVariable (TypeManager.int32_type, loc);
4998 lengths [i].Resolve (ec);
5000 list.Add (counter [i]);
5003 access = new ElementAccess (copy, list).Resolve (ec);
5007 conv = Convert.ExplicitConversion (ec, access, var_type, loc);
5013 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
5014 ec.CurrentBranching.CreateSibling ();
5016 variable = variable.ResolveLValue (ec, conv, loc);
5017 if (variable == null)
5020 ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
5021 if (!statement.Resolve (ec))
5023 ec.EndFlowBranching ();
5025 // There's no direct control flow from the end of the embedded statement to the end of the loop
5026 ec.CurrentBranching.CurrentUsageVector.Goto ();
5028 ec.EndFlowBranching ();
5033 protected override void DoEmit (EmitContext ec)
5035 ILGenerator ig = ec.ig;
5037 copy.Store (ec, expr);
5039 Label[] test = new Label [rank];
5040 Label[] loop = new Label [rank];
5042 for (int i = 0; i < rank; i++) {
5043 test [i] = ig.DefineLabel ();
5044 loop [i] = ig.DefineLabel ();
5046 lengths [i].EmitThis (ec);
5047 ((ArrayAccess) access).EmitGetLength (ec, i);
5048 lengths [i].EmitStore (ec);
5051 for (int i = 0; i < rank; i++) {
5052 counter [i].Initialize (ec);
5054 ig.Emit (OpCodes.Br, test [i]);
5055 ig.MarkLabel (loop [i]);
5058 ((IAssignMethod) variable).EmitAssign (ec, conv, false, false);
5060 statement.Emit (ec);
5062 ig.MarkLabel (ec.LoopBegin);
5064 for (int i = rank - 1; i >= 0; i--){
5065 counter [i].Increment (ec);
5067 ig.MarkLabel (test [i]);
5068 counter [i].Emit (ec);
5069 lengths [i].Emit (ec);
5070 ig.Emit (OpCodes.Blt, loop [i]);
5073 ig.MarkLabel (ec.LoopEnd);
5077 protected class CollectionForeach : ExceptionStatement
5079 Expression variable, expr;
5080 Statement statement;
5082 TemporaryVariable enumerator;
5086 MethodGroupExpr get_enumerator;
5087 PropertyExpr get_current;
5088 MethodInfo move_next;
5089 Type var_type, enumerator_type;
5091 bool enumerator_found;
5093 public CollectionForeach (Type var_type, Expression var,
5094 Expression expr, Statement stmt, Location l)
5096 this.var_type = var_type;
5097 this.variable = var;
5103 bool GetEnumeratorFilter (EmitContext ec, MethodInfo mi)
5105 Type return_type = mi.ReturnType;
5107 if ((return_type == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
5109 // Apply the same optimization as MS: skip the GetEnumerator
5110 // returning an IEnumerator, and use the one returning a
5111 // CharEnumerator instead. This allows us to avoid the
5112 // try-finally block and the boxing.
5117 // Ok, we can access it, now make sure that we can do something
5118 // with this `GetEnumerator'
5121 if (return_type == TypeManager.ienumerator_type ||
5122 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
5123 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
5125 // If it is not an interface, lets try to find the methods ourselves.
5126 // For example, if we have:
5127 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
5128 // We can avoid the iface call. This is a runtime perf boost.
5129 // even bigger if we have a ValueType, because we avoid the cost
5132 // We have to make sure that both methods exist for us to take
5133 // this path. If one of the methods does not exist, we will just
5134 // use the interface. Sadly, this complex if statement is the only
5135 // way I could do this without a goto
5140 // Prefer a generic enumerator over a non-generic one.
5142 if (return_type.IsInterface && return_type.IsGenericType) {
5143 enumerator_type = return_type;
5144 if (!FetchGetCurrent (ec, return_type))
5145 get_current = new PropertyExpr (
5146 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5147 if (!FetchMoveNext (return_type))
5148 move_next = TypeManager.bool_movenext_void;
5153 if (return_type.IsInterface ||
5154 !FetchMoveNext (return_type) ||
5155 !FetchGetCurrent (ec, return_type)) {
5156 enumerator_type = return_type;
5157 move_next = TypeManager.bool_movenext_void;
5158 get_current = new PropertyExpr (
5159 ec.ContainerType, TypeManager.ienumerator_getcurrent, loc);
5164 // Ok, so they dont return an IEnumerable, we will have to
5165 // find if they support the GetEnumerator pattern.
5168 if (TypeManager.HasElementType (return_type) || !FetchMoveNext (return_type) || !FetchGetCurrent (ec, return_type)) {
5169 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",
5170 TypeManager.CSharpName (return_type), TypeManager.CSharpSignature (mi));
5175 enumerator_type = return_type;
5176 is_disposable = !enumerator_type.IsSealed ||
5177 TypeManager.ImplementsInterface (
5178 enumerator_type, TypeManager.idisposable_type);
5184 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5186 bool FetchMoveNext (Type t)
5188 MemberList move_next_list;
5190 move_next_list = TypeContainer.FindMembers (
5191 t, MemberTypes.Method,
5192 BindingFlags.Public | BindingFlags.Instance,
5193 Type.FilterName, "MoveNext");
5194 if (move_next_list.Count == 0)
5197 foreach (MemberInfo m in move_next_list){
5198 MethodInfo mi = (MethodInfo) m;
5200 if ((TypeManager.GetParameterData (mi).Count == 0) &&
5201 TypeManager.TypeToCoreType (mi.ReturnType) == TypeManager.bool_type) {
5211 // Retrieves a `public T get_Current ()' method from the Type `t'
5213 bool FetchGetCurrent (EmitContext ec, Type t)
5215 PropertyExpr pe = Expression.MemberLookup (
5216 ec.ContainerType, t, "Current", MemberTypes.Property,
5217 Expression.AllBindingFlags, loc) as PropertyExpr;
5226 // Retrieves a `public void Dispose ()' method from the Type `t'
5228 static MethodInfo FetchMethodDispose (Type t)
5230 MemberList dispose_list;
5232 dispose_list = TypeContainer.FindMembers (
5233 t, MemberTypes.Method,
5234 BindingFlags.Public | BindingFlags.Instance,
5235 Type.FilterName, "Dispose");
5236 if (dispose_list.Count == 0)
5239 foreach (MemberInfo m in dispose_list){
5240 MethodInfo mi = (MethodInfo) m;
5242 if (TypeManager.GetParameterData (mi).Count == 0){
5243 if (mi.ReturnType == TypeManager.void_type)
5250 public void Error_Enumerator ()
5252 if (enumerator_found) {
5256 Report.Error (1579, loc,
5257 "foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `GetEnumerator' or is not accessible",
5258 TypeManager.CSharpName (expr.Type));
5261 public static bool IsOverride (MethodInfo m)
5263 m = (MethodInfo) TypeManager.DropGenericMethodArguments (m);
5265 if (!m.IsVirtual || ((m.Attributes & MethodAttributes.NewSlot) != 0))
5267 if (m is MethodBuilder)
5270 MethodInfo base_method = m.GetBaseDefinition ();
5271 return base_method != m;
5274 bool TryType (EmitContext ec, Type t)
5276 MethodGroupExpr mg = Expression.MemberLookup (
5277 ec.ContainerType, t, "GetEnumerator", MemberTypes.Method,
5278 Expression.AllBindingFlags, loc) as MethodGroupExpr;
5282 MethodInfo result = null;
5283 MethodInfo tmp_move_next = null;
5284 PropertyExpr tmp_get_cur = null;
5285 Type tmp_enumerator_type = enumerator_type;
5286 foreach (MethodInfo mi in mg.Methods) {
5287 if (TypeManager.GetParameterData (mi).Count != 0)
5290 // Check whether GetEnumerator is public
5291 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
5294 if (IsOverride (mi))
5297 enumerator_found = true;
5299 if (!GetEnumeratorFilter (ec, mi))
5302 if (result != null) {
5303 if (TypeManager.IsGenericType (result.ReturnType)) {
5304 if (!TypeManager.IsGenericType (mi.ReturnType))
5307 MethodBase mb = TypeManager.DropGenericMethodArguments (mi);
5308 Report.SymbolRelatedToPreviousError (t);
5309 Report.Error(1640, loc, "foreach statement cannot operate on variables of type `{0}' " +
5310 "because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
5311 TypeManager.CSharpName (t), TypeManager.CSharpSignature (mb));
5315 // Always prefer generics enumerators
5316 if (!TypeManager.IsGenericType (mi.ReturnType)) {
5317 if (TypeManager.ImplementsInterface (mi.DeclaringType, result.DeclaringType) ||
5318 TypeManager.ImplementsInterface (result.DeclaringType, mi.DeclaringType))
5321 Report.SymbolRelatedToPreviousError (result);
5322 Report.SymbolRelatedToPreviousError (mi);
5323 Report.Warning (278, 2, loc, "`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
5324 TypeManager.CSharpName (t), "enumerable", TypeManager.CSharpSignature (result), TypeManager.CSharpSignature (mi));
5329 tmp_move_next = move_next;
5330 tmp_get_cur = get_current;
5331 tmp_enumerator_type = enumerator_type;
5332 if (mi.DeclaringType == t)
5336 if (result != null) {
5337 move_next = tmp_move_next;
5338 get_current = tmp_get_cur;
5339 enumerator_type = tmp_enumerator_type;
5340 MethodInfo[] mi = new MethodInfo[] { (MethodInfo) result };
5341 get_enumerator = new MethodGroupExpr (mi, loc);
5343 if (t != expr.Type) {
5344 expr = Convert.ExplicitConversion (
5347 throw new InternalErrorException ();
5350 get_enumerator.InstanceExpression = expr;
5351 get_enumerator.IsBase = t != expr.Type;
5359 bool ProbeCollectionType (EmitContext ec, Type t)
5361 int errors = Report.Errors;
5362 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
5363 if (TryType (ec, tt))
5368 if (Report.Errors > errors)
5372 // Now try to find the method in the interfaces
5374 Type [] ifaces = TypeManager.GetInterfaces (t);
5375 foreach (Type i in ifaces){
5376 if (TryType (ec, i))
5383 public override bool Resolve (EmitContext ec)
5385 enumerator_type = TypeManager.ienumerator_type;
5386 is_disposable = true;
5388 if (!ProbeCollectionType (ec, expr.Type)) {
5389 Error_Enumerator ();
5393 enumerator = new TemporaryVariable (enumerator_type, loc);
5394 enumerator.Resolve (ec);
5396 init = new Invocation (get_enumerator, new ArrayList ());
5397 init = init.Resolve (ec);
5401 Expression move_next_expr;
5403 MemberInfo[] mi = new MemberInfo[] { move_next };
5404 MethodGroupExpr mg = new MethodGroupExpr (mi, loc);
5405 mg.InstanceExpression = enumerator;
5407 move_next_expr = new Invocation (mg, new ArrayList ());
5410 get_current.InstanceExpression = enumerator;
5412 Statement block = new CollectionForeachStatement (
5413 var_type, variable, get_current, statement, loc);
5415 loop = new While (move_next_expr, block, loc);
5419 FlowBranchingException branching = null;
5421 branching = ec.StartFlowBranching (this);
5423 if (!loop.Resolve (ec))
5426 if (is_disposable) {
5427 ResolveFinally (branching);
5428 ec.EndFlowBranching ();
5430 emit_finally = true;
5435 protected override void DoEmit (EmitContext ec)
5437 ILGenerator ig = ec.ig;
5439 enumerator.Store (ec, init);
5442 // Protect the code in a try/finalize block, so that
5443 // if the beast implement IDisposable, we get rid of it
5445 if (is_disposable && emit_finally)
5446 ig.BeginExceptionBlock ();
5451 // Now the finally block
5453 if (is_disposable) {
5456 ig.EndExceptionBlock ();
5461 public override void EmitFinally (EmitContext ec)
5463 ILGenerator ig = ec.ig;
5465 if (enumerator_type.IsValueType) {
5466 MethodInfo mi = FetchMethodDispose (enumerator_type);
5468 enumerator.EmitLoadAddress (ec);
5469 ig.Emit (OpCodes.Call, mi);
5471 enumerator.Emit (ec);
5472 ig.Emit (OpCodes.Box, enumerator_type);
5473 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5476 Label call_dispose = ig.DefineLabel ();
5478 enumerator.Emit (ec);
5479 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5480 ig.Emit (OpCodes.Dup);
5481 ig.Emit (OpCodes.Brtrue_S, call_dispose);
5482 ig.Emit (OpCodes.Pop);
5484 Label end_finally = ig.DefineLabel ();
5485 ig.Emit (OpCodes.Br, end_finally);
5487 ig.MarkLabel (call_dispose);
5488 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5489 ig.MarkLabel (end_finally);
5494 protected class CollectionForeachStatement : Statement
5497 Expression variable, current, conv;
5498 Statement statement;
5501 public CollectionForeachStatement (Type type, Expression variable,
5502 Expression current, Statement statement,
5506 this.variable = variable;
5507 this.current = current;
5508 this.statement = statement;
5512 public override bool Resolve (EmitContext ec)
5514 current = current.Resolve (ec);
5515 if (current == null)
5518 conv = Convert.ExplicitConversion (ec, current, type, loc);
5522 assign = new Assign (variable, conv, loc);
5523 if (assign.Resolve (ec) == null)
5526 if (!statement.Resolve (ec))
5532 protected override void DoEmit (EmitContext ec)
5534 assign.EmitStatement (ec);
5535 statement.Emit (ec);
5539 protected override void CloneTo (CloneContext clonectx, Statement t)
5541 Foreach target = (Foreach) t;
5543 target.type = type.Clone (clonectx);
5544 target.variable = variable.Clone (clonectx);
5545 target.expr = expr.Clone (clonectx);
5546 target.statement = statement.Clone (clonectx);