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");
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");
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)
242 if (!EmbeddedStatement.Resolve (ec))
245 expr = ResolveBoolean (ec, expr, loc);
252 public override bool Emit (EmitContext ec)
254 ILGenerator ig = ec.ig;
255 Label loop = ig.DefineLabel ();
256 Label old_begin = ec.LoopBegin;
257 Label old_end = ec.LoopEnd;
258 bool old_inloop = ec.InLoop;
259 bool old_breaks = ec.Breaks;
260 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
262 ec.LoopBegin = ig.DefineLabel ();
263 ec.LoopEnd = ig.DefineLabel ();
265 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
269 EmbeddedStatement.Emit (ec);
270 bool breaks = ec.Breaks;
271 ig.MarkLabel (ec.LoopBegin);
274 // Dead code elimination
276 if (expr is BoolConstant){
277 bool res = ((BoolConstant) expr).Value;
280 ec.ig.Emit (OpCodes.Br, loop);
282 EmitBoolExpression (ec, expr, loop, true);
284 ig.MarkLabel (ec.LoopEnd);
286 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
287 ec.LoopBegin = old_begin;
288 ec.LoopEnd = old_end;
289 ec.InLoop = old_inloop;
290 ec.Breaks = old_breaks;
293 // Inform whether we are infinite or not
295 if (expr is BoolConstant){
296 BoolConstant bc = (BoolConstant) expr;
298 if (bc.Value == true)
299 return breaks == false;
306 public class While : Statement {
307 public Expression expr;
308 public readonly Statement Statement;
310 public While (Expression boolExpr, Statement statement, Location l)
312 this.expr = boolExpr;
313 Statement = statement;
317 public override bool Resolve (EmitContext ec)
319 expr = ResolveBoolean (ec, expr, loc);
323 return Statement.Resolve (ec);
326 public override bool Emit (EmitContext ec)
328 ILGenerator ig = ec.ig;
329 Label old_begin = ec.LoopBegin;
330 Label old_end = ec.LoopEnd;
331 bool old_inloop = ec.InLoop;
332 bool old_breaks = ec.Breaks;
333 Label while_loop = ig.DefineLabel ();
334 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
337 ec.LoopBegin = ig.DefineLabel ();
338 ec.LoopEnd = ig.DefineLabel ();
340 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
342 ig.Emit (OpCodes.Br, ec.LoopBegin);
343 ig.MarkLabel (while_loop);
346 // Inform whether we are infinite or not
348 if (expr is BoolConstant){
349 BoolConstant bc = (BoolConstant) expr;
351 ig.MarkLabel (ec.LoopBegin);
352 if (bc.Value == false){
353 Warning_DeadCodeFound (Statement.loc);
361 ig.Emit (OpCodes.Br, ec.LoopBegin);
364 // Inform that we are infinite (ie, `we return'), only
365 // if we do not `break' inside the code.
367 ret = breaks == false;
369 ig.MarkLabel (ec.LoopEnd);
373 ig.MarkLabel (ec.LoopBegin);
375 EmitBoolExpression (ec, expr, while_loop, true);
376 ig.MarkLabel (ec.LoopEnd);
381 ec.LoopBegin = old_begin;
382 ec.LoopEnd = old_end;
383 ec.InLoop = old_inloop;
384 ec.Breaks = old_breaks;
385 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
391 public class For : Statement {
393 readonly Statement InitStatement;
394 readonly Statement Increment;
395 readonly Statement Statement;
397 public For (Statement initStatement,
403 InitStatement = initStatement;
405 Increment = increment;
406 Statement = statement;
410 public override bool Resolve (EmitContext ec)
414 if (InitStatement != null){
415 if (!InitStatement.Resolve (ec))
420 Test = ResolveBoolean (ec, Test, loc);
425 if (Increment != null){
426 if (!Increment.Resolve (ec))
430 return Statement.Resolve (ec) && ok;
433 public override bool Emit (EmitContext ec)
435 ILGenerator ig = ec.ig;
436 Label old_begin = ec.LoopBegin;
437 Label old_end = ec.LoopEnd;
438 bool old_inloop = ec.InLoop;
439 bool old_breaks = ec.Breaks;
440 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
441 Label loop = ig.DefineLabel ();
442 Label test = ig.DefineLabel ();
444 if (InitStatement != null)
445 if (! (InitStatement is EmptyStatement))
446 InitStatement.Emit (ec);
448 ec.LoopBegin = ig.DefineLabel ();
449 ec.LoopEnd = ig.DefineLabel ();
451 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
453 ig.Emit (OpCodes.Br, test);
457 bool breaks = ec.Breaks;
459 ig.MarkLabel (ec.LoopBegin);
460 if (!(Increment is EmptyStatement))
465 // If test is null, there is no test, and we are just
469 EmitBoolExpression (ec, Test, loop, true);
471 ig.Emit (OpCodes.Br, loop);
472 ig.MarkLabel (ec.LoopEnd);
474 ec.LoopBegin = old_begin;
475 ec.LoopEnd = old_end;
476 ec.InLoop = old_inloop;
477 ec.Breaks = old_breaks;
478 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
481 // Inform whether we are infinite or not
484 if (Test is BoolConstant){
485 BoolConstant bc = (BoolConstant) Test;
488 return breaks == false;
496 public class StatementExpression : Statement {
499 public StatementExpression (ExpressionStatement expr, Location l)
505 public override bool Resolve (EmitContext ec)
507 expr = (Expression) expr.Resolve (ec);
511 public override bool Emit (EmitContext ec)
513 ILGenerator ig = ec.ig;
515 if (expr is ExpressionStatement)
516 ((ExpressionStatement) expr).EmitStatement (ec);
519 ig.Emit (OpCodes.Pop);
525 public override string ToString ()
527 return "StatementExpression (" + expr + ")";
532 /// Implements the return statement
534 public class Return : Statement {
535 public Expression Expr;
537 public Return (Expression expr, Location l)
543 public override bool Resolve (EmitContext ec)
546 Expr = Expr.Resolve (ec);
551 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
553 if (ec.CurrentBranching.InTryBlock ())
554 ec.CurrentBranching.AddFinallyVector (vector);
556 vector.Returns = FlowReturns.ALWAYS;
557 vector.Breaks = FlowReturns.ALWAYS;
562 public override bool Emit (EmitContext ec)
565 Report.Error (157,loc,"Control can not leave the body of the finally block");
569 if (ec.ReturnType == null){
571 Report.Error (127, loc, "Return with a value not allowed here");
576 Report.Error (126, loc, "An object of type `" +
577 TypeManager.CSharpName (ec.ReturnType) + "' is " +
578 "expected for the return statement");
582 if (Expr.Type != ec.ReturnType)
583 Expr = Expression.ConvertImplicitRequired (
584 ec, Expr, ec.ReturnType, loc);
591 if (ec.InTry || ec.InCatch)
592 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
595 if (ec.InTry || ec.InCatch) {
596 if (!ec.HasReturnLabel) {
597 ec.ReturnLabel = ec.ig.DefineLabel ();
598 ec.HasReturnLabel = true;
600 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
602 ec.ig.Emit (OpCodes.Ret);
608 public class Goto : Statement {
611 LabeledStatement label;
613 public override bool Resolve (EmitContext ec)
615 label = block.LookupLabel (target);
619 "No such label `" + target + "' in this scope");
623 // If this is a forward goto.
624 if (!label.IsDefined)
625 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
627 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
632 public Goto (Block parent_block, string label, Location l)
634 block = parent_block;
639 public string Target {
645 public override bool Emit (EmitContext ec)
647 Label l = label.LabelTarget (ec);
648 ec.ig.Emit (OpCodes.Br, l);
654 public class LabeledStatement : Statement {
655 public readonly Location Location;
663 public LabeledStatement (string label_name, Location l)
665 this.label_name = label_name;
669 public Label LabelTarget (EmitContext ec)
673 label = ec.ig.DefineLabel ();
679 public bool IsDefined {
685 public bool HasBeenReferenced {
691 public void AddUsageVector (FlowBranching.UsageVector vector)
694 vectors = new ArrayList ();
696 vectors.Add (vector.Clone ());
699 public override bool Resolve (EmitContext ec)
702 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
709 public override bool Emit (EmitContext ec)
712 ec.ig.MarkLabel (label);
720 /// `goto default' statement
722 public class GotoDefault : Statement {
724 public GotoDefault (Location l)
729 public override bool Resolve (EmitContext ec)
731 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
732 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
736 public override bool Emit (EmitContext ec)
738 if (ec.Switch == null){
739 Report.Error (153, loc, "goto default is only valid in a switch statement");
743 if (!ec.Switch.GotDefault){
744 Report.Error (159, loc, "No default target on switch statement");
747 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
753 /// `goto case' statement
755 public class GotoCase : Statement {
759 public GotoCase (Expression e, Location l)
765 public override bool Resolve (EmitContext ec)
767 if (ec.Switch == null){
768 Report.Error (153, loc, "goto case is only valid in a switch statement");
772 expr = expr.Resolve (ec);
776 if (!(expr is Constant)){
777 Report.Error (159, loc, "Target expression for goto case is not constant");
781 object val = Expression.ConvertIntLiteral (
782 (Constant) expr, ec.Switch.SwitchType, loc);
787 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
792 "No such label 'case " + val + "': for the goto case");
795 label = sl.ILLabelCode;
797 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
798 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
802 public override bool Emit (EmitContext ec)
804 ec.ig.Emit (OpCodes.Br, label);
809 public class Throw : Statement {
812 public Throw (Expression expr, Location l)
818 public override bool Resolve (EmitContext ec)
821 expr = expr.Resolve (ec);
825 ExprClass eclass = expr.eclass;
827 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
828 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
829 expr.Error118 ("value, variable, property or indexer access ");
835 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)) {
836 Report.Error (155, loc,
837 "The type caught or thrown must be derived " +
838 "from System.Exception");
843 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
844 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
848 public override bool Emit (EmitContext ec)
852 ec.ig.Emit (OpCodes.Rethrow);
856 "A throw statement with no argument is only " +
857 "allowed in a catch clause");
864 ec.ig.Emit (OpCodes.Throw);
870 public class Break : Statement {
872 public Break (Location l)
877 public override bool Resolve (EmitContext ec)
879 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
883 public override bool Emit (EmitContext ec)
885 ILGenerator ig = ec.ig;
887 if (ec.InLoop == false && ec.Switch == null){
888 Report.Error (139, loc, "No enclosing loop or switch to continue to");
893 if (ec.InTry || ec.InCatch)
894 ig.Emit (OpCodes.Leave, ec.LoopEnd);
896 ig.Emit (OpCodes.Br, ec.LoopEnd);
902 public class Continue : Statement {
904 public Continue (Location l)
909 public override bool Resolve (EmitContext ec)
911 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
915 public override bool Emit (EmitContext ec)
917 Label begin = ec.LoopBegin;
920 Report.Error (139, loc, "No enclosing loop to continue to");
925 // UGH: Non trivial. This Br might cross a try/catch boundary
929 // try { ... } catch { continue; }
933 // try {} catch { while () { continue; }}
935 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
936 ec.ig.Emit (OpCodes.Leave, begin);
937 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
938 throw new Exception ("Should never happen");
940 ec.ig.Emit (OpCodes.Br, begin);
946 // This is used in the control flow analysis code to specify whether the
947 // current code block may return to its enclosing block before reaching
950 public enum FlowReturns {
951 // It can never return.
954 // This means that the block contains a conditional return statement
958 // The code always returns, ie. there's an unconditional return / break
962 // The code always throws an exception.
965 // The current code block is unreachable. This happens if it's immediately
966 // following a FlowReturns.ALWAYS block.
971 // This is a special bit vector which can inherit from another bit vector doing a
972 // copy-on-write strategy. The inherited vector may have a smaller size than the
975 public class MyBitVector {
976 public readonly int Count;
977 public readonly MyBitVector InheritsFrom;
982 public MyBitVector (int Count)
986 public MyBitVector (MyBitVector InheritsFrom, int Count)
988 this.InheritsFrom = InheritsFrom;
993 // Checks whether this bit vector has been modified. After setting this to true,
994 // we won't use the inherited vector anymore, but our own copy of it.
996 public bool IsDirty {
1003 initialize_vector ();
1008 // Get/set bit `index' in the bit vector.
1010 public bool this [int index]
1014 throw new ArgumentOutOfRangeException ();
1016 // We're doing a "copy-on-write" strategy here; as long
1017 // as nobody writes to the array, we can use our parent's
1018 // copy instead of duplicating the vector.
1021 return vector [index];
1022 else if (InheritsFrom != null) {
1023 BitArray inherited = InheritsFrom.Vector;
1025 if (index < inherited.Count)
1026 return inherited [index];
1035 throw new ArgumentOutOfRangeException ();
1037 // Only copy the vector if we're actually modifying it.
1039 if (this [index] != value) {
1040 initialize_vector ();
1042 vector [index] = value;
1048 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1049 // copy of the bit vector.
1051 public static explicit operator BitArray (MyBitVector vector)
1053 vector.initialize_vector ();
1054 return vector.Vector;
1058 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1059 // different size than the current one.
1061 public void Or (MyBitVector new_vector)
1063 BitArray new_array = new_vector.Vector;
1065 initialize_vector ();
1068 if (vector.Count < new_array.Count)
1069 upper = vector.Count;
1071 upper = new_array.Count;
1073 for (int i = 0; i < upper; i++)
1074 vector [i] = vector [i] | new_array [i];
1078 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1079 // a different size than the current one.
1081 public void And (MyBitVector new_vector)
1083 BitArray new_array = new_vector.Vector;
1085 initialize_vector ();
1088 if (vector.Count < new_array.Count)
1089 lower = upper = vector.Count;
1091 lower = new_array.Count;
1092 upper = vector.Count;
1095 for (int i = 0; i < lower; i++)
1096 vector [i] = vector [i] & new_array [i];
1098 for (int i = lower; i < upper; i++)
1103 // This does a deep copy of the bit vector.
1105 public MyBitVector Clone ()
1107 MyBitVector retval = new MyBitVector (Count);
1109 retval.Vector = Vector;
1118 else if (!is_dirty && (InheritsFrom != null))
1119 return InheritsFrom.Vector;
1121 initialize_vector ();
1127 initialize_vector ();
1129 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1130 vector [i] = value [i];
1134 void initialize_vector ()
1139 vector = new BitArray (Count, false);
1140 if (InheritsFrom != null)
1141 Vector = InheritsFrom.Vector;
1146 public override string ToString ()
1148 StringBuilder sb = new StringBuilder ("MyBitVector (");
1150 BitArray vector = Vector;
1154 sb.Append ("INHERITED - ");
1155 for (int i = 0; i < vector.Count; i++) {
1158 sb.Append (vector [i]);
1162 return sb.ToString ();
1167 // The type of a FlowBranching.
1169 public enum FlowBranchingType {
1170 // Normal (conditional or toplevel) block.
1184 // A new instance of this class is created every time a new block is resolved
1185 // and if there's branching in the block's control flow.
1187 public class FlowBranching {
1189 // The type of this flow branching.
1191 public readonly FlowBranchingType Type;
1194 // The block this branching is contained in. This may be null if it's not
1195 // a top-level block and it doesn't declare any local variables.
1197 public readonly Block Block;
1200 // The parent of this branching or null if this is the top-block.
1202 public readonly FlowBranching Parent;
1205 // Start-Location of this flow branching.
1207 public readonly Location Location;
1210 // A list of UsageVectors. A new vector is added each time control flow may
1211 // take a different path.
1213 public ArrayList Siblings;
1218 InternalParameters param_info;
1221 ArrayList finally_vectors;
1223 static int next_id = 0;
1227 // Performs an `And' operation on the FlowReturns status
1228 // (for instance, a block only returns ALWAYS if all its siblings
1231 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1233 if (b == FlowReturns.UNREACHABLE)
1237 case FlowReturns.NEVER:
1238 if (b == FlowReturns.NEVER)
1239 return FlowReturns.NEVER;
1241 return FlowReturns.SOMETIMES;
1243 case FlowReturns.SOMETIMES:
1244 return FlowReturns.SOMETIMES;
1246 case FlowReturns.ALWAYS:
1247 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1248 return FlowReturns.ALWAYS;
1250 return FlowReturns.SOMETIMES;
1252 case FlowReturns.EXCEPTION:
1253 if (b == FlowReturns.EXCEPTION)
1254 return FlowReturns.EXCEPTION;
1255 else if (b == FlowReturns.ALWAYS)
1256 return FlowReturns.ALWAYS;
1258 return FlowReturns.SOMETIMES;
1265 // The vector contains a BitArray with information about which local variables
1266 // and parameters are already initialized at the current code position.
1268 public class UsageVector {
1270 // If this is true, then the usage vector has been modified and must be
1271 // merged when we're done with this branching.
1273 public bool IsDirty;
1276 // The number of parameters in this block.
1278 public readonly int CountParameters;
1281 // The number of locals in this block.
1283 public readonly int CountLocals;
1286 // If not null, then we inherit our state from this vector and do a
1287 // copy-on-write. If null, then we're the first sibling in a top-level
1288 // block and inherit from the empty vector.
1290 public readonly UsageVector InheritsFrom;
1295 MyBitVector locals, parameters;
1296 FlowReturns real_returns, real_breaks;
1297 bool returns_set, breaks_set, is_finally;
1299 static int next_id = 0;
1303 // Normally, you should not use any of these constructors.
1305 public UsageVector (UsageVector parent, int num_params, int num_locals)
1307 this.InheritsFrom = parent;
1308 this.CountParameters = num_params;
1309 this.CountLocals = num_locals;
1310 this.real_returns = FlowReturns.NEVER;
1311 this.real_breaks = FlowReturns.NEVER;
1313 if (parent != null) {
1314 locals = new MyBitVector (parent.locals, CountLocals);
1316 parameters = new MyBitVector (parent.parameters, num_params);
1318 locals = new MyBitVector (null, CountLocals);
1320 parameters = new MyBitVector (null, num_params);
1326 public UsageVector (UsageVector parent)
1327 : this (parent, parent.CountParameters, parent.CountLocals)
1331 // This does a deep copy of the usage vector.
1333 public UsageVector Clone ()
1335 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1337 retval.locals = locals.Clone ();
1338 if (parameters != null)
1339 retval.parameters = parameters.Clone ();
1340 retval.real_returns = real_returns;
1341 retval.real_breaks = real_breaks;
1347 // State of parameter `number'.
1349 public bool this [int number]
1354 else if (number == 0)
1355 throw new ArgumentException ();
1357 return parameters [number - 1];
1363 else if (number == 0)
1364 throw new ArgumentException ();
1366 parameters [number - 1] = value;
1371 // State of the local variable `vi'.
1373 public bool this [VariableInfo vi]
1376 if (vi.Number == -1)
1378 else if (vi.Number == 0)
1379 throw new ArgumentException ();
1381 return locals [vi.Number - 1];
1385 if (vi.Number == -1)
1387 else if (vi.Number == 0)
1388 throw new ArgumentException ();
1390 locals [vi.Number - 1] = value;
1395 // Specifies when the current block returns.
1397 public FlowReturns Returns {
1399 return real_returns;
1403 real_returns = value;
1409 // Specifies whether control may return to our containing block
1410 // before reaching the end of this block. This happens if there
1411 // is a break/continue/goto/return in it.
1413 public FlowReturns Breaks {
1419 real_breaks = value;
1425 // Merge a child branching.
1427 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1429 MyBitVector new_locals = null;
1430 MyBitVector new_params = null;
1432 FlowReturns new_returns = FlowReturns.NEVER;
1433 FlowReturns new_breaks = FlowReturns.NEVER;
1434 bool new_returns_set = false, new_breaks_set = false;
1437 Report.Debug (1, "MERGING CHILDREN", branching, this);
1439 foreach (UsageVector child in children) {
1440 Report.Debug (1, " MERGING CHILD", child);
1442 // If Returns is already set, perform an `And' operation on it,
1443 // otherwise just set just.
1444 if (!new_returns_set) {
1445 new_returns = child.Returns;
1446 new_returns_set = true;
1448 new_returns = AndFlowReturns (new_returns, child.Returns);
1450 // If Breaks is already set, perform an `And' operation on it,
1451 // otherwise just set just.
1452 if (!new_breaks_set) {
1453 new_breaks = child.Breaks;
1454 new_breaks_set = true;
1456 new_breaks = AndFlowReturns (new_breaks, child.Breaks);
1458 // Ignore unreachable children.
1459 if (child.Returns == FlowReturns.UNREACHABLE)
1462 // If we're a switch section, `break' won't leave the current
1463 // branching (NOTE: the type check here means that we're "a"
1464 // switch section, not that we're "in" a switch section!).
1465 breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1466 child.Returns : child.Breaks;
1468 // A local variable is initialized after a flow branching if it
1469 // has been initialized in all its branches which do neither
1470 // always return or always throw an exception.
1472 // If a branch may return, but does not always return, then we
1473 // can treat it like a never-returning branch here: control will
1474 // only reach the code position after the branching if we did not
1477 // It's important to distinguish between always and sometimes
1478 // returning branches here:
1481 // 2 if (something) {
1485 // 6 Console.WriteLine (a);
1487 // The if block in lines 3-4 always returns, so we must not look
1488 // at the initialization of `a' in line 4 - thus it'll still be
1489 // uninitialized in line 6.
1491 // On the other hand, the following is allowed:
1498 // 6 Console.WriteLine (a);
1500 // Here, `a' is initialized in line 3 and we must not look at
1501 // line 5 since it always returns.
1503 if ((breaks != FlowReturns.EXCEPTION) &&
1504 (breaks != FlowReturns.ALWAYS)) {
1505 if (new_locals != null)
1506 new_locals.And (child.locals);
1508 new_locals = locals.Clone ();
1509 new_locals.Or (child.locals);
1513 // An `out' parameter must be assigned in all branches which do
1514 // not always throw an exception.
1515 if (!child.is_finally && (child.Returns != FlowReturns.EXCEPTION)) {
1516 if (parameters != null) {
1517 if (new_params != null)
1518 new_params.And (child.parameters);
1520 new_params = parameters.Clone ();
1521 new_params.Or (child.parameters);
1526 // If we always return, check whether all `out' parameters have
1528 if ((child.Returns == FlowReturns.ALWAYS) && (child.parameters != null)) {
1529 branching.CheckOutParameters (
1530 child.parameters, branching.Location);
1534 // Set new `Returns' status.
1536 Returns = new_returns;
1539 Returns = AndFlowReturns (Returns, new_returns);
1542 // We've now either reached the point after the branching or we will
1543 // never get there since we always return or always throw an exception.
1545 // If we can reach the point after the branching, mark all locals and
1546 // parameters as initialized which have been initialized in all branches
1547 // we need to look at (see above).
1550 breaks = (branching.Type == FlowBranchingType.SWITCH_SECTION) ?
1553 if ((new_locals != null) &&
1554 ((breaks == FlowReturns.NEVER) || (breaks == FlowReturns.SOMETIMES))) {
1555 locals.Or (new_locals);
1558 if ((new_params != null) && (Breaks == FlowReturns.NEVER))
1559 parameters.Or (new_params);
1562 // If we may have returned (this only happens if there was a reachable
1563 // `return' statement in one of the branches), then we may return to our
1564 // parent block before reaching the end of the block, so set `Breaks'.
1567 if ((Returns != FlowReturns.NEVER) && (Returns != FlowReturns.SOMETIMES)) {
1568 real_breaks = Returns;
1572 Report.Debug (1, "MERGING CHILDREN DONE", new_params, new_locals,
1573 new_returns, new_breaks, this);
1579 // Tells control flow analysis that the current code position may be reached with
1580 // a forward jump from any of the origins listed in `origin_vectors' which is a
1581 // list of UsageVectors.
1583 // This is used when resolving forward gotos - in the following example, the
1584 // variable `a' is uninitialized in line 8 becase this line may be reached via
1585 // the goto in line 4:
1595 // 8 Console.WriteLine (a);
1598 public void MergeJumpOrigins (ICollection origin_vectors)
1600 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1602 real_breaks = FlowReturns.NEVER;
1605 foreach (UsageVector vector in origin_vectors) {
1606 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1608 locals.And (vector.locals);
1609 if (parameters != null)
1610 parameters.And (vector.parameters);
1611 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1614 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1618 // This is used at the beginning of a finally block if there were
1619 // any return statements in the try block or one of the catch blocks.
1621 public void MergeFinallyOrigins (ICollection finally_vectors)
1623 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1625 real_breaks = FlowReturns.NEVER;
1628 foreach (UsageVector vector in finally_vectors) {
1629 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1631 if (parameters != null)
1632 parameters.And (vector.parameters);
1633 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1638 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1642 // Performs an `or' operation on the locals and the parameters.
1644 public void Or (UsageVector new_vector)
1646 locals.Or (new_vector.locals);
1647 if (parameters != null)
1648 parameters.Or (new_vector.parameters);
1652 // Performs an `and' operation on the locals.
1654 public void AndLocals (UsageVector new_vector)
1656 locals.And (new_vector.locals);
1660 // Returns a deep copy of the parameters.
1662 public MyBitVector Parameters {
1664 if (parameters != null)
1665 return parameters.Clone ();
1672 // Returns a deep copy of the locals.
1674 public MyBitVector Locals {
1676 return locals.Clone ();
1684 public override string ToString ()
1686 StringBuilder sb = new StringBuilder ();
1688 sb.Append ("Vector (");
1691 sb.Append (Returns);
1694 if (parameters != null) {
1696 sb.Append (parameters);
1702 return sb.ToString ();
1706 FlowBranching (FlowBranchingType type, Location loc)
1708 this.Siblings = new ArrayList ();
1710 this.Location = loc;
1716 // Creates a new flow branching for `block'.
1717 // This is used from Block.Resolve to create the top-level branching of
1720 public FlowBranching (Block block, InternalParameters ip, Location loc)
1721 : this (FlowBranchingType.BLOCK, loc)
1727 param_map = new int [(param_info != null) ? param_info.Count : 0];
1730 for (int i = 0; i < param_map.Length; i++) {
1731 Parameter.Modifier mod = param_info.ParameterModifier (i);
1733 if ((mod & Parameter.Modifier.OUT) == 0)
1736 param_map [i] = ++num_params;
1739 Siblings = new ArrayList ();
1740 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1744 // Creates a new flow branching which is contained in `parent'.
1745 // You should only pass non-null for the `block' argument if this block
1746 // introduces any new variables - in this case, we need to create a new
1747 // usage vector with a different size than our parent's one.
1749 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1750 Block block, Location loc)
1756 if (parent != null) {
1757 param_info = parent.param_info;
1758 param_map = parent.param_map;
1759 num_params = parent.num_params;
1764 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1765 Block.CountVariables);
1767 vector = new UsageVector (Parent.CurrentUsageVector);
1769 Siblings.Add (vector);
1772 case FlowBranchingType.EXCEPTION:
1773 finally_vectors = new ArrayList ();
1782 // Returns the branching's current usage vector.
1784 public UsageVector CurrentUsageVector
1787 return (UsageVector) Siblings [Siblings.Count - 1];
1792 // Creates a sibling of the current usage vector.
1794 public void CreateSibling ()
1796 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1798 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1802 // Creates a sibling for a `finally' block.
1804 public void CreateSiblingForFinally ()
1806 if (Type != FlowBranchingType.EXCEPTION)
1807 throw new NotSupportedException ();
1811 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1815 // Check whether all `out' parameters have been assigned.
1817 public void CheckOutParameters (MyBitVector parameters, Location loc)
1822 for (int i = 0; i < param_map.Length; i++) {
1823 if (param_map [i] == 0)
1826 if (!parameters [param_map [i] - 1]) {
1828 177, loc, "The out parameter `" +
1829 param_info.ParameterName (i) + "` must be " +
1830 "assigned before control leave the current method.");
1837 // Merge a child branching.
1839 public FlowReturns MergeChild (FlowBranching child)
1841 return CurrentUsageVector.MergeChildren (child, child.Siblings);
1845 // Does the toplevel merging.
1847 public FlowReturns MergeTopBlock ()
1849 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1850 throw new NotSupportedException ();
1852 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1854 vector.MergeChildren (this, Siblings);
1857 Siblings.Add (vector);
1859 Report.Debug (1, "MERGING TOP BLOCK", vector);
1861 if (vector.Returns != FlowReturns.EXCEPTION)
1862 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1864 return vector.Returns;
1867 public bool InTryBlock ()
1869 if (finally_vectors != null)
1871 else if (Parent != null)
1872 return Parent.InTryBlock ();
1877 public void AddFinallyVector (UsageVector vector)
1879 if (finally_vectors != null) {
1880 finally_vectors.Add (vector.Clone ());
1885 Parent.AddFinallyVector (vector);
1887 throw new NotSupportedException ();
1890 public bool IsVariableAssigned (VariableInfo vi)
1892 Report.Debug (2, "CHECK VARIABLE ACCESS", this, vi);
1894 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1897 return CurrentUsageVector [vi];
1900 public void SetVariableAssigned (VariableInfo vi)
1902 Report.Debug (2, "SET VARIABLE ACCESS", this, vi, CurrentUsageVector);
1904 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1907 CurrentUsageVector [vi] = true;
1910 public bool IsParameterAssigned (int number)
1912 Report.Debug (2, "IS PARAMETER ASSIGNED", this, number);
1914 if (param_map [number] == 0)
1917 return CurrentUsageVector [param_map [number]];
1920 public void SetParameterAssigned (int number)
1922 Report.Debug (2, "SET PARAMETER ACCESS", this, number, param_map [number],
1923 CurrentUsageVector);
1925 if (param_map [number] == 0)
1928 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
1929 CurrentUsageVector [param_map [number]] = true;
1932 public override string ToString ()
1934 StringBuilder sb = new StringBuilder ("FlowBranching (");
1939 if (Block != null) {
1941 sb.Append (Block.ID);
1943 sb.Append (Block.StartLocation);
1946 sb.Append (Siblings.Count);
1948 sb.Append (CurrentUsageVector);
1950 return sb.ToString ();
1954 public class VariableInfo {
1955 public Expression Type;
1956 public LocalBuilder LocalBuilder;
1957 public Type VariableType;
1958 public readonly Location Location;
1959 public readonly int Block;
1964 public bool Assigned;
1965 public bool ReadOnly;
1967 public VariableInfo (Expression type, int block, Location l)
1971 LocalBuilder = null;
1975 public void MakePinned ()
1977 TypeManager.MakePinned (LocalBuilder);
1980 public override string ToString ()
1982 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
1987 /// Block represents a C# block.
1991 /// This class is used in a number of places: either to represent
1992 /// explicit blocks that the programmer places or implicit blocks.
1994 /// Implicit blocks are used as labels or to introduce variable
1997 public class Block : Statement {
1998 public readonly Block Parent;
1999 public readonly bool Implicit;
2000 public readonly Location StartLocation;
2001 public Location EndLocation;
2004 // The statements in this block
2006 ArrayList statements;
2009 // An array of Blocks. We keep track of children just
2010 // to generate the local variable declarations.
2012 // Statements and child statements are handled through the
2018 // Labels. (label, block) pairs.
2023 // Keeps track of (name, type) pairs
2025 Hashtable variables;
2028 // Keeps track of constants
2029 Hashtable constants;
2032 // Maps variable names to ILGenerator.LocalBuilders
2034 Hashtable local_builders;
2042 public Block (Block parent)
2043 : this (parent, false, Location.Null, Location.Null)
2046 public Block (Block parent, bool implicit_block)
2047 : this (parent, implicit_block, Location.Null, Location.Null)
2050 public Block (Block parent, Location start, Location end)
2051 : this (parent, false, start, end)
2054 public Block (Block parent, bool implicit_block, Location start, Location end)
2057 parent.AddChild (this);
2059 this.Parent = parent;
2060 this.Implicit = implicit_block;
2061 this.StartLocation = start;
2062 this.EndLocation = end;
2065 statements = new ArrayList ();
2077 void AddChild (Block b)
2079 if (children == null)
2080 children = new ArrayList ();
2085 public void SetEndLocation (Location loc)
2091 /// Adds a label to the current block.
2095 /// false if the name already exists in this block. true
2099 public bool AddLabel (string name, LabeledStatement target)
2102 labels = new Hashtable ();
2103 if (labels.Contains (name))
2106 labels.Add (name, target);
2110 public LabeledStatement LookupLabel (string name)
2112 if (labels != null){
2113 if (labels.Contains (name))
2114 return ((LabeledStatement) labels [name]);
2118 return Parent.LookupLabel (name);
2123 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2125 if (variables == null)
2126 variables = new Hashtable ();
2128 VariableInfo vi = GetVariableInfo (name);
2131 Report.Error (136, l, "A local variable named `" + name + "' " +
2132 "cannot be declared in this scope since it would " +
2133 "give a different meaning to `" + name + "', which " +
2134 "is already used in a `parent or current' scope to " +
2135 "denote something else");
2137 Report.Error (128, l, "A local variable `" + name + "' is already " +
2138 "defined in this scope");
2144 Parameter p = pars.GetParameterByName (name, out idx);
2146 Report.Error (136, l, "A local variable named `" + name + "' " +
2147 "cannot be declared in this scope since it would " +
2148 "give a different meaning to `" + name + "', which " +
2149 "is already used in a `parent or current' scope to " +
2150 "denote something else");
2155 vi = new VariableInfo (type, ID, l);
2157 variables.Add (name, vi);
2159 if (variables_initialized)
2160 throw new Exception ();
2162 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2166 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2168 if (AddVariable (type, name, pars, l) == null)
2171 if (constants == null)
2172 constants = new Hashtable ();
2174 constants.Add (name, value);
2178 public Hashtable Variables {
2184 public VariableInfo GetVariableInfo (string name)
2186 if (variables != null) {
2188 temp = variables [name];
2191 return (VariableInfo) temp;
2196 return Parent.GetVariableInfo (name);
2201 public Expression GetVariableType (string name)
2203 VariableInfo vi = GetVariableInfo (name);
2211 public Expression GetConstantExpression (string name)
2213 if (constants != null) {
2215 temp = constants [name];
2218 return (Expression) temp;
2222 return Parent.GetConstantExpression (name);
2228 /// True if the variable named @name has been defined
2231 public bool IsVariableDefined (string name)
2233 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2234 if (variables != null) {
2235 if (variables.Contains (name))
2240 return Parent.IsVariableDefined (name);
2246 /// True if the variable named @name is a constant
2248 public bool IsConstant (string name)
2250 Expression e = null;
2252 e = GetConstantExpression (name);
2258 /// Use to fetch the statement associated with this label
2260 public Statement this [string name] {
2262 return (Statement) labels [name];
2267 /// A list of labels that were not used within this block
2269 public string [] GetUnreferenced ()
2271 // FIXME: Implement me
2275 public void AddStatement (Statement s)
2292 bool variables_initialized = false;
2293 int count_variables = 0, first_variable = 0;
2295 void UpdateVariableInfo (EmitContext ec)
2297 DeclSpace ds = ec.DeclSpace;
2302 first_variable += Parent.CountVariables;
2304 count_variables = first_variable;
2305 if (variables != null) {
2306 foreach (VariableInfo vi in variables.Values) {
2307 Report.Debug (2, "VARIABLE", vi);
2309 Type type = ds.ResolveType (vi.Type, false, vi.Location);
2315 vi.VariableType = type;
2317 Report.Debug (2, "VARIABLE", vi, type, type.IsValueType,
2318 TypeManager.IsValueType (type),
2319 TypeManager.IsBuiltinType (type));
2321 // FIXME: we don't have support for structs yet.
2322 if (TypeManager.IsValueType (type) && !TypeManager.IsBuiltinType (type))
2325 vi.Number = ++count_variables;
2329 variables_initialized = true;
2334 // The number of local variables in this block
2336 public int CountVariables
2339 if (!variables_initialized)
2340 throw new Exception ();
2342 return count_variables;
2347 /// Emits the variable declarations and labels.
2350 /// tc: is our typecontainer (to resolve type references)
2351 /// ig: is the code generator:
2352 /// toplevel: the toplevel block. This is used for checking
2353 /// that no two labels with the same name are used.
2355 public void EmitMeta (EmitContext ec, Block toplevel)
2357 DeclSpace ds = ec.DeclSpace;
2358 ILGenerator ig = ec.ig;
2360 if (!variables_initialized)
2361 UpdateVariableInfo (ec);
2364 // Process this block variables
2366 if (variables != null){
2367 local_builders = new Hashtable ();
2369 foreach (DictionaryEntry de in variables){
2370 string name = (string) de.Key;
2371 VariableInfo vi = (VariableInfo) de.Value;
2373 if (vi.VariableType == null)
2376 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2378 if (CodeGen.SymbolWriter != null)
2379 vi.LocalBuilder.SetLocalSymInfo (name);
2381 if (constants == null)
2384 Expression cv = (Expression) constants [name];
2388 Expression e = cv.Resolve (ec);
2392 if (!(e is Constant)){
2393 Report.Error (133, vi.Location,
2394 "The expression being assigned to `" +
2395 name + "' must be constant (" + e + ")");
2399 constants.Remove (name);
2400 constants.Add (name, e);
2405 // Now, handle the children
2407 if (children != null){
2408 foreach (Block b in children)
2409 b.EmitMeta (ec, toplevel);
2413 public void UsageWarning ()
2417 if (variables != null){
2418 foreach (DictionaryEntry de in variables){
2419 VariableInfo vi = (VariableInfo) de.Value;
2424 name = (string) de.Key;
2428 219, vi.Location, "The variable `" + name +
2429 "' is assigned but its value is never used");
2432 168, vi.Location, "The variable `" +
2434 "' is declared but never used");
2439 if (children != null)
2440 foreach (Block b in children)
2444 public override bool Resolve (EmitContext ec)
2446 Block prev_block = ec.CurrentBlock;
2449 ec.CurrentBlock = this;
2450 ec.StartFlowBranching (this);
2452 Report.Debug (1, "RESOLVE BLOCK", StartLocation);
2454 if (!variables_initialized)
2455 UpdateVariableInfo (ec);
2457 foreach (Statement s in statements){
2458 if (s.Resolve (ec) == false)
2462 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation);
2464 ec.EndFlowBranching ();
2465 ec.CurrentBlock = prev_block;
2467 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2468 foreach (LabeledStatement label in labels.Values)
2469 if (!label.HasBeenReferenced)
2470 Report.Warning (164, label.Location,
2471 "This label has not been referenced");
2477 public override bool Emit (EmitContext ec)
2479 bool is_ret = false, this_ret = false;
2480 Block prev_block = ec.CurrentBlock;
2481 bool warning_shown = false;
2483 ec.CurrentBlock = this;
2485 if (CodeGen.SymbolWriter != null) {
2486 ec.Mark (StartLocation);
2488 foreach (Statement s in statements) {
2491 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2492 warning_shown = true;
2493 Warning_DeadCodeFound (s.loc);
2495 this_ret = s.Emit (ec);
2500 ec.Mark (EndLocation);
2502 foreach (Statement s in statements){
2503 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2504 warning_shown = true;
2505 Warning_DeadCodeFound (s.loc);
2507 this_ret = s.Emit (ec);
2513 ec.CurrentBlock = prev_block;
2518 public class SwitchLabel {
2521 public Location loc;
2522 public Label ILLabel;
2523 public Label ILLabelCode;
2526 // if expr == null, then it is the default case.
2528 public SwitchLabel (Expression expr, Location l)
2534 public Expression Label {
2540 public object Converted {
2547 // Resolves the expression, reduces it to a literal if possible
2548 // and then converts it to the requested type.
2550 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2552 ILLabel = ec.ig.DefineLabel ();
2553 ILLabelCode = ec.ig.DefineLabel ();
2558 Expression e = label.Resolve (ec);
2563 if (!(e is Constant)){
2564 Console.WriteLine ("Value is: " + label);
2565 Report.Error (150, loc, "A constant value is expected");
2569 if (e is StringConstant || e is NullLiteral){
2570 if (required_type == TypeManager.string_type){
2572 ILLabel = ec.ig.DefineLabel ();
2577 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2578 if (converted == null)
2585 public class SwitchSection {
2586 // An array of SwitchLabels.
2587 public readonly ArrayList Labels;
2588 public readonly Block Block;
2590 public SwitchSection (ArrayList labels, Block block)
2597 public class Switch : Statement {
2598 public readonly ArrayList Sections;
2599 public Expression Expr;
2602 /// Maps constants whose type type SwitchType to their SwitchLabels.
2604 public Hashtable Elements;
2607 /// The governing switch type
2609 public Type SwitchType;
2615 Label default_target;
2616 Expression new_expr;
2619 // The types allowed to be implicitly cast from
2620 // on the governing type
2622 static Type [] allowed_types;
2624 public Switch (Expression e, ArrayList sects, Location l)
2631 public bool GotDefault {
2637 public Label DefaultTarget {
2639 return default_target;
2644 // Determines the governing type for a switch. The returned
2645 // expression might be the expression from the switch, or an
2646 // expression that includes any potential conversions to the
2647 // integral types or to string.
2649 Expression SwitchGoverningType (EmitContext ec, Type t)
2651 if (t == TypeManager.int32_type ||
2652 t == TypeManager.uint32_type ||
2653 t == TypeManager.char_type ||
2654 t == TypeManager.byte_type ||
2655 t == TypeManager.sbyte_type ||
2656 t == TypeManager.ushort_type ||
2657 t == TypeManager.short_type ||
2658 t == TypeManager.uint64_type ||
2659 t == TypeManager.int64_type ||
2660 t == TypeManager.string_type ||
2661 t == TypeManager.bool_type ||
2662 t.IsSubclassOf (TypeManager.enum_type))
2665 if (allowed_types == null){
2666 allowed_types = new Type [] {
2667 TypeManager.sbyte_type,
2668 TypeManager.byte_type,
2669 TypeManager.short_type,
2670 TypeManager.ushort_type,
2671 TypeManager.int32_type,
2672 TypeManager.uint32_type,
2673 TypeManager.int64_type,
2674 TypeManager.uint64_type,
2675 TypeManager.char_type,
2676 TypeManager.bool_type,
2677 TypeManager.string_type
2682 // Try to find a *user* defined implicit conversion.
2684 // If there is no implicit conversion, or if there are multiple
2685 // conversions, we have to report an error
2687 Expression converted = null;
2688 foreach (Type tt in allowed_types){
2691 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
2695 if (converted != null){
2696 Report.Error (-12, loc, "More than one conversion to an integral " +
2697 " type exists for type `" +
2698 TypeManager.CSharpName (Expr.Type)+"'");
2706 void error152 (string n)
2709 152, "The label `" + n + ":' " +
2710 "is already present on this switch statement");
2714 // Performs the basic sanity checks on the switch statement
2715 // (looks for duplicate keys and non-constant expressions).
2717 // It also returns a hashtable with the keys that we will later
2718 // use to compute the switch tables
2720 bool CheckSwitch (EmitContext ec)
2724 Elements = new Hashtable ();
2726 got_default = false;
2728 if (TypeManager.IsEnumType (SwitchType)){
2729 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2731 compare_type = SwitchType;
2733 foreach (SwitchSection ss in Sections){
2734 foreach (SwitchLabel sl in ss.Labels){
2735 if (!sl.ResolveAndReduce (ec, SwitchType)){
2740 if (sl.Label == null){
2742 error152 ("default");
2749 object key = sl.Converted;
2751 if (key is Constant)
2752 key = ((Constant) key).GetValue ();
2755 key = NullLiteral.Null;
2757 string lname = null;
2758 if (compare_type == TypeManager.uint64_type){
2759 ulong v = (ulong) key;
2761 if (Elements.Contains (v))
2762 lname = v.ToString ();
2764 Elements.Add (v, sl);
2765 } else if (compare_type == TypeManager.int64_type){
2766 long v = (long) key;
2768 if (Elements.Contains (v))
2769 lname = v.ToString ();
2771 Elements.Add (v, sl);
2772 } else if (compare_type == TypeManager.uint32_type){
2773 uint v = (uint) key;
2775 if (Elements.Contains (v))
2776 lname = v.ToString ();
2778 Elements.Add (v, sl);
2779 } else if (compare_type == TypeManager.char_type){
2780 char v = (char) key;
2782 if (Elements.Contains (v))
2783 lname = v.ToString ();
2785 Elements.Add (v, sl);
2786 } else if (compare_type == TypeManager.byte_type){
2787 byte v = (byte) key;
2789 if (Elements.Contains (v))
2790 lname = v.ToString ();
2792 Elements.Add (v, sl);
2793 } else if (compare_type == TypeManager.sbyte_type){
2794 sbyte v = (sbyte) key;
2796 if (Elements.Contains (v))
2797 lname = v.ToString ();
2799 Elements.Add (v, sl);
2800 } else if (compare_type == TypeManager.short_type){
2801 short v = (short) key;
2803 if (Elements.Contains (v))
2804 lname = v.ToString ();
2806 Elements.Add (v, sl);
2807 } else if (compare_type == TypeManager.ushort_type){
2808 ushort v = (ushort) key;
2810 if (Elements.Contains (v))
2811 lname = v.ToString ();
2813 Elements.Add (v, sl);
2814 } else if (compare_type == TypeManager.string_type){
2815 if (key is NullLiteral){
2816 if (Elements.Contains (NullLiteral.Null))
2819 Elements.Add (NullLiteral.Null, null);
2821 string s = (string) key;
2823 if (Elements.Contains (s))
2826 Elements.Add (s, sl);
2828 } else if (compare_type == TypeManager.int32_type) {
2831 if (Elements.Contains (v))
2832 lname = v.ToString ();
2834 Elements.Add (v, sl);
2835 } else if (compare_type == TypeManager.bool_type) {
2836 bool v = (bool) key;
2838 if (Elements.Contains (v))
2839 lname = v.ToString ();
2841 Elements.Add (v, sl);
2845 throw new Exception ("Unknown switch type!" +
2846 SwitchType + " " + compare_type);
2850 error152 ("case + " + lname);
2861 void EmitObjectInteger (ILGenerator ig, object k)
2864 IntConstant.EmitInt (ig, (int) k);
2865 else if (k is Constant) {
2866 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2869 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2872 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2874 IntConstant.EmitInt (ig, (int) (long) k);
2875 ig.Emit (OpCodes.Conv_I8);
2878 LongConstant.EmitLong (ig, (long) k);
2880 else if (k is ulong)
2882 if ((ulong) k < (1L<<32))
2884 IntConstant.EmitInt (ig, (int) (long) k);
2885 ig.Emit (OpCodes.Conv_U8);
2889 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2893 IntConstant.EmitInt (ig, (int) ((char) k));
2894 else if (k is sbyte)
2895 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2897 IntConstant.EmitInt (ig, (int) ((byte) k));
2898 else if (k is short)
2899 IntConstant.EmitInt (ig, (int) ((short) k));
2900 else if (k is ushort)
2901 IntConstant.EmitInt (ig, (int) ((ushort) k));
2903 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2905 throw new Exception ("Unhandled case");
2908 // structure used to hold blocks of keys while calculating table switch
2909 class KeyBlock : IComparable
2911 public KeyBlock (long _nFirst)
2913 nFirst = nLast = _nFirst;
2917 public ArrayList rgKeys = null;
2920 get { return (int) (nLast - nFirst + 1); }
2922 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2924 return kbLast.nLast - kbFirst.nFirst + 1;
2926 public int CompareTo (object obj)
2928 KeyBlock kb = (KeyBlock) obj;
2929 int nLength = Length;
2930 int nLengthOther = kb.Length;
2931 if (nLengthOther == nLength)
2932 return (int) (kb.nFirst - nFirst);
2933 return nLength - nLengthOther;
2938 /// This method emits code for a lookup-based switch statement (non-string)
2939 /// Basically it groups the cases into blocks that are at least half full,
2940 /// and then spits out individual lookup opcodes for each block.
2941 /// It emits the longest blocks first, and short blocks are just
2942 /// handled with direct compares.
2944 /// <param name="ec"></param>
2945 /// <param name="val"></param>
2946 /// <returns></returns>
2947 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
2949 int cElements = Elements.Count;
2950 object [] rgKeys = new object [cElements];
2951 Elements.Keys.CopyTo (rgKeys, 0);
2952 Array.Sort (rgKeys);
2954 // initialize the block list with one element per key
2955 ArrayList rgKeyBlocks = new ArrayList ();
2956 foreach (object key in rgKeys)
2957 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
2960 // iteratively merge the blocks while they are at least half full
2961 // there's probably a really cool way to do this with a tree...
2962 while (rgKeyBlocks.Count > 1)
2964 ArrayList rgKeyBlocksNew = new ArrayList ();
2965 kbCurr = (KeyBlock) rgKeyBlocks [0];
2966 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2968 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2969 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2972 kbCurr.nLast = kb.nLast;
2976 // start a new block
2977 rgKeyBlocksNew.Add (kbCurr);
2981 rgKeyBlocksNew.Add (kbCurr);
2982 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2984 rgKeyBlocks = rgKeyBlocksNew;
2987 // initialize the key lists
2988 foreach (KeyBlock kb in rgKeyBlocks)
2989 kb.rgKeys = new ArrayList ();
2991 // fill the key lists
2993 if (rgKeyBlocks.Count > 0) {
2994 kbCurr = (KeyBlock) rgKeyBlocks [0];
2995 foreach (object key in rgKeys)
2997 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
2999 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3000 kbCurr.rgKeys.Add (key);
3004 // sort the blocks so we can tackle the largest ones first
3005 rgKeyBlocks.Sort ();
3007 // okay now we can start...
3008 ILGenerator ig = ec.ig;
3009 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3010 Label lblDefault = ig.DefineLabel ();
3012 Type typeKeys = null;
3013 if (rgKeys.Length > 0)
3014 typeKeys = rgKeys [0].GetType (); // used for conversions
3016 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3018 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3019 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3022 foreach (object key in kb.rgKeys)
3024 ig.Emit (OpCodes.Ldloc, val);
3025 EmitObjectInteger (ig, key);
3026 SwitchLabel sl = (SwitchLabel) Elements [key];
3027 ig.Emit (OpCodes.Beq, sl.ILLabel);
3032 // TODO: if all the keys in the block are the same and there are
3033 // no gaps/defaults then just use a range-check.
3034 if (SwitchType == TypeManager.int64_type ||
3035 SwitchType == TypeManager.uint64_type)
3037 // TODO: optimize constant/I4 cases
3039 // check block range (could be > 2^31)
3040 ig.Emit (OpCodes.Ldloc, val);
3041 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3042 ig.Emit (OpCodes.Blt, lblDefault);
3043 ig.Emit (OpCodes.Ldloc, val);
3044 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3045 ig.Emit (OpCodes.Bgt, lblDefault);
3048 ig.Emit (OpCodes.Ldloc, val);
3051 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3052 ig.Emit (OpCodes.Sub);
3054 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3059 ig.Emit (OpCodes.Ldloc, val);
3060 int nFirst = (int) kb.nFirst;
3063 IntConstant.EmitInt (ig, nFirst);
3064 ig.Emit (OpCodes.Sub);
3066 else if (nFirst < 0)
3068 IntConstant.EmitInt (ig, -nFirst);
3069 ig.Emit (OpCodes.Add);
3073 // first, build the list of labels for the switch
3075 int cJumps = kb.Length;
3076 Label [] rgLabels = new Label [cJumps];
3077 for (int iJump = 0; iJump < cJumps; iJump++)
3079 object key = kb.rgKeys [iKey];
3080 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3082 SwitchLabel sl = (SwitchLabel) Elements [key];
3083 rgLabels [iJump] = sl.ILLabel;
3087 rgLabels [iJump] = lblDefault;
3089 // emit the switch opcode
3090 ig.Emit (OpCodes.Switch, rgLabels);
3093 // mark the default for this block
3095 ig.MarkLabel (lblDefault);
3098 // TODO: find the default case and emit it here,
3099 // to prevent having to do the following jump.
3100 // make sure to mark other labels in the default section
3102 // the last default just goes to the end
3103 ig.Emit (OpCodes.Br, lblDefault);
3105 // now emit the code for the sections
3106 bool fFoundDefault = false;
3107 bool fAllReturn = true;
3108 foreach (SwitchSection ss in Sections)
3110 foreach (SwitchLabel sl in ss.Labels)
3112 ig.MarkLabel (sl.ILLabel);
3113 ig.MarkLabel (sl.ILLabelCode);
3114 if (sl.Label == null)
3116 ig.MarkLabel (lblDefault);
3117 fFoundDefault = true;
3120 fAllReturn &= ss.Block.Emit (ec);
3121 //ig.Emit (OpCodes.Br, lblEnd);
3124 if (!fFoundDefault) {
3125 ig.MarkLabel (lblDefault);
3128 ig.MarkLabel (lblEnd);
3133 // This simple emit switch works, but does not take advantage of the
3135 // TODO: remove non-string logic from here
3136 // TODO: binary search strings?
3138 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3140 ILGenerator ig = ec.ig;
3141 Label end_of_switch = ig.DefineLabel ();
3142 Label next_test = ig.DefineLabel ();
3143 Label null_target = ig.DefineLabel ();
3144 bool default_found = false;
3145 bool first_test = true;
3146 bool pending_goto_end = false;
3147 bool all_return = true;
3148 bool is_string = false;
3152 // Special processing for strings: we cant compare
3155 if (SwitchType == TypeManager.string_type){
3156 ig.Emit (OpCodes.Ldloc, val);
3159 if (Elements.Contains (NullLiteral.Null)){
3160 ig.Emit (OpCodes.Brfalse, null_target);
3162 ig.Emit (OpCodes.Brfalse, default_target);
3164 ig.Emit (OpCodes.Ldloc, val);
3165 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3166 ig.Emit (OpCodes.Stloc, val);
3169 SwitchSection last_section;
3170 last_section = (SwitchSection) Sections [Sections.Count-1];
3172 foreach (SwitchSection ss in Sections){
3173 Label sec_begin = ig.DefineLabel ();
3175 if (pending_goto_end)
3176 ig.Emit (OpCodes.Br, end_of_switch);
3178 int label_count = ss.Labels.Count;
3180 foreach (SwitchLabel sl in ss.Labels){
3181 ig.MarkLabel (sl.ILLabel);
3184 ig.MarkLabel (next_test);
3185 next_test = ig.DefineLabel ();
3188 // If we are the default target
3190 if (sl.Label == null){
3191 ig.MarkLabel (default_target);
3192 default_found = true;
3194 object lit = sl.Converted;
3196 if (lit is NullLiteral){
3198 if (label_count == 1)
3199 ig.Emit (OpCodes.Br, next_test);
3204 StringConstant str = (StringConstant) lit;
3206 ig.Emit (OpCodes.Ldloc, val);
3207 ig.Emit (OpCodes.Ldstr, str.Value);
3208 if (label_count == 1)
3209 ig.Emit (OpCodes.Bne_Un, next_test);
3211 ig.Emit (OpCodes.Beq, sec_begin);
3213 ig.Emit (OpCodes.Ldloc, val);
3214 EmitObjectInteger (ig, lit);
3215 ig.Emit (OpCodes.Ceq);
3216 if (label_count == 1)
3217 ig.Emit (OpCodes.Brfalse, next_test);
3219 ig.Emit (OpCodes.Brtrue, sec_begin);
3223 if (label_count != 1 && ss != last_section)
3224 ig.Emit (OpCodes.Br, next_test);
3227 ig.MarkLabel (null_target);
3228 ig.MarkLabel (sec_begin);
3229 foreach (SwitchLabel sl in ss.Labels)
3230 ig.MarkLabel (sl.ILLabelCode);
3231 if (ss.Block.Emit (ec))
3232 pending_goto_end = false;
3235 pending_goto_end = true;
3239 if (!default_found){
3240 ig.MarkLabel (default_target);
3243 ig.MarkLabel (next_test);
3244 ig.MarkLabel (end_of_switch);
3249 public override bool Resolve (EmitContext ec)
3251 Expr = Expr.Resolve (ec);
3255 new_expr = SwitchGoverningType (ec, Expr.Type);
3256 if (new_expr == null){
3257 Report.Error (151, loc, "An integer type or string was expected for switch");
3262 SwitchType = new_expr.Type;
3264 if (!CheckSwitch (ec))
3267 Switch old_switch = ec.Switch;
3269 ec.Switch.SwitchType = SwitchType;
3271 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3274 foreach (SwitchSection ss in Sections){
3276 ec.CurrentBranching.CreateSibling ();
3280 if (ss.Block.Resolve (ec) != true)
3284 ec.EndFlowBranching ();
3285 ec.Switch = old_switch;
3290 public override bool Emit (EmitContext ec)
3292 // Store variable for comparission purposes
3293 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3295 ec.ig.Emit (OpCodes.Stloc, value);
3297 ILGenerator ig = ec.ig;
3299 default_target = ig.DefineLabel ();
3302 // Setup the codegen context
3304 Label old_end = ec.LoopEnd;
3305 Switch old_switch = ec.Switch;
3307 ec.LoopEnd = ig.DefineLabel ();
3312 if (SwitchType == TypeManager.string_type)
3313 all_return = SimpleSwitchEmit (ec, value);
3315 all_return = TableSwitchEmit (ec, value);
3317 // Restore context state.
3318 ig.MarkLabel (ec.LoopEnd);
3321 // Restore the previous context
3323 ec.LoopEnd = old_end;
3324 ec.Switch = old_switch;
3330 public class Lock : Statement {
3332 Statement Statement;
3334 public Lock (Expression expr, Statement stmt, Location l)
3341 public override bool Resolve (EmitContext ec)
3343 expr = expr.Resolve (ec);
3344 return Statement.Resolve (ec) && expr != null;
3347 public override bool Emit (EmitContext ec)
3349 Type type = expr.Type;
3352 if (type.IsValueType){
3353 Report.Error (185, loc, "lock statement requires the expression to be " +
3354 " a reference type (type is: `" +
3355 TypeManager.CSharpName (type) + "'");
3359 ILGenerator ig = ec.ig;
3360 LocalBuilder temp = ig.DeclareLocal (type);
3363 ig.Emit (OpCodes.Dup);
3364 ig.Emit (OpCodes.Stloc, temp);
3365 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3368 Label end = ig.BeginExceptionBlock ();
3369 bool old_in_try = ec.InTry;
3371 Label finish = ig.DefineLabel ();
3372 val = Statement.Emit (ec);
3373 ec.InTry = old_in_try;
3374 // ig.Emit (OpCodes.Leave, finish);
3376 ig.MarkLabel (finish);
3379 ig.BeginFinallyBlock ();
3380 ig.Emit (OpCodes.Ldloc, temp);
3381 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3382 ig.EndExceptionBlock ();
3388 public class Unchecked : Statement {
3389 public readonly Block Block;
3391 public Unchecked (Block b)
3396 public override bool Resolve (EmitContext ec)
3398 return Block.Resolve (ec);
3401 public override bool Emit (EmitContext ec)
3403 bool previous_state = ec.CheckState;
3404 bool previous_state_const = ec.ConstantCheckState;
3407 ec.CheckState = false;
3408 ec.ConstantCheckState = false;
3409 val = Block.Emit (ec);
3410 ec.CheckState = previous_state;
3411 ec.ConstantCheckState = previous_state_const;
3417 public class Checked : Statement {
3418 public readonly Block Block;
3420 public Checked (Block b)
3425 public override bool Resolve (EmitContext ec)
3427 bool previous_state = ec.CheckState;
3428 bool previous_state_const = ec.ConstantCheckState;
3430 ec.CheckState = true;
3431 ec.ConstantCheckState = true;
3432 bool ret = Block.Resolve (ec);
3433 ec.CheckState = previous_state;
3434 ec.ConstantCheckState = previous_state_const;
3439 public override bool Emit (EmitContext ec)
3441 bool previous_state = ec.CheckState;
3442 bool previous_state_const = ec.ConstantCheckState;
3445 ec.CheckState = true;
3446 ec.ConstantCheckState = true;
3447 val = Block.Emit (ec);
3448 ec.CheckState = previous_state;
3449 ec.ConstantCheckState = previous_state_const;
3455 public class Unsafe : Statement {
3456 public readonly Block Block;
3458 public Unsafe (Block b)
3463 public override bool Resolve (EmitContext ec)
3465 bool previous_state = ec.InUnsafe;
3469 val = Block.Resolve (ec);
3470 ec.InUnsafe = previous_state;
3475 public override bool Emit (EmitContext ec)
3477 bool previous_state = ec.InUnsafe;
3481 val = Block.Emit (ec);
3482 ec.InUnsafe = previous_state;
3491 public class Fixed : Statement {
3493 ArrayList declarators;
3494 Statement statement;
3499 public bool is_object;
3500 public VariableInfo vi;
3501 public Expression expr;
3502 public Expression converted;
3505 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3508 declarators = decls;
3513 public override bool Resolve (EmitContext ec)
3515 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3516 if (expr_type == null)
3519 data = new FixedData [declarators.Count];
3522 foreach (Pair p in declarators){
3523 VariableInfo vi = (VariableInfo) p.First;
3524 Expression e = (Expression) p.Second;
3529 // The rules for the possible declarators are pretty wise,
3530 // but the production on the grammar is more concise.
3532 // So we have to enforce these rules here.
3534 // We do not resolve before doing the case 1 test,
3535 // because the grammar is explicit in that the token &
3536 // is present, so we need to test for this particular case.
3540 // Case 1: & object.
3542 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3543 Expression child = ((Unary) e).Expr;
3546 if (child is ParameterReference || child is LocalVariableReference){
3549 "No need to use fixed statement for parameters or " +
3550 "local variable declarations (address is already " +
3559 child = ((Unary) e).Expr;
3561 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3564 data [i].is_object = true;
3566 data [i].converted = null;
3580 if (e.Type.IsArray){
3581 Type array_type = e.Type.GetElementType ();
3585 // Provided that array_type is unmanaged,
3587 if (!TypeManager.VerifyUnManaged (array_type, loc))
3591 // and T* is implicitly convertible to the
3592 // pointer type given in the fixed statement.
3594 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3596 Expression converted = Expression.ConvertImplicitRequired (
3597 ec, array_ptr, vi.VariableType, loc);
3598 if (converted == null)
3601 data [i].is_object = false;
3603 data [i].converted = converted;
3613 if (e.Type == TypeManager.string_type){
3614 data [i].is_object = false;
3616 data [i].converted = null;
3622 return statement.Resolve (ec);
3625 public override bool Emit (EmitContext ec)
3627 ILGenerator ig = ec.ig;
3629 bool is_ret = false;
3631 for (int i = 0; i < data.Length; i++) {
3632 VariableInfo vi = data [i].vi;
3635 // Case 1: & object.
3637 if (data [i].is_object) {
3639 // Store pointer in pinned location
3641 data [i].expr.Emit (ec);
3642 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3644 is_ret = statement.Emit (ec);
3646 // Clear the pinned variable.
3647 ig.Emit (OpCodes.Ldc_I4_0);
3648 ig.Emit (OpCodes.Conv_U);
3649 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3657 if (data [i].expr.Type.IsArray){
3659 // Store pointer in pinned location
3661 data [i].converted.Emit (ec);
3663 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3665 is_ret = statement.Emit (ec);
3667 // Clear the pinned variable.
3668 ig.Emit (OpCodes.Ldc_I4_0);
3669 ig.Emit (OpCodes.Conv_U);
3670 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3678 if (data [i].expr.Type == TypeManager.string_type){
3679 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3680 TypeManager.MakePinned (pinned_string);
3682 data [i].expr.Emit (ec);
3683 ig.Emit (OpCodes.Stloc, pinned_string);
3685 Expression sptr = new StringPtr (pinned_string, loc);
3686 Expression converted = Expression.ConvertImplicitRequired (
3687 ec, sptr, vi.VariableType, loc);
3689 if (converted == null)
3692 converted.Emit (ec);
3693 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3695 is_ret = statement.Emit (ec);
3697 // Clear the pinned variable
3698 ig.Emit (OpCodes.Ldnull);
3699 ig.Emit (OpCodes.Stloc, pinned_string);
3707 public class Catch {
3708 public readonly string Name;
3709 public readonly Block Block;
3710 public readonly Location Location;
3714 public Catch (Expression type, string name, Block block, Location l)
3722 public Type CatchType {
3725 throw new InvalidOperationException ();
3731 public bool IsGeneral {
3733 return type == null;
3737 public bool Resolve (EmitContext ec)
3740 type = type.DoResolve (ec);
3745 if (t != TypeManager.exception_type && !t.IsSubclassOf (TypeManager.exception_type)){
3746 Report.Error (155, Location,
3747 "The type caught or thrown must be derived " +
3748 "from System.Exception");
3753 if (!Block.Resolve (ec))
3760 public class Try : Statement {
3761 public readonly Block Fini, Block;
3762 public readonly ArrayList Specific;
3763 public readonly Catch General;
3766 // specific, general and fini might all be null.
3768 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3770 if (specific == null && general == null){
3771 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3775 this.Specific = specific;
3776 this.General = general;
3781 public override bool Resolve (EmitContext ec)
3785 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
3787 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3789 bool old_in_try = ec.InTry;
3792 if (!Block.Resolve (ec))
3795 ec.InTry = old_in_try;
3797 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3799 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3801 foreach (Catch c in Specific){
3802 ec.CurrentBranching.CreateSibling ();
3803 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3805 if (c.Name != null) {
3806 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
3808 throw new Exception ();
3813 bool old_in_catch = ec.InCatch;
3816 if (!c.Resolve (ec))
3819 ec.InCatch = old_in_catch;
3821 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3823 if ((current.Returns == FlowReturns.NEVER) ||
3824 (current.Returns == FlowReturns.SOMETIMES)) {
3825 vector.AndLocals (current);
3829 if (General != null){
3830 ec.CurrentBranching.CreateSibling ();
3831 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3833 bool old_in_catch = ec.InCatch;
3836 if (!General.Resolve (ec))
3839 ec.InCatch = old_in_catch;
3841 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3843 if ((current.Returns == FlowReturns.NEVER) ||
3844 (current.Returns == FlowReturns.SOMETIMES)) {
3845 vector.AndLocals (current);
3849 ec.CurrentBranching.CreateSiblingForFinally ();
3850 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3853 bool old_in_finally = ec.InFinally;
3854 ec.InFinally = true;
3856 if (!Fini.Resolve (ec))
3859 ec.InFinally = old_in_finally;
3862 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3864 FlowReturns returns = ec.EndFlowBranching ();
3866 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
3868 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
3869 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
3872 ec.CurrentBranching.CurrentUsageVector.Or (vector);
3874 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
3879 public override bool Emit (EmitContext ec)
3881 ILGenerator ig = ec.ig;
3883 Label finish = ig.DefineLabel ();;
3887 end = ig.BeginExceptionBlock ();
3888 bool old_in_try = ec.InTry;
3890 returns = Block.Emit (ec);
3891 ec.InTry = old_in_try;
3894 // System.Reflection.Emit provides this automatically:
3895 // ig.Emit (OpCodes.Leave, finish);
3897 bool old_in_catch = ec.InCatch;
3899 DeclSpace ds = ec.DeclSpace;
3901 foreach (Catch c in Specific){
3904 ig.BeginCatchBlock (c.CatchType);
3906 if (c.Name != null){
3907 vi = c.Block.GetVariableInfo (c.Name);
3909 throw new Exception ("Variable does not exist in this block");
3911 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3913 ig.Emit (OpCodes.Pop);
3915 if (!c.Block.Emit (ec))
3919 if (General != null){
3920 ig.BeginCatchBlock (TypeManager.object_type);
3921 ig.Emit (OpCodes.Pop);
3922 if (!General.Block.Emit (ec))
3925 ec.InCatch = old_in_catch;
3927 ig.MarkLabel (finish);
3929 ig.BeginFinallyBlock ();
3930 bool old_in_finally = ec.InFinally;
3931 ec.InFinally = true;
3933 ec.InFinally = old_in_finally;
3936 ig.EndExceptionBlock ();
3939 if (!returns || ec.InTry || ec.InCatch)
3942 // Unfortunately, System.Reflection.Emit automatically emits a leave
3943 // to the end of the finally block. This is a problem if `returns'
3944 // is true since we may jump to a point after the end of the method.
3945 // As a workaround, emit an explicit ret here.
3947 if (ec.ReturnType != null)
3948 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
3949 ec.ig.Emit (OpCodes.Ret);
3956 // FIXME: We still do not support the expression variant of the using
3959 public class Using : Statement {
3960 object expression_or_block;
3961 Statement Statement;
3966 Expression [] converted_vars;
3967 ExpressionStatement [] assign;
3969 public Using (object expression_or_block, Statement stmt, Location l)
3971 this.expression_or_block = expression_or_block;
3977 // Resolves for the case of using using a local variable declaration.
3979 bool ResolveLocalVariableDecls (EmitContext ec)
3981 bool need_conv = false;
3982 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3985 if (expr_type == null)
3989 // The type must be an IDisposable or an implicit conversion
3992 converted_vars = new Expression [var_list.Count];
3993 assign = new ExpressionStatement [var_list.Count];
3994 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3995 foreach (DictionaryEntry e in var_list){
3996 Expression var = (Expression) e.Key;
3998 var = var.ResolveLValue (ec, new EmptyExpression ());
4002 converted_vars [i] = Expression.ConvertImplicit (
4003 ec, var, TypeManager.idisposable_type, loc);
4005 if (converted_vars [i] == null)
4013 foreach (DictionaryEntry e in var_list){
4014 LocalVariableReference var = (LocalVariableReference) e.Key;
4015 Expression new_expr = (Expression) e.Value;
4018 a = new Assign (var, new_expr, loc);
4024 converted_vars [i] = var;
4025 assign [i] = (ExpressionStatement) a;
4032 bool ResolveExpression (EmitContext ec)
4034 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4035 conv = Expression.ConvertImplicit (
4036 ec, expr, TypeManager.idisposable_type, loc);
4046 // Emits the code for the case of using using a local variable declaration.
4048 bool EmitLocalVariableDecls (EmitContext ec)
4050 ILGenerator ig = ec.ig;
4053 bool old_in_try = ec.InTry;
4055 for (i = 0; i < assign.Length; i++) {
4056 assign [i].EmitStatement (ec);
4058 ig.BeginExceptionBlock ();
4060 Statement.Emit (ec);
4061 ec.InTry = old_in_try;
4063 bool old_in_finally = ec.InFinally;
4064 ec.InFinally = true;
4065 var_list.Reverse ();
4066 foreach (DictionaryEntry e in var_list){
4067 LocalVariableReference var = (LocalVariableReference) e.Key;
4068 Label skip = ig.DefineLabel ();
4071 ig.BeginFinallyBlock ();
4074 ig.Emit (OpCodes.Brfalse, skip);
4075 converted_vars [i].Emit (ec);
4076 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4077 ig.MarkLabel (skip);
4078 ig.EndExceptionBlock ();
4080 ec.InFinally = old_in_finally;
4085 bool EmitExpression (EmitContext ec)
4088 // Make a copy of the expression and operate on that.
4090 ILGenerator ig = ec.ig;
4091 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4096 ig.Emit (OpCodes.Stloc, local_copy);
4098 bool old_in_try = ec.InTry;
4100 ig.BeginExceptionBlock ();
4101 Statement.Emit (ec);
4102 ec.InTry = old_in_try;
4104 Label skip = ig.DefineLabel ();
4105 bool old_in_finally = ec.InFinally;
4106 ig.BeginFinallyBlock ();
4107 ig.Emit (OpCodes.Ldloc, local_copy);
4108 ig.Emit (OpCodes.Brfalse, skip);
4109 ig.Emit (OpCodes.Ldloc, local_copy);
4110 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4111 ig.MarkLabel (skip);
4112 ec.InFinally = old_in_finally;
4113 ig.EndExceptionBlock ();
4118 public override bool Resolve (EmitContext ec)
4120 if (expression_or_block is DictionaryEntry){
4121 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4122 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4124 if (!ResolveLocalVariableDecls (ec))
4127 } else if (expression_or_block is Expression){
4128 expr = (Expression) expression_or_block;
4130 expr = expr.Resolve (ec);
4134 expr_type = expr.Type;
4136 if (!ResolveExpression (ec))
4140 return Statement.Resolve (ec);
4143 public override bool Emit (EmitContext ec)
4145 if (expression_or_block is DictionaryEntry)
4146 return EmitLocalVariableDecls (ec);
4147 else if (expression_or_block is Expression)
4148 return EmitExpression (ec);
4155 /// Implementation of the foreach C# statement
4157 public class Foreach : Statement {
4159 LocalVariableReference variable;
4161 Statement statement;
4162 ForeachHelperMethods hm;
4163 Expression empty, conv;
4164 Type array_type, element_type;
4167 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4168 Statement stmt, Location l)
4171 this.variable = var;
4177 public override bool Resolve (EmitContext ec)
4179 expr = expr.Resolve (ec);
4183 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4184 if (var_type == null)
4188 // We need an instance variable. Not sure this is the best
4189 // way of doing this.
4191 // FIXME: When we implement propertyaccess, will those turn
4192 // out to return values in ExprClass? I think they should.
4194 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4195 expr.eclass == ExprClass.PropertyAccess)){
4196 error1579 (expr.Type);
4200 if (expr.Type.IsArray) {
4201 array_type = expr.Type;
4202 element_type = array_type.GetElementType ();
4204 empty = new EmptyExpression (element_type);
4206 hm = ProbeCollectionType (ec, expr.Type);
4208 error1579 (expr.Type);
4212 array_type = expr.Type;
4213 element_type = hm.element_type;
4215 empty = new EmptyExpression (hm.element_type);
4219 // FIXME: maybe we can apply the same trick we do in the
4220 // array handling to avoid creating empty and conv in some cases.
4222 // Although it is not as important in this case, as the type
4223 // will not likely be object (what the enumerator will return).
4225 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4229 if (variable.ResolveLValue (ec, empty) == null)
4232 if (!statement.Resolve (ec))
4239 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4241 static MethodInfo FetchMethodMoveNext (Type t)
4243 MemberInfo [] move_next_list;
4245 move_next_list = TypeContainer.FindMembers (
4246 t, MemberTypes.Method,
4247 BindingFlags.Public | BindingFlags.Instance,
4248 Type.FilterName, "MoveNext");
4249 if (move_next_list == null || move_next_list.Length == 0)
4252 foreach (MemberInfo m in move_next_list){
4253 MethodInfo mi = (MethodInfo) m;
4256 args = TypeManager.GetArgumentTypes (mi);
4257 if (args != null && args.Length == 0){
4258 if (mi.ReturnType == TypeManager.bool_type)
4266 // Retrieves a `public T get_Current ()' method from the Type `t'
4268 static MethodInfo FetchMethodGetCurrent (Type t)
4270 MemberInfo [] move_next_list;
4272 move_next_list = TypeContainer.FindMembers (
4273 t, MemberTypes.Method,
4274 BindingFlags.Public | BindingFlags.Instance,
4275 Type.FilterName, "get_Current");
4276 if (move_next_list == null || move_next_list.Length == 0)
4279 foreach (MemberInfo m in move_next_list){
4280 MethodInfo mi = (MethodInfo) m;
4283 args = TypeManager.GetArgumentTypes (mi);
4284 if (args != null && args.Length == 0)
4291 // This struct records the helper methods used by the Foreach construct
4293 class ForeachHelperMethods {
4294 public EmitContext ec;
4295 public MethodInfo get_enumerator;
4296 public MethodInfo move_next;
4297 public MethodInfo get_current;
4298 public Type element_type;
4299 public Type enumerator_type;
4300 public bool is_disposable;
4302 public ForeachHelperMethods (EmitContext ec)
4305 this.element_type = TypeManager.object_type;
4306 this.enumerator_type = TypeManager.ienumerator_type;
4307 this.is_disposable = true;
4311 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4316 if (!(m is MethodInfo))
4319 if (m.Name != "GetEnumerator")
4322 MethodInfo mi = (MethodInfo) m;
4323 Type [] args = TypeManager.GetArgumentTypes (mi);
4325 if (args.Length != 0)
4328 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4329 EmitContext ec = hm.ec;
4332 // Check whether GetEnumerator is accessible to us
4334 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4336 Type declaring = mi.DeclaringType;
4337 if (prot == MethodAttributes.Private){
4338 if (declaring != ec.ContainerType)
4340 } else if (prot == MethodAttributes.FamANDAssem){
4341 // If from a different assembly, false
4342 if (!(mi is MethodBuilder))
4345 // Are we being invoked from the same class, or from a derived method?
4347 if (ec.ContainerType != declaring){
4348 if (!ec.ContainerType.IsSubclassOf (declaring))
4351 } else if (prot == MethodAttributes.FamORAssem){
4352 if (!(mi is MethodBuilder ||
4353 ec.ContainerType == declaring ||
4354 ec.ContainerType.IsSubclassOf (declaring)))
4356 } if (prot == MethodAttributes.Family){
4357 if (!(ec.ContainerType == declaring ||
4358 ec.ContainerType.IsSubclassOf (declaring)))
4363 // Ok, we can access it, now make sure that we can do something
4364 // with this `GetEnumerator'
4367 if (mi.ReturnType == TypeManager.ienumerator_type ||
4368 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4369 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4370 hm.move_next = TypeManager.bool_movenext_void;
4371 hm.get_current = TypeManager.object_getcurrent_void;
4376 // Ok, so they dont return an IEnumerable, we will have to
4377 // find if they support the GetEnumerator pattern.
4379 Type return_type = mi.ReturnType;
4381 hm.move_next = FetchMethodMoveNext (return_type);
4382 if (hm.move_next == null)
4384 hm.get_current = FetchMethodGetCurrent (return_type);
4385 if (hm.get_current == null)
4388 hm.element_type = hm.get_current.ReturnType;
4389 hm.enumerator_type = return_type;
4390 hm.is_disposable = TypeManager.ImplementsInterface (
4391 hm.enumerator_type, TypeManager.idisposable_type);
4397 /// This filter is used to find the GetEnumerator method
4398 /// on which IEnumerator operates
4400 static MemberFilter FilterEnumerator;
4404 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4407 void error1579 (Type t)
4409 Report.Error (1579, loc,
4410 "foreach statement cannot operate on variables of type `" +
4411 t.FullName + "' because that class does not provide a " +
4412 " GetEnumerator method or it is inaccessible");
4415 static bool TryType (Type t, ForeachHelperMethods hm)
4419 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4420 BindingFlags.Public | BindingFlags.NonPublic |
4421 BindingFlags.Instance,
4422 FilterEnumerator, hm);
4424 if (mi == null || mi.Length == 0)
4427 hm.get_enumerator = (MethodInfo) mi [0];
4432 // Looks for a usable GetEnumerator in the Type, and if found returns
4433 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4435 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4437 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4439 if (TryType (t, hm))
4443 // Now try to find the method in the interfaces
4446 Type [] ifaces = t.GetInterfaces ();
4448 foreach (Type i in ifaces){
4449 if (TryType (i, hm))
4454 // Since TypeBuilder.GetInterfaces only returns the interface
4455 // types for this type, we have to keep looping, but once
4456 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4457 // done, because it returns all the types
4459 if ((t is TypeBuilder))
4469 // FIXME: possible optimization.
4470 // We might be able to avoid creating `empty' if the type is the sam
4472 bool EmitCollectionForeach (EmitContext ec)
4474 ILGenerator ig = ec.ig;
4475 LocalBuilder enumerator, disposable;
4477 enumerator = ig.DeclareLocal (hm.enumerator_type);
4478 if (hm.is_disposable)
4479 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4484 // Instantiate the enumerator
4486 if (expr.Type.IsValueType){
4487 if (expr is IMemoryLocation){
4488 IMemoryLocation ml = (IMemoryLocation) expr;
4490 ml.AddressOf (ec, AddressOp.Load);
4492 throw new Exception ("Expr " + expr + " of type " + expr.Type +
4493 " does not implement IMemoryLocation");
4494 ig.Emit (OpCodes.Call, hm.get_enumerator);
4497 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4499 ig.Emit (OpCodes.Stloc, enumerator);
4502 // Protect the code in a try/finalize block, so that
4503 // if the beast implement IDisposable, we get rid of it
4506 bool old_in_try = ec.InTry;
4508 if (hm.is_disposable) {
4509 l = ig.BeginExceptionBlock ();
4513 Label end_try = ig.DefineLabel ();
4515 ig.MarkLabel (ec.LoopBegin);
4516 ig.Emit (OpCodes.Ldloc, enumerator);
4517 ig.Emit (OpCodes.Callvirt, hm.move_next);
4518 ig.Emit (OpCodes.Brfalse, end_try);
4519 ig.Emit (OpCodes.Ldloc, enumerator);
4520 ig.Emit (OpCodes.Callvirt, hm.get_current);
4521 variable.EmitAssign (ec, conv);
4522 statement.Emit (ec);
4523 ig.Emit (OpCodes.Br, ec.LoopBegin);
4524 ig.MarkLabel (end_try);
4525 ec.InTry = old_in_try;
4527 // The runtime provides this for us.
4528 // ig.Emit (OpCodes.Leave, end);
4531 // Now the finally block
4533 if (hm.is_disposable) {
4534 Label end_finally = ig.DefineLabel ();
4535 bool old_in_finally = ec.InFinally;
4536 ec.InFinally = true;
4537 ig.BeginFinallyBlock ();
4539 ig.Emit (OpCodes.Ldloc, enumerator);
4540 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4541 ig.Emit (OpCodes.Stloc, disposable);
4542 ig.Emit (OpCodes.Ldloc, disposable);
4543 ig.Emit (OpCodes.Brfalse, end_finally);
4544 ig.Emit (OpCodes.Ldloc, disposable);
4545 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4546 ig.MarkLabel (end_finally);
4547 ec.InFinally = old_in_finally;
4549 // The runtime generates this anyways.
4550 // ig.Emit (OpCodes.Endfinally);
4552 ig.EndExceptionBlock ();
4555 ig.MarkLabel (ec.LoopEnd);
4560 // FIXME: possible optimization.
4561 // We might be able to avoid creating `empty' if the type is the sam
4563 bool EmitArrayForeach (EmitContext ec)
4565 int rank = array_type.GetArrayRank ();
4566 ILGenerator ig = ec.ig;
4568 LocalBuilder copy = ig.DeclareLocal (array_type);
4571 // Make our copy of the array
4574 ig.Emit (OpCodes.Stloc, copy);
4577 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
4581 ig.Emit (OpCodes.Ldc_I4_0);
4582 ig.Emit (OpCodes.Stloc, counter);
4583 test = ig.DefineLabel ();
4584 ig.Emit (OpCodes.Br, test);
4586 loop = ig.DefineLabel ();
4587 ig.MarkLabel (loop);
4589 ig.Emit (OpCodes.Ldloc, copy);
4590 ig.Emit (OpCodes.Ldloc, counter);
4591 ArrayAccess.EmitLoadOpcode (ig, var_type);
4593 variable.EmitAssign (ec, conv);
4595 statement.Emit (ec);
4597 ig.MarkLabel (ec.LoopBegin);
4598 ig.Emit (OpCodes.Ldloc, counter);
4599 ig.Emit (OpCodes.Ldc_I4_1);
4600 ig.Emit (OpCodes.Add);
4601 ig.Emit (OpCodes.Stloc, counter);
4603 ig.MarkLabel (test);
4604 ig.Emit (OpCodes.Ldloc, counter);
4605 ig.Emit (OpCodes.Ldloc, copy);
4606 ig.Emit (OpCodes.Ldlen);
4607 ig.Emit (OpCodes.Conv_I4);
4608 ig.Emit (OpCodes.Blt, loop);
4610 LocalBuilder [] dim_len = new LocalBuilder [rank];
4611 LocalBuilder [] dim_count = new LocalBuilder [rank];
4612 Label [] loop = new Label [rank];
4613 Label [] test = new Label [rank];
4616 for (dim = 0; dim < rank; dim++){
4617 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
4618 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
4619 test [dim] = ig.DefineLabel ();
4620 loop [dim] = ig.DefineLabel ();
4623 for (dim = 0; dim < rank; dim++){
4624 ig.Emit (OpCodes.Ldloc, copy);
4625 IntLiteral.EmitInt (ig, dim);
4626 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4627 ig.Emit (OpCodes.Stloc, dim_len [dim]);
4630 for (dim = 0; dim < rank; dim++){
4631 ig.Emit (OpCodes.Ldc_I4_0);
4632 ig.Emit (OpCodes.Stloc, dim_count [dim]);
4633 ig.Emit (OpCodes.Br, test [dim]);
4634 ig.MarkLabel (loop [dim]);
4637 ig.Emit (OpCodes.Ldloc, copy);
4638 for (dim = 0; dim < rank; dim++)
4639 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4642 // FIXME: Maybe we can cache the computation of `get'?
4644 Type [] args = new Type [rank];
4647 for (int i = 0; i < rank; i++)
4648 args [i] = TypeManager.int32_type;
4650 ModuleBuilder mb = CodeGen.ModuleBuilder;
4651 get = mb.GetArrayMethod (
4653 CallingConventions.HasThis| CallingConventions.Standard,
4655 ig.Emit (OpCodes.Call, get);
4656 variable.EmitAssign (ec, conv);
4657 statement.Emit (ec);
4658 ig.MarkLabel (ec.LoopBegin);
4659 for (dim = rank - 1; dim >= 0; dim--){
4660 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4661 ig.Emit (OpCodes.Ldc_I4_1);
4662 ig.Emit (OpCodes.Add);
4663 ig.Emit (OpCodes.Stloc, dim_count [dim]);
4665 ig.MarkLabel (test [dim]);
4666 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
4667 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
4668 ig.Emit (OpCodes.Blt, loop [dim]);
4671 ig.MarkLabel (ec.LoopEnd);
4676 public override bool Emit (EmitContext ec)
4680 ILGenerator ig = ec.ig;
4682 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4683 bool old_inloop = ec.InLoop;
4684 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4685 ec.LoopBegin = ig.DefineLabel ();
4686 ec.LoopEnd = ig.DefineLabel ();
4688 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4691 ret_val = EmitCollectionForeach (ec);
4693 ret_val = EmitArrayForeach (ec);
4695 ec.LoopBegin = old_begin;
4696 ec.LoopEnd = old_end;
4697 ec.InLoop = old_inloop;
4698 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;