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) &&
856 !t.IsSubclassOf (TypeManager.exception_type) &&
857 !(expr is NullLiteral)) {
858 Report.Error (155, loc,
859 "The type caught or thrown must be derived " +
860 "from System.Exception");
865 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
869 public override bool Emit (EmitContext ec)
873 ec.ig.Emit (OpCodes.Rethrow);
877 "A throw statement with no argument is only " +
878 "allowed in a catch clause");
885 ec.ig.Emit (OpCodes.Throw);
891 public class Break : Statement {
893 public Break (Location l)
898 public override bool Resolve (EmitContext ec)
900 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
904 public override bool Emit (EmitContext ec)
906 ILGenerator ig = ec.ig;
908 if (ec.InLoop == false && ec.Switch == null){
909 Report.Error (139, loc, "No enclosing loop or switch to continue to");
914 if (ec.InTry || ec.InCatch)
915 ig.Emit (OpCodes.Leave, ec.LoopEnd);
917 ig.Emit (OpCodes.Br, ec.LoopEnd);
923 public class Continue : Statement {
925 public Continue (Location l)
930 public override bool Resolve (EmitContext ec)
932 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
936 public override bool Emit (EmitContext ec)
938 Label begin = ec.LoopBegin;
941 Report.Error (139, loc, "No enclosing loop to continue to");
946 // UGH: Non trivial. This Br might cross a try/catch boundary
950 // try { ... } catch { continue; }
954 // try {} catch { while () { continue; }}
956 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
957 ec.ig.Emit (OpCodes.Leave, begin);
958 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
959 throw new Exception ("Should never happen");
961 ec.ig.Emit (OpCodes.Br, begin);
967 // This is used in the control flow analysis code to specify whether the
968 // current code block may return to its enclosing block before reaching
971 public enum FlowReturns {
972 // It can never return.
975 // This means that the block contains a conditional return statement
979 // The code always returns, ie. there's an unconditional return / break
983 // The code always throws an exception.
986 // The current code block is unreachable. This happens if it's immediately
987 // following a FlowReturns.ALWAYS block.
992 // This is a special bit vector which can inherit from another bit vector doing a
993 // copy-on-write strategy. The inherited vector may have a smaller size than the
996 public class MyBitVector {
997 public readonly int Count;
998 public readonly MyBitVector InheritsFrom;
1003 public MyBitVector (int Count)
1004 : this (null, Count)
1007 public MyBitVector (MyBitVector InheritsFrom, int Count)
1009 this.InheritsFrom = InheritsFrom;
1014 // Checks whether this bit vector has been modified. After setting this to true,
1015 // we won't use the inherited vector anymore, but our own copy of it.
1017 public bool IsDirty {
1024 initialize_vector ();
1029 // Get/set bit `index' in the bit vector.
1031 public bool this [int index]
1035 throw new ArgumentOutOfRangeException ();
1037 // We're doing a "copy-on-write" strategy here; as long
1038 // as nobody writes to the array, we can use our parent's
1039 // copy instead of duplicating the vector.
1042 return vector [index];
1043 else if (InheritsFrom != null) {
1044 BitArray inherited = InheritsFrom.Vector;
1046 if (index < inherited.Count)
1047 return inherited [index];
1056 throw new ArgumentOutOfRangeException ();
1058 // Only copy the vector if we're actually modifying it.
1060 if (this [index] != value) {
1061 initialize_vector ();
1063 vector [index] = value;
1069 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1070 // copy of the bit vector.
1072 public static explicit operator BitArray (MyBitVector vector)
1074 vector.initialize_vector ();
1075 return vector.Vector;
1079 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1080 // different size than the current one.
1082 public void Or (MyBitVector new_vector)
1084 BitArray new_array = new_vector.Vector;
1086 initialize_vector ();
1089 if (vector.Count < new_array.Count)
1090 upper = vector.Count;
1092 upper = new_array.Count;
1094 for (int i = 0; i < upper; i++)
1095 vector [i] = vector [i] | new_array [i];
1099 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1100 // a different size than the current one.
1102 public void And (MyBitVector new_vector)
1104 BitArray new_array = new_vector.Vector;
1106 initialize_vector ();
1109 if (vector.Count < new_array.Count)
1110 lower = upper = vector.Count;
1112 lower = new_array.Count;
1113 upper = vector.Count;
1116 for (int i = 0; i < lower; i++)
1117 vector [i] = vector [i] & new_array [i];
1119 for (int i = lower; i < upper; i++)
1124 // This does a deep copy of the bit vector.
1126 public MyBitVector Clone ()
1128 MyBitVector retval = new MyBitVector (Count);
1130 retval.Vector = Vector;
1139 else if (!is_dirty && (InheritsFrom != null))
1140 return InheritsFrom.Vector;
1142 initialize_vector ();
1148 initialize_vector ();
1150 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1151 vector [i] = value [i];
1155 void initialize_vector ()
1160 vector = new BitArray (Count, false);
1161 if (InheritsFrom != null)
1162 Vector = InheritsFrom.Vector;
1167 public override string ToString ()
1169 StringBuilder sb = new StringBuilder ("MyBitVector (");
1171 BitArray vector = Vector;
1175 sb.Append ("INHERITED - ");
1176 for (int i = 0; i < vector.Count; i++) {
1179 sb.Append (vector [i]);
1183 return sb.ToString ();
1188 // The type of a FlowBranching.
1190 public enum FlowBranchingType {
1191 // Normal (conditional or toplevel) block.
1208 // A new instance of this class is created every time a new block is resolved
1209 // and if there's branching in the block's control flow.
1211 public class FlowBranching {
1213 // The type of this flow branching.
1215 public readonly FlowBranchingType Type;
1218 // The block this branching is contained in. This may be null if it's not
1219 // a top-level block and it doesn't declare any local variables.
1221 public readonly Block Block;
1224 // The parent of this branching or null if this is the top-block.
1226 public readonly FlowBranching Parent;
1229 // Start-Location of this flow branching.
1231 public readonly Location Location;
1234 // A list of UsageVectors. A new vector is added each time control flow may
1235 // take a different path.
1237 public ArrayList Siblings;
1242 InternalParameters param_info;
1244 MyStructInfo[] struct_params;
1246 ArrayList finally_vectors;
1248 static int next_id = 0;
1252 // Performs an `And' operation on the FlowReturns status
1253 // (for instance, a block only returns ALWAYS if all its siblings
1256 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1258 if (b == FlowReturns.UNREACHABLE)
1262 case FlowReturns.NEVER:
1263 if (b == FlowReturns.NEVER)
1264 return FlowReturns.NEVER;
1266 return FlowReturns.SOMETIMES;
1268 case FlowReturns.SOMETIMES:
1269 return FlowReturns.SOMETIMES;
1271 case FlowReturns.ALWAYS:
1272 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1273 return FlowReturns.ALWAYS;
1275 return FlowReturns.SOMETIMES;
1277 case FlowReturns.EXCEPTION:
1278 if (b == FlowReturns.EXCEPTION)
1279 return FlowReturns.EXCEPTION;
1280 else if (b == FlowReturns.ALWAYS)
1281 return FlowReturns.ALWAYS;
1283 return FlowReturns.SOMETIMES;
1290 // The vector contains a BitArray with information about which local variables
1291 // and parameters are already initialized at the current code position.
1293 public class UsageVector {
1295 // If this is true, then the usage vector has been modified and must be
1296 // merged when we're done with this branching.
1298 public bool IsDirty;
1301 // The number of parameters in this block.
1303 public readonly int CountParameters;
1306 // The number of locals in this block.
1308 public readonly int CountLocals;
1311 // If not null, then we inherit our state from this vector and do a
1312 // copy-on-write. If null, then we're the first sibling in a top-level
1313 // block and inherit from the empty vector.
1315 public readonly UsageVector InheritsFrom;
1320 MyBitVector locals, parameters;
1321 FlowReturns real_returns, real_breaks;
1322 bool returns_set, breaks_set, is_finally;
1324 static int next_id = 0;
1328 // Normally, you should not use any of these constructors.
1330 public UsageVector (UsageVector parent, int num_params, int num_locals)
1332 this.InheritsFrom = parent;
1333 this.CountParameters = num_params;
1334 this.CountLocals = num_locals;
1335 this.real_returns = FlowReturns.NEVER;
1336 this.real_breaks = FlowReturns.NEVER;
1338 if (parent != null) {
1339 locals = new MyBitVector (parent.locals, CountLocals);
1341 parameters = new MyBitVector (parent.parameters, num_params);
1343 locals = new MyBitVector (null, CountLocals);
1345 parameters = new MyBitVector (null, num_params);
1351 public UsageVector (UsageVector parent)
1352 : this (parent, parent.CountParameters, parent.CountLocals)
1356 // This does a deep copy of the usage vector.
1358 public UsageVector Clone ()
1360 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1362 retval.locals = locals.Clone ();
1363 if (parameters != null)
1364 retval.parameters = parameters.Clone ();
1365 retval.real_returns = real_returns;
1366 retval.real_breaks = real_breaks;
1372 // State of parameter `number'.
1374 public bool this [int number]
1379 else if (number == 0)
1380 throw new ArgumentException ();
1382 return parameters [number - 1];
1388 else if (number == 0)
1389 throw new ArgumentException ();
1391 parameters [number - 1] = value;
1396 // State of the local variable `vi'.
1397 // If the local variable is a struct, use a non-zero `field_idx'
1398 // to check an individual field in it.
1400 public bool this [VariableInfo vi, int field_idx]
1403 if (vi.Number == -1)
1405 else if (vi.Number == 0)
1406 throw new ArgumentException ();
1408 return locals [vi.Number + field_idx - 1];
1412 if (vi.Number == -1)
1414 else if (vi.Number == 0)
1415 throw new ArgumentException ();
1417 locals [vi.Number + field_idx - 1] = value;
1422 // Specifies when the current block returns.
1424 public FlowReturns Returns {
1426 return real_returns;
1430 real_returns = value;
1436 // Specifies whether control may return to our containing block
1437 // before reaching the end of this block. This happens if there
1438 // is a break/continue/goto/return in it.
1440 public FlowReturns Breaks {
1446 real_breaks = value;
1452 // Merge a child branching.
1454 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1456 MyBitVector new_locals = null;
1457 MyBitVector new_params = null;
1459 FlowReturns new_returns = FlowReturns.NEVER;
1460 FlowReturns new_breaks = FlowReturns.NEVER;
1461 bool new_returns_set = false, new_breaks_set = false;
1464 Report.Debug (1, "MERGING CHILDREN", branching, this);
1466 foreach (UsageVector child in children) {
1467 Report.Debug (1, " MERGING CHILD", child, child.is_finally);
1469 if (!child.is_finally) {
1470 // If Returns is already set, perform an
1471 // `And' operation on it, otherwise just set just.
1472 if (!new_returns_set) {
1473 new_returns = child.Returns;
1474 new_returns_set = true;
1476 new_returns = AndFlowReturns (
1477 new_returns, child.Returns);
1479 // If Breaks is already set, perform an
1480 // `And' operation on it, otherwise just set just.
1481 if (!new_breaks_set) {
1482 new_breaks = child.Breaks;
1483 new_breaks_set = true;
1485 new_breaks = AndFlowReturns (
1486 new_breaks, child.Breaks);
1488 // Check whether control may reach the end of this sibling.
1489 // This happens unless we either always return or always break.
1490 if ((child.Returns == FlowReturns.EXCEPTION) ||
1491 (child.Returns == FlowReturns.ALWAYS) ||
1492 ((branching.Type != FlowBranchingType.SWITCH_SECTION) &&
1493 (branching.Type != FlowBranchingType.LOOP_BLOCK) &&
1494 (child.Breaks == FlowReturns.ALWAYS)))
1501 // Ignore unreachable children.
1502 if (child.Returns == FlowReturns.UNREACHABLE)
1505 // A local variable is initialized after a flow branching if it
1506 // has been initialized in all its branches which do neither
1507 // always return or always throw an exception.
1509 // If a branch may return, but does not always return, then we
1510 // can treat it like a never-returning branch here: control will
1511 // only reach the code position after the branching if we did not
1514 // It's important to distinguish between always and sometimes
1515 // returning branches here:
1518 // 2 if (something) {
1522 // 6 Console.WriteLine (a);
1524 // The if block in lines 3-4 always returns, so we must not look
1525 // at the initialization of `a' in line 4 - thus it'll still be
1526 // uninitialized in line 6.
1528 // On the other hand, the following is allowed:
1535 // 6 Console.WriteLine (a);
1537 // Here, `a' is initialized in line 3 and we must not look at
1538 // line 5 since it always returns.
1541 if (new_locals != null)
1542 new_locals.And (child.locals);
1544 new_locals = locals.Clone ();
1545 new_locals.Or (child.locals);
1549 // An `out' parameter must be assigned in all branches which do
1550 // not always throw an exception.
1551 if (!child.is_finally && (child.Returns != FlowReturns.EXCEPTION)) {
1552 if (parameters != null) {
1553 if (new_params != null)
1554 new_params.And (child.parameters);
1556 new_params = parameters.Clone ();
1557 new_params.Or (child.parameters);
1562 // If we always return, check whether all `out' parameters have
1564 if ((child.Returns == FlowReturns.ALWAYS) && (child.parameters != null)) {
1565 branching.CheckOutParameters (
1566 child.parameters, branching.Location);
1570 // Set new `Returns' status.
1572 Returns = new_returns;
1575 Returns = AndFlowReturns (Returns, new_returns);
1578 // We've now either reached the point after the branching or we will
1579 // never get there since we always return or always throw an exception.
1581 // If we can reach the point after the branching, mark all locals and
1582 // parameters as initialized which have been initialized in all branches
1583 // we need to look at (see above).
1586 bool or_locals = (Returns == FlowReturns.NEVER) ||
1587 (Returns == FlowReturns.SOMETIMES);
1588 if ((branching.Type != FlowBranchingType.SWITCH_SECTION) &&
1589 (branching.Type != FlowBranchingType.LOOP_BLOCK))
1590 or_locals &= ((Breaks == FlowReturns.NEVER) ||
1591 (Breaks == FlowReturns.SOMETIMES));
1593 if ((new_locals != null) && or_locals) {
1594 locals.Or (new_locals);
1597 if ((new_params != null) && (Breaks == FlowReturns.NEVER))
1598 parameters.Or (new_params);
1601 // If we may have returned (this only happens if there was a reachable
1602 // `return' statement in one of the branches), then we may return to our
1603 // parent block before reaching the end of the block, so set `Breaks'.
1605 if ((Returns != FlowReturns.NEVER) && (Returns != FlowReturns.SOMETIMES)) {
1606 // real_breaks = Returns;
1607 // breaks_set = true;
1608 } else if (branching.Type == FlowBranchingType.BLOCK) {
1610 // If this is not a loop or switch block, `break' actually breaks.
1614 Breaks = new_breaks;
1617 Breaks = AndFlowReturns (Breaks, new_breaks);
1620 if (new_returns == FlowReturns.EXCEPTION)
1621 Breaks = FlowReturns.UNREACHABLE;
1623 Report.Debug (1, "MERGING CHILDREN DONE", new_params, new_locals,
1624 new_returns, new_breaks, this);
1630 // Tells control flow analysis that the current code position may be reached with
1631 // a forward jump from any of the origins listed in `origin_vectors' which is a
1632 // list of UsageVectors.
1634 // This is used when resolving forward gotos - in the following example, the
1635 // variable `a' is uninitialized in line 8 becase this line may be reached via
1636 // the goto in line 4:
1646 // 8 Console.WriteLine (a);
1649 public void MergeJumpOrigins (ICollection origin_vectors)
1651 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1653 real_breaks = FlowReturns.NEVER;
1656 foreach (UsageVector vector in origin_vectors) {
1657 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1659 locals.And (vector.locals);
1660 if (parameters != null)
1661 parameters.And (vector.parameters);
1662 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1665 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1669 // This is used at the beginning of a finally block if there were
1670 // any return statements in the try block or one of the catch blocks.
1672 public void MergeFinallyOrigins (ICollection finally_vectors)
1674 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1676 real_breaks = FlowReturns.NEVER;
1679 foreach (UsageVector vector in finally_vectors) {
1680 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1682 if (parameters != null)
1683 parameters.And (vector.parameters);
1684 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1689 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1693 // Performs an `or' operation on the locals and the parameters.
1695 public void Or (UsageVector new_vector)
1697 locals.Or (new_vector.locals);
1698 if (parameters != null)
1699 parameters.Or (new_vector.parameters);
1703 // Performs an `and' operation on the locals.
1705 public void AndLocals (UsageVector new_vector)
1707 locals.And (new_vector.locals);
1711 // Returns a deep copy of the parameters.
1713 public MyBitVector Parameters {
1715 if (parameters != null)
1716 return parameters.Clone ();
1723 // Returns a deep copy of the locals.
1725 public MyBitVector Locals {
1727 return locals.Clone ();
1735 public override string ToString ()
1737 StringBuilder sb = new StringBuilder ();
1739 sb.Append ("Vector (");
1742 sb.Append (Returns);
1745 if (parameters != null) {
1747 sb.Append (parameters);
1753 return sb.ToString ();
1757 FlowBranching (FlowBranchingType type, Location loc)
1759 this.Siblings = new ArrayList ();
1761 this.Location = loc;
1767 // Creates a new flow branching for `block'.
1768 // This is used from Block.Resolve to create the top-level branching of
1771 public FlowBranching (Block block, InternalParameters ip, Location loc)
1772 : this (FlowBranchingType.BLOCK, loc)
1777 int count = (ip != null) ? ip.Count : 0;
1780 param_map = new int [count];
1781 struct_params = new MyStructInfo [count];
1784 for (int i = 0; i < count; i++) {
1785 Parameter.Modifier mod = param_info.ParameterModifier (i);
1787 if ((mod & Parameter.Modifier.OUT) == 0)
1790 param_map [i] = ++num_params;
1792 Type param_type = param_info.ParameterType (i);
1794 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1795 if (struct_params [i] != null)
1796 num_params += struct_params [i].Count;
1799 Siblings = new ArrayList ();
1800 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1804 // Creates a new flow branching which is contained in `parent'.
1805 // You should only pass non-null for the `block' argument if this block
1806 // introduces any new variables - in this case, we need to create a new
1807 // usage vector with a different size than our parent's one.
1809 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1810 Block block, Location loc)
1816 if (parent != null) {
1817 param_info = parent.param_info;
1818 param_map = parent.param_map;
1819 struct_params = parent.struct_params;
1820 num_params = parent.num_params;
1825 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1826 Block.CountVariables);
1828 vector = new UsageVector (Parent.CurrentUsageVector);
1830 Siblings.Add (vector);
1833 case FlowBranchingType.EXCEPTION:
1834 finally_vectors = new ArrayList ();
1843 // Returns the branching's current usage vector.
1845 public UsageVector CurrentUsageVector
1848 return (UsageVector) Siblings [Siblings.Count - 1];
1853 // Creates a sibling of the current usage vector.
1855 public void CreateSibling ()
1857 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1859 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1863 // Creates a sibling for a `finally' block.
1865 public void CreateSiblingForFinally ()
1867 if (Type != FlowBranchingType.EXCEPTION)
1868 throw new NotSupportedException ();
1872 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1876 // Check whether all `out' parameters have been assigned.
1878 public void CheckOutParameters (MyBitVector parameters, Location loc)
1883 for (int i = 0; i < param_map.Length; i++) {
1884 int index = param_map [i];
1889 if (parameters [index - 1])
1892 // If it's a struct, we must ensure that all its fields have
1893 // been assigned. If the struct has any non-public fields, this
1894 // can only be done by assigning the whole struct.
1896 MyStructInfo struct_info = struct_params [index - 1];
1897 if ((struct_info == null) || struct_info.HasNonPublicFields) {
1899 177, loc, "The out parameter `" +
1900 param_info.ParameterName (i) + "' must be " +
1901 "assigned before control leave the current method.");
1907 for (int j = 0; j < struct_info.Count; j++) {
1908 if (!parameters [index + j]) {
1910 177, loc, "The out parameter `" +
1911 param_info.ParameterName (i) + "' must be " +
1912 "assigned before control leave the current method.");
1921 // Merge a child branching.
1923 public FlowReturns MergeChild (FlowBranching child)
1925 return CurrentUsageVector.MergeChildren (child, child.Siblings);
1929 // Does the toplevel merging.
1931 public FlowReturns MergeTopBlock ()
1933 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1934 throw new NotSupportedException ();
1936 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1938 vector.MergeChildren (this, Siblings);
1941 Siblings.Add (vector);
1943 Report.Debug (1, "MERGING TOP BLOCK", vector);
1945 if (vector.Returns != FlowReturns.EXCEPTION)
1946 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1948 return vector.Returns;
1951 public bool InTryBlock ()
1953 if (finally_vectors != null)
1955 else if (Parent != null)
1956 return Parent.InTryBlock ();
1961 public void AddFinallyVector (UsageVector vector)
1963 if (finally_vectors != null) {
1964 finally_vectors.Add (vector.Clone ());
1969 Parent.AddFinallyVector (vector);
1971 throw new NotSupportedException ();
1974 public bool IsVariableAssigned (VariableInfo vi)
1976 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1979 return CurrentUsageVector [vi, 0];
1982 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
1984 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1987 return CurrentUsageVector [vi, field_idx];
1990 public void SetVariableAssigned (VariableInfo vi)
1992 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1995 CurrentUsageVector [vi, 0] = true;
1998 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2000 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
2003 CurrentUsageVector [vi, field_idx] = true;
2006 public bool IsParameterAssigned (int number)
2008 int index = param_map [number];
2013 if (CurrentUsageVector [index])
2016 // Parameter is not assigned, so check whether it's a struct.
2017 // If it's either not a struct or a struct which non-public
2018 // fields, return false.
2019 MyStructInfo struct_info = struct_params [number];
2020 if ((struct_info == null) || struct_info.HasNonPublicFields)
2023 // Ok, so each field must be assigned.
2024 for (int i = 0; i < struct_info.Count; i++)
2025 if (!CurrentUsageVector [index + i])
2031 public bool IsParameterAssigned (int number, string field_name)
2033 int index = param_map [number];
2038 int field_idx = struct_params [number] [field_name];
2040 return CurrentUsageVector [index + field_idx];
2043 public void SetParameterAssigned (int number)
2045 if (param_map [number] == 0)
2048 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
2049 CurrentUsageVector [param_map [number]] = true;
2052 public void SetParameterAssigned (int number, string field_name)
2054 int index = param_map [number];
2059 int field_idx = struct_params [number] [field_name];
2061 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
2062 CurrentUsageVector [index + field_idx] = true;
2065 public override string ToString ()
2067 StringBuilder sb = new StringBuilder ("FlowBranching (");
2072 if (Block != null) {
2074 sb.Append (Block.ID);
2076 sb.Append (Block.StartLocation);
2079 sb.Append (Siblings.Count);
2081 sb.Append (CurrentUsageVector);
2083 return sb.ToString ();
2087 public class MyStructInfo {
2088 public readonly Type Type;
2089 public readonly FieldInfo[] Fields;
2090 public readonly FieldInfo[] NonPublicFields;
2091 public readonly int Count;
2092 public readonly int CountNonPublic;
2093 public readonly bool HasNonPublicFields;
2095 private static Hashtable field_type_hash = new Hashtable ();
2096 private Hashtable field_hash;
2098 // Private constructor. To save memory usage, we only need to create one instance
2099 // of this class per struct type.
2100 private MyStructInfo (Type type)
2104 if (type is TypeBuilder) {
2105 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2107 ArrayList fields = tc.Fields;
2108 if (fields != null) {
2109 foreach (Field field in fields) {
2110 if ((field.ModFlags & Modifiers.STATIC) != 0)
2112 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2119 Fields = new FieldInfo [Count];
2120 NonPublicFields = new FieldInfo [CountNonPublic];
2122 Count = CountNonPublic = 0;
2123 if (fields != null) {
2124 foreach (Field field in fields) {
2125 if ((field.ModFlags & Modifiers.STATIC) != 0)
2127 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2128 Fields [Count++] = field.FieldBuilder;
2130 NonPublicFields [CountNonPublic++] =
2136 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2137 Count = Fields.Length;
2139 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2140 CountNonPublic = NonPublicFields.Length;
2143 Count += NonPublicFields.Length;
2146 field_hash = new Hashtable ();
2147 foreach (FieldInfo field in Fields)
2148 field_hash.Add (field.Name, ++number);
2150 if (NonPublicFields.Length != 0)
2151 HasNonPublicFields = true;
2153 foreach (FieldInfo field in NonPublicFields)
2154 field_hash.Add (field.Name, ++number);
2157 public int this [string name] {
2159 if (field_hash.Contains (name))
2160 return (int) field_hash [name];
2166 public FieldInfo this [int index] {
2168 if (index >= Fields.Length)
2169 return NonPublicFields [index - Fields.Length];
2171 return Fields [index];
2175 public static MyStructInfo GetStructInfo (Type type)
2177 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2180 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2183 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2187 info = new MyStructInfo (type);
2188 field_type_hash.Add (type, info);
2192 public static MyStructInfo GetStructInfo (TypeContainer tc)
2194 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2198 info = new MyStructInfo (tc.TypeBuilder);
2199 field_type_hash.Add (tc.TypeBuilder, info);
2204 public class VariableInfo : IVariable {
2205 public Expression Type;
2206 public LocalBuilder LocalBuilder;
2207 public Type VariableType;
2208 public readonly string Name;
2209 public readonly Location Location;
2210 public readonly int Block;
2215 public bool Assigned;
2216 public bool ReadOnly;
2218 public VariableInfo (Expression type, string name, int block, Location l)
2223 LocalBuilder = null;
2227 public VariableInfo (TypeContainer tc, int block, Location l)
2229 VariableType = tc.TypeBuilder;
2230 struct_info = MyStructInfo.GetStructInfo (tc);
2232 LocalBuilder = null;
2236 MyStructInfo struct_info;
2237 public MyStructInfo StructInfo {
2243 public bool IsAssigned (EmitContext ec, Location loc)
2245 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2248 MyStructInfo struct_info = StructInfo;
2249 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2250 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2251 ec.CurrentBranching.SetVariableAssigned (this);
2255 int count = struct_info.Count;
2257 for (int i = 0; i < count; i++) {
2258 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2260 Report.Error (165, loc,
2261 "Use of unassigned local variable `" +
2263 ec.CurrentBranching.SetVariableAssigned (this);
2267 FieldInfo field = struct_info [i];
2268 Report.Error (171, loc,
2269 "Field `" + TypeManager.CSharpName (VariableType) +
2270 "." + field.Name + "' must be fully initialized " +
2271 "before control leaves the constructor");
2279 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2281 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2282 (struct_info == null))
2285 int field_idx = StructInfo [name];
2289 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2290 Report.Error (170, loc,
2291 "Use of possibly unassigned field `" + name + "'");
2292 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2299 public void SetAssigned (EmitContext ec)
2301 if (ec.DoFlowAnalysis)
2302 ec.CurrentBranching.SetVariableAssigned (this);
2305 public void SetFieldAssigned (EmitContext ec, string name)
2307 if (ec.DoFlowAnalysis && (struct_info != null))
2308 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2311 public bool Resolve (DeclSpace decl)
2313 if (struct_info != null)
2316 if (VariableType == null)
2317 VariableType = decl.ResolveType (Type, false, Location);
2319 if (VariableType == null)
2322 struct_info = MyStructInfo.GetStructInfo (VariableType);
2327 public void MakePinned ()
2329 TypeManager.MakePinned (LocalBuilder);
2332 public override string ToString ()
2334 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2339 /// Block represents a C# block.
2343 /// This class is used in a number of places: either to represent
2344 /// explicit blocks that the programmer places or implicit blocks.
2346 /// Implicit blocks are used as labels or to introduce variable
2349 public class Block : Statement {
2350 public readonly Block Parent;
2351 public readonly bool Implicit;
2352 public readonly Location StartLocation;
2353 public Location EndLocation;
2356 // The statements in this block
2358 ArrayList statements;
2361 // An array of Blocks. We keep track of children just
2362 // to generate the local variable declarations.
2364 // Statements and child statements are handled through the
2370 // Labels. (label, block) pairs.
2375 // Keeps track of (name, type) pairs
2377 Hashtable variables;
2380 // Keeps track of constants
2381 Hashtable constants;
2384 // Maps variable names to ILGenerator.LocalBuilders
2386 Hashtable local_builders;
2394 public Block (Block parent)
2395 : this (parent, false, Location.Null, Location.Null)
2398 public Block (Block parent, bool implicit_block)
2399 : this (parent, implicit_block, Location.Null, Location.Null)
2402 public Block (Block parent, bool implicit_block, Parameters parameters)
2403 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2406 public Block (Block parent, Location start, Location end)
2407 : this (parent, false, start, end)
2410 public Block (Block parent, Parameters parameters, Location start, Location end)
2411 : this (parent, false, parameters, start, end)
2414 public Block (Block parent, bool implicit_block, Location start, Location end)
2415 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2419 public Block (Block parent, bool implicit_block, Parameters parameters,
2420 Location start, Location end)
2423 parent.AddChild (this);
2425 this.Parent = parent;
2426 this.Implicit = implicit_block;
2427 this.parameters = parameters;
2428 this.StartLocation = start;
2429 this.EndLocation = end;
2432 statements = new ArrayList ();
2441 void AddChild (Block b)
2443 if (children == null)
2444 children = new ArrayList ();
2449 public void SetEndLocation (Location loc)
2455 /// Adds a label to the current block.
2459 /// false if the name already exists in this block. true
2463 public bool AddLabel (string name, LabeledStatement target)
2466 labels = new Hashtable ();
2467 if (labels.Contains (name))
2470 labels.Add (name, target);
2474 public LabeledStatement LookupLabel (string name)
2476 if (labels != null){
2477 if (labels.Contains (name))
2478 return ((LabeledStatement) labels [name]);
2482 return Parent.LookupLabel (name);
2487 VariableInfo this_variable = null;
2490 // Returns the "this" instance variable of this block.
2491 // See AddThisVariable() for more information.
2493 public VariableInfo ThisVariable {
2495 if (this_variable != null)
2496 return this_variable;
2497 else if (Parent != null)
2498 return Parent.ThisVariable;
2504 Hashtable child_variable_names;
2507 // Marks a variable with name @name as being used in a child block.
2508 // If a variable name has been used in a child block, it's illegal to
2509 // declare a variable with the same name in the current block.
2511 public void AddChildVariableName (string name)
2513 if (child_variable_names == null)
2514 child_variable_names = new Hashtable ();
2516 if (!child_variable_names.Contains (name))
2517 child_variable_names.Add (name, true);
2521 // Marks all variables from block @block and all its children as being
2522 // used in a child block.
2524 public void AddChildVariableNames (Block block)
2526 if (block.Variables != null) {
2527 foreach (string name in block.Variables.Keys)
2528 AddChildVariableName (name);
2531 foreach (Block child in block.children) {
2532 if (child.Variables != null) {
2533 foreach (string name in child.Variables.Keys)
2534 AddChildVariableName (name);
2540 // Checks whether a variable name has already been used in a child block.
2542 public bool IsVariableNameUsedInChildBlock (string name)
2544 if (child_variable_names == null)
2547 return child_variable_names.Contains (name);
2551 // This is used by non-static `struct' constructors which do not have an
2552 // initializer - in this case, the constructor must initialize all of the
2553 // struct's fields. To do this, we add a "this" variable and use the flow
2554 // analysis code to ensure that it's been fully initialized before control
2555 // leaves the constructor.
2557 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2559 if (this_variable != null)
2560 return this_variable;
2562 this_variable = new VariableInfo (tc, ID, l);
2564 if (variables == null)
2565 variables = new Hashtable ();
2566 variables.Add ("this", this_variable);
2568 return this_variable;
2571 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2573 if (variables == null)
2574 variables = new Hashtable ();
2576 VariableInfo vi = GetVariableInfo (name);
2579 Report.Error (136, l, "A local variable named `" + name + "' " +
2580 "cannot be declared in this scope since it would " +
2581 "give a different meaning to `" + name + "', which " +
2582 "is already used in a `parent or current' scope to " +
2583 "denote something else");
2585 Report.Error (128, l, "A local variable `" + name + "' is already " +
2586 "defined in this scope");
2590 if (IsVariableNameUsedInChildBlock (name)) {
2591 Report.Error (136, l, "A local variable named `" + name + "' " +
2592 "cannot be declared in this scope since it would " +
2593 "give a different meaning to `" + name + "', which " +
2594 "is already used in a `child' scope to denote something " +
2601 Parameter p = pars.GetParameterByName (name, out idx);
2603 Report.Error (136, l, "A local variable named `" + name + "' " +
2604 "cannot be declared in this scope since it would " +
2605 "give a different meaning to `" + name + "', which " +
2606 "is already used in a `parent or current' scope to " +
2607 "denote something else");
2612 vi = new VariableInfo (type, name, ID, l);
2614 variables.Add (name, vi);
2616 if (variables_initialized)
2617 throw new Exception ();
2619 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2623 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2625 if (AddVariable (type, name, pars, l) == null)
2628 if (constants == null)
2629 constants = new Hashtable ();
2631 constants.Add (name, value);
2635 public Hashtable Variables {
2641 public VariableInfo GetVariableInfo (string name)
2643 if (variables != null) {
2645 temp = variables [name];
2648 return (VariableInfo) temp;
2653 return Parent.GetVariableInfo (name);
2658 public Expression GetVariableType (string name)
2660 VariableInfo vi = GetVariableInfo (name);
2668 public Expression GetConstantExpression (string name)
2670 if (constants != null) {
2672 temp = constants [name];
2675 return (Expression) temp;
2679 return Parent.GetConstantExpression (name);
2685 /// True if the variable named @name has been defined
2688 public bool IsVariableDefined (string name)
2690 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2691 if (variables != null) {
2692 if (variables.Contains (name))
2697 return Parent.IsVariableDefined (name);
2703 /// True if the variable named @name is a constant
2705 public bool IsConstant (string name)
2707 Expression e = null;
2709 e = GetConstantExpression (name);
2715 /// Use to fetch the statement associated with this label
2717 public Statement this [string name] {
2719 return (Statement) labels [name];
2723 Parameters parameters = null;
2724 public Parameters Parameters {
2727 return Parent.Parameters;
2734 /// A list of labels that were not used within this block
2736 public string [] GetUnreferenced ()
2738 // FIXME: Implement me
2742 public void AddStatement (Statement s)
2759 bool variables_initialized = false;
2760 int count_variables = 0, first_variable = 0;
2762 void UpdateVariableInfo (EmitContext ec)
2764 DeclSpace ds = ec.DeclSpace;
2769 first_variable += Parent.CountVariables;
2771 count_variables = first_variable;
2772 if (variables != null) {
2773 foreach (VariableInfo vi in variables.Values) {
2774 if (!vi.Resolve (ds)) {
2779 vi.Number = ++count_variables;
2781 if (vi.StructInfo != null)
2782 count_variables += vi.StructInfo.Count;
2786 variables_initialized = true;
2791 // The number of local variables in this block
2793 public int CountVariables
2796 if (!variables_initialized)
2797 throw new Exception ();
2799 return count_variables;
2804 /// Emits the variable declarations and labels.
2807 /// tc: is our typecontainer (to resolve type references)
2808 /// ig: is the code generator:
2809 /// toplevel: the toplevel block. This is used for checking
2810 /// that no two labels with the same name are used.
2812 public void EmitMeta (EmitContext ec, Block toplevel)
2814 DeclSpace ds = ec.DeclSpace;
2815 ILGenerator ig = ec.ig;
2817 if (!variables_initialized)
2818 UpdateVariableInfo (ec);
2821 // Process this block variables
2823 if (variables != null){
2824 local_builders = new Hashtable ();
2826 foreach (DictionaryEntry de in variables){
2827 string name = (string) de.Key;
2828 VariableInfo vi = (VariableInfo) de.Value;
2830 if (vi.VariableType == null)
2833 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2835 if (CodeGen.SymbolWriter != null)
2836 vi.LocalBuilder.SetLocalSymInfo (name);
2838 if (constants == null)
2841 Expression cv = (Expression) constants [name];
2845 Expression e = cv.Resolve (ec);
2849 if (!(e is Constant)){
2850 Report.Error (133, vi.Location,
2851 "The expression being assigned to `" +
2852 name + "' must be constant (" + e + ")");
2856 constants.Remove (name);
2857 constants.Add (name, e);
2862 // Now, handle the children
2864 if (children != null){
2865 foreach (Block b in children)
2866 b.EmitMeta (ec, toplevel);
2870 public void UsageWarning ()
2874 if (variables != null){
2875 foreach (DictionaryEntry de in variables){
2876 VariableInfo vi = (VariableInfo) de.Value;
2881 name = (string) de.Key;
2885 219, vi.Location, "The variable `" + name +
2886 "' is assigned but its value is never used");
2889 168, vi.Location, "The variable `" +
2891 "' is declared but never used");
2896 if (children != null)
2897 foreach (Block b in children)
2901 public override bool Resolve (EmitContext ec)
2903 Block prev_block = ec.CurrentBlock;
2906 ec.CurrentBlock = this;
2907 ec.StartFlowBranching (this);
2909 Report.Debug (1, "RESOLVE BLOCK", StartLocation);
2911 if (!variables_initialized)
2912 UpdateVariableInfo (ec);
2914 foreach (Statement s in statements){
2915 if (s.Resolve (ec) == false)
2919 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation);
2921 FlowReturns returns = ec.EndFlowBranching ();
2922 ec.CurrentBlock = prev_block;
2924 // If we're a non-static `struct' constructor which doesn't have an
2925 // initializer, then we must initialize all of the struct's fields.
2926 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
2927 !this_variable.IsAssigned (ec, loc))
2930 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2931 foreach (LabeledStatement label in labels.Values)
2932 if (!label.HasBeenReferenced)
2933 Report.Warning (164, label.Location,
2934 "This label has not been referenced");
2940 public override bool Emit (EmitContext ec)
2942 bool is_ret = false, this_ret = false;
2943 Block prev_block = ec.CurrentBlock;
2944 bool warning_shown = false;
2946 ec.CurrentBlock = this;
2948 if (CodeGen.SymbolWriter != null) {
2949 ec.Mark (StartLocation);
2951 foreach (Statement s in statements) {
2954 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2955 warning_shown = true;
2956 Warning_DeadCodeFound (s.loc);
2958 this_ret = s.Emit (ec);
2963 ec.Mark (EndLocation);
2965 foreach (Statement s in statements){
2966 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2967 warning_shown = true;
2968 Warning_DeadCodeFound (s.loc);
2970 this_ret = s.Emit (ec);
2976 ec.CurrentBlock = prev_block;
2981 public class SwitchLabel {
2984 public Location loc;
2985 public Label ILLabel;
2986 public Label ILLabelCode;
2989 // if expr == null, then it is the default case.
2991 public SwitchLabel (Expression expr, Location l)
2997 public Expression Label {
3003 public object Converted {
3010 // Resolves the expression, reduces it to a literal if possible
3011 // and then converts it to the requested type.
3013 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3015 ILLabel = ec.ig.DefineLabel ();
3016 ILLabelCode = ec.ig.DefineLabel ();
3021 Expression e = label.Resolve (ec);
3026 if (!(e is Constant)){
3027 Console.WriteLine ("Value is: " + label);
3028 Report.Error (150, loc, "A constant value is expected");
3032 if (e is StringConstant || e is NullLiteral){
3033 if (required_type == TypeManager.string_type){
3035 ILLabel = ec.ig.DefineLabel ();
3040 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3041 if (converted == null)
3048 public class SwitchSection {
3049 // An array of SwitchLabels.
3050 public readonly ArrayList Labels;
3051 public readonly Block Block;
3053 public SwitchSection (ArrayList labels, Block block)
3060 public class Switch : Statement {
3061 public readonly ArrayList Sections;
3062 public Expression Expr;
3065 /// Maps constants whose type type SwitchType to their SwitchLabels.
3067 public Hashtable Elements;
3070 /// The governing switch type
3072 public Type SwitchType;
3078 Label default_target;
3079 Expression new_expr;
3082 // The types allowed to be implicitly cast from
3083 // on the governing type
3085 static Type [] allowed_types;
3087 public Switch (Expression e, ArrayList sects, Location l)
3094 public bool GotDefault {
3100 public Label DefaultTarget {
3102 return default_target;
3107 // Determines the governing type for a switch. The returned
3108 // expression might be the expression from the switch, or an
3109 // expression that includes any potential conversions to the
3110 // integral types or to string.
3112 Expression SwitchGoverningType (EmitContext ec, Type t)
3114 if (t == TypeManager.int32_type ||
3115 t == TypeManager.uint32_type ||
3116 t == TypeManager.char_type ||
3117 t == TypeManager.byte_type ||
3118 t == TypeManager.sbyte_type ||
3119 t == TypeManager.ushort_type ||
3120 t == TypeManager.short_type ||
3121 t == TypeManager.uint64_type ||
3122 t == TypeManager.int64_type ||
3123 t == TypeManager.string_type ||
3124 t == TypeManager.bool_type ||
3125 t.IsSubclassOf (TypeManager.enum_type))
3128 if (allowed_types == null){
3129 allowed_types = new Type [] {
3130 TypeManager.sbyte_type,
3131 TypeManager.byte_type,
3132 TypeManager.short_type,
3133 TypeManager.ushort_type,
3134 TypeManager.int32_type,
3135 TypeManager.uint32_type,
3136 TypeManager.int64_type,
3137 TypeManager.uint64_type,
3138 TypeManager.char_type,
3139 TypeManager.bool_type,
3140 TypeManager.string_type
3145 // Try to find a *user* defined implicit conversion.
3147 // If there is no implicit conversion, or if there are multiple
3148 // conversions, we have to report an error
3150 Expression converted = null;
3151 foreach (Type tt in allowed_types){
3154 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3158 if (converted != null){
3159 Report.Error (-12, loc, "More than one conversion to an integral " +
3160 " type exists for type `" +
3161 TypeManager.CSharpName (Expr.Type)+"'");
3169 void error152 (string n)
3172 152, "The label `" + n + ":' " +
3173 "is already present on this switch statement");
3177 // Performs the basic sanity checks on the switch statement
3178 // (looks for duplicate keys and non-constant expressions).
3180 // It also returns a hashtable with the keys that we will later
3181 // use to compute the switch tables
3183 bool CheckSwitch (EmitContext ec)
3187 Elements = new Hashtable ();
3189 got_default = false;
3191 if (TypeManager.IsEnumType (SwitchType)){
3192 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3194 compare_type = SwitchType;
3196 foreach (SwitchSection ss in Sections){
3197 foreach (SwitchLabel sl in ss.Labels){
3198 if (!sl.ResolveAndReduce (ec, SwitchType)){
3203 if (sl.Label == null){
3205 error152 ("default");
3212 object key = sl.Converted;
3214 if (key is Constant)
3215 key = ((Constant) key).GetValue ();
3218 key = NullLiteral.Null;
3220 string lname = null;
3221 if (compare_type == TypeManager.uint64_type){
3222 ulong v = (ulong) key;
3224 if (Elements.Contains (v))
3225 lname = v.ToString ();
3227 Elements.Add (v, sl);
3228 } else if (compare_type == TypeManager.int64_type){
3229 long v = (long) key;
3231 if (Elements.Contains (v))
3232 lname = v.ToString ();
3234 Elements.Add (v, sl);
3235 } else if (compare_type == TypeManager.uint32_type){
3236 uint v = (uint) key;
3238 if (Elements.Contains (v))
3239 lname = v.ToString ();
3241 Elements.Add (v, sl);
3242 } else if (compare_type == TypeManager.char_type){
3243 char v = (char) key;
3245 if (Elements.Contains (v))
3246 lname = v.ToString ();
3248 Elements.Add (v, sl);
3249 } else if (compare_type == TypeManager.byte_type){
3250 byte v = (byte) key;
3252 if (Elements.Contains (v))
3253 lname = v.ToString ();
3255 Elements.Add (v, sl);
3256 } else if (compare_type == TypeManager.sbyte_type){
3257 sbyte v = (sbyte) key;
3259 if (Elements.Contains (v))
3260 lname = v.ToString ();
3262 Elements.Add (v, sl);
3263 } else if (compare_type == TypeManager.short_type){
3264 short v = (short) key;
3266 if (Elements.Contains (v))
3267 lname = v.ToString ();
3269 Elements.Add (v, sl);
3270 } else if (compare_type == TypeManager.ushort_type){
3271 ushort v = (ushort) key;
3273 if (Elements.Contains (v))
3274 lname = v.ToString ();
3276 Elements.Add (v, sl);
3277 } else if (compare_type == TypeManager.string_type){
3278 if (key is NullLiteral){
3279 if (Elements.Contains (NullLiteral.Null))
3282 Elements.Add (NullLiteral.Null, null);
3284 string s = (string) key;
3286 if (Elements.Contains (s))
3289 Elements.Add (s, sl);
3291 } else if (compare_type == TypeManager.int32_type) {
3294 if (Elements.Contains (v))
3295 lname = v.ToString ();
3297 Elements.Add (v, sl);
3298 } else if (compare_type == TypeManager.bool_type) {
3299 bool v = (bool) key;
3301 if (Elements.Contains (v))
3302 lname = v.ToString ();
3304 Elements.Add (v, sl);
3308 throw new Exception ("Unknown switch type!" +
3309 SwitchType + " " + compare_type);
3313 error152 ("case + " + lname);
3324 void EmitObjectInteger (ILGenerator ig, object k)
3327 IntConstant.EmitInt (ig, (int) k);
3328 else if (k is Constant) {
3329 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3332 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3335 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3337 IntConstant.EmitInt (ig, (int) (long) k);
3338 ig.Emit (OpCodes.Conv_I8);
3341 LongConstant.EmitLong (ig, (long) k);
3343 else if (k is ulong)
3345 if ((ulong) k < (1L<<32))
3347 IntConstant.EmitInt (ig, (int) (long) k);
3348 ig.Emit (OpCodes.Conv_U8);
3352 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3356 IntConstant.EmitInt (ig, (int) ((char) k));
3357 else if (k is sbyte)
3358 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3360 IntConstant.EmitInt (ig, (int) ((byte) k));
3361 else if (k is short)
3362 IntConstant.EmitInt (ig, (int) ((short) k));
3363 else if (k is ushort)
3364 IntConstant.EmitInt (ig, (int) ((ushort) k));
3366 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3368 throw new Exception ("Unhandled case");
3371 // structure used to hold blocks of keys while calculating table switch
3372 class KeyBlock : IComparable
3374 public KeyBlock (long _nFirst)
3376 nFirst = nLast = _nFirst;
3380 public ArrayList rgKeys = null;
3383 get { return (int) (nLast - nFirst + 1); }
3385 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3387 return kbLast.nLast - kbFirst.nFirst + 1;
3389 public int CompareTo (object obj)
3391 KeyBlock kb = (KeyBlock) obj;
3392 int nLength = Length;
3393 int nLengthOther = kb.Length;
3394 if (nLengthOther == nLength)
3395 return (int) (kb.nFirst - nFirst);
3396 return nLength - nLengthOther;
3401 /// This method emits code for a lookup-based switch statement (non-string)
3402 /// Basically it groups the cases into blocks that are at least half full,
3403 /// and then spits out individual lookup opcodes for each block.
3404 /// It emits the longest blocks first, and short blocks are just
3405 /// handled with direct compares.
3407 /// <param name="ec"></param>
3408 /// <param name="val"></param>
3409 /// <returns></returns>
3410 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3412 int cElements = Elements.Count;
3413 object [] rgKeys = new object [cElements];
3414 Elements.Keys.CopyTo (rgKeys, 0);
3415 Array.Sort (rgKeys);
3417 // initialize the block list with one element per key
3418 ArrayList rgKeyBlocks = new ArrayList ();
3419 foreach (object key in rgKeys)
3420 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3423 // iteratively merge the blocks while they are at least half full
3424 // there's probably a really cool way to do this with a tree...
3425 while (rgKeyBlocks.Count > 1)
3427 ArrayList rgKeyBlocksNew = new ArrayList ();
3428 kbCurr = (KeyBlock) rgKeyBlocks [0];
3429 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3431 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3432 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3435 kbCurr.nLast = kb.nLast;
3439 // start a new block
3440 rgKeyBlocksNew.Add (kbCurr);
3444 rgKeyBlocksNew.Add (kbCurr);
3445 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3447 rgKeyBlocks = rgKeyBlocksNew;
3450 // initialize the key lists
3451 foreach (KeyBlock kb in rgKeyBlocks)
3452 kb.rgKeys = new ArrayList ();
3454 // fill the key lists
3456 if (rgKeyBlocks.Count > 0) {
3457 kbCurr = (KeyBlock) rgKeyBlocks [0];
3458 foreach (object key in rgKeys)
3460 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3462 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3463 kbCurr.rgKeys.Add (key);
3467 // sort the blocks so we can tackle the largest ones first
3468 rgKeyBlocks.Sort ();
3470 // okay now we can start...
3471 ILGenerator ig = ec.ig;
3472 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3473 Label lblDefault = ig.DefineLabel ();
3475 Type typeKeys = null;
3476 if (rgKeys.Length > 0)
3477 typeKeys = rgKeys [0].GetType (); // used for conversions
3479 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3481 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3482 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3485 foreach (object key in kb.rgKeys)
3487 ig.Emit (OpCodes.Ldloc, val);
3488 EmitObjectInteger (ig, key);
3489 SwitchLabel sl = (SwitchLabel) Elements [key];
3490 ig.Emit (OpCodes.Beq, sl.ILLabel);
3495 // TODO: if all the keys in the block are the same and there are
3496 // no gaps/defaults then just use a range-check.
3497 if (SwitchType == TypeManager.int64_type ||
3498 SwitchType == TypeManager.uint64_type)
3500 // TODO: optimize constant/I4 cases
3502 // check block range (could be > 2^31)
3503 ig.Emit (OpCodes.Ldloc, val);
3504 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3505 ig.Emit (OpCodes.Blt, lblDefault);
3506 ig.Emit (OpCodes.Ldloc, val);
3507 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3508 ig.Emit (OpCodes.Bgt, lblDefault);
3511 ig.Emit (OpCodes.Ldloc, val);
3514 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3515 ig.Emit (OpCodes.Sub);
3517 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3522 ig.Emit (OpCodes.Ldloc, val);
3523 int nFirst = (int) kb.nFirst;
3526 IntConstant.EmitInt (ig, nFirst);
3527 ig.Emit (OpCodes.Sub);
3529 else if (nFirst < 0)
3531 IntConstant.EmitInt (ig, -nFirst);
3532 ig.Emit (OpCodes.Add);
3536 // first, build the list of labels for the switch
3538 int cJumps = kb.Length;
3539 Label [] rgLabels = new Label [cJumps];
3540 for (int iJump = 0; iJump < cJumps; iJump++)
3542 object key = kb.rgKeys [iKey];
3543 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3545 SwitchLabel sl = (SwitchLabel) Elements [key];
3546 rgLabels [iJump] = sl.ILLabel;
3550 rgLabels [iJump] = lblDefault;
3552 // emit the switch opcode
3553 ig.Emit (OpCodes.Switch, rgLabels);
3556 // mark the default for this block
3558 ig.MarkLabel (lblDefault);
3561 // TODO: find the default case and emit it here,
3562 // to prevent having to do the following jump.
3563 // make sure to mark other labels in the default section
3565 // the last default just goes to the end
3566 ig.Emit (OpCodes.Br, lblDefault);
3568 // now emit the code for the sections
3569 bool fFoundDefault = false;
3570 bool fAllReturn = true;
3571 foreach (SwitchSection ss in Sections)
3573 foreach (SwitchLabel sl in ss.Labels)
3575 ig.MarkLabel (sl.ILLabel);
3576 ig.MarkLabel (sl.ILLabelCode);
3577 if (sl.Label == null)
3579 ig.MarkLabel (lblDefault);
3580 fFoundDefault = true;
3583 fAllReturn &= ss.Block.Emit (ec);
3584 //ig.Emit (OpCodes.Br, lblEnd);
3587 if (!fFoundDefault) {
3588 ig.MarkLabel (lblDefault);
3591 ig.MarkLabel (lblEnd);
3596 // This simple emit switch works, but does not take advantage of the
3598 // TODO: remove non-string logic from here
3599 // TODO: binary search strings?
3601 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3603 ILGenerator ig = ec.ig;
3604 Label end_of_switch = ig.DefineLabel ();
3605 Label next_test = ig.DefineLabel ();
3606 Label null_target = ig.DefineLabel ();
3607 bool default_found = false;
3608 bool first_test = true;
3609 bool pending_goto_end = false;
3610 bool all_return = true;
3611 bool is_string = false;
3615 // Special processing for strings: we cant compare
3618 if (SwitchType == TypeManager.string_type){
3619 ig.Emit (OpCodes.Ldloc, val);
3622 if (Elements.Contains (NullLiteral.Null)){
3623 ig.Emit (OpCodes.Brfalse, null_target);
3625 ig.Emit (OpCodes.Brfalse, default_target);
3627 ig.Emit (OpCodes.Ldloc, val);
3628 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3629 ig.Emit (OpCodes.Stloc, val);
3632 SwitchSection last_section;
3633 last_section = (SwitchSection) Sections [Sections.Count-1];
3635 foreach (SwitchSection ss in Sections){
3636 Label sec_begin = ig.DefineLabel ();
3638 if (pending_goto_end)
3639 ig.Emit (OpCodes.Br, end_of_switch);
3641 int label_count = ss.Labels.Count;
3643 foreach (SwitchLabel sl in ss.Labels){
3644 ig.MarkLabel (sl.ILLabel);
3647 ig.MarkLabel (next_test);
3648 next_test = ig.DefineLabel ();
3651 // If we are the default target
3653 if (sl.Label == null){
3654 ig.MarkLabel (default_target);
3655 default_found = true;
3657 object lit = sl.Converted;
3659 if (lit is NullLiteral){
3661 if (label_count == 1)
3662 ig.Emit (OpCodes.Br, next_test);
3667 StringConstant str = (StringConstant) lit;
3669 ig.Emit (OpCodes.Ldloc, val);
3670 ig.Emit (OpCodes.Ldstr, str.Value);
3671 if (label_count == 1)
3672 ig.Emit (OpCodes.Bne_Un, next_test);
3674 ig.Emit (OpCodes.Beq, sec_begin);
3676 ig.Emit (OpCodes.Ldloc, val);
3677 EmitObjectInteger (ig, lit);
3678 ig.Emit (OpCodes.Ceq);
3679 if (label_count == 1)
3680 ig.Emit (OpCodes.Brfalse, next_test);
3682 ig.Emit (OpCodes.Brtrue, sec_begin);
3686 if (label_count != 1 && ss != last_section)
3687 ig.Emit (OpCodes.Br, next_test);
3690 ig.MarkLabel (null_target);
3691 ig.MarkLabel (sec_begin);
3692 foreach (SwitchLabel sl in ss.Labels)
3693 ig.MarkLabel (sl.ILLabelCode);
3694 if (ss.Block.Emit (ec))
3695 pending_goto_end = false;
3698 pending_goto_end = true;
3702 if (!default_found){
3703 ig.MarkLabel (default_target);
3706 ig.MarkLabel (next_test);
3707 ig.MarkLabel (end_of_switch);
3712 public override bool Resolve (EmitContext ec)
3714 Expr = Expr.Resolve (ec);
3718 new_expr = SwitchGoverningType (ec, Expr.Type);
3719 if (new_expr == null){
3720 Report.Error (151, loc, "An integer type or string was expected for switch");
3725 SwitchType = new_expr.Type;
3727 if (!CheckSwitch (ec))
3730 Switch old_switch = ec.Switch;
3732 ec.Switch.SwitchType = SwitchType;
3734 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3737 foreach (SwitchSection ss in Sections){
3739 ec.CurrentBranching.CreateSibling ();
3743 if (ss.Block.Resolve (ec) != true)
3747 ec.EndFlowBranching ();
3748 ec.Switch = old_switch;
3753 public override bool Emit (EmitContext ec)
3755 // Store variable for comparission purposes
3756 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3758 ec.ig.Emit (OpCodes.Stloc, value);
3760 ILGenerator ig = ec.ig;
3762 default_target = ig.DefineLabel ();
3765 // Setup the codegen context
3767 Label old_end = ec.LoopEnd;
3768 Switch old_switch = ec.Switch;
3770 ec.LoopEnd = ig.DefineLabel ();
3775 if (SwitchType == TypeManager.string_type)
3776 all_return = SimpleSwitchEmit (ec, value);
3778 all_return = TableSwitchEmit (ec, value);
3780 // Restore context state.
3781 ig.MarkLabel (ec.LoopEnd);
3784 // Restore the previous context
3786 ec.LoopEnd = old_end;
3787 ec.Switch = old_switch;
3793 public class Lock : Statement {
3795 Statement Statement;
3797 public Lock (Expression expr, Statement stmt, Location l)
3804 public override bool Resolve (EmitContext ec)
3806 expr = expr.Resolve (ec);
3807 return Statement.Resolve (ec) && expr != null;
3810 public override bool Emit (EmitContext ec)
3812 Type type = expr.Type;
3815 if (type.IsValueType){
3816 Report.Error (185, loc, "lock statement requires the expression to be " +
3817 " a reference type (type is: `" +
3818 TypeManager.CSharpName (type) + "'");
3822 ILGenerator ig = ec.ig;
3823 LocalBuilder temp = ig.DeclareLocal (type);
3826 ig.Emit (OpCodes.Dup);
3827 ig.Emit (OpCodes.Stloc, temp);
3828 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3831 Label end = ig.BeginExceptionBlock ();
3832 bool old_in_try = ec.InTry;
3834 Label finish = ig.DefineLabel ();
3835 val = Statement.Emit (ec);
3836 ec.InTry = old_in_try;
3837 // ig.Emit (OpCodes.Leave, finish);
3839 ig.MarkLabel (finish);
3842 ig.BeginFinallyBlock ();
3843 ig.Emit (OpCodes.Ldloc, temp);
3844 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3845 ig.EndExceptionBlock ();
3851 public class Unchecked : Statement {
3852 public readonly Block Block;
3854 public Unchecked (Block b)
3859 public override bool Resolve (EmitContext ec)
3861 return Block.Resolve (ec);
3864 public override bool Emit (EmitContext ec)
3866 bool previous_state = ec.CheckState;
3867 bool previous_state_const = ec.ConstantCheckState;
3870 ec.CheckState = false;
3871 ec.ConstantCheckState = false;
3872 val = Block.Emit (ec);
3873 ec.CheckState = previous_state;
3874 ec.ConstantCheckState = previous_state_const;
3880 public class Checked : Statement {
3881 public readonly Block Block;
3883 public Checked (Block b)
3888 public override bool Resolve (EmitContext ec)
3890 bool previous_state = ec.CheckState;
3891 bool previous_state_const = ec.ConstantCheckState;
3893 ec.CheckState = true;
3894 ec.ConstantCheckState = true;
3895 bool ret = Block.Resolve (ec);
3896 ec.CheckState = previous_state;
3897 ec.ConstantCheckState = previous_state_const;
3902 public override bool Emit (EmitContext ec)
3904 bool previous_state = ec.CheckState;
3905 bool previous_state_const = ec.ConstantCheckState;
3908 ec.CheckState = true;
3909 ec.ConstantCheckState = true;
3910 val = Block.Emit (ec);
3911 ec.CheckState = previous_state;
3912 ec.ConstantCheckState = previous_state_const;
3918 public class Unsafe : Statement {
3919 public readonly Block Block;
3921 public Unsafe (Block b)
3926 public override bool Resolve (EmitContext ec)
3928 bool previous_state = ec.InUnsafe;
3932 val = Block.Resolve (ec);
3933 ec.InUnsafe = previous_state;
3938 public override bool Emit (EmitContext ec)
3940 bool previous_state = ec.InUnsafe;
3944 val = Block.Emit (ec);
3945 ec.InUnsafe = previous_state;
3954 public class Fixed : Statement {
3956 ArrayList declarators;
3957 Statement statement;
3962 public bool is_object;
3963 public VariableInfo vi;
3964 public Expression expr;
3965 public Expression converted;
3968 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3971 declarators = decls;
3976 public override bool Resolve (EmitContext ec)
3978 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3979 if (expr_type == null)
3982 data = new FixedData [declarators.Count];
3985 foreach (Pair p in declarators){
3986 VariableInfo vi = (VariableInfo) p.First;
3987 Expression e = (Expression) p.Second;
3992 // The rules for the possible declarators are pretty wise,
3993 // but the production on the grammar is more concise.
3995 // So we have to enforce these rules here.
3997 // We do not resolve before doing the case 1 test,
3998 // because the grammar is explicit in that the token &
3999 // is present, so we need to test for this particular case.
4003 // Case 1: & object.
4005 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4006 Expression child = ((Unary) e).Expr;
4009 if (child is ParameterReference || child is LocalVariableReference){
4012 "No need to use fixed statement for parameters or " +
4013 "local variable declarations (address is already " +
4022 child = ((Unary) e).Expr;
4024 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4027 data [i].is_object = true;
4029 data [i].converted = null;
4043 if (e.Type.IsArray){
4044 Type array_type = e.Type.GetElementType ();
4048 // Provided that array_type is unmanaged,
4050 if (!TypeManager.VerifyUnManaged (array_type, loc))
4054 // and T* is implicitly convertible to the
4055 // pointer type given in the fixed statement.
4057 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4059 Expression converted = Expression.ConvertImplicitRequired (
4060 ec, array_ptr, vi.VariableType, loc);
4061 if (converted == null)
4064 data [i].is_object = false;
4066 data [i].converted = converted;
4076 if (e.Type == TypeManager.string_type){
4077 data [i].is_object = false;
4079 data [i].converted = null;
4085 return statement.Resolve (ec);
4088 public override bool Emit (EmitContext ec)
4090 ILGenerator ig = ec.ig;
4092 bool is_ret = false;
4094 for (int i = 0; i < data.Length; i++) {
4095 VariableInfo vi = data [i].vi;
4098 // Case 1: & object.
4100 if (data [i].is_object) {
4102 // Store pointer in pinned location
4104 data [i].expr.Emit (ec);
4105 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4107 is_ret = statement.Emit (ec);
4109 // Clear the pinned variable.
4110 ig.Emit (OpCodes.Ldc_I4_0);
4111 ig.Emit (OpCodes.Conv_U);
4112 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4120 if (data [i].expr.Type.IsArray){
4122 // Store pointer in pinned location
4124 data [i].converted.Emit (ec);
4126 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4128 is_ret = statement.Emit (ec);
4130 // Clear the pinned variable.
4131 ig.Emit (OpCodes.Ldc_I4_0);
4132 ig.Emit (OpCodes.Conv_U);
4133 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4141 if (data [i].expr.Type == TypeManager.string_type){
4142 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4143 TypeManager.MakePinned (pinned_string);
4145 data [i].expr.Emit (ec);
4146 ig.Emit (OpCodes.Stloc, pinned_string);
4148 Expression sptr = new StringPtr (pinned_string, loc);
4149 Expression converted = Expression.ConvertImplicitRequired (
4150 ec, sptr, vi.VariableType, loc);
4152 if (converted == null)
4155 converted.Emit (ec);
4156 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4158 is_ret = statement.Emit (ec);
4160 // Clear the pinned variable
4161 ig.Emit (OpCodes.Ldnull);
4162 ig.Emit (OpCodes.Stloc, pinned_string);
4170 public class Catch {
4171 public readonly string Name;
4172 public readonly Block Block;
4173 public readonly Location Location;
4177 public Catch (Expression type, string name, Block block, Location l)
4185 public Type CatchType {
4188 throw new InvalidOperationException ();
4194 public bool IsGeneral {
4196 return type == null;
4200 public bool Resolve (EmitContext ec)
4203 type = type.DoResolve (ec);
4208 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)){
4209 Report.Error (155, Location,
4210 "The type caught or thrown must be derived " +
4211 "from System.Exception");
4216 if (!Block.Resolve (ec))
4223 public class Try : Statement {
4224 public readonly Block Fini, Block;
4225 public readonly ArrayList Specific;
4226 public readonly Catch General;
4229 // specific, general and fini might all be null.
4231 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4233 if (specific == null && general == null){
4234 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4238 this.Specific = specific;
4239 this.General = general;
4244 public override bool Resolve (EmitContext ec)
4248 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4250 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4252 bool old_in_try = ec.InTry;
4255 if (!Block.Resolve (ec))
4258 ec.InTry = old_in_try;
4260 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4262 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4264 foreach (Catch c in Specific){
4265 ec.CurrentBranching.CreateSibling ();
4266 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4268 if (c.Name != null) {
4269 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4271 throw new Exception ();
4276 bool old_in_catch = ec.InCatch;
4279 if (!c.Resolve (ec))
4282 ec.InCatch = old_in_catch;
4284 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4286 if ((current.Returns == FlowReturns.NEVER) ||
4287 (current.Returns == FlowReturns.SOMETIMES)) {
4288 vector.AndLocals (current);
4292 if (General != null){
4293 ec.CurrentBranching.CreateSibling ();
4294 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4296 bool old_in_catch = ec.InCatch;
4299 if (!General.Resolve (ec))
4302 ec.InCatch = old_in_catch;
4304 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4306 if ((current.Returns == FlowReturns.NEVER) ||
4307 (current.Returns == FlowReturns.SOMETIMES)) {
4308 vector.AndLocals (current);
4312 ec.CurrentBranching.CreateSiblingForFinally ();
4313 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4316 bool old_in_finally = ec.InFinally;
4317 ec.InFinally = true;
4319 if (!Fini.Resolve (ec))
4322 ec.InFinally = old_in_finally;
4325 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4327 FlowReturns returns = ec.EndFlowBranching ();
4329 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4331 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4332 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4335 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4337 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4342 public override bool Emit (EmitContext ec)
4344 ILGenerator ig = ec.ig;
4346 Label finish = ig.DefineLabel ();;
4350 end = ig.BeginExceptionBlock ();
4351 bool old_in_try = ec.InTry;
4353 returns = Block.Emit (ec);
4354 ec.InTry = old_in_try;
4357 // System.Reflection.Emit provides this automatically:
4358 // ig.Emit (OpCodes.Leave, finish);
4360 bool old_in_catch = ec.InCatch;
4362 DeclSpace ds = ec.DeclSpace;
4364 foreach (Catch c in Specific){
4367 ig.BeginCatchBlock (c.CatchType);
4369 if (c.Name != null){
4370 vi = c.Block.GetVariableInfo (c.Name);
4372 throw new Exception ("Variable does not exist in this block");
4374 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4376 ig.Emit (OpCodes.Pop);
4378 if (!c.Block.Emit (ec))
4382 if (General != null){
4383 ig.BeginCatchBlock (TypeManager.object_type);
4384 ig.Emit (OpCodes.Pop);
4385 if (!General.Block.Emit (ec))
4388 ec.InCatch = old_in_catch;
4390 ig.MarkLabel (finish);
4392 ig.BeginFinallyBlock ();
4393 bool old_in_finally = ec.InFinally;
4394 ec.InFinally = true;
4396 ec.InFinally = old_in_finally;
4399 ig.EndExceptionBlock ();
4402 if (!returns || ec.InTry || ec.InCatch)
4405 // Unfortunately, System.Reflection.Emit automatically emits a leave
4406 // to the end of the finally block. This is a problem if `returns'
4407 // is true since we may jump to a point after the end of the method.
4408 // As a workaround, emit an explicit ret here.
4410 if (ec.ReturnType != null)
4411 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4412 ec.ig.Emit (OpCodes.Ret);
4419 // FIXME: We still do not support the expression variant of the using
4422 public class Using : Statement {
4423 object expression_or_block;
4424 Statement Statement;
4429 Expression [] converted_vars;
4430 ExpressionStatement [] assign;
4432 public Using (object expression_or_block, Statement stmt, Location l)
4434 this.expression_or_block = expression_or_block;
4440 // Resolves for the case of using using a local variable declaration.
4442 bool ResolveLocalVariableDecls (EmitContext ec)
4444 bool need_conv = false;
4445 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4448 if (expr_type == null)
4452 // The type must be an IDisposable or an implicit conversion
4455 converted_vars = new Expression [var_list.Count];
4456 assign = new ExpressionStatement [var_list.Count];
4457 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4458 foreach (DictionaryEntry e in var_list){
4459 Expression var = (Expression) e.Key;
4461 var = var.ResolveLValue (ec, new EmptyExpression ());
4465 converted_vars [i] = Expression.ConvertImplicit (
4466 ec, var, TypeManager.idisposable_type, loc);
4468 if (converted_vars [i] == null)
4476 foreach (DictionaryEntry e in var_list){
4477 LocalVariableReference var = (LocalVariableReference) e.Key;
4478 Expression new_expr = (Expression) e.Value;
4481 a = new Assign (var, new_expr, loc);
4487 converted_vars [i] = var;
4488 assign [i] = (ExpressionStatement) a;
4495 bool ResolveExpression (EmitContext ec)
4497 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4498 conv = Expression.ConvertImplicit (
4499 ec, expr, TypeManager.idisposable_type, loc);
4509 // Emits the code for the case of using using a local variable declaration.
4511 bool EmitLocalVariableDecls (EmitContext ec)
4513 ILGenerator ig = ec.ig;
4516 bool old_in_try = ec.InTry;
4518 for (i = 0; i < assign.Length; i++) {
4519 assign [i].EmitStatement (ec);
4521 ig.BeginExceptionBlock ();
4523 Statement.Emit (ec);
4524 ec.InTry = old_in_try;
4526 bool old_in_finally = ec.InFinally;
4527 ec.InFinally = true;
4528 var_list.Reverse ();
4529 foreach (DictionaryEntry e in var_list){
4530 LocalVariableReference var = (LocalVariableReference) e.Key;
4531 Label skip = ig.DefineLabel ();
4534 ig.BeginFinallyBlock ();
4537 ig.Emit (OpCodes.Brfalse, skip);
4538 converted_vars [i].Emit (ec);
4539 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4540 ig.MarkLabel (skip);
4541 ig.EndExceptionBlock ();
4543 ec.InFinally = old_in_finally;
4548 bool EmitExpression (EmitContext ec)
4551 // Make a copy of the expression and operate on that.
4553 ILGenerator ig = ec.ig;
4554 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4559 ig.Emit (OpCodes.Stloc, local_copy);
4561 bool old_in_try = ec.InTry;
4563 ig.BeginExceptionBlock ();
4564 Statement.Emit (ec);
4565 ec.InTry = old_in_try;
4567 Label skip = ig.DefineLabel ();
4568 bool old_in_finally = ec.InFinally;
4569 ig.BeginFinallyBlock ();
4570 ig.Emit (OpCodes.Ldloc, local_copy);
4571 ig.Emit (OpCodes.Brfalse, skip);
4572 ig.Emit (OpCodes.Ldloc, local_copy);
4573 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4574 ig.MarkLabel (skip);
4575 ec.InFinally = old_in_finally;
4576 ig.EndExceptionBlock ();
4581 public override bool Resolve (EmitContext ec)
4583 if (expression_or_block is DictionaryEntry){
4584 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4585 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4587 if (!ResolveLocalVariableDecls (ec))
4590 } else if (expression_or_block is Expression){
4591 expr = (Expression) expression_or_block;
4593 expr = expr.Resolve (ec);
4597 expr_type = expr.Type;
4599 if (!ResolveExpression (ec))
4603 return Statement.Resolve (ec);
4606 public override bool Emit (EmitContext ec)
4608 if (expression_or_block is DictionaryEntry)
4609 return EmitLocalVariableDecls (ec);
4610 else if (expression_or_block is Expression)
4611 return EmitExpression (ec);
4618 /// Implementation of the foreach C# statement
4620 public class Foreach : Statement {
4622 LocalVariableReference variable;
4624 Statement statement;
4625 ForeachHelperMethods hm;
4626 Expression empty, conv;
4627 Type array_type, element_type;
4630 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4631 Statement stmt, Location l)
4634 this.variable = var;
4640 public override bool Resolve (EmitContext ec)
4642 expr = expr.Resolve (ec);
4646 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4647 if (var_type == null)
4651 // We need an instance variable. Not sure this is the best
4652 // way of doing this.
4654 // FIXME: When we implement propertyaccess, will those turn
4655 // out to return values in ExprClass? I think they should.
4657 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4658 expr.eclass == ExprClass.PropertyAccess)){
4659 error1579 (expr.Type);
4663 if (expr.Type.IsArray) {
4664 array_type = expr.Type;
4665 element_type = array_type.GetElementType ();
4667 empty = new EmptyExpression (element_type);
4669 hm = ProbeCollectionType (ec, expr.Type);
4671 error1579 (expr.Type);
4675 array_type = expr.Type;
4676 element_type = hm.element_type;
4678 empty = new EmptyExpression (hm.element_type);
4682 // FIXME: maybe we can apply the same trick we do in the
4683 // array handling to avoid creating empty and conv in some cases.
4685 // Although it is not as important in this case, as the type
4686 // will not likely be object (what the enumerator will return).
4688 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4692 if (variable.ResolveLValue (ec, empty) == null)
4695 if (!statement.Resolve (ec))
4702 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4704 static MethodInfo FetchMethodMoveNext (Type t)
4706 MemberList move_next_list;
4708 move_next_list = TypeContainer.FindMembers (
4709 t, MemberTypes.Method,
4710 BindingFlags.Public | BindingFlags.Instance,
4711 Type.FilterName, "MoveNext");
4712 if (move_next_list.Count == 0)
4715 foreach (MemberInfo m in move_next_list){
4716 MethodInfo mi = (MethodInfo) m;
4719 args = TypeManager.GetArgumentTypes (mi);
4720 if (args != null && args.Length == 0){
4721 if (mi.ReturnType == TypeManager.bool_type)
4729 // Retrieves a `public T get_Current ()' method from the Type `t'
4731 static MethodInfo FetchMethodGetCurrent (Type t)
4733 MemberList move_next_list;
4735 move_next_list = TypeContainer.FindMembers (
4736 t, MemberTypes.Method,
4737 BindingFlags.Public | BindingFlags.Instance,
4738 Type.FilterName, "get_Current");
4739 if (move_next_list.Count == 0)
4742 foreach (MemberInfo m in move_next_list){
4743 MethodInfo mi = (MethodInfo) m;
4746 args = TypeManager.GetArgumentTypes (mi);
4747 if (args != null && args.Length == 0)
4754 // This struct records the helper methods used by the Foreach construct
4756 class ForeachHelperMethods {
4757 public EmitContext ec;
4758 public MethodInfo get_enumerator;
4759 public MethodInfo move_next;
4760 public MethodInfo get_current;
4761 public Type element_type;
4762 public Type enumerator_type;
4763 public bool is_disposable;
4765 public ForeachHelperMethods (EmitContext ec)
4768 this.element_type = TypeManager.object_type;
4769 this.enumerator_type = TypeManager.ienumerator_type;
4770 this.is_disposable = true;
4774 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4779 if (!(m is MethodInfo))
4782 if (m.Name != "GetEnumerator")
4785 MethodInfo mi = (MethodInfo) m;
4786 Type [] args = TypeManager.GetArgumentTypes (mi);
4788 if (args.Length != 0)
4791 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4792 EmitContext ec = hm.ec;
4795 // Check whether GetEnumerator is accessible to us
4797 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4799 Type declaring = mi.DeclaringType;
4800 if (prot == MethodAttributes.Private){
4801 if (declaring != ec.ContainerType)
4803 } else if (prot == MethodAttributes.FamANDAssem){
4804 // If from a different assembly, false
4805 if (!(mi is MethodBuilder))
4808 // Are we being invoked from the same class, or from a derived method?
4810 if (ec.ContainerType != declaring){
4811 if (!ec.ContainerType.IsSubclassOf (declaring))
4814 } else if (prot == MethodAttributes.FamORAssem){
4815 if (!(mi is MethodBuilder ||
4816 ec.ContainerType == declaring ||
4817 ec.ContainerType.IsSubclassOf (declaring)))
4819 } if (prot == MethodAttributes.Family){
4820 if (!(ec.ContainerType == declaring ||
4821 ec.ContainerType.IsSubclassOf (declaring)))
4826 // Ok, we can access it, now make sure that we can do something
4827 // with this `GetEnumerator'
4830 if (mi.ReturnType == TypeManager.ienumerator_type ||
4831 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4832 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4833 hm.move_next = TypeManager.bool_movenext_void;
4834 hm.get_current = TypeManager.object_getcurrent_void;
4839 // Ok, so they dont return an IEnumerable, we will have to
4840 // find if they support the GetEnumerator pattern.
4842 Type return_type = mi.ReturnType;
4844 hm.move_next = FetchMethodMoveNext (return_type);
4845 if (hm.move_next == null)
4847 hm.get_current = FetchMethodGetCurrent (return_type);
4848 if (hm.get_current == null)
4851 hm.element_type = hm.get_current.ReturnType;
4852 hm.enumerator_type = return_type;
4853 hm.is_disposable = TypeManager.ImplementsInterface (
4854 hm.enumerator_type, TypeManager.idisposable_type);
4860 /// This filter is used to find the GetEnumerator method
4861 /// on which IEnumerator operates
4863 static MemberFilter FilterEnumerator;
4867 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4870 void error1579 (Type t)
4872 Report.Error (1579, loc,
4873 "foreach statement cannot operate on variables of type `" +
4874 t.FullName + "' because that class does not provide a " +
4875 " GetEnumerator method or it is inaccessible");
4878 static bool TryType (Type t, ForeachHelperMethods hm)
4882 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4883 BindingFlags.Public | BindingFlags.NonPublic |
4884 BindingFlags.Instance,
4885 FilterEnumerator, hm);
4890 hm.get_enumerator = (MethodInfo) mi [0];
4895 // Looks for a usable GetEnumerator in the Type, and if found returns
4896 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4898 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4900 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4902 if (TryType (t, hm))
4906 // Now try to find the method in the interfaces
4909 Type [] ifaces = t.GetInterfaces ();
4911 foreach (Type i in ifaces){
4912 if (TryType (i, hm))
4917 // Since TypeBuilder.GetInterfaces only returns the interface
4918 // types for this type, we have to keep looping, but once
4919 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4920 // done, because it returns all the types
4922 if ((t is TypeBuilder))
4932 // FIXME: possible optimization.
4933 // We might be able to avoid creating `empty' if the type is the sam
4935 bool EmitCollectionForeach (EmitContext ec)
4937 ILGenerator ig = ec.ig;
4938 LocalBuilder enumerator, disposable;
4940 enumerator = ig.DeclareLocal (hm.enumerator_type);
4941 if (hm.is_disposable)
4942 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4947 // Instantiate the enumerator
4949 if (expr.Type.IsValueType){
4950 if (expr is IMemoryLocation){
4951 IMemoryLocation ml = (IMemoryLocation) expr;
4953 ml.AddressOf (ec, AddressOp.Load);
4955 throw new Exception ("Expr " + expr + " of type " + expr.Type +
4956 " does not implement IMemoryLocation");
4957 ig.Emit (OpCodes.Call, hm.get_enumerator);
4960 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4962 ig.Emit (OpCodes.Stloc, enumerator);
4965 // Protect the code in a try/finalize block, so that
4966 // if the beast implement IDisposable, we get rid of it
4969 bool old_in_try = ec.InTry;
4971 if (hm.is_disposable) {
4972 l = ig.BeginExceptionBlock ();
4976 Label end_try = ig.DefineLabel ();
4978 ig.MarkLabel (ec.LoopBegin);
4979 ig.Emit (OpCodes.Ldloc, enumerator);
4980 ig.Emit (OpCodes.Callvirt, hm.move_next);
4981 ig.Emit (OpCodes.Brfalse, end_try);
4982 ig.Emit (OpCodes.Ldloc, enumerator);
4983 ig.Emit (OpCodes.Callvirt, hm.get_current);
4984 variable.EmitAssign (ec, conv);
4985 statement.Emit (ec);
4986 ig.Emit (OpCodes.Br, ec.LoopBegin);
4987 ig.MarkLabel (end_try);
4988 ec.InTry = old_in_try;
4990 // The runtime provides this for us.
4991 // ig.Emit (OpCodes.Leave, end);
4994 // Now the finally block
4996 if (hm.is_disposable) {
4997 Label end_finally = ig.DefineLabel ();
4998 bool old_in_finally = ec.InFinally;
4999 ec.InFinally = true;
5000 ig.BeginFinallyBlock ();
5002 ig.Emit (OpCodes.Ldloc, enumerator);
5003 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5004 ig.Emit (OpCodes.Stloc, disposable);
5005 ig.Emit (OpCodes.Ldloc, disposable);
5006 ig.Emit (OpCodes.Brfalse, end_finally);
5007 ig.Emit (OpCodes.Ldloc, disposable);
5008 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5009 ig.MarkLabel (end_finally);
5010 ec.InFinally = old_in_finally;
5012 // The runtime generates this anyways.
5013 // ig.Emit (OpCodes.Endfinally);
5015 ig.EndExceptionBlock ();
5018 ig.MarkLabel (ec.LoopEnd);
5023 // FIXME: possible optimization.
5024 // We might be able to avoid creating `empty' if the type is the sam
5026 bool EmitArrayForeach (EmitContext ec)
5028 int rank = array_type.GetArrayRank ();
5029 ILGenerator ig = ec.ig;
5031 LocalBuilder copy = ig.DeclareLocal (array_type);
5034 // Make our copy of the array
5037 ig.Emit (OpCodes.Stloc, copy);
5040 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5044 ig.Emit (OpCodes.Ldc_I4_0);
5045 ig.Emit (OpCodes.Stloc, counter);
5046 test = ig.DefineLabel ();
5047 ig.Emit (OpCodes.Br, test);
5049 loop = ig.DefineLabel ();
5050 ig.MarkLabel (loop);
5052 ig.Emit (OpCodes.Ldloc, copy);
5053 ig.Emit (OpCodes.Ldloc, counter);
5054 ArrayAccess.EmitLoadOpcode (ig, var_type);
5056 variable.EmitAssign (ec, conv);
5058 statement.Emit (ec);
5060 ig.MarkLabel (ec.LoopBegin);
5061 ig.Emit (OpCodes.Ldloc, counter);
5062 ig.Emit (OpCodes.Ldc_I4_1);
5063 ig.Emit (OpCodes.Add);
5064 ig.Emit (OpCodes.Stloc, counter);
5066 ig.MarkLabel (test);
5067 ig.Emit (OpCodes.Ldloc, counter);
5068 ig.Emit (OpCodes.Ldloc, copy);
5069 ig.Emit (OpCodes.Ldlen);
5070 ig.Emit (OpCodes.Conv_I4);
5071 ig.Emit (OpCodes.Blt, loop);
5073 LocalBuilder [] dim_len = new LocalBuilder [rank];
5074 LocalBuilder [] dim_count = new LocalBuilder [rank];
5075 Label [] loop = new Label [rank];
5076 Label [] test = new Label [rank];
5079 for (dim = 0; dim < rank; dim++){
5080 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5081 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5082 test [dim] = ig.DefineLabel ();
5083 loop [dim] = ig.DefineLabel ();
5086 for (dim = 0; dim < rank; dim++){
5087 ig.Emit (OpCodes.Ldloc, copy);
5088 IntLiteral.EmitInt (ig, dim);
5089 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5090 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5093 for (dim = 0; dim < rank; dim++){
5094 ig.Emit (OpCodes.Ldc_I4_0);
5095 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5096 ig.Emit (OpCodes.Br, test [dim]);
5097 ig.MarkLabel (loop [dim]);
5100 ig.Emit (OpCodes.Ldloc, copy);
5101 for (dim = 0; dim < rank; dim++)
5102 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5105 // FIXME: Maybe we can cache the computation of `get'?
5107 Type [] args = new Type [rank];
5110 for (int i = 0; i < rank; i++)
5111 args [i] = TypeManager.int32_type;
5113 ModuleBuilder mb = CodeGen.ModuleBuilder;
5114 get = mb.GetArrayMethod (
5116 CallingConventions.HasThis| CallingConventions.Standard,
5118 ig.Emit (OpCodes.Call, get);
5119 variable.EmitAssign (ec, conv);
5120 statement.Emit (ec);
5121 ig.MarkLabel (ec.LoopBegin);
5122 for (dim = rank - 1; dim >= 0; dim--){
5123 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5124 ig.Emit (OpCodes.Ldc_I4_1);
5125 ig.Emit (OpCodes.Add);
5126 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5128 ig.MarkLabel (test [dim]);
5129 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5130 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5131 ig.Emit (OpCodes.Blt, loop [dim]);
5134 ig.MarkLabel (ec.LoopEnd);
5139 public override bool Emit (EmitContext ec)
5143 ILGenerator ig = ec.ig;
5145 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5146 bool old_inloop = ec.InLoop;
5147 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5148 ec.LoopBegin = ig.DefineLabel ();
5149 ec.LoopEnd = ig.DefineLabel ();
5151 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5154 ret_val = EmitCollectionForeach (ec);
5156 ret_val = EmitArrayForeach (ec);
5158 ec.LoopBegin = old_begin;
5159 ec.LoopEnd = old_end;
5160 ec.InLoop = old_inloop;
5161 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;