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;
514 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.CheckOutParameters (ec.CurrentBranching);
580 vector.Returns = FlowReturns.ALWAYS;
581 vector.Breaks = FlowReturns.ALWAYS;
585 public override bool Emit (EmitContext ec)
588 Report.Error (157,loc,"Control can not leave the body of the finally block");
592 if (ec.ReturnType == null){
594 Report.Error (127, loc, "Return with a value not allowed here");
599 Report.Error (126, loc, "An object of type `" +
600 TypeManager.CSharpName (ec.ReturnType) + "' is " +
601 "expected for the return statement");
605 if (Expr.Type != ec.ReturnType)
606 Expr = Expression.ConvertImplicitRequired (
607 ec, Expr, ec.ReturnType, loc);
614 if (ec.InTry || ec.InCatch)
615 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
618 if (ec.InTry || ec.InCatch) {
619 if (!ec.HasReturnLabel) {
620 ec.ReturnLabel = ec.ig.DefineLabel ();
621 ec.HasReturnLabel = true;
623 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
625 ec.ig.Emit (OpCodes.Ret);
631 public class Goto : Statement {
634 LabeledStatement label;
636 public override bool Resolve (EmitContext ec)
638 label = block.LookupLabel (target);
642 "No such label `" + target + "' in this scope");
646 // If this is a forward goto.
647 if (!label.IsDefined)
648 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
650 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
655 public Goto (Block parent_block, string label, Location l)
657 block = parent_block;
662 public string Target {
668 public override bool Emit (EmitContext ec)
671 Label l = label.LabelTarget (ec);
672 ec.ig.Emit (OpCodes.Br, l);
678 public class LabeledStatement : Statement {
679 public readonly Location Location;
687 public LabeledStatement (string label_name, Location l)
689 this.label_name = label_name;
693 public Label LabelTarget (EmitContext ec)
697 label = ec.ig.DefineLabel ();
703 public bool IsDefined {
709 public bool HasBeenReferenced {
715 public void AddUsageVector (FlowBranching.UsageVector vector)
718 vectors = new ArrayList ();
720 vectors.Add (vector.Clone ());
723 public override bool Resolve (EmitContext ec)
726 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
733 public override bool Emit (EmitContext ec)
736 ec.ig.MarkLabel (label);
744 /// `goto default' statement
746 public class GotoDefault : Statement {
748 public GotoDefault (Location l)
753 public override bool Resolve (EmitContext ec)
755 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
759 public override bool Emit (EmitContext ec)
761 if (ec.Switch == null){
762 Report.Error (153, loc, "goto default is only valid in a switch statement");
766 if (!ec.Switch.GotDefault){
767 Report.Error (159, loc, "No default target on switch statement");
771 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
777 /// `goto case' statement
779 public class GotoCase : Statement {
783 public GotoCase (Expression e, Location l)
789 public override bool Resolve (EmitContext ec)
791 if (ec.Switch == null){
792 Report.Error (153, loc, "goto case is only valid in a switch statement");
796 expr = expr.Resolve (ec);
800 if (!(expr is Constant)){
801 Report.Error (159, loc, "Target expression for goto case is not constant");
805 object val = Expression.ConvertIntLiteral (
806 (Constant) expr, ec.Switch.SwitchType, loc);
811 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
816 "No such label 'case " + val + "': for the goto case");
819 label = sl.ILLabelCode;
821 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
825 public override bool Emit (EmitContext ec)
828 ec.ig.Emit (OpCodes.Br, label);
833 public class Throw : Statement {
836 public Throw (Expression expr, Location l)
842 public override bool Resolve (EmitContext ec)
845 expr = expr.Resolve (ec);
849 ExprClass eclass = expr.eclass;
851 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
852 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
853 expr.Error118 ("value, variable, property or indexer access ");
859 if ((t != TypeManager.exception_type) &&
860 !t.IsSubclassOf (TypeManager.exception_type) &&
861 !(expr is NullLiteral)) {
862 Report.Error (155, loc,
863 "The type caught or thrown must be derived " +
864 "from System.Exception");
869 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
873 public override bool Emit (EmitContext ec)
878 ec.ig.Emit (OpCodes.Rethrow);
882 "A throw statement with no argument is only " +
883 "allowed in a catch clause");
890 ec.ig.Emit (OpCodes.Throw);
896 public class Break : Statement {
898 public Break (Location l)
903 public override bool Resolve (EmitContext ec)
905 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
909 public override bool Emit (EmitContext ec)
911 ILGenerator ig = ec.ig;
913 if (ec.InLoop == false && ec.Switch == null){
914 Report.Error (139, loc, "No enclosing loop or switch to continue to");
919 if (ec.InTry || ec.InCatch)
920 ig.Emit (OpCodes.Leave, ec.LoopEnd);
922 ig.Emit (OpCodes.Br, ec.LoopEnd);
928 public class Continue : Statement {
930 public Continue (Location l)
935 public override bool Resolve (EmitContext ec)
937 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
941 public override bool Emit (EmitContext ec)
943 Label begin = ec.LoopBegin;
946 Report.Error (139, loc, "No enclosing loop to continue to");
951 // UGH: Non trivial. This Br might cross a try/catch boundary
955 // try { ... } catch { continue; }
959 // try {} catch { while () { continue; }}
962 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
963 ec.ig.Emit (OpCodes.Leave, begin);
964 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
965 throw new Exception ("Should never happen");
967 ec.ig.Emit (OpCodes.Br, begin);
973 // This is used in the control flow analysis code to specify whether the
974 // current code block may return to its enclosing block before reaching
977 public enum FlowReturns {
978 // It can never return.
981 // This means that the block contains a conditional return statement
985 // The code always returns, ie. there's an unconditional return / break
989 // The code always throws an exception.
992 // The current code block is unreachable. This happens if it's immediately
993 // following a FlowReturns.ALWAYS block.
998 // This is a special bit vector which can inherit from another bit vector doing a
999 // copy-on-write strategy. The inherited vector may have a smaller size than the
1002 public class MyBitVector {
1003 public readonly int Count;
1004 public readonly MyBitVector InheritsFrom;
1009 public MyBitVector (int Count)
1010 : this (null, Count)
1013 public MyBitVector (MyBitVector InheritsFrom, int Count)
1015 this.InheritsFrom = InheritsFrom;
1020 // Checks whether this bit vector has been modified. After setting this to true,
1021 // we won't use the inherited vector anymore, but our own copy of it.
1023 public bool IsDirty {
1030 initialize_vector ();
1035 // Get/set bit `index' in the bit vector.
1037 public bool this [int index]
1041 throw new ArgumentOutOfRangeException ();
1043 // We're doing a "copy-on-write" strategy here; as long
1044 // as nobody writes to the array, we can use our parent's
1045 // copy instead of duplicating the vector.
1048 return vector [index];
1049 else if (InheritsFrom != null) {
1050 BitArray inherited = InheritsFrom.Vector;
1052 if (index < inherited.Count)
1053 return inherited [index];
1062 throw new ArgumentOutOfRangeException ();
1064 // Only copy the vector if we're actually modifying it.
1066 if (this [index] != value) {
1067 initialize_vector ();
1069 vector [index] = value;
1075 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1076 // copy of the bit vector.
1078 public static explicit operator BitArray (MyBitVector vector)
1080 vector.initialize_vector ();
1081 return vector.Vector;
1085 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1086 // different size than the current one.
1088 public void Or (MyBitVector new_vector)
1090 BitArray new_array = new_vector.Vector;
1092 initialize_vector ();
1095 if (vector.Count < new_array.Count)
1096 upper = vector.Count;
1098 upper = new_array.Count;
1100 for (int i = 0; i < upper; i++)
1101 vector [i] = vector [i] | new_array [i];
1105 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1106 // a different size than the current one.
1108 public void And (MyBitVector new_vector)
1110 BitArray new_array = new_vector.Vector;
1112 initialize_vector ();
1115 if (vector.Count < new_array.Count)
1116 lower = upper = vector.Count;
1118 lower = new_array.Count;
1119 upper = vector.Count;
1122 for (int i = 0; i < lower; i++)
1123 vector [i] = vector [i] & new_array [i];
1125 for (int i = lower; i < upper; i++)
1130 // This does a deep copy of the bit vector.
1132 public MyBitVector Clone ()
1134 MyBitVector retval = new MyBitVector (Count);
1136 retval.Vector = Vector;
1145 else if (!is_dirty && (InheritsFrom != null))
1146 return InheritsFrom.Vector;
1148 initialize_vector ();
1154 initialize_vector ();
1156 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1157 vector [i] = value [i];
1161 void initialize_vector ()
1166 vector = new BitArray (Count, false);
1167 if (InheritsFrom != null)
1168 Vector = InheritsFrom.Vector;
1173 public override string ToString ()
1175 StringBuilder sb = new StringBuilder ("MyBitVector (");
1177 BitArray vector = Vector;
1181 sb.Append ("INHERITED - ");
1182 for (int i = 0; i < vector.Count; i++) {
1185 sb.Append (vector [i]);
1189 return sb.ToString ();
1194 // The type of a FlowBranching.
1196 public enum FlowBranchingType {
1197 // Normal (conditional or toplevel) block.
1214 // A new instance of this class is created every time a new block is resolved
1215 // and if there's branching in the block's control flow.
1217 public class FlowBranching {
1219 // The type of this flow branching.
1221 public readonly FlowBranchingType Type;
1224 // The block this branching is contained in. This may be null if it's not
1225 // a top-level block and it doesn't declare any local variables.
1227 public readonly Block Block;
1230 // The parent of this branching or null if this is the top-block.
1232 public readonly FlowBranching Parent;
1235 // Start-Location of this flow branching.
1237 public readonly Location Location;
1240 // A list of UsageVectors. A new vector is added each time control flow may
1241 // take a different path.
1243 public ArrayList Siblings;
1248 InternalParameters param_info;
1250 MyStructInfo[] struct_params;
1252 ArrayList finally_vectors;
1254 static int next_id = 0;
1258 // Performs an `And' operation on the FlowReturns status
1259 // (for instance, a block only returns ALWAYS if all its siblings
1262 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1264 if (b == FlowReturns.UNREACHABLE)
1268 case FlowReturns.NEVER:
1269 if (b == FlowReturns.NEVER)
1270 return FlowReturns.NEVER;
1272 return FlowReturns.SOMETIMES;
1274 case FlowReturns.SOMETIMES:
1275 return FlowReturns.SOMETIMES;
1277 case FlowReturns.ALWAYS:
1278 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1279 return FlowReturns.ALWAYS;
1281 return FlowReturns.SOMETIMES;
1283 case FlowReturns.EXCEPTION:
1284 if (b == FlowReturns.EXCEPTION)
1285 return FlowReturns.EXCEPTION;
1286 else if (b == FlowReturns.ALWAYS)
1287 return FlowReturns.ALWAYS;
1289 return FlowReturns.SOMETIMES;
1296 // The vector contains a BitArray with information about which local variables
1297 // and parameters are already initialized at the current code position.
1299 public class UsageVector {
1301 // If this is true, then the usage vector has been modified and must be
1302 // merged when we're done with this branching.
1304 public bool IsDirty;
1307 // The number of parameters in this block.
1309 public readonly int CountParameters;
1312 // The number of locals in this block.
1314 public readonly int CountLocals;
1317 // If not null, then we inherit our state from this vector and do a
1318 // copy-on-write. If null, then we're the first sibling in a top-level
1319 // block and inherit from the empty vector.
1321 public readonly UsageVector InheritsFrom;
1326 MyBitVector locals, parameters;
1327 FlowReturns real_returns, real_breaks;
1328 bool breaks_set, is_finally;
1330 static int next_id = 0;
1334 // Normally, you should not use any of these constructors.
1336 public UsageVector (UsageVector parent, int num_params, int num_locals)
1338 this.InheritsFrom = parent;
1339 this.CountParameters = num_params;
1340 this.CountLocals = num_locals;
1341 this.real_returns = FlowReturns.NEVER;
1342 this.real_breaks = FlowReturns.NEVER;
1344 if (parent != null) {
1345 locals = new MyBitVector (parent.locals, CountLocals);
1347 parameters = new MyBitVector (parent.parameters, num_params);
1348 real_returns = parent.Returns;
1349 real_breaks = parent.Breaks;
1351 locals = new MyBitVector (null, CountLocals);
1353 parameters = new MyBitVector (null, num_params);
1359 public UsageVector (UsageVector parent)
1360 : this (parent, parent.CountParameters, parent.CountLocals)
1364 // This does a deep copy of the usage vector.
1366 public UsageVector Clone ()
1368 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1370 retval.locals = locals.Clone ();
1371 if (parameters != null)
1372 retval.parameters = parameters.Clone ();
1373 retval.real_returns = real_returns;
1374 retval.real_breaks = real_breaks;
1380 // State of parameter `number'.
1382 public bool this [int number]
1387 else if (number == 0)
1388 throw new ArgumentException ();
1390 return parameters [number - 1];
1396 else if (number == 0)
1397 throw new ArgumentException ();
1399 parameters [number - 1] = value;
1404 // State of the local variable `vi'.
1405 // If the local variable is a struct, use a non-zero `field_idx'
1406 // to check an individual field in it.
1408 public bool this [VariableInfo vi, int field_idx]
1411 if (vi.Number == -1)
1413 else if (vi.Number == 0)
1414 throw new ArgumentException ();
1416 return locals [vi.Number + field_idx - 1];
1420 if (vi.Number == -1)
1422 else if (vi.Number == 0)
1423 throw new ArgumentException ();
1425 locals [vi.Number + field_idx - 1] = value;
1430 // Specifies when the current block returns.
1432 public FlowReturns Returns {
1434 return real_returns;
1438 real_returns = value;
1443 // Specifies whether control may return to our containing block
1444 // before reaching the end of this block. This happens if there
1445 // is a break/continue/goto/return in it.
1447 public FlowReturns Breaks {
1453 real_breaks = value;
1458 public bool AlwaysBreaks {
1460 return (Breaks == FlowReturns.ALWAYS) ||
1461 (Breaks == FlowReturns.EXCEPTION) ||
1462 (Breaks == FlowReturns.UNREACHABLE);
1466 public bool MayBreak {
1468 return Breaks != FlowReturns.NEVER;
1472 public bool AlwaysReturns {
1474 return Returns == FlowReturns.ALWAYS;
1478 public bool MayReturn {
1480 return (Returns == FlowReturns.SOMETIMES) ||
1481 (Returns == FlowReturns.ALWAYS);
1486 // Merge a child branching.
1488 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1490 MyBitVector new_locals = null;
1491 MyBitVector new_params = null;
1493 FlowReturns new_returns = FlowReturns.NEVER;
1494 FlowReturns new_breaks = FlowReturns.NEVER;
1495 bool new_returns_set = false, new_breaks_set = false;
1497 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1498 this, children.Count);
1500 foreach (UsageVector child in children) {
1501 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1503 if (!child.is_finally) {
1504 // If Returns is already set, perform an
1505 // `And' operation on it, otherwise just set just.
1506 if (!new_returns_set) {
1507 new_returns = child.Returns;
1508 new_returns_set = true;
1510 new_returns = AndFlowReturns (
1511 new_returns, child.Returns);
1513 // If Breaks is already set, perform an
1514 // `And' operation on it, otherwise just set just.
1515 if (!new_breaks_set) {
1516 new_breaks = child.Breaks;
1517 new_breaks_set = true;
1519 new_breaks = AndFlowReturns (
1520 new_breaks, child.Breaks);
1523 // Ignore unreachable children.
1524 if (child.Returns == FlowReturns.UNREACHABLE)
1527 // A local variable is initialized after a flow branching if it
1528 // has been initialized in all its branches which do neither
1529 // always return or always throw an exception.
1531 // If a branch may return, but does not always return, then we
1532 // can treat it like a never-returning branch here: control will
1533 // only reach the code position after the branching if we did not
1536 // It's important to distinguish between always and sometimes
1537 // returning branches here:
1540 // 2 if (something) {
1544 // 6 Console.WriteLine (a);
1546 // The if block in lines 3-4 always returns, so we must not look
1547 // at the initialization of `a' in line 4 - thus it'll still be
1548 // uninitialized in line 6.
1550 // On the other hand, the following is allowed:
1557 // 6 Console.WriteLine (a);
1559 // Here, `a' is initialized in line 3 and we must not look at
1560 // line 5 since it always returns.
1562 if (child.is_finally) {
1563 if (new_locals == null)
1564 new_locals = locals.Clone ();
1565 new_locals.Or (child.locals);
1567 if (parameters != null) {
1568 if (new_params == null)
1569 new_params = parameters.Clone ();
1570 new_params.Or (child.parameters);
1574 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1575 if (new_locals != null)
1576 new_locals.And (child.locals);
1578 new_locals = locals.Clone ();
1579 new_locals.Or (child.locals);
1581 } else if (children.Count == 1) {
1582 new_locals = locals.Clone ();
1583 new_locals.Or (child.locals);
1586 // An `out' parameter must be assigned in all branches which do
1587 // not always throw an exception.
1588 if (parameters != null) {
1589 if (child.Breaks != FlowReturns.EXCEPTION) {
1590 if (new_params != null)
1591 new_params.And (child.parameters);
1593 new_params = parameters.Clone ();
1594 new_params.Or (child.parameters);
1596 } else if (children.Count == 1) {
1597 new_params = parameters.Clone ();
1598 new_params.Or (child.parameters);
1604 Returns = new_returns;
1605 if ((branching.Type == FlowBranchingType.BLOCK) ||
1606 (branching.Type == FlowBranchingType.EXCEPTION) ||
1607 (new_breaks == FlowReturns.UNREACHABLE) ||
1608 (new_breaks == FlowReturns.EXCEPTION))
1609 Breaks = new_breaks;
1612 // We've now either reached the point after the branching or we will
1613 // never get there since we always return or always throw an exception.
1615 // If we can reach the point after the branching, mark all locals and
1616 // parameters as initialized which have been initialized in all branches
1617 // we need to look at (see above).
1620 if (((new_breaks != FlowReturns.ALWAYS) &&
1621 (new_breaks != FlowReturns.EXCEPTION) &&
1622 (new_breaks != FlowReturns.UNREACHABLE)) ||
1623 (children.Count == 1)) {
1624 if (new_locals != null)
1625 locals.Or (new_locals);
1627 if (new_params != null)
1628 parameters.Or (new_params);
1631 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1632 new_params, new_locals, new_returns, new_breaks, this);
1634 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1635 if ((new_breaks != FlowReturns.ALWAYS) &&
1636 (new_breaks != FlowReturns.EXCEPTION) &&
1637 (new_breaks != FlowReturns.UNREACHABLE))
1638 Report.Error (163, branching.Location,
1639 "Control cannot fall through from one " +
1640 "case label to another");
1647 // Tells control flow analysis that the current code position may be reached with
1648 // a forward jump from any of the origins listed in `origin_vectors' which is a
1649 // list of UsageVectors.
1651 // This is used when resolving forward gotos - in the following example, the
1652 // variable `a' is uninitialized in line 8 becase this line may be reached via
1653 // the goto in line 4:
1663 // 8 Console.WriteLine (a);
1666 public void MergeJumpOrigins (ICollection origin_vectors)
1668 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1670 real_breaks = FlowReturns.NEVER;
1673 foreach (UsageVector vector in origin_vectors) {
1674 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1676 locals.And (vector.locals);
1677 if (parameters != null)
1678 parameters.And (vector.parameters);
1679 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1682 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1686 // This is used at the beginning of a finally block if there were
1687 // any return statements in the try block or one of the catch blocks.
1689 public void MergeFinallyOrigins (ICollection finally_vectors)
1691 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1693 real_breaks = FlowReturns.NEVER;
1696 foreach (UsageVector vector in finally_vectors) {
1697 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1699 if (parameters != null)
1700 parameters.And (vector.parameters);
1701 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1706 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1709 public void CheckOutParameters (FlowBranching branching)
1711 if (parameters != null)
1712 branching.CheckOutParameters (parameters, branching.Location);
1716 // Performs an `or' operation on the locals and the parameters.
1718 public void Or (UsageVector new_vector)
1720 locals.Or (new_vector.locals);
1721 if (parameters != null)
1722 parameters.Or (new_vector.parameters);
1726 // Performs an `and' operation on the locals.
1728 public void AndLocals (UsageVector new_vector)
1730 locals.And (new_vector.locals);
1734 // Returns a deep copy of the parameters.
1736 public MyBitVector Parameters {
1738 if (parameters != null)
1739 return parameters.Clone ();
1746 // Returns a deep copy of the locals.
1748 public MyBitVector Locals {
1750 return locals.Clone ();
1758 public override string ToString ()
1760 StringBuilder sb = new StringBuilder ();
1762 sb.Append ("Vector (");
1765 sb.Append (Returns);
1768 if (parameters != null) {
1770 sb.Append (parameters);
1776 return sb.ToString ();
1780 FlowBranching (FlowBranchingType type, Location loc)
1782 this.Siblings = new ArrayList ();
1784 this.Location = loc;
1790 // Creates a new flow branching for `block'.
1791 // This is used from Block.Resolve to create the top-level branching of
1794 public FlowBranching (Block block, InternalParameters ip, Location loc)
1795 : this (FlowBranchingType.BLOCK, loc)
1800 int count = (ip != null) ? ip.Count : 0;
1803 param_map = new int [count];
1804 struct_params = new MyStructInfo [count];
1807 for (int i = 0; i < count; i++) {
1808 Parameter.Modifier mod = param_info.ParameterModifier (i);
1810 if ((mod & Parameter.Modifier.OUT) == 0)
1813 param_map [i] = ++num_params;
1815 Type param_type = param_info.ParameterType (i);
1817 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1818 if (struct_params [i] != null)
1819 num_params += struct_params [i].Count;
1822 Siblings = new ArrayList ();
1823 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1827 // Creates a new flow branching which is contained in `parent'.
1828 // You should only pass non-null for the `block' argument if this block
1829 // introduces any new variables - in this case, we need to create a new
1830 // usage vector with a different size than our parent's one.
1832 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1833 Block block, Location loc)
1839 if (parent != null) {
1840 param_info = parent.param_info;
1841 param_map = parent.param_map;
1842 struct_params = parent.struct_params;
1843 num_params = parent.num_params;
1848 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1849 Block.CountVariables);
1851 vector = new UsageVector (Parent.CurrentUsageVector);
1853 Siblings.Add (vector);
1856 case FlowBranchingType.EXCEPTION:
1857 finally_vectors = new ArrayList ();
1866 // Returns the branching's current usage vector.
1868 public UsageVector CurrentUsageVector
1871 return (UsageVector) Siblings [Siblings.Count - 1];
1876 // Creates a sibling of the current usage vector.
1878 public void CreateSibling ()
1880 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1882 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1886 // Creates a sibling for a `finally' block.
1888 public void CreateSiblingForFinally ()
1890 if (Type != FlowBranchingType.EXCEPTION)
1891 throw new NotSupportedException ();
1895 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1899 // Check whether all `out' parameters have been assigned.
1901 public void CheckOutParameters (MyBitVector parameters, Location loc)
1906 for (int i = 0; i < param_map.Length; i++) {
1907 int index = param_map [i];
1912 if (parameters [index - 1])
1915 // If it's a struct, we must ensure that all its fields have
1916 // been assigned. If the struct has any non-public fields, this
1917 // can only be done by assigning the whole struct.
1919 MyStructInfo struct_info = struct_params [index - 1];
1920 if ((struct_info == null) || struct_info.HasNonPublicFields) {
1922 177, loc, "The out parameter `" +
1923 param_info.ParameterName (i) + "' must be " +
1924 "assigned before control leave the current method.");
1930 for (int j = 0; j < struct_info.Count; j++) {
1931 if (!parameters [index + j]) {
1933 177, loc, "The out parameter `" +
1934 param_info.ParameterName (i) + "' must be " +
1935 "assigned before control leave the current method.");
1944 // Merge a child branching.
1946 public FlowReturns MergeChild (FlowBranching child)
1948 return CurrentUsageVector.MergeChildren (child, child.Siblings);
1952 // Does the toplevel merging.
1954 public FlowReturns MergeTopBlock ()
1956 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1957 throw new NotSupportedException ();
1959 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1961 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
1963 vector.MergeChildren (this, Siblings);
1966 Siblings.Add (vector);
1968 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
1970 if (vector.Breaks != FlowReturns.EXCEPTION) {
1971 if (!vector.AlwaysBreaks)
1972 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1973 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
1975 return FlowReturns.EXCEPTION;
1978 public bool InTryBlock ()
1980 if (finally_vectors != null)
1982 else if (Parent != null)
1983 return Parent.InTryBlock ();
1988 public void AddFinallyVector (UsageVector vector)
1990 if (finally_vectors != null) {
1991 finally_vectors.Add (vector.Clone ());
1996 Parent.AddFinallyVector (vector);
1998 throw new NotSupportedException ();
2001 public bool IsVariableAssigned (VariableInfo vi)
2003 if (CurrentUsageVector.AlwaysBreaks)
2006 return CurrentUsageVector [vi, 0];
2009 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2011 if (CurrentUsageVector.AlwaysBreaks)
2014 return CurrentUsageVector [vi, field_idx];
2017 public void SetVariableAssigned (VariableInfo vi)
2019 if (CurrentUsageVector.AlwaysBreaks)
2022 CurrentUsageVector [vi, 0] = true;
2025 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2027 if (CurrentUsageVector.AlwaysBreaks)
2030 CurrentUsageVector [vi, field_idx] = true;
2033 public bool IsParameterAssigned (int number)
2035 int index = param_map [number];
2040 if (CurrentUsageVector [index])
2043 // Parameter is not assigned, so check whether it's a struct.
2044 // If it's either not a struct or a struct which non-public
2045 // fields, return false.
2046 MyStructInfo struct_info = struct_params [number];
2047 if ((struct_info == null) || struct_info.HasNonPublicFields)
2050 // Ok, so each field must be assigned.
2051 for (int i = 0; i < struct_info.Count; i++)
2052 if (!CurrentUsageVector [index + i])
2058 public bool IsParameterAssigned (int number, string field_name)
2060 int index = param_map [number];
2065 int field_idx = struct_params [number] [field_name];
2067 return CurrentUsageVector [index + field_idx];
2070 public void SetParameterAssigned (int number)
2072 if (param_map [number] == 0)
2075 if (!CurrentUsageVector.AlwaysBreaks)
2076 CurrentUsageVector [param_map [number]] = true;
2079 public void SetParameterAssigned (int number, string field_name)
2081 int index = param_map [number];
2086 int field_idx = struct_params [number] [field_name];
2088 if (!CurrentUsageVector.AlwaysBreaks)
2089 CurrentUsageVector [index + field_idx] = true;
2092 public override string ToString ()
2094 StringBuilder sb = new StringBuilder ("FlowBranching (");
2099 if (Block != null) {
2101 sb.Append (Block.ID);
2103 sb.Append (Block.StartLocation);
2106 sb.Append (Siblings.Count);
2108 sb.Append (CurrentUsageVector);
2110 return sb.ToString ();
2114 public class MyStructInfo {
2115 public readonly Type Type;
2116 public readonly FieldInfo[] Fields;
2117 public readonly FieldInfo[] NonPublicFields;
2118 public readonly int Count;
2119 public readonly int CountNonPublic;
2120 public readonly bool HasNonPublicFields;
2122 private static Hashtable field_type_hash = new Hashtable ();
2123 private Hashtable field_hash;
2125 // Private constructor. To save memory usage, we only need to create one instance
2126 // of this class per struct type.
2127 private MyStructInfo (Type type)
2131 if (type is TypeBuilder) {
2132 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2134 ArrayList fields = tc.Fields;
2135 if (fields != null) {
2136 foreach (Field field in fields) {
2137 if ((field.ModFlags & Modifiers.STATIC) != 0)
2139 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2146 Fields = new FieldInfo [Count];
2147 NonPublicFields = new FieldInfo [CountNonPublic];
2149 Count = CountNonPublic = 0;
2150 if (fields != null) {
2151 foreach (Field field in fields) {
2152 if ((field.ModFlags & Modifiers.STATIC) != 0)
2154 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2155 Fields [Count++] = field.FieldBuilder;
2157 NonPublicFields [CountNonPublic++] =
2163 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2164 Count = Fields.Length;
2166 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2167 CountNonPublic = NonPublicFields.Length;
2170 Count += NonPublicFields.Length;
2173 field_hash = new Hashtable ();
2174 foreach (FieldInfo field in Fields)
2175 field_hash.Add (field.Name, ++number);
2177 if (NonPublicFields.Length != 0)
2178 HasNonPublicFields = true;
2180 foreach (FieldInfo field in NonPublicFields)
2181 field_hash.Add (field.Name, ++number);
2184 public int this [string name] {
2186 if (field_hash.Contains (name))
2187 return (int) field_hash [name];
2193 public FieldInfo this [int index] {
2195 if (index >= Fields.Length)
2196 return NonPublicFields [index - Fields.Length];
2198 return Fields [index];
2202 public static MyStructInfo GetStructInfo (Type type)
2204 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2207 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2210 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2214 info = new MyStructInfo (type);
2215 field_type_hash.Add (type, info);
2219 public static MyStructInfo GetStructInfo (TypeContainer tc)
2221 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2225 info = new MyStructInfo (tc.TypeBuilder);
2226 field_type_hash.Add (tc.TypeBuilder, info);
2231 public class VariableInfo : IVariable {
2232 public Expression Type;
2233 public LocalBuilder LocalBuilder;
2234 public Type VariableType;
2235 public readonly string Name;
2236 public readonly Location Location;
2237 public readonly int Block;
2242 public bool Assigned;
2243 public bool ReadOnly;
2245 public VariableInfo (Expression type, string name, int block, Location l)
2250 LocalBuilder = null;
2254 public VariableInfo (TypeContainer tc, int block, Location l)
2256 VariableType = tc.TypeBuilder;
2257 struct_info = MyStructInfo.GetStructInfo (tc);
2259 LocalBuilder = null;
2263 MyStructInfo struct_info;
2264 public MyStructInfo StructInfo {
2270 public bool IsAssigned (EmitContext ec, Location loc)
2272 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2275 MyStructInfo struct_info = StructInfo;
2276 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2277 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2278 ec.CurrentBranching.SetVariableAssigned (this);
2282 int count = struct_info.Count;
2284 for (int i = 0; i < count; i++) {
2285 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2287 Report.Error (165, loc,
2288 "Use of unassigned local variable `" +
2290 ec.CurrentBranching.SetVariableAssigned (this);
2294 FieldInfo field = struct_info [i];
2295 Report.Error (171, loc,
2296 "Field `" + TypeManager.CSharpName (VariableType) +
2297 "." + field.Name + "' must be fully initialized " +
2298 "before control leaves the constructor");
2306 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2308 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2309 (struct_info == null))
2312 int field_idx = StructInfo [name];
2316 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2317 Report.Error (170, loc,
2318 "Use of possibly unassigned field `" + name + "'");
2319 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2326 public void SetAssigned (EmitContext ec)
2328 if (ec.DoFlowAnalysis)
2329 ec.CurrentBranching.SetVariableAssigned (this);
2332 public void SetFieldAssigned (EmitContext ec, string name)
2334 if (ec.DoFlowAnalysis && (struct_info != null))
2335 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2338 public bool Resolve (DeclSpace decl)
2340 if (struct_info != null)
2343 if (VariableType == null)
2344 VariableType = decl.ResolveType (Type, false, Location);
2346 if (VariableType == null)
2349 struct_info = MyStructInfo.GetStructInfo (VariableType);
2354 public void MakePinned ()
2356 TypeManager.MakePinned (LocalBuilder);
2359 public override string ToString ()
2361 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2366 /// Block represents a C# block.
2370 /// This class is used in a number of places: either to represent
2371 /// explicit blocks that the programmer places or implicit blocks.
2373 /// Implicit blocks are used as labels or to introduce variable
2376 public class Block : Statement {
2377 public readonly Block Parent;
2378 public readonly bool Implicit;
2379 public readonly Location StartLocation;
2380 public Location EndLocation;
2383 // The statements in this block
2385 ArrayList statements;
2388 // An array of Blocks. We keep track of children just
2389 // to generate the local variable declarations.
2391 // Statements and child statements are handled through the
2397 // Labels. (label, block) pairs.
2402 // Keeps track of (name, type) pairs
2404 Hashtable variables;
2407 // Keeps track of constants
2408 Hashtable constants;
2411 // Maps variable names to ILGenerator.LocalBuilders
2413 Hashtable local_builders;
2421 public Block (Block parent)
2422 : this (parent, false, Location.Null, Location.Null)
2425 public Block (Block parent, bool implicit_block)
2426 : this (parent, implicit_block, Location.Null, Location.Null)
2429 public Block (Block parent, bool implicit_block, Parameters parameters)
2430 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2433 public Block (Block parent, Location start, Location end)
2434 : this (parent, false, start, end)
2437 public Block (Block parent, Parameters parameters, Location start, Location end)
2438 : this (parent, false, parameters, start, end)
2441 public Block (Block parent, bool implicit_block, Location start, Location end)
2442 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2446 public Block (Block parent, bool implicit_block, Parameters parameters,
2447 Location start, Location end)
2450 parent.AddChild (this);
2452 this.Parent = parent;
2453 this.Implicit = implicit_block;
2454 this.parameters = parameters;
2455 this.StartLocation = start;
2456 this.EndLocation = end;
2459 statements = new ArrayList ();
2468 void AddChild (Block b)
2470 if (children == null)
2471 children = new ArrayList ();
2476 public void SetEndLocation (Location loc)
2482 /// Adds a label to the current block.
2486 /// false if the name already exists in this block. true
2490 public bool AddLabel (string name, LabeledStatement target)
2493 labels = new Hashtable ();
2494 if (labels.Contains (name))
2497 labels.Add (name, target);
2501 public LabeledStatement LookupLabel (string name)
2503 if (labels != null){
2504 if (labels.Contains (name))
2505 return ((LabeledStatement) labels [name]);
2509 return Parent.LookupLabel (name);
2514 VariableInfo this_variable = null;
2517 // Returns the "this" instance variable of this block.
2518 // See AddThisVariable() for more information.
2520 public VariableInfo ThisVariable {
2522 if (this_variable != null)
2523 return this_variable;
2524 else if (Parent != null)
2525 return Parent.ThisVariable;
2531 Hashtable child_variable_names;
2534 // Marks a variable with name @name as being used in a child block.
2535 // If a variable name has been used in a child block, it's illegal to
2536 // declare a variable with the same name in the current block.
2538 public void AddChildVariableName (string name)
2540 if (child_variable_names == null)
2541 child_variable_names = new Hashtable ();
2543 if (!child_variable_names.Contains (name))
2544 child_variable_names.Add (name, true);
2548 // Marks all variables from block @block and all its children as being
2549 // used in a child block.
2551 public void AddChildVariableNames (Block block)
2553 if (block.Variables != null) {
2554 foreach (string name in block.Variables.Keys)
2555 AddChildVariableName (name);
2558 foreach (Block child in block.children) {
2559 if (child.Variables != null) {
2560 foreach (string name in child.Variables.Keys)
2561 AddChildVariableName (name);
2567 // Checks whether a variable name has already been used in a child block.
2569 public bool IsVariableNameUsedInChildBlock (string name)
2571 if (child_variable_names == null)
2574 return child_variable_names.Contains (name);
2578 // This is used by non-static `struct' constructors which do not have an
2579 // initializer - in this case, the constructor must initialize all of the
2580 // struct's fields. To do this, we add a "this" variable and use the flow
2581 // analysis code to ensure that it's been fully initialized before control
2582 // leaves the constructor.
2584 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2586 if (this_variable != null)
2587 return this_variable;
2589 this_variable = new VariableInfo (tc, ID, l);
2591 if (variables == null)
2592 variables = new Hashtable ();
2593 variables.Add ("this", this_variable);
2595 return this_variable;
2598 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2600 if (variables == null)
2601 variables = new Hashtable ();
2603 VariableInfo vi = GetVariableInfo (name);
2606 Report.Error (136, l, "A local variable named `" + name + "' " +
2607 "cannot be declared in this scope since it would " +
2608 "give a different meaning to `" + name + "', which " +
2609 "is already used in a `parent or current' scope to " +
2610 "denote something else");
2612 Report.Error (128, l, "A local variable `" + name + "' is already " +
2613 "defined in this scope");
2617 if (IsVariableNameUsedInChildBlock (name)) {
2618 Report.Error (136, l, "A local variable named `" + name + "' " +
2619 "cannot be declared in this scope since it would " +
2620 "give a different meaning to `" + name + "', which " +
2621 "is already used in a `child' scope to denote something " +
2628 Parameter p = pars.GetParameterByName (name, out idx);
2630 Report.Error (136, l, "A local variable named `" + name + "' " +
2631 "cannot be declared in this scope since it would " +
2632 "give a different meaning to `" + name + "', which " +
2633 "is already used in a `parent or current' scope to " +
2634 "denote something else");
2639 vi = new VariableInfo (type, name, ID, l);
2641 variables.Add (name, vi);
2643 if (variables_initialized)
2644 throw new Exception ();
2646 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2650 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2652 if (AddVariable (type, name, pars, l) == null)
2655 if (constants == null)
2656 constants = new Hashtable ();
2658 constants.Add (name, value);
2662 public Hashtable Variables {
2668 public VariableInfo GetVariableInfo (string name)
2670 if (variables != null) {
2672 temp = variables [name];
2675 return (VariableInfo) temp;
2680 return Parent.GetVariableInfo (name);
2685 public Expression GetVariableType (string name)
2687 VariableInfo vi = GetVariableInfo (name);
2695 public Expression GetConstantExpression (string name)
2697 if (constants != null) {
2699 temp = constants [name];
2702 return (Expression) temp;
2706 return Parent.GetConstantExpression (name);
2712 /// True if the variable named @name has been defined
2715 public bool IsVariableDefined (string name)
2717 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2718 if (variables != null) {
2719 if (variables.Contains (name))
2724 return Parent.IsVariableDefined (name);
2730 /// True if the variable named @name is a constant
2732 public bool IsConstant (string name)
2734 Expression e = null;
2736 e = GetConstantExpression (name);
2742 /// Use to fetch the statement associated with this label
2744 public Statement this [string name] {
2746 return (Statement) labels [name];
2750 Parameters parameters = null;
2751 public Parameters Parameters {
2754 return Parent.Parameters;
2761 /// A list of labels that were not used within this block
2763 public string [] GetUnreferenced ()
2765 // FIXME: Implement me
2769 public void AddStatement (Statement s)
2786 bool variables_initialized = false;
2787 int count_variables = 0, first_variable = 0;
2789 void UpdateVariableInfo (EmitContext ec)
2791 DeclSpace ds = ec.DeclSpace;
2796 first_variable += Parent.CountVariables;
2798 count_variables = first_variable;
2799 if (variables != null) {
2800 foreach (VariableInfo vi in variables.Values) {
2801 if (!vi.Resolve (ds)) {
2806 vi.Number = ++count_variables;
2808 if (vi.StructInfo != null)
2809 count_variables += vi.StructInfo.Count;
2813 variables_initialized = true;
2818 // The number of local variables in this block
2820 public int CountVariables
2823 if (!variables_initialized)
2824 throw new Exception ();
2826 return count_variables;
2831 /// Emits the variable declarations and labels.
2834 /// tc: is our typecontainer (to resolve type references)
2835 /// ig: is the code generator:
2836 /// toplevel: the toplevel block. This is used for checking
2837 /// that no two labels with the same name are used.
2839 public void EmitMeta (EmitContext ec, Block toplevel)
2841 DeclSpace ds = ec.DeclSpace;
2842 ILGenerator ig = ec.ig;
2844 if (!variables_initialized)
2845 UpdateVariableInfo (ec);
2848 // Process this block variables
2850 if (variables != null){
2851 local_builders = new Hashtable ();
2853 foreach (DictionaryEntry de in variables){
2854 string name = (string) de.Key;
2855 VariableInfo vi = (VariableInfo) de.Value;
2857 if (vi.VariableType == null)
2860 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2862 if (CodeGen.SymbolWriter != null)
2863 vi.LocalBuilder.SetLocalSymInfo (name);
2865 if (constants == null)
2868 Expression cv = (Expression) constants [name];
2872 Expression e = cv.Resolve (ec);
2876 if (!(e is Constant)){
2877 Report.Error (133, vi.Location,
2878 "The expression being assigned to `" +
2879 name + "' must be constant (" + e + ")");
2883 constants.Remove (name);
2884 constants.Add (name, e);
2889 // Now, handle the children
2891 if (children != null){
2892 foreach (Block b in children)
2893 b.EmitMeta (ec, toplevel);
2897 public void UsageWarning ()
2901 if (variables != null){
2902 foreach (DictionaryEntry de in variables){
2903 VariableInfo vi = (VariableInfo) de.Value;
2908 name = (string) de.Key;
2912 219, vi.Location, "The variable `" + name +
2913 "' is assigned but its value is never used");
2916 168, vi.Location, "The variable `" +
2918 "' is declared but never used");
2923 if (children != null)
2924 foreach (Block b in children)
2928 public override bool Resolve (EmitContext ec)
2930 Block prev_block = ec.CurrentBlock;
2933 ec.CurrentBlock = this;
2934 ec.StartFlowBranching (this);
2936 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
2938 if (!variables_initialized)
2939 UpdateVariableInfo (ec);
2941 foreach (Statement s in statements){
2942 if (s.Resolve (ec) == false)
2946 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
2948 FlowReturns returns = ec.EndFlowBranching ();
2949 ec.CurrentBlock = prev_block;
2951 // If we're a non-static `struct' constructor which doesn't have an
2952 // initializer, then we must initialize all of the struct's fields.
2953 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
2954 !this_variable.IsAssigned (ec, loc))
2957 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2958 foreach (LabeledStatement label in labels.Values)
2959 if (!label.HasBeenReferenced)
2960 Report.Warning (164, label.Location,
2961 "This label has not been referenced");
2967 public override bool Emit (EmitContext ec)
2969 bool is_ret = false, this_ret = false;
2970 Block prev_block = ec.CurrentBlock;
2971 bool warning_shown = false;
2973 ec.CurrentBlock = this;
2975 if (CodeGen.SymbolWriter != null) {
2976 ec.Mark (StartLocation);
2978 foreach (Statement s in statements) {
2981 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2982 warning_shown = true;
2983 Warning_DeadCodeFound (s.loc);
2986 this_ret = s.Emit (ec);
2991 ec.Mark (EndLocation);
2993 foreach (Statement s in statements){
2994 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2995 warning_shown = true;
2996 Warning_DeadCodeFound (s.loc);
2999 this_ret = s.Emit (ec);
3005 ec.CurrentBlock = prev_block;
3010 public class SwitchLabel {
3013 public Location loc;
3014 public Label ILLabel;
3015 public Label ILLabelCode;
3018 // if expr == null, then it is the default case.
3020 public SwitchLabel (Expression expr, Location l)
3026 public Expression Label {
3032 public object Converted {
3039 // Resolves the expression, reduces it to a literal if possible
3040 // and then converts it to the requested type.
3042 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3044 ILLabel = ec.ig.DefineLabel ();
3045 ILLabelCode = ec.ig.DefineLabel ();
3050 Expression e = label.Resolve (ec);
3055 if (!(e is Constant)){
3056 Console.WriteLine ("Value is: " + label);
3057 Report.Error (150, loc, "A constant value is expected");
3061 if (e is StringConstant || e is NullLiteral){
3062 if (required_type == TypeManager.string_type){
3064 ILLabel = ec.ig.DefineLabel ();
3069 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3070 if (converted == null)
3077 public class SwitchSection {
3078 // An array of SwitchLabels.
3079 public readonly ArrayList Labels;
3080 public readonly Block Block;
3082 public SwitchSection (ArrayList labels, Block block)
3089 public class Switch : Statement {
3090 public readonly ArrayList Sections;
3091 public Expression Expr;
3094 /// Maps constants whose type type SwitchType to their SwitchLabels.
3096 public Hashtable Elements;
3099 /// The governing switch type
3101 public Type SwitchType;
3107 Label default_target;
3108 Expression new_expr;
3111 // The types allowed to be implicitly cast from
3112 // on the governing type
3114 static Type [] allowed_types;
3116 public Switch (Expression e, ArrayList sects, Location l)
3123 public bool GotDefault {
3129 public Label DefaultTarget {
3131 return default_target;
3136 // Determines the governing type for a switch. The returned
3137 // expression might be the expression from the switch, or an
3138 // expression that includes any potential conversions to the
3139 // integral types or to string.
3141 Expression SwitchGoverningType (EmitContext ec, Type t)
3143 if (t == TypeManager.int32_type ||
3144 t == TypeManager.uint32_type ||
3145 t == TypeManager.char_type ||
3146 t == TypeManager.byte_type ||
3147 t == TypeManager.sbyte_type ||
3148 t == TypeManager.ushort_type ||
3149 t == TypeManager.short_type ||
3150 t == TypeManager.uint64_type ||
3151 t == TypeManager.int64_type ||
3152 t == TypeManager.string_type ||
3153 t == TypeManager.bool_type ||
3154 t.IsSubclassOf (TypeManager.enum_type))
3157 if (allowed_types == null){
3158 allowed_types = new Type [] {
3159 TypeManager.sbyte_type,
3160 TypeManager.byte_type,
3161 TypeManager.short_type,
3162 TypeManager.ushort_type,
3163 TypeManager.int32_type,
3164 TypeManager.uint32_type,
3165 TypeManager.int64_type,
3166 TypeManager.uint64_type,
3167 TypeManager.char_type,
3168 TypeManager.bool_type,
3169 TypeManager.string_type
3174 // Try to find a *user* defined implicit conversion.
3176 // If there is no implicit conversion, or if there are multiple
3177 // conversions, we have to report an error
3179 Expression converted = null;
3180 foreach (Type tt in allowed_types){
3183 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3187 if (converted != null){
3188 Report.Error (-12, loc, "More than one conversion to an integral " +
3189 " type exists for type `" +
3190 TypeManager.CSharpName (Expr.Type)+"'");
3198 void error152 (string n)
3201 152, "The label `" + n + ":' " +
3202 "is already present on this switch statement");
3206 // Performs the basic sanity checks on the switch statement
3207 // (looks for duplicate keys and non-constant expressions).
3209 // It also returns a hashtable with the keys that we will later
3210 // use to compute the switch tables
3212 bool CheckSwitch (EmitContext ec)
3216 Elements = new Hashtable ();
3218 got_default = false;
3220 if (TypeManager.IsEnumType (SwitchType)){
3221 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3223 compare_type = SwitchType;
3225 foreach (SwitchSection ss in Sections){
3226 foreach (SwitchLabel sl in ss.Labels){
3227 if (!sl.ResolveAndReduce (ec, SwitchType)){
3232 if (sl.Label == null){
3234 error152 ("default");
3241 object key = sl.Converted;
3243 if (key is Constant)
3244 key = ((Constant) key).GetValue ();
3247 key = NullLiteral.Null;
3249 string lname = null;
3250 if (compare_type == TypeManager.uint64_type){
3251 ulong v = (ulong) key;
3253 if (Elements.Contains (v))
3254 lname = v.ToString ();
3256 Elements.Add (v, sl);
3257 } else if (compare_type == TypeManager.int64_type){
3258 long v = (long) key;
3260 if (Elements.Contains (v))
3261 lname = v.ToString ();
3263 Elements.Add (v, sl);
3264 } else if (compare_type == TypeManager.uint32_type){
3265 uint v = (uint) key;
3267 if (Elements.Contains (v))
3268 lname = v.ToString ();
3270 Elements.Add (v, sl);
3271 } else if (compare_type == TypeManager.char_type){
3272 char v = (char) key;
3274 if (Elements.Contains (v))
3275 lname = v.ToString ();
3277 Elements.Add (v, sl);
3278 } else if (compare_type == TypeManager.byte_type){
3279 byte v = (byte) key;
3281 if (Elements.Contains (v))
3282 lname = v.ToString ();
3284 Elements.Add (v, sl);
3285 } else if (compare_type == TypeManager.sbyte_type){
3286 sbyte v = (sbyte) key;
3288 if (Elements.Contains (v))
3289 lname = v.ToString ();
3291 Elements.Add (v, sl);
3292 } else if (compare_type == TypeManager.short_type){
3293 short v = (short) key;
3295 if (Elements.Contains (v))
3296 lname = v.ToString ();
3298 Elements.Add (v, sl);
3299 } else if (compare_type == TypeManager.ushort_type){
3300 ushort v = (ushort) key;
3302 if (Elements.Contains (v))
3303 lname = v.ToString ();
3305 Elements.Add (v, sl);
3306 } else if (compare_type == TypeManager.string_type){
3307 if (key is NullLiteral){
3308 if (Elements.Contains (NullLiteral.Null))
3311 Elements.Add (NullLiteral.Null, null);
3313 string s = (string) key;
3315 if (Elements.Contains (s))
3318 Elements.Add (s, sl);
3320 } else if (compare_type == TypeManager.int32_type) {
3323 if (Elements.Contains (v))
3324 lname = v.ToString ();
3326 Elements.Add (v, sl);
3327 } else if (compare_type == TypeManager.bool_type) {
3328 bool v = (bool) key;
3330 if (Elements.Contains (v))
3331 lname = v.ToString ();
3333 Elements.Add (v, sl);
3337 throw new Exception ("Unknown switch type!" +
3338 SwitchType + " " + compare_type);
3342 error152 ("case + " + lname);
3353 void EmitObjectInteger (ILGenerator ig, object k)
3356 IntConstant.EmitInt (ig, (int) k);
3357 else if (k is Constant) {
3358 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3361 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3364 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3366 IntConstant.EmitInt (ig, (int) (long) k);
3367 ig.Emit (OpCodes.Conv_I8);
3370 LongConstant.EmitLong (ig, (long) k);
3372 else if (k is ulong)
3374 if ((ulong) k < (1L<<32))
3376 IntConstant.EmitInt (ig, (int) (long) k);
3377 ig.Emit (OpCodes.Conv_U8);
3381 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3385 IntConstant.EmitInt (ig, (int) ((char) k));
3386 else if (k is sbyte)
3387 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3389 IntConstant.EmitInt (ig, (int) ((byte) k));
3390 else if (k is short)
3391 IntConstant.EmitInt (ig, (int) ((short) k));
3392 else if (k is ushort)
3393 IntConstant.EmitInt (ig, (int) ((ushort) k));
3395 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3397 throw new Exception ("Unhandled case");
3400 // structure used to hold blocks of keys while calculating table switch
3401 class KeyBlock : IComparable
3403 public KeyBlock (long _nFirst)
3405 nFirst = nLast = _nFirst;
3409 public ArrayList rgKeys = null;
3412 get { return (int) (nLast - nFirst + 1); }
3414 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3416 return kbLast.nLast - kbFirst.nFirst + 1;
3418 public int CompareTo (object obj)
3420 KeyBlock kb = (KeyBlock) obj;
3421 int nLength = Length;
3422 int nLengthOther = kb.Length;
3423 if (nLengthOther == nLength)
3424 return (int) (kb.nFirst - nFirst);
3425 return nLength - nLengthOther;
3430 /// This method emits code for a lookup-based switch statement (non-string)
3431 /// Basically it groups the cases into blocks that are at least half full,
3432 /// and then spits out individual lookup opcodes for each block.
3433 /// It emits the longest blocks first, and short blocks are just
3434 /// handled with direct compares.
3436 /// <param name="ec"></param>
3437 /// <param name="val"></param>
3438 /// <returns></returns>
3439 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3441 int cElements = Elements.Count;
3442 object [] rgKeys = new object [cElements];
3443 Elements.Keys.CopyTo (rgKeys, 0);
3444 Array.Sort (rgKeys);
3446 // initialize the block list with one element per key
3447 ArrayList rgKeyBlocks = new ArrayList ();
3448 foreach (object key in rgKeys)
3449 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3452 // iteratively merge the blocks while they are at least half full
3453 // there's probably a really cool way to do this with a tree...
3454 while (rgKeyBlocks.Count > 1)
3456 ArrayList rgKeyBlocksNew = new ArrayList ();
3457 kbCurr = (KeyBlock) rgKeyBlocks [0];
3458 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3460 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3461 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3464 kbCurr.nLast = kb.nLast;
3468 // start a new block
3469 rgKeyBlocksNew.Add (kbCurr);
3473 rgKeyBlocksNew.Add (kbCurr);
3474 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3476 rgKeyBlocks = rgKeyBlocksNew;
3479 // initialize the key lists
3480 foreach (KeyBlock kb in rgKeyBlocks)
3481 kb.rgKeys = new ArrayList ();
3483 // fill the key lists
3485 if (rgKeyBlocks.Count > 0) {
3486 kbCurr = (KeyBlock) rgKeyBlocks [0];
3487 foreach (object key in rgKeys)
3489 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3491 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3492 kbCurr.rgKeys.Add (key);
3496 // sort the blocks so we can tackle the largest ones first
3497 rgKeyBlocks.Sort ();
3499 // okay now we can start...
3500 ILGenerator ig = ec.ig;
3501 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3502 Label lblDefault = ig.DefineLabel ();
3504 Type typeKeys = null;
3505 if (rgKeys.Length > 0)
3506 typeKeys = rgKeys [0].GetType (); // used for conversions
3508 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3510 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3511 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3514 foreach (object key in kb.rgKeys)
3516 ig.Emit (OpCodes.Ldloc, val);
3517 EmitObjectInteger (ig, key);
3518 SwitchLabel sl = (SwitchLabel) Elements [key];
3519 ig.Emit (OpCodes.Beq, sl.ILLabel);
3524 // TODO: if all the keys in the block are the same and there are
3525 // no gaps/defaults then just use a range-check.
3526 if (SwitchType == TypeManager.int64_type ||
3527 SwitchType == TypeManager.uint64_type)
3529 // TODO: optimize constant/I4 cases
3531 // check block range (could be > 2^31)
3532 ig.Emit (OpCodes.Ldloc, val);
3533 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3534 ig.Emit (OpCodes.Blt, lblDefault);
3535 ig.Emit (OpCodes.Ldloc, val);
3536 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3537 ig.Emit (OpCodes.Bgt, lblDefault);
3540 ig.Emit (OpCodes.Ldloc, val);
3543 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3544 ig.Emit (OpCodes.Sub);
3546 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3551 ig.Emit (OpCodes.Ldloc, val);
3552 int nFirst = (int) kb.nFirst;
3555 IntConstant.EmitInt (ig, nFirst);
3556 ig.Emit (OpCodes.Sub);
3558 else if (nFirst < 0)
3560 IntConstant.EmitInt (ig, -nFirst);
3561 ig.Emit (OpCodes.Add);
3565 // first, build the list of labels for the switch
3567 int cJumps = kb.Length;
3568 Label [] rgLabels = new Label [cJumps];
3569 for (int iJump = 0; iJump < cJumps; iJump++)
3571 object key = kb.rgKeys [iKey];
3572 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3574 SwitchLabel sl = (SwitchLabel) Elements [key];
3575 rgLabels [iJump] = sl.ILLabel;
3579 rgLabels [iJump] = lblDefault;
3581 // emit the switch opcode
3582 ig.Emit (OpCodes.Switch, rgLabels);
3585 // mark the default for this block
3587 ig.MarkLabel (lblDefault);
3590 // TODO: find the default case and emit it here,
3591 // to prevent having to do the following jump.
3592 // make sure to mark other labels in the default section
3594 // the last default just goes to the end
3595 ig.Emit (OpCodes.Br, lblDefault);
3597 // now emit the code for the sections
3598 bool fFoundDefault = false;
3599 bool fAllReturn = true;
3600 foreach (SwitchSection ss in Sections)
3602 foreach (SwitchLabel sl in ss.Labels)
3604 ig.MarkLabel (sl.ILLabel);
3605 ig.MarkLabel (sl.ILLabelCode);
3606 if (sl.Label == null)
3608 ig.MarkLabel (lblDefault);
3609 fFoundDefault = true;
3613 bool returns = ss.Block.Emit (ec);
3614 if (!ec.Breaks && !returns)
3615 Report.Error (163, ((SwitchLabel) ss.Labels [0]).loc,
3616 "Control cannot fall through from one " +
3617 "case label to another");
3618 fAllReturn &= returns;
3619 //ig.Emit (OpCodes.Br, lblEnd);
3622 if (!fFoundDefault) {
3623 ig.MarkLabel (lblDefault);
3626 ig.MarkLabel (lblEnd);
3631 // This simple emit switch works, but does not take advantage of the
3633 // TODO: remove non-string logic from here
3634 // TODO: binary search strings?
3636 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3638 ILGenerator ig = ec.ig;
3639 Label end_of_switch = ig.DefineLabel ();
3640 Label next_test = ig.DefineLabel ();
3641 Label null_target = ig.DefineLabel ();
3642 bool default_found = false;
3643 bool first_test = true;
3644 bool pending_goto_end = false;
3645 bool all_return = true;
3646 bool is_string = false;
3650 // Special processing for strings: we cant compare
3653 if (SwitchType == TypeManager.string_type){
3654 ig.Emit (OpCodes.Ldloc, val);
3657 if (Elements.Contains (NullLiteral.Null)){
3658 ig.Emit (OpCodes.Brfalse, null_target);
3660 ig.Emit (OpCodes.Brfalse, default_target);
3662 ig.Emit (OpCodes.Ldloc, val);
3663 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3664 ig.Emit (OpCodes.Stloc, val);
3667 SwitchSection last_section;
3668 last_section = (SwitchSection) Sections [Sections.Count-1];
3670 foreach (SwitchSection ss in Sections){
3671 Label sec_begin = ig.DefineLabel ();
3673 if (pending_goto_end)
3674 ig.Emit (OpCodes.Br, end_of_switch);
3676 int label_count = ss.Labels.Count;
3678 foreach (SwitchLabel sl in ss.Labels){
3679 ig.MarkLabel (sl.ILLabel);
3682 ig.MarkLabel (next_test);
3683 next_test = ig.DefineLabel ();
3686 // If we are the default target
3688 if (sl.Label == null){
3689 ig.MarkLabel (default_target);
3690 default_found = true;
3692 object lit = sl.Converted;
3694 if (lit is NullLiteral){
3696 if (label_count == 1)
3697 ig.Emit (OpCodes.Br, next_test);
3702 StringConstant str = (StringConstant) lit;
3704 ig.Emit (OpCodes.Ldloc, val);
3705 ig.Emit (OpCodes.Ldstr, str.Value);
3706 if (label_count == 1)
3707 ig.Emit (OpCodes.Bne_Un, next_test);
3709 ig.Emit (OpCodes.Beq, sec_begin);
3711 ig.Emit (OpCodes.Ldloc, val);
3712 EmitObjectInteger (ig, lit);
3713 ig.Emit (OpCodes.Ceq);
3714 if (label_count == 1)
3715 ig.Emit (OpCodes.Brfalse, next_test);
3717 ig.Emit (OpCodes.Brtrue, sec_begin);
3721 if (label_count != 1 && ss != last_section)
3722 ig.Emit (OpCodes.Br, next_test);
3725 ig.MarkLabel (null_target);
3726 ig.MarkLabel (sec_begin);
3727 foreach (SwitchLabel sl in ss.Labels)
\r
3728 ig.MarkLabel (sl.ILLabelCode);
3731 bool returns = ss.Block.Emit (ec);
3732 if (!ec.Breaks && !returns)
3733 Report.Error (163, ((SwitchLabel) ss.Labels [0]).loc,
3734 "Control cannot fall through from one " +
3735 "case label to another");
3737 pending_goto_end = false;
3740 pending_goto_end = true;
3744 if (!default_found){
3745 ig.MarkLabel (default_target);
3748 ig.MarkLabel (next_test);
3749 ig.MarkLabel (end_of_switch);
3754 public override bool Resolve (EmitContext ec)
3756 Expr = Expr.Resolve (ec);
3760 new_expr = SwitchGoverningType (ec, Expr.Type);
3761 if (new_expr == null){
3762 Report.Error (151, loc, "An integer type or string was expected for switch");
3767 SwitchType = new_expr.Type;
3769 if (!CheckSwitch (ec))
3772 Switch old_switch = ec.Switch;
3774 ec.Switch.SwitchType = SwitchType;
3776 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3779 foreach (SwitchSection ss in Sections){
3781 ec.CurrentBranching.CreateSibling ();
3785 if (ss.Block.Resolve (ec) != true)
3791 ec.CurrentBranching.CreateSibling ();
3793 ec.EndFlowBranching ();
3794 ec.Switch = old_switch;
3799 public override bool Emit (EmitContext ec)
3801 // Store variable for comparission purposes
3802 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3804 ec.ig.Emit (OpCodes.Stloc, value);
3806 ILGenerator ig = ec.ig;
3808 default_target = ig.DefineLabel ();
3811 // Setup the codegen context
3813 Label old_end = ec.LoopEnd;
3814 Switch old_switch = ec.Switch;
3816 ec.LoopEnd = ig.DefineLabel ();
3821 if (SwitchType == TypeManager.string_type)
3822 all_return = SimpleSwitchEmit (ec, value);
3824 all_return = TableSwitchEmit (ec, value);
3826 // Restore context state.
3827 ig.MarkLabel (ec.LoopEnd);
3830 // Restore the previous context
3832 ec.LoopEnd = old_end;
3833 ec.Switch = old_switch;
3839 public class Lock : Statement {
3841 Statement Statement;
3843 public Lock (Expression expr, Statement stmt, Location l)
3850 public override bool Resolve (EmitContext ec)
3852 expr = expr.Resolve (ec);
3853 return Statement.Resolve (ec) && expr != null;
3856 public override bool Emit (EmitContext ec)
3858 Type type = expr.Type;
3861 if (type.IsValueType){
3862 Report.Error (185, loc, "lock statement requires the expression to be " +
3863 " a reference type (type is: `" +
3864 TypeManager.CSharpName (type) + "'");
3868 ILGenerator ig = ec.ig;
3869 LocalBuilder temp = ig.DeclareLocal (type);
3872 ig.Emit (OpCodes.Dup);
3873 ig.Emit (OpCodes.Stloc, temp);
3874 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3877 Label end = ig.BeginExceptionBlock ();
3878 bool old_in_try = ec.InTry;
3880 Label finish = ig.DefineLabel ();
3881 val = Statement.Emit (ec);
3882 ec.InTry = old_in_try;
3883 // ig.Emit (OpCodes.Leave, finish);
3885 ig.MarkLabel (finish);
3888 ig.BeginFinallyBlock ();
3889 ig.Emit (OpCodes.Ldloc, temp);
3890 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3891 ig.EndExceptionBlock ();
3897 public class Unchecked : Statement {
3898 public readonly Block Block;
3900 public Unchecked (Block b)
3905 public override bool Resolve (EmitContext ec)
3907 return Block.Resolve (ec);
3910 public override bool Emit (EmitContext ec)
3912 bool previous_state = ec.CheckState;
3913 bool previous_state_const = ec.ConstantCheckState;
3916 ec.CheckState = false;
3917 ec.ConstantCheckState = false;
3918 val = Block.Emit (ec);
3919 ec.CheckState = previous_state;
3920 ec.ConstantCheckState = previous_state_const;
3926 public class Checked : Statement {
3927 public readonly Block Block;
3929 public Checked (Block b)
3934 public override bool Resolve (EmitContext ec)
3936 bool previous_state = ec.CheckState;
3937 bool previous_state_const = ec.ConstantCheckState;
3939 ec.CheckState = true;
3940 ec.ConstantCheckState = true;
3941 bool ret = Block.Resolve (ec);
3942 ec.CheckState = previous_state;
3943 ec.ConstantCheckState = previous_state_const;
3948 public override bool Emit (EmitContext ec)
3950 bool previous_state = ec.CheckState;
3951 bool previous_state_const = ec.ConstantCheckState;
3954 ec.CheckState = true;
3955 ec.ConstantCheckState = true;
3956 val = Block.Emit (ec);
3957 ec.CheckState = previous_state;
3958 ec.ConstantCheckState = previous_state_const;
3964 public class Unsafe : Statement {
3965 public readonly Block Block;
3967 public Unsafe (Block b)
3972 public override bool Resolve (EmitContext ec)
3974 bool previous_state = ec.InUnsafe;
3978 val = Block.Resolve (ec);
3979 ec.InUnsafe = previous_state;
3984 public override bool Emit (EmitContext ec)
3986 bool previous_state = ec.InUnsafe;
3990 val = Block.Emit (ec);
3991 ec.InUnsafe = previous_state;
4000 public class Fixed : Statement {
4002 ArrayList declarators;
4003 Statement statement;
4008 public bool is_object;
4009 public VariableInfo vi;
4010 public Expression expr;
4011 public Expression converted;
4014 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4017 declarators = decls;
4022 public override bool Resolve (EmitContext ec)
4024 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4025 if (expr_type == null)
4028 data = new FixedData [declarators.Count];
4031 foreach (Pair p in declarators){
4032 VariableInfo vi = (VariableInfo) p.First;
4033 Expression e = (Expression) p.Second;
4038 // The rules for the possible declarators are pretty wise,
4039 // but the production on the grammar is more concise.
4041 // So we have to enforce these rules here.
4043 // We do not resolve before doing the case 1 test,
4044 // because the grammar is explicit in that the token &
4045 // is present, so we need to test for this particular case.
4049 // Case 1: & object.
4051 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4052 Expression child = ((Unary) e).Expr;
4055 if (child is ParameterReference || child is LocalVariableReference){
4058 "No need to use fixed statement for parameters or " +
4059 "local variable declarations (address is already " +
4068 child = ((Unary) e).Expr;
4070 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4073 data [i].is_object = true;
4075 data [i].converted = null;
4089 if (e.Type.IsArray){
4090 Type array_type = e.Type.GetElementType ();
4094 // Provided that array_type is unmanaged,
4096 if (!TypeManager.VerifyUnManaged (array_type, loc))
4100 // and T* is implicitly convertible to the
4101 // pointer type given in the fixed statement.
4103 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4105 Expression converted = Expression.ConvertImplicitRequired (
4106 ec, array_ptr, vi.VariableType, loc);
4107 if (converted == null)
4110 data [i].is_object = false;
4112 data [i].converted = converted;
4122 if (e.Type == TypeManager.string_type){
4123 data [i].is_object = false;
4125 data [i].converted = null;
4131 return statement.Resolve (ec);
4134 public override bool Emit (EmitContext ec)
4136 ILGenerator ig = ec.ig;
4138 bool is_ret = false;
4140 for (int i = 0; i < data.Length; i++) {
4141 VariableInfo vi = data [i].vi;
4144 // Case 1: & object.
4146 if (data [i].is_object) {
4148 // Store pointer in pinned location
4150 data [i].expr.Emit (ec);
4151 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4153 is_ret = statement.Emit (ec);
4155 // Clear the pinned variable.
4156 ig.Emit (OpCodes.Ldc_I4_0);
4157 ig.Emit (OpCodes.Conv_U);
4158 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4166 if (data [i].expr.Type.IsArray){
4168 // Store pointer in pinned location
4170 data [i].converted.Emit (ec);
4172 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4174 is_ret = statement.Emit (ec);
4176 // Clear the pinned variable.
4177 ig.Emit (OpCodes.Ldc_I4_0);
4178 ig.Emit (OpCodes.Conv_U);
4179 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4187 if (data [i].expr.Type == TypeManager.string_type){
4188 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4189 TypeManager.MakePinned (pinned_string);
4191 data [i].expr.Emit (ec);
4192 ig.Emit (OpCodes.Stloc, pinned_string);
4194 Expression sptr = new StringPtr (pinned_string, loc);
4195 Expression converted = Expression.ConvertImplicitRequired (
4196 ec, sptr, vi.VariableType, loc);
4198 if (converted == null)
4201 converted.Emit (ec);
4202 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4204 is_ret = statement.Emit (ec);
4206 // Clear the pinned variable
4207 ig.Emit (OpCodes.Ldnull);
4208 ig.Emit (OpCodes.Stloc, pinned_string);
4216 public class Catch {
4217 public readonly string Name;
4218 public readonly Block Block;
4219 public readonly Location Location;
4221 Expression type_expr;
4224 public Catch (Expression type, string name, Block block, Location l)
4232 public Type CatchType {
4238 public bool IsGeneral {
4240 return type_expr == null;
4244 public bool Resolve (EmitContext ec)
4246 if (type_expr != null) {
4247 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4251 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4252 Report.Error (155, Location,
4253 "The type caught or thrown must be derived " +
4254 "from System.Exception");
4260 if (!Block.Resolve (ec))
4267 public class Try : Statement {
4268 public readonly Block Fini, Block;
4269 public readonly ArrayList Specific;
4270 public readonly Catch General;
4273 // specific, general and fini might all be null.
4275 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4277 if (specific == null && general == null){
4278 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4282 this.Specific = specific;
4283 this.General = general;
4288 public override bool Resolve (EmitContext ec)
4292 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4294 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4296 bool old_in_try = ec.InTry;
4299 if (!Block.Resolve (ec))
4302 ec.InTry = old_in_try;
4304 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4306 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4308 foreach (Catch c in Specific){
4309 ec.CurrentBranching.CreateSibling ();
4310 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4312 if (c.Name != null) {
4313 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4315 throw new Exception ();
4320 bool old_in_catch = ec.InCatch;
4323 if (!c.Resolve (ec))
4326 ec.InCatch = old_in_catch;
4328 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4330 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4331 vector.AndLocals (current);
4334 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4336 if (General != null){
4337 ec.CurrentBranching.CreateSibling ();
4338 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4340 bool old_in_catch = ec.InCatch;
4343 if (!General.Resolve (ec))
4346 ec.InCatch = old_in_catch;
4348 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4350 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4351 vector.AndLocals (current);
4354 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4357 ec.CurrentBranching.CreateSiblingForFinally ();
4358 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4360 bool old_in_finally = ec.InFinally;
4361 ec.InFinally = true;
4363 if (!Fini.Resolve (ec))
4366 ec.InFinally = old_in_finally;
4369 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4371 FlowReturns returns = ec.EndFlowBranching ();
4373 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4375 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4376 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4379 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4381 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4386 public override bool Emit (EmitContext ec)
4388 ILGenerator ig = ec.ig;
4390 Label finish = ig.DefineLabel ();;
4394 end = ig.BeginExceptionBlock ();
4395 bool old_in_try = ec.InTry;
4397 returns = Block.Emit (ec);
4398 ec.InTry = old_in_try;
4401 // System.Reflection.Emit provides this automatically:
4402 // ig.Emit (OpCodes.Leave, finish);
4404 bool old_in_catch = ec.InCatch;
4406 DeclSpace ds = ec.DeclSpace;
4408 foreach (Catch c in Specific){
4411 ig.BeginCatchBlock (c.CatchType);
4413 if (c.Name != null){
4414 vi = c.Block.GetVariableInfo (c.Name);
4416 throw new Exception ("Variable does not exist in this block");
4418 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4420 ig.Emit (OpCodes.Pop);
4422 if (!c.Block.Emit (ec))
4426 if (General != null){
4427 ig.BeginCatchBlock (TypeManager.object_type);
4428 ig.Emit (OpCodes.Pop);
4429 if (!General.Block.Emit (ec))
4432 ec.InCatch = old_in_catch;
4434 ig.MarkLabel (finish);
4436 ig.BeginFinallyBlock ();
4437 bool old_in_finally = ec.InFinally;
4438 ec.InFinally = true;
4440 ec.InFinally = old_in_finally;
4443 ig.EndExceptionBlock ();
4446 if (!returns || ec.InTry || ec.InCatch)
4449 // Unfortunately, System.Reflection.Emit automatically emits a leave
4450 // to the end of the finally block. This is a problem if `returns'
4451 // is true since we may jump to a point after the end of the method.
4452 // As a workaround, emit an explicit ret here.
4454 if (ec.ReturnType != null)
4455 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4456 ec.ig.Emit (OpCodes.Ret);
4463 // FIXME: We still do not support the expression variant of the using
4466 public class Using : Statement {
4467 object expression_or_block;
4468 Statement Statement;
4473 Expression [] converted_vars;
4474 ExpressionStatement [] assign;
4476 public Using (object expression_or_block, Statement stmt, Location l)
4478 this.expression_or_block = expression_or_block;
4484 // Resolves for the case of using using a local variable declaration.
4486 bool ResolveLocalVariableDecls (EmitContext ec)
4488 bool need_conv = false;
4489 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4492 if (expr_type == null)
4496 // The type must be an IDisposable or an implicit conversion
4499 converted_vars = new Expression [var_list.Count];
4500 assign = new ExpressionStatement [var_list.Count];
4501 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4502 foreach (DictionaryEntry e in var_list){
4503 Expression var = (Expression) e.Key;
4505 var = var.ResolveLValue (ec, new EmptyExpression ());
4509 converted_vars [i] = Expression.ConvertImplicit (
4510 ec, var, TypeManager.idisposable_type, loc);
4512 if (converted_vars [i] == null)
4520 foreach (DictionaryEntry e in var_list){
4521 LocalVariableReference var = (LocalVariableReference) e.Key;
4522 Expression new_expr = (Expression) e.Value;
4525 a = new Assign (var, new_expr, loc);
4531 converted_vars [i] = var;
4532 assign [i] = (ExpressionStatement) a;
4539 bool ResolveExpression (EmitContext ec)
4541 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4542 conv = Expression.ConvertImplicit (
4543 ec, expr, TypeManager.idisposable_type, loc);
4553 // Emits the code for the case of using using a local variable declaration.
4555 bool EmitLocalVariableDecls (EmitContext ec)
4557 ILGenerator ig = ec.ig;
4560 bool old_in_try = ec.InTry;
4562 for (i = 0; i < assign.Length; i++) {
4563 assign [i].EmitStatement (ec);
4565 ig.BeginExceptionBlock ();
4567 Statement.Emit (ec);
4568 ec.InTry = old_in_try;
4570 bool old_in_finally = ec.InFinally;
4571 ec.InFinally = true;
4572 var_list.Reverse ();
4573 foreach (DictionaryEntry e in var_list){
4574 LocalVariableReference var = (LocalVariableReference) e.Key;
4575 Label skip = ig.DefineLabel ();
4578 ig.BeginFinallyBlock ();
4581 ig.Emit (OpCodes.Brfalse, skip);
4582 converted_vars [i].Emit (ec);
4583 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4584 ig.MarkLabel (skip);
4585 ig.EndExceptionBlock ();
4587 ec.InFinally = old_in_finally;
4592 bool EmitExpression (EmitContext ec)
4595 // Make a copy of the expression and operate on that.
4597 ILGenerator ig = ec.ig;
4598 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4603 ig.Emit (OpCodes.Stloc, local_copy);
4605 bool old_in_try = ec.InTry;
4607 ig.BeginExceptionBlock ();
4608 Statement.Emit (ec);
4609 ec.InTry = old_in_try;
4611 Label skip = ig.DefineLabel ();
4612 bool old_in_finally = ec.InFinally;
4613 ig.BeginFinallyBlock ();
4614 ig.Emit (OpCodes.Ldloc, local_copy);
4615 ig.Emit (OpCodes.Brfalse, skip);
4616 ig.Emit (OpCodes.Ldloc, local_copy);
4617 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4618 ig.MarkLabel (skip);
4619 ec.InFinally = old_in_finally;
4620 ig.EndExceptionBlock ();
4625 public override bool Resolve (EmitContext ec)
4627 if (expression_or_block is DictionaryEntry){
4628 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4629 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4631 if (!ResolveLocalVariableDecls (ec))
4634 } else if (expression_or_block is Expression){
4635 expr = (Expression) expression_or_block;
4637 expr = expr.Resolve (ec);
4641 expr_type = expr.Type;
4643 if (!ResolveExpression (ec))
4647 return Statement.Resolve (ec);
4650 public override bool Emit (EmitContext ec)
4652 if (expression_or_block is DictionaryEntry)
4653 return EmitLocalVariableDecls (ec);
4654 else if (expression_or_block is Expression)
4655 return EmitExpression (ec);
4662 /// Implementation of the foreach C# statement
4664 public class Foreach : Statement {
4666 LocalVariableReference variable;
4668 Statement statement;
4669 ForeachHelperMethods hm;
4670 Expression empty, conv;
4671 Type array_type, element_type;
4674 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4675 Statement stmt, Location l)
4678 this.variable = var;
4684 public override bool Resolve (EmitContext ec)
4686 expr = expr.Resolve (ec);
4690 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4691 if (var_type == null)
4695 // We need an instance variable. Not sure this is the best
4696 // way of doing this.
4698 // FIXME: When we implement propertyaccess, will those turn
4699 // out to return values in ExprClass? I think they should.
4701 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4702 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4703 error1579 (expr.Type);
4707 if (expr.Type.IsArray) {
4708 array_type = expr.Type;
4709 element_type = array_type.GetElementType ();
4711 empty = new EmptyExpression (element_type);
4713 hm = ProbeCollectionType (ec, expr.Type);
4715 error1579 (expr.Type);
4719 array_type = expr.Type;
4720 element_type = hm.element_type;
4722 empty = new EmptyExpression (hm.element_type);
4726 // FIXME: maybe we can apply the same trick we do in the
4727 // array handling to avoid creating empty and conv in some cases.
4729 // Although it is not as important in this case, as the type
4730 // will not likely be object (what the enumerator will return).
4732 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4736 if (variable.ResolveLValue (ec, empty) == null)
4739 if (!statement.Resolve (ec))
4746 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4748 static MethodInfo FetchMethodMoveNext (Type t)
4750 MemberList move_next_list;
4752 move_next_list = TypeContainer.FindMembers (
4753 t, MemberTypes.Method,
4754 BindingFlags.Public | BindingFlags.Instance,
4755 Type.FilterName, "MoveNext");
4756 if (move_next_list.Count == 0)
4759 foreach (MemberInfo m in move_next_list){
4760 MethodInfo mi = (MethodInfo) m;
4763 args = TypeManager.GetArgumentTypes (mi);
4764 if (args != null && args.Length == 0){
4765 if (mi.ReturnType == TypeManager.bool_type)
4773 // Retrieves a `public T get_Current ()' method from the Type `t'
4775 static MethodInfo FetchMethodGetCurrent (Type t)
4777 MemberList move_next_list;
4779 move_next_list = TypeContainer.FindMembers (
4780 t, MemberTypes.Method,
4781 BindingFlags.Public | BindingFlags.Instance,
4782 Type.FilterName, "get_Current");
4783 if (move_next_list.Count == 0)
4786 foreach (MemberInfo m in move_next_list){
4787 MethodInfo mi = (MethodInfo) m;
4790 args = TypeManager.GetArgumentTypes (mi);
4791 if (args != null && args.Length == 0)
4798 // This struct records the helper methods used by the Foreach construct
4800 class ForeachHelperMethods {
4801 public EmitContext ec;
4802 public MethodInfo get_enumerator;
4803 public MethodInfo move_next;
4804 public MethodInfo get_current;
4805 public Type element_type;
4806 public Type enumerator_type;
4807 public bool is_disposable;
4809 public ForeachHelperMethods (EmitContext ec)
4812 this.element_type = TypeManager.object_type;
4813 this.enumerator_type = TypeManager.ienumerator_type;
4814 this.is_disposable = true;
4818 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4823 if (!(m is MethodInfo))
4826 if (m.Name != "GetEnumerator")
4829 MethodInfo mi = (MethodInfo) m;
4830 Type [] args = TypeManager.GetArgumentTypes (mi);
4832 if (args.Length != 0)
4835 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4836 EmitContext ec = hm.ec;
4839 // Check whether GetEnumerator is accessible to us
4841 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4843 Type declaring = mi.DeclaringType;
4844 if (prot == MethodAttributes.Private){
4845 if (declaring != ec.ContainerType)
4847 } else if (prot == MethodAttributes.FamANDAssem){
4848 // If from a different assembly, false
4849 if (!(mi is MethodBuilder))
4852 // Are we being invoked from the same class, or from a derived method?
4854 if (ec.ContainerType != declaring){
4855 if (!ec.ContainerType.IsSubclassOf (declaring))
4858 } else if (prot == MethodAttributes.FamORAssem){
4859 if (!(mi is MethodBuilder ||
4860 ec.ContainerType == declaring ||
4861 ec.ContainerType.IsSubclassOf (declaring)))
4863 } if (prot == MethodAttributes.Family){
4864 if (!(ec.ContainerType == declaring ||
4865 ec.ContainerType.IsSubclassOf (declaring)))
4870 // Ok, we can access it, now make sure that we can do something
4871 // with this `GetEnumerator'
4874 if (mi.ReturnType == TypeManager.ienumerator_type ||
4875 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4876 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4877 hm.move_next = TypeManager.bool_movenext_void;
4878 hm.get_current = TypeManager.object_getcurrent_void;
4883 // Ok, so they dont return an IEnumerable, we will have to
4884 // find if they support the GetEnumerator pattern.
4886 Type return_type = mi.ReturnType;
4888 hm.move_next = FetchMethodMoveNext (return_type);
4889 if (hm.move_next == null)
4891 hm.get_current = FetchMethodGetCurrent (return_type);
4892 if (hm.get_current == null)
4895 hm.element_type = hm.get_current.ReturnType;
4896 hm.enumerator_type = return_type;
4897 hm.is_disposable = TypeManager.ImplementsInterface (
4898 hm.enumerator_type, TypeManager.idisposable_type);
4904 /// This filter is used to find the GetEnumerator method
4905 /// on which IEnumerator operates
4907 static MemberFilter FilterEnumerator;
4911 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4914 void error1579 (Type t)
4916 Report.Error (1579, loc,
4917 "foreach statement cannot operate on variables of type `" +
4918 t.FullName + "' because that class does not provide a " +
4919 " GetEnumerator method or it is inaccessible");
4922 static bool TryType (Type t, ForeachHelperMethods hm)
4926 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4927 BindingFlags.Public | BindingFlags.NonPublic |
4928 BindingFlags.Instance,
4929 FilterEnumerator, hm);
4934 hm.get_enumerator = (MethodInfo) mi [0];
4939 // Looks for a usable GetEnumerator in the Type, and if found returns
4940 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4942 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4944 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4946 if (TryType (t, hm))
4950 // Now try to find the method in the interfaces
4953 Type [] ifaces = t.GetInterfaces ();
4955 foreach (Type i in ifaces){
4956 if (TryType (i, hm))
4961 // Since TypeBuilder.GetInterfaces only returns the interface
4962 // types for this type, we have to keep looping, but once
4963 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4964 // done, because it returns all the types
4966 if ((t is TypeBuilder))
4976 // FIXME: possible optimization.
4977 // We might be able to avoid creating `empty' if the type is the sam
4979 bool EmitCollectionForeach (EmitContext ec)
4981 ILGenerator ig = ec.ig;
4982 LocalBuilder enumerator, disposable;
4984 enumerator = ig.DeclareLocal (hm.enumerator_type);
4985 if (hm.is_disposable)
4986 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4991 // Instantiate the enumerator
4993 if (expr.Type.IsValueType){
4994 if (expr is IMemoryLocation){
4995 IMemoryLocation ml = (IMemoryLocation) expr;
4997 ml.AddressOf (ec, AddressOp.Load);
4999 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5000 " does not implement IMemoryLocation");
5001 ig.Emit (OpCodes.Call, hm.get_enumerator);
5004 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5006 ig.Emit (OpCodes.Stloc, enumerator);
5009 // Protect the code in a try/finalize block, so that
5010 // if the beast implement IDisposable, we get rid of it
5013 bool old_in_try = ec.InTry;
5015 if (hm.is_disposable) {
5016 l = ig.BeginExceptionBlock ();
5020 Label end_try = ig.DefineLabel ();
5022 ig.MarkLabel (ec.LoopBegin);
5023 ig.Emit (OpCodes.Ldloc, enumerator);
5024 ig.Emit (OpCodes.Callvirt, hm.move_next);
5025 ig.Emit (OpCodes.Brfalse, end_try);
5026 ig.Emit (OpCodes.Ldloc, enumerator);
5027 ig.Emit (OpCodes.Callvirt, hm.get_current);
5028 variable.EmitAssign (ec, conv);
5029 statement.Emit (ec);
5030 ig.Emit (OpCodes.Br, ec.LoopBegin);
5031 ig.MarkLabel (end_try);
5032 ec.InTry = old_in_try;
5034 // The runtime provides this for us.
5035 // ig.Emit (OpCodes.Leave, end);
5038 // Now the finally block
5040 if (hm.is_disposable) {
5041 Label end_finally = ig.DefineLabel ();
5042 bool old_in_finally = ec.InFinally;
5043 ec.InFinally = true;
5044 ig.BeginFinallyBlock ();
5046 ig.Emit (OpCodes.Ldloc, enumerator);
5047 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5048 ig.Emit (OpCodes.Stloc, disposable);
5049 ig.Emit (OpCodes.Ldloc, disposable);
5050 ig.Emit (OpCodes.Brfalse, end_finally);
5051 ig.Emit (OpCodes.Ldloc, disposable);
5052 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5053 ig.MarkLabel (end_finally);
5054 ec.InFinally = old_in_finally;
5056 // The runtime generates this anyways.
5057 // ig.Emit (OpCodes.Endfinally);
5059 ig.EndExceptionBlock ();
5062 ig.MarkLabel (ec.LoopEnd);
5067 // FIXME: possible optimization.
5068 // We might be able to avoid creating `empty' if the type is the sam
5070 bool EmitArrayForeach (EmitContext ec)
5072 int rank = array_type.GetArrayRank ();
5073 ILGenerator ig = ec.ig;
5075 LocalBuilder copy = ig.DeclareLocal (array_type);
5078 // Make our copy of the array
5081 ig.Emit (OpCodes.Stloc, copy);
5084 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5088 ig.Emit (OpCodes.Ldc_I4_0);
5089 ig.Emit (OpCodes.Stloc, counter);
5090 test = ig.DefineLabel ();
5091 ig.Emit (OpCodes.Br, test);
5093 loop = ig.DefineLabel ();
5094 ig.MarkLabel (loop);
5096 ig.Emit (OpCodes.Ldloc, copy);
5097 ig.Emit (OpCodes.Ldloc, counter);
5098 ArrayAccess.EmitLoadOpcode (ig, var_type);
5100 variable.EmitAssign (ec, conv);
5102 statement.Emit (ec);
5104 ig.MarkLabel (ec.LoopBegin);
5105 ig.Emit (OpCodes.Ldloc, counter);
5106 ig.Emit (OpCodes.Ldc_I4_1);
5107 ig.Emit (OpCodes.Add);
5108 ig.Emit (OpCodes.Stloc, counter);
5110 ig.MarkLabel (test);
5111 ig.Emit (OpCodes.Ldloc, counter);
5112 ig.Emit (OpCodes.Ldloc, copy);
5113 ig.Emit (OpCodes.Ldlen);
5114 ig.Emit (OpCodes.Conv_I4);
5115 ig.Emit (OpCodes.Blt, loop);
5117 LocalBuilder [] dim_len = new LocalBuilder [rank];
5118 LocalBuilder [] dim_count = new LocalBuilder [rank];
5119 Label [] loop = new Label [rank];
5120 Label [] test = new Label [rank];
5123 for (dim = 0; dim < rank; dim++){
5124 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5125 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5126 test [dim] = ig.DefineLabel ();
5127 loop [dim] = ig.DefineLabel ();
5130 for (dim = 0; dim < rank; dim++){
5131 ig.Emit (OpCodes.Ldloc, copy);
5132 IntLiteral.EmitInt (ig, dim);
5133 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5134 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5137 for (dim = 0; dim < rank; dim++){
5138 ig.Emit (OpCodes.Ldc_I4_0);
5139 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5140 ig.Emit (OpCodes.Br, test [dim]);
5141 ig.MarkLabel (loop [dim]);
5144 ig.Emit (OpCodes.Ldloc, copy);
5145 for (dim = 0; dim < rank; dim++)
5146 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5149 // FIXME: Maybe we can cache the computation of `get'?
5151 Type [] args = new Type [rank];
5154 for (int i = 0; i < rank; i++)
5155 args [i] = TypeManager.int32_type;
5157 ModuleBuilder mb = CodeGen.ModuleBuilder;
5158 get = mb.GetArrayMethod (
5160 CallingConventions.HasThis| CallingConventions.Standard,
5162 ig.Emit (OpCodes.Call, get);
5163 variable.EmitAssign (ec, conv);
5164 statement.Emit (ec);
5165 ig.MarkLabel (ec.LoopBegin);
5166 for (dim = rank - 1; dim >= 0; dim--){
5167 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5168 ig.Emit (OpCodes.Ldc_I4_1);
5169 ig.Emit (OpCodes.Add);
5170 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5172 ig.MarkLabel (test [dim]);
5173 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5174 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5175 ig.Emit (OpCodes.Blt, loop [dim]);
5178 ig.MarkLabel (ec.LoopEnd);
5183 public override bool Emit (EmitContext ec)
5187 ILGenerator ig = ec.ig;
5189 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5190 bool old_inloop = ec.InLoop;
5191 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5192 ec.LoopBegin = ig.DefineLabel ();
5193 ec.LoopEnd = ig.DefineLabel ();
5195 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5198 ret_val = EmitCollectionForeach (ec);
5200 ret_val = EmitArrayForeach (ec);
5202 ec.LoopBegin = old_begin;
5203 ec.LoopEnd = old_end;
5204 ec.InLoop = old_inloop;
5205 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;