2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
8 // (C) 2001, 2002 Ximian, Inc.
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 using System.Collections;
21 public abstract class Statement {
25 /// Resolves the statement, true means that all sub-statements
28 public virtual bool Resolve (EmitContext ec)
34 /// Return value indicates whether all code paths emitted return.
36 public abstract bool Emit (EmitContext ec);
38 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
44 if (e.Type != TypeManager.bool_type){
45 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
51 31, loc, "Can not convert the expression to a boolean");
54 if (CodeGen.SymbolWriter != null)
61 /// Encapsulates the emission of a boolean test and jumping to a
64 /// This will emit the bool expression in `bool_expr' and if
65 /// `target_is_for_true' is true, then the code will generate a
66 /// brtrue to the target. Otherwise a brfalse.
68 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
69 Label target, bool target_is_for_true)
71 ILGenerator ig = ec.ig;
74 if (bool_expr is Unary){
75 Unary u = (Unary) bool_expr;
77 if (u.Oper == Unary.Operator.LogicalNot){
80 u.EmitLogicalNot (ec);
82 } else if (bool_expr is Binary){
83 Binary b = (Binary) bool_expr;
85 if (b.EmitBranchable (ec, target, target_is_for_true))
92 if (target_is_for_true){
94 ig.Emit (OpCodes.Brfalse, target);
96 ig.Emit (OpCodes.Brtrue, target);
99 ig.Emit (OpCodes.Brtrue, target);
101 ig.Emit (OpCodes.Brfalse, target);
105 public static void Warning_DeadCodeFound (Location loc)
107 Report.Warning (162, loc, "Unreachable code detected");
111 public class EmptyStatement : Statement {
112 public override bool Resolve (EmitContext ec)
117 public override bool Emit (EmitContext ec)
123 public class If : Statement {
125 public Statement TrueStatement;
126 public Statement FalseStatement;
128 public If (Expression expr, Statement trueStatement, Location l)
131 TrueStatement = trueStatement;
135 public If (Expression expr,
136 Statement trueStatement,
137 Statement falseStatement,
141 TrueStatement = trueStatement;
142 FalseStatement = falseStatement;
146 public override bool Resolve (EmitContext ec)
148 Report.Debug (1, "START IF BLOCK", loc);
150 expr = ResolveBoolean (ec, expr, loc);
155 ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
157 if (!TrueStatement.Resolve (ec)) {
158 ec.KillFlowBranching ();
162 ec.CurrentBranching.CreateSibling ();
164 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
165 ec.KillFlowBranching ();
169 ec.EndFlowBranching ();
171 Report.Debug (1, "END IF BLOCK", loc);
176 public override bool Emit (EmitContext ec)
178 ILGenerator ig = ec.ig;
179 Label false_target = ig.DefineLabel ();
181 bool is_true_ret, is_false_ret;
184 // Dead code elimination
186 if (expr is BoolConstant){
187 bool take = ((BoolConstant) expr).Value;
190 if (FalseStatement != null){
191 Warning_DeadCodeFound (FalseStatement.loc);
193 return TrueStatement.Emit (ec);
195 Warning_DeadCodeFound (TrueStatement.loc);
196 if (FalseStatement != null)
197 return FalseStatement.Emit (ec);
201 EmitBoolExpression (ec, expr, false_target, false);
203 is_true_ret = TrueStatement.Emit (ec);
204 is_false_ret = is_true_ret;
206 if (FalseStatement != null){
207 bool branch_emitted = false;
209 end = ig.DefineLabel ();
211 ig.Emit (OpCodes.Br, end);
212 branch_emitted = true;
215 ig.MarkLabel (false_target);
216 is_false_ret = FalseStatement.Emit (ec);
221 ig.MarkLabel (false_target);
222 is_false_ret = false;
225 return is_true_ret && is_false_ret;
229 public class Do : Statement {
230 public Expression expr;
231 public readonly Statement EmbeddedStatement;
233 public Do (Statement statement, Expression boolExpr, Location l)
236 EmbeddedStatement = statement;
240 public override bool Resolve (EmitContext ec)
244 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
246 if (!EmbeddedStatement.Resolve (ec))
249 ec.EndFlowBranching ();
251 expr = ResolveBoolean (ec, expr, loc);
258 public override bool Emit (EmitContext ec)
260 ILGenerator ig = ec.ig;
261 Label loop = ig.DefineLabel ();
262 Label old_begin = ec.LoopBegin;
263 Label old_end = ec.LoopEnd;
264 bool old_inloop = ec.InLoop;
265 bool old_breaks = ec.Breaks;
266 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
268 ec.LoopBegin = ig.DefineLabel ();
269 ec.LoopEnd = ig.DefineLabel ();
271 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
275 EmbeddedStatement.Emit (ec);
276 bool breaks = ec.Breaks;
277 ig.MarkLabel (ec.LoopBegin);
280 // Dead code elimination
282 if (expr is BoolConstant){
283 bool res = ((BoolConstant) expr).Value;
286 ec.ig.Emit (OpCodes.Br, loop);
288 EmitBoolExpression (ec, expr, loop, true);
290 ig.MarkLabel (ec.LoopEnd);
292 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
293 ec.LoopBegin = old_begin;
294 ec.LoopEnd = old_end;
295 ec.InLoop = old_inloop;
296 ec.Breaks = old_breaks;
299 // Inform whether we are infinite or not
301 if (expr is BoolConstant){
302 BoolConstant bc = (BoolConstant) expr;
304 if (bc.Value == true)
305 return breaks == false;
312 public class While : Statement {
313 public Expression expr;
314 public readonly Statement Statement;
316 public While (Expression boolExpr, Statement statement, Location l)
318 this.expr = boolExpr;
319 Statement = statement;
323 public override bool Resolve (EmitContext ec)
327 expr = ResolveBoolean (ec, expr, loc);
331 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
333 if (!Statement.Resolve (ec))
336 ec.EndFlowBranching ();
341 public override bool Emit (EmitContext ec)
343 ILGenerator ig = ec.ig;
344 Label old_begin = ec.LoopBegin;
345 Label old_end = ec.LoopEnd;
346 bool old_inloop = ec.InLoop;
347 bool old_breaks = ec.Breaks;
348 Label while_loop = ig.DefineLabel ();
349 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
352 ec.LoopBegin = ig.DefineLabel ();
353 ec.LoopEnd = ig.DefineLabel ();
355 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
357 ig.Emit (OpCodes.Br, ec.LoopBegin);
358 ig.MarkLabel (while_loop);
361 // Inform whether we are infinite or not
363 if (expr is BoolConstant){
364 BoolConstant bc = (BoolConstant) expr;
366 ig.MarkLabel (ec.LoopBegin);
367 if (bc.Value == false){
368 Warning_DeadCodeFound (Statement.loc);
376 ig.Emit (OpCodes.Br, ec.LoopBegin);
379 // Inform that we are infinite (ie, `we return'), only
380 // if we do not `break' inside the code.
382 ret = breaks == false;
384 ig.MarkLabel (ec.LoopEnd);
388 ig.MarkLabel (ec.LoopBegin);
390 EmitBoolExpression (ec, expr, while_loop, true);
391 ig.MarkLabel (ec.LoopEnd);
396 ec.LoopBegin = old_begin;
397 ec.LoopEnd = old_end;
398 ec.InLoop = old_inloop;
399 ec.Breaks = old_breaks;
400 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
406 public class For : Statement {
408 readonly Statement InitStatement;
409 readonly Statement Increment;
410 readonly Statement Statement;
412 public For (Statement initStatement,
418 InitStatement = initStatement;
420 Increment = increment;
421 Statement = statement;
425 public override bool Resolve (EmitContext ec)
429 if (InitStatement != null){
430 if (!InitStatement.Resolve (ec))
435 Test = ResolveBoolean (ec, Test, loc);
440 if (Increment != null){
441 if (!Increment.Resolve (ec))
445 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
447 if (!Statement.Resolve (ec))
450 ec.EndFlowBranching ();
455 public override bool Emit (EmitContext ec)
457 ILGenerator ig = ec.ig;
458 Label old_begin = ec.LoopBegin;
459 Label old_end = ec.LoopEnd;
460 bool old_inloop = ec.InLoop;
461 bool old_breaks = ec.Breaks;
462 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
463 Label loop = ig.DefineLabel ();
464 Label test = ig.DefineLabel ();
466 if (InitStatement != null)
467 if (! (InitStatement is EmptyStatement))
468 InitStatement.Emit (ec);
470 ec.LoopBegin = ig.DefineLabel ();
471 ec.LoopEnd = ig.DefineLabel ();
473 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
475 ig.Emit (OpCodes.Br, test);
479 bool breaks = ec.Breaks;
481 ig.MarkLabel (ec.LoopBegin);
482 if (!(Increment is EmptyStatement))
487 // If test is null, there is no test, and we are just
491 EmitBoolExpression (ec, Test, loop, true);
493 ig.Emit (OpCodes.Br, loop);
494 ig.MarkLabel (ec.LoopEnd);
496 ec.LoopBegin = old_begin;
497 ec.LoopEnd = old_end;
498 ec.InLoop = old_inloop;
499 ec.Breaks = old_breaks;
500 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
503 // Inform whether we are infinite or not
506 if (Test is BoolConstant){
507 BoolConstant bc = (BoolConstant) Test;
510 return breaks == false;
518 public class StatementExpression : Statement {
521 public StatementExpression (ExpressionStatement expr, Location l)
527 public override bool Resolve (EmitContext ec)
529 expr = (Expression) expr.Resolve (ec);
533 public override bool Emit (EmitContext ec)
535 ILGenerator ig = ec.ig;
537 if (expr is ExpressionStatement)
538 ((ExpressionStatement) expr).EmitStatement (ec);
541 ig.Emit (OpCodes.Pop);
547 public override string ToString ()
549 return "StatementExpression (" + expr + ")";
554 /// Implements the return statement
556 public class Return : Statement {
557 public Expression Expr;
559 public Return (Expression expr, Location l)
565 public override bool Resolve (EmitContext ec)
568 Expr = Expr.Resolve (ec);
573 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
575 if (ec.CurrentBranching.InTryBlock ())
576 ec.CurrentBranching.AddFinallyVector (vector);
578 vector.Returns = FlowReturns.ALWAYS;
582 public override bool Emit (EmitContext ec)
585 Report.Error (157,loc,"Control can not leave the body of the finally block");
589 if (ec.ReturnType == null){
591 Report.Error (127, loc, "Return with a value not allowed here");
596 Report.Error (126, loc, "An object of type `" +
597 TypeManager.CSharpName (ec.ReturnType) + "' is " +
598 "expected for the return statement");
602 if (Expr.Type != ec.ReturnType)
603 Expr = Expression.ConvertImplicitRequired (
604 ec, Expr, ec.ReturnType, loc);
611 if (ec.InTry || ec.InCatch)
612 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
615 if (ec.InTry || ec.InCatch) {
616 if (!ec.HasReturnLabel) {
617 ec.ReturnLabel = ec.ig.DefineLabel ();
618 ec.HasReturnLabel = true;
620 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
622 ec.ig.Emit (OpCodes.Ret);
628 public class Goto : Statement {
631 LabeledStatement label;
633 public override bool Resolve (EmitContext ec)
635 label = block.LookupLabel (target);
639 "No such label `" + target + "' in this scope");
643 // If this is a forward goto.
644 if (!label.IsDefined)
645 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
647 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
652 public Goto (Block parent_block, string label, Location l)
654 block = parent_block;
659 public string Target {
665 public override bool Emit (EmitContext ec)
667 Label l = label.LabelTarget (ec);
668 ec.ig.Emit (OpCodes.Br, l);
674 public class LabeledStatement : Statement {
675 public readonly Location Location;
683 public LabeledStatement (string label_name, Location l)
685 this.label_name = label_name;
689 public Label LabelTarget (EmitContext ec)
693 label = ec.ig.DefineLabel ();
699 public bool IsDefined {
705 public bool HasBeenReferenced {
711 public void AddUsageVector (FlowBranching.UsageVector vector)
714 vectors = new ArrayList ();
716 vectors.Add (vector.Clone ());
719 public override bool Resolve (EmitContext ec)
722 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
729 public override bool Emit (EmitContext ec)
732 ec.ig.MarkLabel (label);
740 /// `goto default' statement
742 public class GotoDefault : Statement {
744 public GotoDefault (Location l)
749 public override bool Resolve (EmitContext ec)
751 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
752 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
756 public override bool Emit (EmitContext ec)
758 if (ec.Switch == null){
759 Report.Error (153, loc, "goto default is only valid in a switch statement");
763 if (!ec.Switch.GotDefault){
764 Report.Error (159, loc, "No default target on switch statement");
767 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
773 /// `goto case' statement
775 public class GotoCase : Statement {
779 public GotoCase (Expression e, Location l)
785 public override bool Resolve (EmitContext ec)
787 if (ec.Switch == null){
788 Report.Error (153, loc, "goto case is only valid in a switch statement");
792 expr = expr.Resolve (ec);
796 if (!(expr is Constant)){
797 Report.Error (159, loc, "Target expression for goto case is not constant");
801 object val = Expression.ConvertIntLiteral (
802 (Constant) expr, ec.Switch.SwitchType, loc);
807 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
812 "No such label 'case " + val + "': for the goto case");
815 label = sl.ILLabelCode;
817 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
818 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
822 public override bool Emit (EmitContext ec)
824 ec.ig.Emit (OpCodes.Br, label);
829 public class Throw : Statement {
832 public Throw (Expression expr, Location l)
838 public override bool Resolve (EmitContext ec)
841 expr = expr.Resolve (ec);
845 ExprClass eclass = expr.eclass;
847 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
848 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
849 expr.Error118 ("value, variable, property or indexer access ");
855 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)) {
856 Report.Error (155, loc,
857 "The type caught or thrown must be derived " +
858 "from System.Exception");
863 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
867 public override bool Emit (EmitContext ec)
871 ec.ig.Emit (OpCodes.Rethrow);
875 "A throw statement with no argument is only " +
876 "allowed in a catch clause");
883 ec.ig.Emit (OpCodes.Throw);
889 public class Break : Statement {
891 public Break (Location l)
896 public override bool Resolve (EmitContext ec)
898 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
902 public override bool Emit (EmitContext ec)
904 ILGenerator ig = ec.ig;
906 if (ec.InLoop == false && ec.Switch == null){
907 Report.Error (139, loc, "No enclosing loop or switch to continue to");
912 if (ec.InTry || ec.InCatch)
913 ig.Emit (OpCodes.Leave, ec.LoopEnd);
915 ig.Emit (OpCodes.Br, ec.LoopEnd);
921 public class Continue : Statement {
923 public Continue (Location l)
928 public override bool Resolve (EmitContext ec)
930 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
934 public override bool Emit (EmitContext ec)
936 Label begin = ec.LoopBegin;
939 Report.Error (139, loc, "No enclosing loop to continue to");
944 // UGH: Non trivial. This Br might cross a try/catch boundary
948 // try { ... } catch { continue; }
952 // try {} catch { while () { continue; }}
954 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
955 ec.ig.Emit (OpCodes.Leave, begin);
956 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
957 throw new Exception ("Should never happen");
959 ec.ig.Emit (OpCodes.Br, begin);
965 // This is used in the control flow analysis code to specify whether the
966 // current code block may return to its enclosing block before reaching
969 public enum FlowReturns {
970 // It can never return.
973 // This means that the block contains a conditional return statement
977 // The code always returns, ie. there's an unconditional return / break
981 // The code always throws an exception.
984 // The current code block is unreachable. This happens if it's immediately
985 // following a FlowReturns.ALWAYS block.
990 // This is a special bit vector which can inherit from another bit vector doing a
991 // copy-on-write strategy. The inherited vector may have a smaller size than the
994 public class MyBitVector {
995 public readonly int Count;
996 public readonly MyBitVector InheritsFrom;
1001 public MyBitVector (int Count)
1002 : this (null, Count)
1005 public MyBitVector (MyBitVector InheritsFrom, int Count)
1007 this.InheritsFrom = InheritsFrom;
1012 // Checks whether this bit vector has been modified. After setting this to true,
1013 // we won't use the inherited vector anymore, but our own copy of it.
1015 public bool IsDirty {
1022 initialize_vector ();
1027 // Get/set bit `index' in the bit vector.
1029 public bool this [int index]
1033 throw new ArgumentOutOfRangeException ();
1035 // We're doing a "copy-on-write" strategy here; as long
1036 // as nobody writes to the array, we can use our parent's
1037 // copy instead of duplicating the vector.
1040 return vector [index];
1041 else if (InheritsFrom != null) {
1042 BitArray inherited = InheritsFrom.Vector;
1044 if (index < inherited.Count)
1045 return inherited [index];
1054 throw new ArgumentOutOfRangeException ();
1056 // Only copy the vector if we're actually modifying it.
1058 if (this [index] != value) {
1059 initialize_vector ();
1061 vector [index] = value;
1067 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1068 // copy of the bit vector.
1070 public static explicit operator BitArray (MyBitVector vector)
1072 vector.initialize_vector ();
1073 return vector.Vector;
1077 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1078 // different size than the current one.
1080 public void Or (MyBitVector new_vector)
1082 BitArray new_array = new_vector.Vector;
1084 initialize_vector ();
1087 if (vector.Count < new_array.Count)
1088 upper = vector.Count;
1090 upper = new_array.Count;
1092 for (int i = 0; i < upper; i++)
1093 vector [i] = vector [i] | new_array [i];
1097 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1098 // a different size than the current one.
1100 public void And (MyBitVector new_vector)
1102 BitArray new_array = new_vector.Vector;
1104 initialize_vector ();
1107 if (vector.Count < new_array.Count)
1108 lower = upper = vector.Count;
1110 lower = new_array.Count;
1111 upper = vector.Count;
1114 for (int i = 0; i < lower; i++)
1115 vector [i] = vector [i] & new_array [i];
1117 for (int i = lower; i < upper; i++)
1122 // This does a deep copy of the bit vector.
1124 public MyBitVector Clone ()
1126 MyBitVector retval = new MyBitVector (Count);
1128 retval.Vector = Vector;
1137 else if (!is_dirty && (InheritsFrom != null))
1138 return InheritsFrom.Vector;
1140 initialize_vector ();
1146 initialize_vector ();
1148 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1149 vector [i] = value [i];
1153 void initialize_vector ()
1158 vector = new BitArray (Count, false);
1159 if (InheritsFrom != null)
1160 Vector = InheritsFrom.Vector;
1165 public override string ToString ()
1167 StringBuilder sb = new StringBuilder ("MyBitVector (");
1169 BitArray vector = Vector;
1173 sb.Append ("INHERITED - ");
1174 for (int i = 0; i < vector.Count; i++) {
1177 sb.Append (vector [i]);
1181 return sb.ToString ();
1186 // The type of a FlowBranching.
1188 public enum FlowBranchingType {
1189 // Normal (conditional or toplevel) block.
1206 // A new instance of this class is created every time a new block is resolved
1207 // and if there's branching in the block's control flow.
1209 public class FlowBranching {
1211 // The type of this flow branching.
1213 public readonly FlowBranchingType Type;
1216 // The block this branching is contained in. This may be null if it's not
1217 // a top-level block and it doesn't declare any local variables.
1219 public readonly Block Block;
1222 // The parent of this branching or null if this is the top-block.
1224 public readonly FlowBranching Parent;
1227 // Start-Location of this flow branching.
1229 public readonly Location Location;
1232 // A list of UsageVectors. A new vector is added each time control flow may
1233 // take a different path.
1235 public ArrayList Siblings;
1240 InternalParameters param_info;
1242 MyStructInfo[] struct_params;
1244 ArrayList finally_vectors;
1246 static int next_id = 0;
1250 // Performs an `And' operation on the FlowReturns status
1251 // (for instance, a block only returns ALWAYS if all its siblings
1254 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1256 if (b == FlowReturns.UNREACHABLE)
1260 case FlowReturns.NEVER:
1261 if (b == FlowReturns.NEVER)
1262 return FlowReturns.NEVER;
1264 return FlowReturns.SOMETIMES;
1266 case FlowReturns.SOMETIMES:
1267 return FlowReturns.SOMETIMES;
1269 case FlowReturns.ALWAYS:
1270 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1271 return FlowReturns.ALWAYS;
1273 return FlowReturns.SOMETIMES;
1275 case FlowReturns.EXCEPTION:
1276 if (b == FlowReturns.EXCEPTION)
1277 return FlowReturns.EXCEPTION;
1278 else if (b == FlowReturns.ALWAYS)
1279 return FlowReturns.ALWAYS;
1281 return FlowReturns.SOMETIMES;
1288 // The vector contains a BitArray with information about which local variables
1289 // and parameters are already initialized at the current code position.
1291 public class UsageVector {
1293 // If this is true, then the usage vector has been modified and must be
1294 // merged when we're done with this branching.
1296 public bool IsDirty;
1299 // The number of parameters in this block.
1301 public readonly int CountParameters;
1304 // The number of locals in this block.
1306 public readonly int CountLocals;
1309 // If not null, then we inherit our state from this vector and do a
1310 // copy-on-write. If null, then we're the first sibling in a top-level
1311 // block and inherit from the empty vector.
1313 public readonly UsageVector InheritsFrom;
1318 MyBitVector locals, parameters;
1319 FlowReturns real_returns, real_breaks;
1320 bool returns_set, breaks_set, is_finally;
1322 static int next_id = 0;
1326 // Normally, you should not use any of these constructors.
1328 public UsageVector (UsageVector parent, int num_params, int num_locals)
1330 this.InheritsFrom = parent;
1331 this.CountParameters = num_params;
1332 this.CountLocals = num_locals;
1333 this.real_returns = FlowReturns.NEVER;
1334 this.real_breaks = FlowReturns.NEVER;
1336 if (parent != null) {
1337 locals = new MyBitVector (parent.locals, CountLocals);
1339 parameters = new MyBitVector (parent.parameters, num_params);
1341 locals = new MyBitVector (null, CountLocals);
1343 parameters = new MyBitVector (null, num_params);
1349 public UsageVector (UsageVector parent)
1350 : this (parent, parent.CountParameters, parent.CountLocals)
1354 // This does a deep copy of the usage vector.
1356 public UsageVector Clone ()
1358 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1360 retval.locals = locals.Clone ();
1361 if (parameters != null)
1362 retval.parameters = parameters.Clone ();
1363 retval.real_returns = real_returns;
1364 retval.real_breaks = real_breaks;
1370 // State of parameter `number'.
1372 public bool this [int number]
1377 else if (number == 0)
1378 throw new ArgumentException ();
1380 return parameters [number - 1];
1386 else if (number == 0)
1387 throw new ArgumentException ();
1389 parameters [number - 1] = value;
1394 // State of the local variable `vi'.
1395 // If the local variable is a struct, use a non-zero `field_idx'
1396 // to check an individual field in it.
1398 public bool this [VariableInfo vi, int field_idx]
1401 if (vi.Number == -1)
1403 else if (vi.Number == 0)
1404 throw new ArgumentException ();
1406 return locals [vi.Number + field_idx - 1];
1410 if (vi.Number == -1)
1412 else if (vi.Number == 0)
1413 throw new ArgumentException ();
1415 locals [vi.Number + field_idx - 1] = value;
1420 // Specifies when the current block returns.
1422 public FlowReturns Returns {
1424 return real_returns;
1428 real_returns = value;
1434 // Specifies whether control may return to our containing block
1435 // before reaching the end of this block. This happens if there
1436 // is a break/continue/goto/return in it.
1438 public FlowReturns Breaks {
1444 real_breaks = value;
1450 // Merge a child branching.
1452 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1454 MyBitVector new_locals = null;
1455 MyBitVector new_params = null;
1457 FlowReturns new_returns = FlowReturns.NEVER;
1458 FlowReturns new_breaks = FlowReturns.NEVER;
1459 bool new_returns_set = false, new_breaks_set = false;
1462 Report.Debug (1, "MERGING CHILDREN", branching, this);
1464 foreach (UsageVector child in children) {
1465 Report.Debug (1, " MERGING CHILD", child);
1467 // If Returns is already set, perform an `And' operation on it,
1468 // otherwise just set just.
1469 if (!new_returns_set) {
1470 new_returns = child.Returns;
1471 new_returns_set = true;
1473 new_returns = AndFlowReturns (new_returns, child.Returns);
1475 // If Breaks is already set, perform an `And' operation on it,
1476 // otherwise just set just.
1477 if (!new_breaks_set) {
1478 new_breaks = child.Breaks;
1479 new_breaks_set = true;
1481 new_breaks = AndFlowReturns (new_breaks, child.Breaks);
1483 // Ignore unreachable children.
1484 if (child.Returns == FlowReturns.UNREACHABLE)
1487 // Check whether control may reach the end of this sibling.
1488 // This happens unless we either always return or always break.
1489 if ((child.Returns == FlowReturns.EXCEPTION) ||
1490 (child.Returns == FlowReturns.ALWAYS) ||
1491 ((branching.Type != FlowBranchingType.SWITCH_SECTION) &&
1492 (branching.Type != FlowBranchingType.LOOP_BLOCK) &&
1493 (child.Breaks == FlowReturns.ALWAYS)))
1498 // A local variable is initialized after a flow branching if it
1499 // has been initialized in all its branches which do neither
1500 // always return or always throw an exception.
1502 // If a branch may return, but does not always return, then we
1503 // can treat it like a never-returning branch here: control will
1504 // only reach the code position after the branching if we did not
1507 // It's important to distinguish between always and sometimes
1508 // returning branches here:
1511 // 2 if (something) {
1515 // 6 Console.WriteLine (a);
1517 // The if block in lines 3-4 always returns, so we must not look
1518 // at the initialization of `a' in line 4 - thus it'll still be
1519 // uninitialized in line 6.
1521 // On the other hand, the following is allowed:
1528 // 6 Console.WriteLine (a);
1530 // Here, `a' is initialized in line 3 and we must not look at
1531 // line 5 since it always returns.
1534 if (new_locals != null)
1535 new_locals.And (child.locals);
1537 new_locals = locals.Clone ();
1538 new_locals.Or (child.locals);
1542 // An `out' parameter must be assigned in all branches which do
1543 // not always throw an exception.
1544 if (!child.is_finally && (child.Returns != FlowReturns.EXCEPTION)) {
1545 if (parameters != null) {
1546 if (new_params != null)
1547 new_params.And (child.parameters);
1549 new_params = parameters.Clone ();
1550 new_params.Or (child.parameters);
1555 // If we always return, check whether all `out' parameters have
1557 if ((child.Returns == FlowReturns.ALWAYS) && (child.parameters != null)) {
1558 branching.CheckOutParameters (
1559 child.parameters, branching.Location);
1563 // Set new `Returns' status.
1565 Returns = new_returns;
1568 Returns = AndFlowReturns (Returns, new_returns);
1571 // We've now either reached the point after the branching or we will
1572 // never get there since we always return or always throw an exception.
1574 // If we can reach the point after the branching, mark all locals and
1575 // parameters as initialized which have been initialized in all branches
1576 // we need to look at (see above).
1579 bool or_locals = (Returns == FlowReturns.NEVER) ||
1580 (Returns == FlowReturns.SOMETIMES);
1581 if ((branching.Type != FlowBranchingType.SWITCH_SECTION) &&
1582 (branching.Type != FlowBranchingType.LOOP_BLOCK))
1583 or_locals &= ((Breaks == FlowReturns.NEVER) ||
1584 (Breaks == FlowReturns.SOMETIMES));
1586 if ((new_locals != null) && or_locals) {
1587 locals.Or (new_locals);
1590 if ((new_params != null) && (Breaks == FlowReturns.NEVER))
1591 parameters.Or (new_params);
1594 // If we may have returned (this only happens if there was a reachable
1595 // `return' statement in one of the branches), then we may return to our
1596 // parent block before reaching the end of the block, so set `Breaks'.
1598 if ((Returns != FlowReturns.NEVER) && (Returns != FlowReturns.SOMETIMES)) {
1599 // real_breaks = Returns;
1600 // breaks_set = true;
1601 } else if (branching.Type == FlowBranchingType.BLOCK) {
1603 // If this is not a loop or switch block, `break' actually breaks.
1607 Breaks = new_breaks;
1610 Breaks = AndFlowReturns (Breaks, new_breaks);
1613 Report.Debug (1, "MERGING CHILDREN DONE", new_params, new_locals,
1614 new_returns, new_breaks, this);
1620 // Tells control flow analysis that the current code position may be reached with
1621 // a forward jump from any of the origins listed in `origin_vectors' which is a
1622 // list of UsageVectors.
1624 // This is used when resolving forward gotos - in the following example, the
1625 // variable `a' is uninitialized in line 8 becase this line may be reached via
1626 // the goto in line 4:
1636 // 8 Console.WriteLine (a);
1639 public void MergeJumpOrigins (ICollection origin_vectors)
1641 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1643 real_breaks = FlowReturns.NEVER;
1646 foreach (UsageVector vector in origin_vectors) {
1647 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1649 locals.And (vector.locals);
1650 if (parameters != null)
1651 parameters.And (vector.parameters);
1652 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1655 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1659 // This is used at the beginning of a finally block if there were
1660 // any return statements in the try block or one of the catch blocks.
1662 public void MergeFinallyOrigins (ICollection finally_vectors)
1664 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1666 real_breaks = FlowReturns.NEVER;
1669 foreach (UsageVector vector in finally_vectors) {
1670 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1672 if (parameters != null)
1673 parameters.And (vector.parameters);
1674 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1679 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1683 // Performs an `or' operation on the locals and the parameters.
1685 public void Or (UsageVector new_vector)
1687 locals.Or (new_vector.locals);
1688 if (parameters != null)
1689 parameters.Or (new_vector.parameters);
1693 // Performs an `and' operation on the locals.
1695 public void AndLocals (UsageVector new_vector)
1697 locals.And (new_vector.locals);
1701 // Returns a deep copy of the parameters.
1703 public MyBitVector Parameters {
1705 if (parameters != null)
1706 return parameters.Clone ();
1713 // Returns a deep copy of the locals.
1715 public MyBitVector Locals {
1717 return locals.Clone ();
1725 public override string ToString ()
1727 StringBuilder sb = new StringBuilder ();
1729 sb.Append ("Vector (");
1732 sb.Append (Returns);
1735 if (parameters != null) {
1737 sb.Append (parameters);
1743 return sb.ToString ();
1747 FlowBranching (FlowBranchingType type, Location loc)
1749 this.Siblings = new ArrayList ();
1751 this.Location = loc;
1757 // Creates a new flow branching for `block'.
1758 // This is used from Block.Resolve to create the top-level branching of
1761 public FlowBranching (Block block, InternalParameters ip, Location loc)
1762 : this (FlowBranchingType.BLOCK, loc)
1767 int count = (ip != null) ? ip.Count : 0;
1770 param_map = new int [count];
1771 struct_params = new MyStructInfo [count];
1774 for (int i = 0; i < count; i++) {
1775 Parameter.Modifier mod = param_info.ParameterModifier (i);
1777 if ((mod & Parameter.Modifier.OUT) == 0)
1780 param_map [i] = ++num_params;
1782 Type param_type = param_info.ParameterType (i);
1784 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1785 if (struct_params [i] != null)
1786 num_params += struct_params [i].Count;
1789 Siblings = new ArrayList ();
1790 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1794 // Creates a new flow branching which is contained in `parent'.
1795 // You should only pass non-null for the `block' argument if this block
1796 // introduces any new variables - in this case, we need to create a new
1797 // usage vector with a different size than our parent's one.
1799 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1800 Block block, Location loc)
1806 if (parent != null) {
1807 param_info = parent.param_info;
1808 param_map = parent.param_map;
1809 struct_params = parent.struct_params;
1810 num_params = parent.num_params;
1815 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1816 Block.CountVariables);
1818 vector = new UsageVector (Parent.CurrentUsageVector);
1820 Siblings.Add (vector);
1823 case FlowBranchingType.EXCEPTION:
1824 finally_vectors = new ArrayList ();
1833 // Returns the branching's current usage vector.
1835 public UsageVector CurrentUsageVector
1838 return (UsageVector) Siblings [Siblings.Count - 1];
1843 // Creates a sibling of the current usage vector.
1845 public void CreateSibling ()
1847 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1849 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1853 // Creates a sibling for a `finally' block.
1855 public void CreateSiblingForFinally ()
1857 if (Type != FlowBranchingType.EXCEPTION)
1858 throw new NotSupportedException ();
1862 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1866 // Check whether all `out' parameters have been assigned.
1868 public void CheckOutParameters (MyBitVector parameters, Location loc)
1873 for (int i = 0; i < param_map.Length; i++) {
1874 int index = param_map [i];
1879 if (parameters [index - 1])
1882 // If it's a struct, we must ensure that all its fields have
1883 // been assigned. If the struct has any non-public fields, this
1884 // can only be done by assigning the whole struct.
1886 MyStructInfo struct_info = struct_params [index - 1];
1887 if ((struct_info == null) || struct_info.HasNonPublicFields) {
1889 177, loc, "The out parameter `" +
1890 param_info.ParameterName (i) + "' must be " +
1891 "assigned before control leave the current method.");
1897 for (int j = 0; j < struct_info.Count; j++) {
1898 if (!parameters [index + j]) {
1900 177, loc, "The out parameter `" +
1901 param_info.ParameterName (i) + "' must be " +
1902 "assigned before control leave the current method.");
1911 // Merge a child branching.
1913 public FlowReturns MergeChild (FlowBranching child)
1915 return CurrentUsageVector.MergeChildren (child, child.Siblings);
1919 // Does the toplevel merging.
1921 public FlowReturns MergeTopBlock ()
1923 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1924 throw new NotSupportedException ();
1926 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1928 vector.MergeChildren (this, Siblings);
1931 Siblings.Add (vector);
1933 Report.Debug (1, "MERGING TOP BLOCK", vector);
1935 if (vector.Returns != FlowReturns.EXCEPTION)
1936 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1938 return vector.Returns;
1941 public bool InTryBlock ()
1943 if (finally_vectors != null)
1945 else if (Parent != null)
1946 return Parent.InTryBlock ();
1951 public void AddFinallyVector (UsageVector vector)
1953 if (finally_vectors != null) {
1954 finally_vectors.Add (vector.Clone ());
1959 Parent.AddFinallyVector (vector);
1961 throw new NotSupportedException ();
1964 public bool IsVariableAssigned (VariableInfo vi)
1966 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1969 return CurrentUsageVector [vi, 0];
1972 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
1974 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1977 return CurrentUsageVector [vi, field_idx];
1980 public void SetVariableAssigned (VariableInfo vi)
1982 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1985 CurrentUsageVector [vi, 0] = true;
1988 public void SetVariableAssigned (VariableInfo vi, int field_idx)
1990 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1993 CurrentUsageVector [vi, field_idx] = true;
1996 public bool IsParameterAssigned (int number)
1998 int index = param_map [number];
2003 if (CurrentUsageVector [index])
2006 // Parameter is not assigned, so check whether it's a struct.
2007 // If it's either not a struct or a struct which non-public
2008 // fields, return false.
2009 MyStructInfo struct_info = struct_params [number];
2010 if ((struct_info == null) || struct_info.HasNonPublicFields)
2013 // Ok, so each field must be assigned.
2014 for (int i = 0; i < struct_info.Count; i++)
2015 if (!CurrentUsageVector [index + i])
2021 public bool IsParameterAssigned (int number, string field_name)
2023 int index = param_map [number];
2028 int field_idx = struct_params [number] [field_name];
2030 return CurrentUsageVector [index + field_idx];
2033 public void SetParameterAssigned (int number)
2035 if (param_map [number] == 0)
2038 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
2039 CurrentUsageVector [param_map [number]] = true;
2042 public void SetParameterAssigned (int number, string field_name)
2044 int index = param_map [number];
2049 int field_idx = struct_params [number] [field_name];
2051 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
2052 CurrentUsageVector [index + field_idx] = true;
2055 public override string ToString ()
2057 StringBuilder sb = new StringBuilder ("FlowBranching (");
2062 if (Block != null) {
2064 sb.Append (Block.ID);
2066 sb.Append (Block.StartLocation);
2069 sb.Append (Siblings.Count);
2071 sb.Append (CurrentUsageVector);
2073 return sb.ToString ();
2077 public class MyStructInfo {
2078 public readonly Type Type;
2079 public readonly FieldInfo[] Fields;
2080 public readonly FieldInfo[] NonPublicFields;
2081 public readonly int Count;
2082 public readonly int CountNonPublic;
2083 public readonly bool HasNonPublicFields;
2085 private static Hashtable field_type_hash = new Hashtable ();
2086 private Hashtable field_hash;
2088 // Private constructor. To save memory usage, we only need to create one instance
2089 // of this class per struct type.
2090 private MyStructInfo (Type type)
2094 if (type is TypeBuilder) {
2095 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2097 ArrayList fields = tc.Fields;
2098 foreach (Field field in fields) {
2099 if ((field.ModFlags & Modifiers.STATIC) != 0)
2101 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2107 Fields = new FieldInfo [Count];
2108 NonPublicFields = new FieldInfo [CountNonPublic];
2110 Count = CountNonPublic = 0;
2111 foreach (Field field in fields) {
2112 if ((field.ModFlags & Modifiers.STATIC) != 0)
2114 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2115 Fields [Count++] = field.FieldBuilder;
2117 NonPublicFields [CountNonPublic++] = field.FieldBuilder;
2120 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2121 Count = Fields.Length;
2123 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2124 CountNonPublic = NonPublicFields.Length;
2127 Count += NonPublicFields.Length;
2130 field_hash = new Hashtable ();
2131 foreach (FieldInfo field in Fields)
2132 field_hash.Add (field.Name, ++number);
2134 if (NonPublicFields.Length != 0)
2135 HasNonPublicFields = true;
2137 foreach (FieldInfo field in NonPublicFields)
2138 field_hash.Add (field.Name, ++number);
2141 public int this [string name] {
2143 if (field_hash.Contains (name))
2144 return (int) field_hash [name];
2150 public FieldInfo this [int index] {
2152 if (index >= Fields.Length)
2153 return NonPublicFields [index - Fields.Length];
2155 return Fields [index];
2159 public static MyStructInfo GetStructInfo (Type type)
2161 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2164 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2167 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2171 info = new MyStructInfo (type);
2172 field_type_hash.Add (type, info);
2176 public static MyStructInfo GetStructInfo (TypeContainer tc)
2178 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2182 info = new MyStructInfo (tc.TypeBuilder);
2183 field_type_hash.Add (tc.TypeBuilder, info);
2188 public class VariableInfo : IVariable {
2189 public Expression Type;
2190 public LocalBuilder LocalBuilder;
2191 public Type VariableType;
2192 public readonly string Name;
2193 public readonly Location Location;
2194 public readonly int Block;
2199 public bool Assigned;
2200 public bool ReadOnly;
2202 public VariableInfo (Expression type, string name, int block, Location l)
2207 LocalBuilder = null;
2211 public VariableInfo (TypeContainer tc, int block, Location l)
2213 VariableType = tc.TypeBuilder;
2214 struct_info = MyStructInfo.GetStructInfo (tc);
2216 LocalBuilder = null;
2220 MyStructInfo struct_info;
2221 public MyStructInfo StructInfo {
2227 public bool IsAssigned (EmitContext ec, Location loc)
2229 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2232 MyStructInfo struct_info = StructInfo;
2233 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2234 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2235 ec.CurrentBranching.SetVariableAssigned (this);
2239 int count = struct_info.Count;
2241 for (int i = 0; i < count; i++) {
2242 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2244 Report.Error (165, loc,
2245 "Use of unassigned local variable `" +
2247 ec.CurrentBranching.SetVariableAssigned (this);
2251 FieldInfo field = struct_info [i];
2252 Report.Error (171, loc,
2253 "Field `" + TypeManager.CSharpName (VariableType) +
2254 "." + field.Name + "' must be fully initialized " +
2255 "before control leaves the constructor");
2263 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2265 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2266 (struct_info == null))
2269 int field_idx = StructInfo [name];
2273 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2274 Report.Error (170, loc,
2275 "Use of possibly unassigned field `" + name + "'");
2276 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2283 public void SetAssigned (EmitContext ec)
2285 if (ec.DoFlowAnalysis)
2286 ec.CurrentBranching.SetVariableAssigned (this);
2289 public void SetFieldAssigned (EmitContext ec, string name)
2291 if (ec.DoFlowAnalysis && (struct_info != null))
2292 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2295 public bool Resolve (DeclSpace decl)
2297 if (struct_info != null)
2300 if (VariableType == null)
2301 VariableType = decl.ResolveType (Type, false, Location);
2303 if (VariableType == null)
2306 struct_info = MyStructInfo.GetStructInfo (VariableType);
2311 public void MakePinned ()
2313 TypeManager.MakePinned (LocalBuilder);
2316 public override string ToString ()
2318 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2323 /// Block represents a C# block.
2327 /// This class is used in a number of places: either to represent
2328 /// explicit blocks that the programmer places or implicit blocks.
2330 /// Implicit blocks are used as labels or to introduce variable
2333 public class Block : Statement {
2334 public readonly Block Parent;
2335 public readonly bool Implicit;
2336 public readonly Location StartLocation;
2337 public Location EndLocation;
2340 // The statements in this block
2342 ArrayList statements;
2345 // An array of Blocks. We keep track of children just
2346 // to generate the local variable declarations.
2348 // Statements and child statements are handled through the
2354 // Labels. (label, block) pairs.
2359 // Keeps track of (name, type) pairs
2361 Hashtable variables;
2364 // Keeps track of constants
2365 Hashtable constants;
2368 // Maps variable names to ILGenerator.LocalBuilders
2370 Hashtable local_builders;
2378 public Block (Block parent)
2379 : this (parent, false, Location.Null, Location.Null)
2382 public Block (Block parent, bool implicit_block)
2383 : this (parent, implicit_block, Location.Null, Location.Null)
2386 public Block (Block parent, bool implicit_block, Parameters parameters)
2387 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2390 public Block (Block parent, Location start, Location end)
2391 : this (parent, false, start, end)
2394 public Block (Block parent, Parameters parameters, Location start, Location end)
2395 : this (parent, false, parameters, start, end)
2398 public Block (Block parent, bool implicit_block, Location start, Location end)
2399 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2403 public Block (Block parent, bool implicit_block, Parameters parameters,
2404 Location start, Location end)
2407 parent.AddChild (this);
2409 this.Parent = parent;
2410 this.Implicit = implicit_block;
2411 this.parameters = parameters;
2412 this.StartLocation = start;
2413 this.EndLocation = end;
2416 statements = new ArrayList ();
2428 void AddChild (Block b)
2430 if (children == null)
2431 children = new ArrayList ();
2436 public void SetEndLocation (Location loc)
2442 /// Adds a label to the current block.
2446 /// false if the name already exists in this block. true
2450 public bool AddLabel (string name, LabeledStatement target)
2453 labels = new Hashtable ();
2454 if (labels.Contains (name))
2457 labels.Add (name, target);
2461 public LabeledStatement LookupLabel (string name)
2463 if (labels != null){
2464 if (labels.Contains (name))
2465 return ((LabeledStatement) labels [name]);
2469 return Parent.LookupLabel (name);
2474 VariableInfo this_variable = null;
2477 // Returns the "this" instance variable of this block.
2478 // See AddThisVariable() for more information.
2480 public VariableInfo ThisVariable {
2482 if (this_variable != null)
2483 return this_variable;
2484 else if (Parent != null)
2485 return Parent.ThisVariable;
2492 // This is used by non-static `struct' constructors which do not have an
2493 // initializer - in this case, the constructor must initialize all of the
2494 // struct's fields. To do this, we add a "this" variable and use the flow
2495 // analysis code to ensure that it's been fully initialized before control
2496 // leaves the constructor.
2498 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2500 if (this_variable != null)
2501 return this_variable;
2503 this_variable = new VariableInfo (tc, ID, l);
2505 if (variables == null)
2506 variables = new Hashtable ();
2507 variables.Add ("this", this_variable);
2509 return this_variable;
2512 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2514 if (variables == null)
2515 variables = new Hashtable ();
2517 VariableInfo vi = GetVariableInfo (name);
2520 Report.Error (136, l, "A local variable named `" + name + "' " +
2521 "cannot be declared in this scope since it would " +
2522 "give a different meaning to `" + name + "', which " +
2523 "is already used in a `parent or current' scope to " +
2524 "denote something else");
2526 Report.Error (128, l, "A local variable `" + name + "' is already " +
2527 "defined in this scope");
2533 Parameter p = pars.GetParameterByName (name, out idx);
2535 Report.Error (136, l, "A local variable named `" + name + "' " +
2536 "cannot be declared in this scope since it would " +
2537 "give a different meaning to `" + name + "', which " +
2538 "is already used in a `parent or current' scope to " +
2539 "denote something else");
2544 vi = new VariableInfo (type, name, ID, l);
2546 variables.Add (name, vi);
2548 if (variables_initialized)
2549 throw new Exception ();
2551 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2555 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2557 if (AddVariable (type, name, pars, l) == null)
2560 if (constants == null)
2561 constants = new Hashtable ();
2563 constants.Add (name, value);
2567 public Hashtable Variables {
2573 public VariableInfo GetVariableInfo (string name)
2575 if (variables != null) {
2577 temp = variables [name];
2580 return (VariableInfo) temp;
2585 return Parent.GetVariableInfo (name);
2590 public Expression GetVariableType (string name)
2592 VariableInfo vi = GetVariableInfo (name);
2600 public Expression GetConstantExpression (string name)
2602 if (constants != null) {
2604 temp = constants [name];
2607 return (Expression) temp;
2611 return Parent.GetConstantExpression (name);
2617 /// True if the variable named @name has been defined
2620 public bool IsVariableDefined (string name)
2622 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2623 if (variables != null) {
2624 if (variables.Contains (name))
2629 return Parent.IsVariableDefined (name);
2635 /// True if the variable named @name is a constant
2637 public bool IsConstant (string name)
2639 Expression e = null;
2641 e = GetConstantExpression (name);
2647 /// Use to fetch the statement associated with this label
2649 public Statement this [string name] {
2651 return (Statement) labels [name];
2655 Parameters parameters = null;
2656 public Parameters Parameters {
2659 return Parent.Parameters;
2666 /// A list of labels that were not used within this block
2668 public string [] GetUnreferenced ()
2670 // FIXME: Implement me
2674 public void AddStatement (Statement s)
2691 bool variables_initialized = false;
2692 int count_variables = 0, first_variable = 0;
2694 void UpdateVariableInfo (EmitContext ec)
2696 DeclSpace ds = ec.DeclSpace;
2701 first_variable += Parent.CountVariables;
2703 count_variables = first_variable;
2704 if (variables != null) {
2705 foreach (VariableInfo vi in variables.Values) {
2706 if (!vi.Resolve (ds)) {
2711 vi.Number = ++count_variables;
2713 if (vi.StructInfo != null)
2714 count_variables += vi.StructInfo.Count;
2718 variables_initialized = true;
2723 // The number of local variables in this block
2725 public int CountVariables
2728 if (!variables_initialized)
2729 throw new Exception ();
2731 return count_variables;
2736 /// Emits the variable declarations and labels.
2739 /// tc: is our typecontainer (to resolve type references)
2740 /// ig: is the code generator:
2741 /// toplevel: the toplevel block. This is used for checking
2742 /// that no two labels with the same name are used.
2744 public void EmitMeta (EmitContext ec, Block toplevel)
2746 DeclSpace ds = ec.DeclSpace;
2747 ILGenerator ig = ec.ig;
2749 if (!variables_initialized)
2750 UpdateVariableInfo (ec);
2753 // Process this block variables
2755 if (variables != null){
2756 local_builders = new Hashtable ();
2758 foreach (DictionaryEntry de in variables){
2759 string name = (string) de.Key;
2760 VariableInfo vi = (VariableInfo) de.Value;
2762 if (vi.VariableType == null)
2765 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2767 if (CodeGen.SymbolWriter != null)
2768 vi.LocalBuilder.SetLocalSymInfo (name);
2770 if (constants == null)
2773 Expression cv = (Expression) constants [name];
2777 Expression e = cv.Resolve (ec);
2781 if (!(e is Constant)){
2782 Report.Error (133, vi.Location,
2783 "The expression being assigned to `" +
2784 name + "' must be constant (" + e + ")");
2788 constants.Remove (name);
2789 constants.Add (name, e);
2794 // Now, handle the children
2796 if (children != null){
2797 foreach (Block b in children)
2798 b.EmitMeta (ec, toplevel);
2802 public void UsageWarning ()
2806 if (variables != null){
2807 foreach (DictionaryEntry de in variables){
2808 VariableInfo vi = (VariableInfo) de.Value;
2813 name = (string) de.Key;
2817 219, vi.Location, "The variable `" + name +
2818 "' is assigned but its value is never used");
2821 168, vi.Location, "The variable `" +
2823 "' is declared but never used");
2828 if (children != null)
2829 foreach (Block b in children)
2833 public override bool Resolve (EmitContext ec)
2835 Block prev_block = ec.CurrentBlock;
2838 ec.CurrentBlock = this;
2839 ec.StartFlowBranching (this);
2841 Report.Debug (1, "RESOLVE BLOCK", StartLocation);
2843 if (!variables_initialized)
2844 UpdateVariableInfo (ec);
2846 foreach (Statement s in statements){
2847 if (s.Resolve (ec) == false)
2851 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation);
2853 FlowReturns returns = ec.EndFlowBranching ();
2854 ec.CurrentBlock = prev_block;
2856 // If we're a non-static `struct' constructor which doesn't have an
2857 // initializer, then we must initialize all of the struct's fields.
2858 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
2859 !this_variable.IsAssigned (ec, loc))
2862 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2863 foreach (LabeledStatement label in labels.Values)
2864 if (!label.HasBeenReferenced)
2865 Report.Warning (164, label.Location,
2866 "This label has not been referenced");
2872 public override bool Emit (EmitContext ec)
2874 bool is_ret = false, this_ret = false;
2875 Block prev_block = ec.CurrentBlock;
2876 bool warning_shown = false;
2878 ec.CurrentBlock = this;
2880 if (CodeGen.SymbolWriter != null) {
2881 ec.Mark (StartLocation);
2883 foreach (Statement s in statements) {
2886 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2887 warning_shown = true;
2888 Warning_DeadCodeFound (s.loc);
2890 this_ret = s.Emit (ec);
2895 ec.Mark (EndLocation);
2897 foreach (Statement s in statements){
2898 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2899 warning_shown = true;
2900 Warning_DeadCodeFound (s.loc);
2902 this_ret = s.Emit (ec);
2908 ec.CurrentBlock = prev_block;
2913 public class SwitchLabel {
2916 public Location loc;
2917 public Label ILLabel;
2918 public Label ILLabelCode;
2921 // if expr == null, then it is the default case.
2923 public SwitchLabel (Expression expr, Location l)
2929 public Expression Label {
2935 public object Converted {
2942 // Resolves the expression, reduces it to a literal if possible
2943 // and then converts it to the requested type.
2945 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2947 ILLabel = ec.ig.DefineLabel ();
2948 ILLabelCode = ec.ig.DefineLabel ();
2953 Expression e = label.Resolve (ec);
2958 if (!(e is Constant)){
2959 Console.WriteLine ("Value is: " + label);
2960 Report.Error (150, loc, "A constant value is expected");
2964 if (e is StringConstant || e is NullLiteral){
2965 if (required_type == TypeManager.string_type){
2967 ILLabel = ec.ig.DefineLabel ();
2972 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2973 if (converted == null)
2980 public class SwitchSection {
2981 // An array of SwitchLabels.
2982 public readonly ArrayList Labels;
2983 public readonly Block Block;
2985 public SwitchSection (ArrayList labels, Block block)
2992 public class Switch : Statement {
2993 public readonly ArrayList Sections;
2994 public Expression Expr;
2997 /// Maps constants whose type type SwitchType to their SwitchLabels.
2999 public Hashtable Elements;
3002 /// The governing switch type
3004 public Type SwitchType;
3010 Label default_target;
3011 Expression new_expr;
3014 // The types allowed to be implicitly cast from
3015 // on the governing type
3017 static Type [] allowed_types;
3019 public Switch (Expression e, ArrayList sects, Location l)
3026 public bool GotDefault {
3032 public Label DefaultTarget {
3034 return default_target;
3039 // Determines the governing type for a switch. The returned
3040 // expression might be the expression from the switch, or an
3041 // expression that includes any potential conversions to the
3042 // integral types or to string.
3044 Expression SwitchGoverningType (EmitContext ec, Type t)
3046 if (t == TypeManager.int32_type ||
3047 t == TypeManager.uint32_type ||
3048 t == TypeManager.char_type ||
3049 t == TypeManager.byte_type ||
3050 t == TypeManager.sbyte_type ||
3051 t == TypeManager.ushort_type ||
3052 t == TypeManager.short_type ||
3053 t == TypeManager.uint64_type ||
3054 t == TypeManager.int64_type ||
3055 t == TypeManager.string_type ||
3056 t == TypeManager.bool_type ||
3057 t.IsSubclassOf (TypeManager.enum_type))
3060 if (allowed_types == null){
3061 allowed_types = new Type [] {
3062 TypeManager.sbyte_type,
3063 TypeManager.byte_type,
3064 TypeManager.short_type,
3065 TypeManager.ushort_type,
3066 TypeManager.int32_type,
3067 TypeManager.uint32_type,
3068 TypeManager.int64_type,
3069 TypeManager.uint64_type,
3070 TypeManager.char_type,
3071 TypeManager.bool_type,
3072 TypeManager.string_type
3077 // Try to find a *user* defined implicit conversion.
3079 // If there is no implicit conversion, or if there are multiple
3080 // conversions, we have to report an error
3082 Expression converted = null;
3083 foreach (Type tt in allowed_types){
3086 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3090 if (converted != null){
3091 Report.Error (-12, loc, "More than one conversion to an integral " +
3092 " type exists for type `" +
3093 TypeManager.CSharpName (Expr.Type)+"'");
3101 void error152 (string n)
3104 152, "The label `" + n + ":' " +
3105 "is already present on this switch statement");
3109 // Performs the basic sanity checks on the switch statement
3110 // (looks for duplicate keys and non-constant expressions).
3112 // It also returns a hashtable with the keys that we will later
3113 // use to compute the switch tables
3115 bool CheckSwitch (EmitContext ec)
3119 Elements = new Hashtable ();
3121 got_default = false;
3123 if (TypeManager.IsEnumType (SwitchType)){
3124 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3126 compare_type = SwitchType;
3128 foreach (SwitchSection ss in Sections){
3129 foreach (SwitchLabel sl in ss.Labels){
3130 if (!sl.ResolveAndReduce (ec, SwitchType)){
3135 if (sl.Label == null){
3137 error152 ("default");
3144 object key = sl.Converted;
3146 if (key is Constant)
3147 key = ((Constant) key).GetValue ();
3150 key = NullLiteral.Null;
3152 string lname = null;
3153 if (compare_type == TypeManager.uint64_type){
3154 ulong v = (ulong) key;
3156 if (Elements.Contains (v))
3157 lname = v.ToString ();
3159 Elements.Add (v, sl);
3160 } else if (compare_type == TypeManager.int64_type){
3161 long v = (long) key;
3163 if (Elements.Contains (v))
3164 lname = v.ToString ();
3166 Elements.Add (v, sl);
3167 } else if (compare_type == TypeManager.uint32_type){
3168 uint v = (uint) key;
3170 if (Elements.Contains (v))
3171 lname = v.ToString ();
3173 Elements.Add (v, sl);
3174 } else if (compare_type == TypeManager.char_type){
3175 char v = (char) key;
3177 if (Elements.Contains (v))
3178 lname = v.ToString ();
3180 Elements.Add (v, sl);
3181 } else if (compare_type == TypeManager.byte_type){
3182 byte v = (byte) key;
3184 if (Elements.Contains (v))
3185 lname = v.ToString ();
3187 Elements.Add (v, sl);
3188 } else if (compare_type == TypeManager.sbyte_type){
3189 sbyte v = (sbyte) key;
3191 if (Elements.Contains (v))
3192 lname = v.ToString ();
3194 Elements.Add (v, sl);
3195 } else if (compare_type == TypeManager.short_type){
3196 short v = (short) key;
3198 if (Elements.Contains (v))
3199 lname = v.ToString ();
3201 Elements.Add (v, sl);
3202 } else if (compare_type == TypeManager.ushort_type){
3203 ushort v = (ushort) key;
3205 if (Elements.Contains (v))
3206 lname = v.ToString ();
3208 Elements.Add (v, sl);
3209 } else if (compare_type == TypeManager.string_type){
3210 if (key is NullLiteral){
3211 if (Elements.Contains (NullLiteral.Null))
3214 Elements.Add (NullLiteral.Null, null);
3216 string s = (string) key;
3218 if (Elements.Contains (s))
3221 Elements.Add (s, sl);
3223 } else if (compare_type == TypeManager.int32_type) {
3226 if (Elements.Contains (v))
3227 lname = v.ToString ();
3229 Elements.Add (v, sl);
3230 } else if (compare_type == TypeManager.bool_type) {
3231 bool v = (bool) key;
3233 if (Elements.Contains (v))
3234 lname = v.ToString ();
3236 Elements.Add (v, sl);
3240 throw new Exception ("Unknown switch type!" +
3241 SwitchType + " " + compare_type);
3245 error152 ("case + " + lname);
3256 void EmitObjectInteger (ILGenerator ig, object k)
3259 IntConstant.EmitInt (ig, (int) k);
3260 else if (k is Constant) {
3261 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3264 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3267 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3269 IntConstant.EmitInt (ig, (int) (long) k);
3270 ig.Emit (OpCodes.Conv_I8);
3273 LongConstant.EmitLong (ig, (long) k);
3275 else if (k is ulong)
3277 if ((ulong) k < (1L<<32))
3279 IntConstant.EmitInt (ig, (int) (long) k);
3280 ig.Emit (OpCodes.Conv_U8);
3284 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3288 IntConstant.EmitInt (ig, (int) ((char) k));
3289 else if (k is sbyte)
3290 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3292 IntConstant.EmitInt (ig, (int) ((byte) k));
3293 else if (k is short)
3294 IntConstant.EmitInt (ig, (int) ((short) k));
3295 else if (k is ushort)
3296 IntConstant.EmitInt (ig, (int) ((ushort) k));
3298 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3300 throw new Exception ("Unhandled case");
3303 // structure used to hold blocks of keys while calculating table switch
3304 class KeyBlock : IComparable
3306 public KeyBlock (long _nFirst)
3308 nFirst = nLast = _nFirst;
3312 public ArrayList rgKeys = null;
3315 get { return (int) (nLast - nFirst + 1); }
3317 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3319 return kbLast.nLast - kbFirst.nFirst + 1;
3321 public int CompareTo (object obj)
3323 KeyBlock kb = (KeyBlock) obj;
3324 int nLength = Length;
3325 int nLengthOther = kb.Length;
3326 if (nLengthOther == nLength)
3327 return (int) (kb.nFirst - nFirst);
3328 return nLength - nLengthOther;
3333 /// This method emits code for a lookup-based switch statement (non-string)
3334 /// Basically it groups the cases into blocks that are at least half full,
3335 /// and then spits out individual lookup opcodes for each block.
3336 /// It emits the longest blocks first, and short blocks are just
3337 /// handled with direct compares.
3339 /// <param name="ec"></param>
3340 /// <param name="val"></param>
3341 /// <returns></returns>
3342 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3344 int cElements = Elements.Count;
3345 object [] rgKeys = new object [cElements];
3346 Elements.Keys.CopyTo (rgKeys, 0);
3347 Array.Sort (rgKeys);
3349 // initialize the block list with one element per key
3350 ArrayList rgKeyBlocks = new ArrayList ();
3351 foreach (object key in rgKeys)
3352 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3355 // iteratively merge the blocks while they are at least half full
3356 // there's probably a really cool way to do this with a tree...
3357 while (rgKeyBlocks.Count > 1)
3359 ArrayList rgKeyBlocksNew = new ArrayList ();
3360 kbCurr = (KeyBlock) rgKeyBlocks [0];
3361 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3363 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3364 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3367 kbCurr.nLast = kb.nLast;
3371 // start a new block
3372 rgKeyBlocksNew.Add (kbCurr);
3376 rgKeyBlocksNew.Add (kbCurr);
3377 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3379 rgKeyBlocks = rgKeyBlocksNew;
3382 // initialize the key lists
3383 foreach (KeyBlock kb in rgKeyBlocks)
3384 kb.rgKeys = new ArrayList ();
3386 // fill the key lists
3388 if (rgKeyBlocks.Count > 0) {
3389 kbCurr = (KeyBlock) rgKeyBlocks [0];
3390 foreach (object key in rgKeys)
3392 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3394 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3395 kbCurr.rgKeys.Add (key);
3399 // sort the blocks so we can tackle the largest ones first
3400 rgKeyBlocks.Sort ();
3402 // okay now we can start...
3403 ILGenerator ig = ec.ig;
3404 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3405 Label lblDefault = ig.DefineLabel ();
3407 Type typeKeys = null;
3408 if (rgKeys.Length > 0)
3409 typeKeys = rgKeys [0].GetType (); // used for conversions
3411 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3413 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3414 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3417 foreach (object key in kb.rgKeys)
3419 ig.Emit (OpCodes.Ldloc, val);
3420 EmitObjectInteger (ig, key);
3421 SwitchLabel sl = (SwitchLabel) Elements [key];
3422 ig.Emit (OpCodes.Beq, sl.ILLabel);
3427 // TODO: if all the keys in the block are the same and there are
3428 // no gaps/defaults then just use a range-check.
3429 if (SwitchType == TypeManager.int64_type ||
3430 SwitchType == TypeManager.uint64_type)
3432 // TODO: optimize constant/I4 cases
3434 // check block range (could be > 2^31)
3435 ig.Emit (OpCodes.Ldloc, val);
3436 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3437 ig.Emit (OpCodes.Blt, lblDefault);
3438 ig.Emit (OpCodes.Ldloc, val);
3439 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3440 ig.Emit (OpCodes.Bgt, lblDefault);
3443 ig.Emit (OpCodes.Ldloc, val);
3446 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3447 ig.Emit (OpCodes.Sub);
3449 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3454 ig.Emit (OpCodes.Ldloc, val);
3455 int nFirst = (int) kb.nFirst;
3458 IntConstant.EmitInt (ig, nFirst);
3459 ig.Emit (OpCodes.Sub);
3461 else if (nFirst < 0)
3463 IntConstant.EmitInt (ig, -nFirst);
3464 ig.Emit (OpCodes.Add);
3468 // first, build the list of labels for the switch
3470 int cJumps = kb.Length;
3471 Label [] rgLabels = new Label [cJumps];
3472 for (int iJump = 0; iJump < cJumps; iJump++)
3474 object key = kb.rgKeys [iKey];
3475 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3477 SwitchLabel sl = (SwitchLabel) Elements [key];
3478 rgLabels [iJump] = sl.ILLabel;
3482 rgLabels [iJump] = lblDefault;
3484 // emit the switch opcode
3485 ig.Emit (OpCodes.Switch, rgLabels);
3488 // mark the default for this block
3490 ig.MarkLabel (lblDefault);
3493 // TODO: find the default case and emit it here,
3494 // to prevent having to do the following jump.
3495 // make sure to mark other labels in the default section
3497 // the last default just goes to the end
3498 ig.Emit (OpCodes.Br, lblDefault);
3500 // now emit the code for the sections
3501 bool fFoundDefault = false;
3502 bool fAllReturn = true;
3503 foreach (SwitchSection ss in Sections)
3505 foreach (SwitchLabel sl in ss.Labels)
3507 ig.MarkLabel (sl.ILLabel);
3508 ig.MarkLabel (sl.ILLabelCode);
3509 if (sl.Label == null)
3511 ig.MarkLabel (lblDefault);
3512 fFoundDefault = true;
3515 fAllReturn &= ss.Block.Emit (ec);
3516 //ig.Emit (OpCodes.Br, lblEnd);
3519 if (!fFoundDefault) {
3520 ig.MarkLabel (lblDefault);
3523 ig.MarkLabel (lblEnd);
3528 // This simple emit switch works, but does not take advantage of the
3530 // TODO: remove non-string logic from here
3531 // TODO: binary search strings?
3533 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3535 ILGenerator ig = ec.ig;
3536 Label end_of_switch = ig.DefineLabel ();
3537 Label next_test = ig.DefineLabel ();
3538 Label null_target = ig.DefineLabel ();
3539 bool default_found = false;
3540 bool first_test = true;
3541 bool pending_goto_end = false;
3542 bool all_return = true;
3543 bool is_string = false;
3547 // Special processing for strings: we cant compare
3550 if (SwitchType == TypeManager.string_type){
3551 ig.Emit (OpCodes.Ldloc, val);
3554 if (Elements.Contains (NullLiteral.Null)){
3555 ig.Emit (OpCodes.Brfalse, null_target);
3557 ig.Emit (OpCodes.Brfalse, default_target);
3559 ig.Emit (OpCodes.Ldloc, val);
3560 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3561 ig.Emit (OpCodes.Stloc, val);
3564 SwitchSection last_section;
3565 last_section = (SwitchSection) Sections [Sections.Count-1];
3567 foreach (SwitchSection ss in Sections){
3568 Label sec_begin = ig.DefineLabel ();
3570 if (pending_goto_end)
3571 ig.Emit (OpCodes.Br, end_of_switch);
3573 int label_count = ss.Labels.Count;
3575 foreach (SwitchLabel sl in ss.Labels){
3576 ig.MarkLabel (sl.ILLabel);
3579 ig.MarkLabel (next_test);
3580 next_test = ig.DefineLabel ();
3583 // If we are the default target
3585 if (sl.Label == null){
3586 ig.MarkLabel (default_target);
3587 default_found = true;
3589 object lit = sl.Converted;
3591 if (lit is NullLiteral){
3593 if (label_count == 1)
3594 ig.Emit (OpCodes.Br, next_test);
3599 StringConstant str = (StringConstant) lit;
3601 ig.Emit (OpCodes.Ldloc, val);
3602 ig.Emit (OpCodes.Ldstr, str.Value);
3603 if (label_count == 1)
3604 ig.Emit (OpCodes.Bne_Un, next_test);
3606 ig.Emit (OpCodes.Beq, sec_begin);
3608 ig.Emit (OpCodes.Ldloc, val);
3609 EmitObjectInteger (ig, lit);
3610 ig.Emit (OpCodes.Ceq);
3611 if (label_count == 1)
3612 ig.Emit (OpCodes.Brfalse, next_test);
3614 ig.Emit (OpCodes.Brtrue, sec_begin);
3618 if (label_count != 1 && ss != last_section)
3619 ig.Emit (OpCodes.Br, next_test);
3622 ig.MarkLabel (null_target);
3623 ig.MarkLabel (sec_begin);
3624 foreach (SwitchLabel sl in ss.Labels)
\r
3625 ig.MarkLabel (sl.ILLabelCode);
3626 if (ss.Block.Emit (ec))
3627 pending_goto_end = false;
3630 pending_goto_end = true;
3634 if (!default_found){
3635 ig.MarkLabel (default_target);
3638 ig.MarkLabel (next_test);
3639 ig.MarkLabel (end_of_switch);
3644 public override bool Resolve (EmitContext ec)
3646 Expr = Expr.Resolve (ec);
3650 new_expr = SwitchGoverningType (ec, Expr.Type);
3651 if (new_expr == null){
3652 Report.Error (151, loc, "An integer type or string was expected for switch");
3657 SwitchType = new_expr.Type;
3659 if (!CheckSwitch (ec))
3662 Switch old_switch = ec.Switch;
3664 ec.Switch.SwitchType = SwitchType;
3666 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3669 foreach (SwitchSection ss in Sections){
3671 ec.CurrentBranching.CreateSibling ();
3675 if (ss.Block.Resolve (ec) != true)
3679 ec.EndFlowBranching ();
3680 ec.Switch = old_switch;
3685 public override bool Emit (EmitContext ec)
3687 // Store variable for comparission purposes
3688 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3690 ec.ig.Emit (OpCodes.Stloc, value);
3692 ILGenerator ig = ec.ig;
3694 default_target = ig.DefineLabel ();
3697 // Setup the codegen context
3699 Label old_end = ec.LoopEnd;
3700 Switch old_switch = ec.Switch;
3702 ec.LoopEnd = ig.DefineLabel ();
3707 if (SwitchType == TypeManager.string_type)
3708 all_return = SimpleSwitchEmit (ec, value);
3710 all_return = TableSwitchEmit (ec, value);
3712 // Restore context state.
3713 ig.MarkLabel (ec.LoopEnd);
3716 // Restore the previous context
3718 ec.LoopEnd = old_end;
3719 ec.Switch = old_switch;
3725 public class Lock : Statement {
3727 Statement Statement;
3729 public Lock (Expression expr, Statement stmt, Location l)
3736 public override bool Resolve (EmitContext ec)
3738 expr = expr.Resolve (ec);
3739 return Statement.Resolve (ec) && expr != null;
3742 public override bool Emit (EmitContext ec)
3744 Type type = expr.Type;
3747 if (type.IsValueType){
3748 Report.Error (185, loc, "lock statement requires the expression to be " +
3749 " a reference type (type is: `" +
3750 TypeManager.CSharpName (type) + "'");
3754 ILGenerator ig = ec.ig;
3755 LocalBuilder temp = ig.DeclareLocal (type);
3758 ig.Emit (OpCodes.Dup);
3759 ig.Emit (OpCodes.Stloc, temp);
3760 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3763 Label end = ig.BeginExceptionBlock ();
3764 bool old_in_try = ec.InTry;
3766 Label finish = ig.DefineLabel ();
3767 val = Statement.Emit (ec);
3768 ec.InTry = old_in_try;
3769 // ig.Emit (OpCodes.Leave, finish);
3771 ig.MarkLabel (finish);
3774 ig.BeginFinallyBlock ();
3775 ig.Emit (OpCodes.Ldloc, temp);
3776 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3777 ig.EndExceptionBlock ();
3783 public class Unchecked : Statement {
3784 public readonly Block Block;
3786 public Unchecked (Block b)
3791 public override bool Resolve (EmitContext ec)
3793 return Block.Resolve (ec);
3796 public override bool Emit (EmitContext ec)
3798 bool previous_state = ec.CheckState;
3799 bool previous_state_const = ec.ConstantCheckState;
3802 ec.CheckState = false;
3803 ec.ConstantCheckState = false;
3804 val = Block.Emit (ec);
3805 ec.CheckState = previous_state;
3806 ec.ConstantCheckState = previous_state_const;
3812 public class Checked : Statement {
3813 public readonly Block Block;
3815 public Checked (Block b)
3820 public override bool Resolve (EmitContext ec)
3822 bool previous_state = ec.CheckState;
3823 bool previous_state_const = ec.ConstantCheckState;
3825 ec.CheckState = true;
3826 ec.ConstantCheckState = true;
3827 bool ret = Block.Resolve (ec);
3828 ec.CheckState = previous_state;
3829 ec.ConstantCheckState = previous_state_const;
3834 public override bool Emit (EmitContext ec)
3836 bool previous_state = ec.CheckState;
3837 bool previous_state_const = ec.ConstantCheckState;
3840 ec.CheckState = true;
3841 ec.ConstantCheckState = true;
3842 val = Block.Emit (ec);
3843 ec.CheckState = previous_state;
3844 ec.ConstantCheckState = previous_state_const;
3850 public class Unsafe : Statement {
3851 public readonly Block Block;
3853 public Unsafe (Block b)
3858 public override bool Resolve (EmitContext ec)
3860 bool previous_state = ec.InUnsafe;
3864 val = Block.Resolve (ec);
3865 ec.InUnsafe = previous_state;
3870 public override bool Emit (EmitContext ec)
3872 bool previous_state = ec.InUnsafe;
3876 val = Block.Emit (ec);
3877 ec.InUnsafe = previous_state;
3886 public class Fixed : Statement {
3888 ArrayList declarators;
3889 Statement statement;
3894 public bool is_object;
3895 public VariableInfo vi;
3896 public Expression expr;
3897 public Expression converted;
3900 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3903 declarators = decls;
3908 public override bool Resolve (EmitContext ec)
3910 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3911 if (expr_type == null)
3914 data = new FixedData [declarators.Count];
3917 foreach (Pair p in declarators){
3918 VariableInfo vi = (VariableInfo) p.First;
3919 Expression e = (Expression) p.Second;
3924 // The rules for the possible declarators are pretty wise,
3925 // but the production on the grammar is more concise.
3927 // So we have to enforce these rules here.
3929 // We do not resolve before doing the case 1 test,
3930 // because the grammar is explicit in that the token &
3931 // is present, so we need to test for this particular case.
3935 // Case 1: & object.
3937 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3938 Expression child = ((Unary) e).Expr;
3941 if (child is ParameterReference || child is LocalVariableReference){
3944 "No need to use fixed statement for parameters or " +
3945 "local variable declarations (address is already " +
3954 child = ((Unary) e).Expr;
3956 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3959 data [i].is_object = true;
3961 data [i].converted = null;
3975 if (e.Type.IsArray){
3976 Type array_type = e.Type.GetElementType ();
3980 // Provided that array_type is unmanaged,
3982 if (!TypeManager.VerifyUnManaged (array_type, loc))
3986 // and T* is implicitly convertible to the
3987 // pointer type given in the fixed statement.
3989 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3991 Expression converted = Expression.ConvertImplicitRequired (
3992 ec, array_ptr, vi.VariableType, loc);
3993 if (converted == null)
3996 data [i].is_object = false;
3998 data [i].converted = converted;
4008 if (e.Type == TypeManager.string_type){
4009 data [i].is_object = false;
4011 data [i].converted = null;
4017 return statement.Resolve (ec);
4020 public override bool Emit (EmitContext ec)
4022 ILGenerator ig = ec.ig;
4024 bool is_ret = false;
4026 for (int i = 0; i < data.Length; i++) {
4027 VariableInfo vi = data [i].vi;
4030 // Case 1: & object.
4032 if (data [i].is_object) {
4034 // Store pointer in pinned location
4036 data [i].expr.Emit (ec);
4037 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4039 is_ret = statement.Emit (ec);
4041 // Clear the pinned variable.
4042 ig.Emit (OpCodes.Ldc_I4_0);
4043 ig.Emit (OpCodes.Conv_U);
4044 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4052 if (data [i].expr.Type.IsArray){
4054 // Store pointer in pinned location
4056 data [i].converted.Emit (ec);
4058 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4060 is_ret = statement.Emit (ec);
4062 // Clear the pinned variable.
4063 ig.Emit (OpCodes.Ldc_I4_0);
4064 ig.Emit (OpCodes.Conv_U);
4065 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4073 if (data [i].expr.Type == TypeManager.string_type){
4074 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4075 TypeManager.MakePinned (pinned_string);
4077 data [i].expr.Emit (ec);
4078 ig.Emit (OpCodes.Stloc, pinned_string);
4080 Expression sptr = new StringPtr (pinned_string, loc);
4081 Expression converted = Expression.ConvertImplicitRequired (
4082 ec, sptr, vi.VariableType, loc);
4084 if (converted == null)
4087 converted.Emit (ec);
4088 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4090 is_ret = statement.Emit (ec);
4092 // Clear the pinned variable
4093 ig.Emit (OpCodes.Ldnull);
4094 ig.Emit (OpCodes.Stloc, pinned_string);
4102 public class Catch {
4103 public readonly string Name;
4104 public readonly Block Block;
4105 public readonly Location Location;
4109 public Catch (Expression type, string name, Block block, Location l)
4117 public Type CatchType {
4120 throw new InvalidOperationException ();
4126 public bool IsGeneral {
4128 return type == null;
4132 public bool Resolve (EmitContext ec)
4135 type = type.DoResolve (ec);
4140 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)){
4141 Report.Error (155, Location,
4142 "The type caught or thrown must be derived " +
4143 "from System.Exception");
4148 if (!Block.Resolve (ec))
4155 public class Try : Statement {
4156 public readonly Block Fini, Block;
4157 public readonly ArrayList Specific;
4158 public readonly Catch General;
4161 // specific, general and fini might all be null.
4163 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4165 if (specific == null && general == null){
4166 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4170 this.Specific = specific;
4171 this.General = general;
4176 public override bool Resolve (EmitContext ec)
4180 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4182 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4184 bool old_in_try = ec.InTry;
4187 if (!Block.Resolve (ec))
4190 ec.InTry = old_in_try;
4192 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4194 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4196 foreach (Catch c in Specific){
4197 ec.CurrentBranching.CreateSibling ();
4198 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4200 if (c.Name != null) {
4201 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4203 throw new Exception ();
4208 bool old_in_catch = ec.InCatch;
4211 if (!c.Resolve (ec))
4214 ec.InCatch = old_in_catch;
4216 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4218 if ((current.Returns == FlowReturns.NEVER) ||
4219 (current.Returns == FlowReturns.SOMETIMES)) {
4220 vector.AndLocals (current);
4224 if (General != null){
4225 ec.CurrentBranching.CreateSibling ();
4226 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4228 bool old_in_catch = ec.InCatch;
4231 if (!General.Resolve (ec))
4234 ec.InCatch = old_in_catch;
4236 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4238 if ((current.Returns == FlowReturns.NEVER) ||
4239 (current.Returns == FlowReturns.SOMETIMES)) {
4240 vector.AndLocals (current);
4244 ec.CurrentBranching.CreateSiblingForFinally ();
4245 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4248 bool old_in_finally = ec.InFinally;
4249 ec.InFinally = true;
4251 if (!Fini.Resolve (ec))
4254 ec.InFinally = old_in_finally;
4257 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4259 FlowReturns returns = ec.EndFlowBranching ();
4261 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4263 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4264 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4267 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4269 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4274 public override bool Emit (EmitContext ec)
4276 ILGenerator ig = ec.ig;
4278 Label finish = ig.DefineLabel ();;
4282 end = ig.BeginExceptionBlock ();
4283 bool old_in_try = ec.InTry;
4285 returns = Block.Emit (ec);
4286 ec.InTry = old_in_try;
4289 // System.Reflection.Emit provides this automatically:
4290 // ig.Emit (OpCodes.Leave, finish);
4292 bool old_in_catch = ec.InCatch;
4294 DeclSpace ds = ec.DeclSpace;
4296 foreach (Catch c in Specific){
4299 ig.BeginCatchBlock (c.CatchType);
4301 if (c.Name != null){
4302 vi = c.Block.GetVariableInfo (c.Name);
4304 throw new Exception ("Variable does not exist in this block");
4306 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4308 ig.Emit (OpCodes.Pop);
4310 if (!c.Block.Emit (ec))
4314 if (General != null){
4315 ig.BeginCatchBlock (TypeManager.object_type);
4316 ig.Emit (OpCodes.Pop);
4317 if (!General.Block.Emit (ec))
4320 ec.InCatch = old_in_catch;
4322 ig.MarkLabel (finish);
4324 ig.BeginFinallyBlock ();
4325 bool old_in_finally = ec.InFinally;
4326 ec.InFinally = true;
4328 ec.InFinally = old_in_finally;
4331 ig.EndExceptionBlock ();
4334 if (!returns || ec.InTry || ec.InCatch)
4337 // Unfortunately, System.Reflection.Emit automatically emits a leave
4338 // to the end of the finally block. This is a problem if `returns'
4339 // is true since we may jump to a point after the end of the method.
4340 // As a workaround, emit an explicit ret here.
4342 if (ec.ReturnType != null)
4343 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4344 ec.ig.Emit (OpCodes.Ret);
4351 // FIXME: We still do not support the expression variant of the using
4354 public class Using : Statement {
4355 object expression_or_block;
4356 Statement Statement;
4361 Expression [] converted_vars;
4362 ExpressionStatement [] assign;
4364 public Using (object expression_or_block, Statement stmt, Location l)
4366 this.expression_or_block = expression_or_block;
4372 // Resolves for the case of using using a local variable declaration.
4374 bool ResolveLocalVariableDecls (EmitContext ec)
4376 bool need_conv = false;
4377 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4380 if (expr_type == null)
4384 // The type must be an IDisposable or an implicit conversion
4387 converted_vars = new Expression [var_list.Count];
4388 assign = new ExpressionStatement [var_list.Count];
4389 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4390 foreach (DictionaryEntry e in var_list){
4391 Expression var = (Expression) e.Key;
4393 var = var.ResolveLValue (ec, new EmptyExpression ());
4397 converted_vars [i] = Expression.ConvertImplicit (
4398 ec, var, TypeManager.idisposable_type, loc);
4400 if (converted_vars [i] == null)
4408 foreach (DictionaryEntry e in var_list){
4409 LocalVariableReference var = (LocalVariableReference) e.Key;
4410 Expression new_expr = (Expression) e.Value;
4413 a = new Assign (var, new_expr, loc);
4419 converted_vars [i] = var;
4420 assign [i] = (ExpressionStatement) a;
4427 bool ResolveExpression (EmitContext ec)
4429 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4430 conv = Expression.ConvertImplicit (
4431 ec, expr, TypeManager.idisposable_type, loc);
4441 // Emits the code for the case of using using a local variable declaration.
4443 bool EmitLocalVariableDecls (EmitContext ec)
4445 ILGenerator ig = ec.ig;
4448 bool old_in_try = ec.InTry;
4450 for (i = 0; i < assign.Length; i++) {
4451 assign [i].EmitStatement (ec);
4453 ig.BeginExceptionBlock ();
4455 Statement.Emit (ec);
4456 ec.InTry = old_in_try;
4458 bool old_in_finally = ec.InFinally;
4459 ec.InFinally = true;
4460 var_list.Reverse ();
4461 foreach (DictionaryEntry e in var_list){
4462 LocalVariableReference var = (LocalVariableReference) e.Key;
4463 Label skip = ig.DefineLabel ();
4466 ig.BeginFinallyBlock ();
4469 ig.Emit (OpCodes.Brfalse, skip);
4470 converted_vars [i].Emit (ec);
4471 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4472 ig.MarkLabel (skip);
4473 ig.EndExceptionBlock ();
4475 ec.InFinally = old_in_finally;
4480 bool EmitExpression (EmitContext ec)
4483 // Make a copy of the expression and operate on that.
4485 ILGenerator ig = ec.ig;
4486 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4491 ig.Emit (OpCodes.Stloc, local_copy);
4493 bool old_in_try = ec.InTry;
4495 ig.BeginExceptionBlock ();
4496 Statement.Emit (ec);
4497 ec.InTry = old_in_try;
4499 Label skip = ig.DefineLabel ();
4500 bool old_in_finally = ec.InFinally;
4501 ig.BeginFinallyBlock ();
4502 ig.Emit (OpCodes.Ldloc, local_copy);
4503 ig.Emit (OpCodes.Brfalse, skip);
4504 ig.Emit (OpCodes.Ldloc, local_copy);
4505 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4506 ig.MarkLabel (skip);
4507 ec.InFinally = old_in_finally;
4508 ig.EndExceptionBlock ();
4513 public override bool Resolve (EmitContext ec)
4515 if (expression_or_block is DictionaryEntry){
4516 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4517 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4519 if (!ResolveLocalVariableDecls (ec))
4522 } else if (expression_or_block is Expression){
4523 expr = (Expression) expression_or_block;
4525 expr = expr.Resolve (ec);
4529 expr_type = expr.Type;
4531 if (!ResolveExpression (ec))
4535 return Statement.Resolve (ec);
4538 public override bool Emit (EmitContext ec)
4540 if (expression_or_block is DictionaryEntry)
4541 return EmitLocalVariableDecls (ec);
4542 else if (expression_or_block is Expression)
4543 return EmitExpression (ec);
4550 /// Implementation of the foreach C# statement
4552 public class Foreach : Statement {
4554 LocalVariableReference variable;
4556 Statement statement;
4557 ForeachHelperMethods hm;
4558 Expression empty, conv;
4559 Type array_type, element_type;
4562 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4563 Statement stmt, Location l)
4566 this.variable = var;
4572 public override bool Resolve (EmitContext ec)
4574 expr = expr.Resolve (ec);
4578 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4579 if (var_type == null)
4583 // We need an instance variable. Not sure this is the best
4584 // way of doing this.
4586 // FIXME: When we implement propertyaccess, will those turn
4587 // out to return values in ExprClass? I think they should.
4589 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4590 expr.eclass == ExprClass.PropertyAccess)){
4591 error1579 (expr.Type);
4595 if (expr.Type.IsArray) {
4596 array_type = expr.Type;
4597 element_type = array_type.GetElementType ();
4599 empty = new EmptyExpression (element_type);
4601 hm = ProbeCollectionType (ec, expr.Type);
4603 error1579 (expr.Type);
4607 array_type = expr.Type;
4608 element_type = hm.element_type;
4610 empty = new EmptyExpression (hm.element_type);
4614 // FIXME: maybe we can apply the same trick we do in the
4615 // array handling to avoid creating empty and conv in some cases.
4617 // Although it is not as important in this case, as the type
4618 // will not likely be object (what the enumerator will return).
4620 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4624 if (variable.ResolveLValue (ec, empty) == null)
4627 if (!statement.Resolve (ec))
4634 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4636 static MethodInfo FetchMethodMoveNext (Type t)
4638 MemberList move_next_list;
4640 move_next_list = TypeContainer.FindMembers (
4641 t, MemberTypes.Method,
4642 BindingFlags.Public | BindingFlags.Instance,
4643 Type.FilterName, "MoveNext");
4644 if (move_next_list.Count == 0)
4647 foreach (MemberInfo m in move_next_list){
4648 MethodInfo mi = (MethodInfo) m;
4651 args = TypeManager.GetArgumentTypes (mi);
4652 if (args != null && args.Length == 0){
4653 if (mi.ReturnType == TypeManager.bool_type)
4661 // Retrieves a `public T get_Current ()' method from the Type `t'
4663 static MethodInfo FetchMethodGetCurrent (Type t)
4665 MemberList move_next_list;
4667 move_next_list = TypeContainer.FindMembers (
4668 t, MemberTypes.Method,
4669 BindingFlags.Public | BindingFlags.Instance,
4670 Type.FilterName, "get_Current");
4671 if (move_next_list.Count == 0)
4674 foreach (MemberInfo m in move_next_list){
4675 MethodInfo mi = (MethodInfo) m;
4678 args = TypeManager.GetArgumentTypes (mi);
4679 if (args != null && args.Length == 0)
4686 // This struct records the helper methods used by the Foreach construct
4688 class ForeachHelperMethods {
4689 public EmitContext ec;
4690 public MethodInfo get_enumerator;
4691 public MethodInfo move_next;
4692 public MethodInfo get_current;
4693 public Type element_type;
4694 public Type enumerator_type;
4695 public bool is_disposable;
4697 public ForeachHelperMethods (EmitContext ec)
4700 this.element_type = TypeManager.object_type;
4701 this.enumerator_type = TypeManager.ienumerator_type;
4702 this.is_disposable = true;
4706 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4711 if (!(m is MethodInfo))
4714 if (m.Name != "GetEnumerator")
4717 MethodInfo mi = (MethodInfo) m;
4718 Type [] args = TypeManager.GetArgumentTypes (mi);
4720 if (args.Length != 0)
4723 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4724 EmitContext ec = hm.ec;
4727 // Check whether GetEnumerator is accessible to us
4729 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4731 Type declaring = mi.DeclaringType;
4732 if (prot == MethodAttributes.Private){
4733 if (declaring != ec.ContainerType)
4735 } else if (prot == MethodAttributes.FamANDAssem){
4736 // If from a different assembly, false
4737 if (!(mi is MethodBuilder))
4740 // Are we being invoked from the same class, or from a derived method?
4742 if (ec.ContainerType != declaring){
4743 if (!ec.ContainerType.IsSubclassOf (declaring))
4746 } else if (prot == MethodAttributes.FamORAssem){
4747 if (!(mi is MethodBuilder ||
4748 ec.ContainerType == declaring ||
4749 ec.ContainerType.IsSubclassOf (declaring)))
4751 } if (prot == MethodAttributes.Family){
4752 if (!(ec.ContainerType == declaring ||
4753 ec.ContainerType.IsSubclassOf (declaring)))
4758 // Ok, we can access it, now make sure that we can do something
4759 // with this `GetEnumerator'
4762 if (mi.ReturnType == TypeManager.ienumerator_type ||
4763 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4764 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4765 hm.move_next = TypeManager.bool_movenext_void;
4766 hm.get_current = TypeManager.object_getcurrent_void;
4771 // Ok, so they dont return an IEnumerable, we will have to
4772 // find if they support the GetEnumerator pattern.
4774 Type return_type = mi.ReturnType;
4776 hm.move_next = FetchMethodMoveNext (return_type);
4777 if (hm.move_next == null)
4779 hm.get_current = FetchMethodGetCurrent (return_type);
4780 if (hm.get_current == null)
4783 hm.element_type = hm.get_current.ReturnType;
4784 hm.enumerator_type = return_type;
4785 hm.is_disposable = TypeManager.ImplementsInterface (
4786 hm.enumerator_type, TypeManager.idisposable_type);
4792 /// This filter is used to find the GetEnumerator method
4793 /// on which IEnumerator operates
4795 static MemberFilter FilterEnumerator;
4799 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4802 void error1579 (Type t)
4804 Report.Error (1579, loc,
4805 "foreach statement cannot operate on variables of type `" +
4806 t.FullName + "' because that class does not provide a " +
4807 " GetEnumerator method or it is inaccessible");
4810 static bool TryType (Type t, ForeachHelperMethods hm)
4814 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4815 BindingFlags.Public | BindingFlags.NonPublic |
4816 BindingFlags.Instance,
4817 FilterEnumerator, hm);
4822 hm.get_enumerator = (MethodInfo) mi [0];
4827 // Looks for a usable GetEnumerator in the Type, and if found returns
4828 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4830 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4832 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4834 if (TryType (t, hm))
4838 // Now try to find the method in the interfaces
4841 Type [] ifaces = t.GetInterfaces ();
4843 foreach (Type i in ifaces){
4844 if (TryType (i, hm))
4849 // Since TypeBuilder.GetInterfaces only returns the interface
4850 // types for this type, we have to keep looping, but once
4851 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4852 // done, because it returns all the types
4854 if ((t is TypeBuilder))
4864 // FIXME: possible optimization.
4865 // We might be able to avoid creating `empty' if the type is the sam
4867 bool EmitCollectionForeach (EmitContext ec)
4869 ILGenerator ig = ec.ig;
4870 LocalBuilder enumerator, disposable;
4872 enumerator = ig.DeclareLocal (hm.enumerator_type);
4873 if (hm.is_disposable)
4874 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4879 // Instantiate the enumerator
4881 if (expr.Type.IsValueType){
4882 if (expr is IMemoryLocation){
4883 IMemoryLocation ml = (IMemoryLocation) expr;
4885 ml.AddressOf (ec, AddressOp.Load);
4887 throw new Exception ("Expr " + expr + " of type " + expr.Type +
4888 " does not implement IMemoryLocation");
4889 ig.Emit (OpCodes.Call, hm.get_enumerator);
4892 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4894 ig.Emit (OpCodes.Stloc, enumerator);
4897 // Protect the code in a try/finalize block, so that
4898 // if the beast implement IDisposable, we get rid of it
4901 bool old_in_try = ec.InTry;
4903 if (hm.is_disposable) {
4904 l = ig.BeginExceptionBlock ();
4908 Label end_try = ig.DefineLabel ();
4910 ig.MarkLabel (ec.LoopBegin);
4911 ig.Emit (OpCodes.Ldloc, enumerator);
4912 ig.Emit (OpCodes.Callvirt, hm.move_next);
4913 ig.Emit (OpCodes.Brfalse, end_try);
4914 ig.Emit (OpCodes.Ldloc, enumerator);
4915 ig.Emit (OpCodes.Callvirt, hm.get_current);
4916 variable.EmitAssign (ec, conv);
4917 statement.Emit (ec);
4918 ig.Emit (OpCodes.Br, ec.LoopBegin);
4919 ig.MarkLabel (end_try);
4920 ec.InTry = old_in_try;
4922 // The runtime provides this for us.
4923 // ig.Emit (OpCodes.Leave, end);
4926 // Now the finally block
4928 if (hm.is_disposable) {
4929 Label end_finally = ig.DefineLabel ();
4930 bool old_in_finally = ec.InFinally;
4931 ec.InFinally = true;
4932 ig.BeginFinallyBlock ();
4934 ig.Emit (OpCodes.Ldloc, enumerator);
4935 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4936 ig.Emit (OpCodes.Stloc, disposable);
4937 ig.Emit (OpCodes.Ldloc, disposable);
4938 ig.Emit (OpCodes.Brfalse, end_finally);
4939 ig.Emit (OpCodes.Ldloc, disposable);
4940 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4941 ig.MarkLabel (end_finally);
4942 ec.InFinally = old_in_finally;
4944 // The runtime generates this anyways.
4945 // ig.Emit (OpCodes.Endfinally);
4947 ig.EndExceptionBlock ();
4950 ig.MarkLabel (ec.LoopEnd);
4955 // FIXME: possible optimization.
4956 // We might be able to avoid creating `empty' if the type is the sam
4958 bool EmitArrayForeach (EmitContext ec)
4960 int rank = array_type.GetArrayRank ();
4961 ILGenerator ig = ec.ig;
4963 LocalBuilder copy = ig.DeclareLocal (array_type);
4966 // Make our copy of the array
4969 ig.Emit (OpCodes.Stloc, copy);
4972 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
4976 ig.Emit (OpCodes.Ldc_I4_0);
4977 ig.Emit (OpCodes.Stloc, counter);
4978 test = ig.DefineLabel ();
4979 ig.Emit (OpCodes.Br, test);
4981 loop = ig.DefineLabel ();
4982 ig.MarkLabel (loop);
4984 ig.Emit (OpCodes.Ldloc, copy);
4985 ig.Emit (OpCodes.Ldloc, counter);
4986 ArrayAccess.EmitLoadOpcode (ig, var_type);
4988 variable.EmitAssign (ec, conv);
4990 statement.Emit (ec);
4992 ig.MarkLabel (ec.LoopBegin);
4993 ig.Emit (OpCodes.Ldloc, counter);
4994 ig.Emit (OpCodes.Ldc_I4_1);
4995 ig.Emit (OpCodes.Add);
4996 ig.Emit (OpCodes.Stloc, counter);
4998 ig.MarkLabel (test);
4999 ig.Emit (OpCodes.Ldloc, counter);
5000 ig.Emit (OpCodes.Ldloc, copy);
5001 ig.Emit (OpCodes.Ldlen);
5002 ig.Emit (OpCodes.Conv_I4);
5003 ig.Emit (OpCodes.Blt, loop);
5005 LocalBuilder [] dim_len = new LocalBuilder [rank];
5006 LocalBuilder [] dim_count = new LocalBuilder [rank];
5007 Label [] loop = new Label [rank];
5008 Label [] test = new Label [rank];
5011 for (dim = 0; dim < rank; dim++){
5012 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5013 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5014 test [dim] = ig.DefineLabel ();
5015 loop [dim] = ig.DefineLabel ();
5018 for (dim = 0; dim < rank; dim++){
5019 ig.Emit (OpCodes.Ldloc, copy);
5020 IntLiteral.EmitInt (ig, dim);
5021 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5022 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5025 for (dim = 0; dim < rank; dim++){
5026 ig.Emit (OpCodes.Ldc_I4_0);
5027 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5028 ig.Emit (OpCodes.Br, test [dim]);
5029 ig.MarkLabel (loop [dim]);
5032 ig.Emit (OpCodes.Ldloc, copy);
5033 for (dim = 0; dim < rank; dim++)
5034 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5037 // FIXME: Maybe we can cache the computation of `get'?
5039 Type [] args = new Type [rank];
5042 for (int i = 0; i < rank; i++)
5043 args [i] = TypeManager.int32_type;
5045 ModuleBuilder mb = CodeGen.ModuleBuilder;
5046 get = mb.GetArrayMethod (
5048 CallingConventions.HasThis| CallingConventions.Standard,
5050 ig.Emit (OpCodes.Call, get);
5051 variable.EmitAssign (ec, conv);
5052 statement.Emit (ec);
5053 ig.MarkLabel (ec.LoopBegin);
5054 for (dim = rank - 1; dim >= 0; dim--){
5055 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5056 ig.Emit (OpCodes.Ldc_I4_1);
5057 ig.Emit (OpCodes.Add);
5058 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5060 ig.MarkLabel (test [dim]);
5061 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5062 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5063 ig.Emit (OpCodes.Blt, loop [dim]);
5066 ig.MarkLabel (ec.LoopEnd);
5071 public override bool Emit (EmitContext ec)
5075 ILGenerator ig = ec.ig;
5077 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5078 bool old_inloop = ec.InLoop;
5079 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5080 ec.LoopBegin = ig.DefineLabel ();
5081 ec.LoopEnd = ig.DefineLabel ();
5083 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5086 ret_val = EmitCollectionForeach (ec);
5088 ret_val = EmitArrayForeach (ec);
5090 ec.LoopBegin = old_begin;
5091 ec.LoopEnd = old_end;
5092 ec.InLoop = old_inloop;
5093 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;