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.Returns = FlowReturns.ALWAYS;
582 public override bool Emit (EmitContext ec)
585 Report.Error (157,loc,"Control can not leave the body of the finally block");
589 if (ec.ReturnType == null){
591 Report.Error (127, loc, "Return with a value not allowed here");
596 Report.Error (126, loc, "An object of type `" +
597 TypeManager.CSharpName (ec.ReturnType) + "' is " +
598 "expected for the return statement");
602 if (Expr.Type != ec.ReturnType)
603 Expr = Expression.ConvertImplicitRequired (
604 ec, Expr, ec.ReturnType, loc);
611 if (ec.InTry || ec.InCatch)
612 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
615 if (ec.InTry || ec.InCatch) {
616 if (!ec.HasReturnLabel) {
617 ec.ReturnLabel = ec.ig.DefineLabel ();
618 ec.HasReturnLabel = true;
620 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
622 ec.ig.Emit (OpCodes.Ret);
628 public class Goto : Statement {
631 LabeledStatement label;
633 public override bool Resolve (EmitContext ec)
635 label = block.LookupLabel (target);
639 "No such label `" + target + "' in this scope");
643 // If this is a forward goto.
644 if (!label.IsDefined)
645 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
647 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
652 public Goto (Block parent_block, string label, Location l)
654 block = parent_block;
659 public string Target {
665 public override bool Emit (EmitContext ec)
668 Label l = label.LabelTarget (ec);
669 ec.ig.Emit (OpCodes.Br, l);
675 public class LabeledStatement : Statement {
676 public readonly Location Location;
684 public LabeledStatement (string label_name, Location l)
686 this.label_name = label_name;
690 public Label LabelTarget (EmitContext ec)
694 label = ec.ig.DefineLabel ();
700 public bool IsDefined {
706 public bool HasBeenReferenced {
712 public void AddUsageVector (FlowBranching.UsageVector vector)
715 vectors = new ArrayList ();
717 vectors.Add (vector.Clone ());
720 public override bool Resolve (EmitContext ec)
723 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
730 public override bool Emit (EmitContext ec)
733 ec.ig.MarkLabel (label);
741 /// `goto default' statement
743 public class GotoDefault : Statement {
745 public GotoDefault (Location l)
750 public override bool Resolve (EmitContext ec)
752 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
753 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
757 public override bool Emit (EmitContext ec)
759 if (ec.Switch == null){
760 Report.Error (153, loc, "goto default is only valid in a switch statement");
764 if (!ec.Switch.GotDefault){
765 Report.Error (159, loc, "No default target on switch statement");
769 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
775 /// `goto case' statement
777 public class GotoCase : Statement {
781 public GotoCase (Expression e, Location l)
787 public override bool Resolve (EmitContext ec)
789 if (ec.Switch == null){
790 Report.Error (153, loc, "goto case is only valid in a switch statement");
794 expr = expr.Resolve (ec);
798 if (!(expr is Constant)){
799 Report.Error (159, loc, "Target expression for goto case is not constant");
803 object val = Expression.ConvertIntLiteral (
804 (Constant) expr, ec.Switch.SwitchType, loc);
809 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
814 "No such label 'case " + val + "': for the goto case");
817 label = sl.ILLabelCode;
819 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.UNREACHABLE;
820 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
824 public override bool Emit (EmitContext ec)
827 ec.ig.Emit (OpCodes.Br, label);
832 public class Throw : Statement {
835 public Throw (Expression expr, Location l)
841 public override bool Resolve (EmitContext ec)
844 expr = expr.Resolve (ec);
848 ExprClass eclass = expr.eclass;
850 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
851 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
852 expr.Error118 ("value, variable, property or indexer access ");
858 if ((t != TypeManager.exception_type) &&
859 !t.IsSubclassOf (TypeManager.exception_type) &&
860 !(expr is NullLiteral)) {
861 Report.Error (155, loc,
862 "The type caught or thrown must be derived " +
863 "from System.Exception");
868 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
872 public override bool Emit (EmitContext ec)
877 ec.ig.Emit (OpCodes.Rethrow);
881 "A throw statement with no argument is only " +
882 "allowed in a catch clause");
889 ec.ig.Emit (OpCodes.Throw);
895 public class Break : Statement {
897 public Break (Location l)
902 public override bool Resolve (EmitContext ec)
904 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
908 public override bool Emit (EmitContext ec)
910 ILGenerator ig = ec.ig;
912 if (ec.InLoop == false && ec.Switch == null){
913 Report.Error (139, loc, "No enclosing loop or switch to continue to");
918 if (ec.InTry || ec.InCatch)
919 ig.Emit (OpCodes.Leave, ec.LoopEnd);
921 ig.Emit (OpCodes.Br, ec.LoopEnd);
927 public class Continue : Statement {
929 public Continue (Location l)
934 public override bool Resolve (EmitContext ec)
936 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
940 public override bool Emit (EmitContext ec)
942 Label begin = ec.LoopBegin;
945 Report.Error (139, loc, "No enclosing loop to continue to");
950 // UGH: Non trivial. This Br might cross a try/catch boundary
954 // try { ... } catch { continue; }
958 // try {} catch { while () { continue; }}
961 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
962 ec.ig.Emit (OpCodes.Leave, begin);
963 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
964 throw new Exception ("Should never happen");
966 ec.ig.Emit (OpCodes.Br, begin);
972 // This is used in the control flow analysis code to specify whether the
973 // current code block may return to its enclosing block before reaching
976 public enum FlowReturns {
977 // It can never return.
980 // This means that the block contains a conditional return statement
984 // The code always returns, ie. there's an unconditional return / break
988 // The code always throws an exception.
991 // The current code block is unreachable. This happens if it's immediately
992 // following a FlowReturns.ALWAYS block.
997 // This is a special bit vector which can inherit from another bit vector doing a
998 // copy-on-write strategy. The inherited vector may have a smaller size than the
1001 public class MyBitVector {
1002 public readonly int Count;
1003 public readonly MyBitVector InheritsFrom;
1008 public MyBitVector (int Count)
1009 : this (null, Count)
1012 public MyBitVector (MyBitVector InheritsFrom, int Count)
1014 this.InheritsFrom = InheritsFrom;
1019 // Checks whether this bit vector has been modified. After setting this to true,
1020 // we won't use the inherited vector anymore, but our own copy of it.
1022 public bool IsDirty {
1029 initialize_vector ();
1034 // Get/set bit `index' in the bit vector.
1036 public bool this [int index]
1040 throw new ArgumentOutOfRangeException ();
1042 // We're doing a "copy-on-write" strategy here; as long
1043 // as nobody writes to the array, we can use our parent's
1044 // copy instead of duplicating the vector.
1047 return vector [index];
1048 else if (InheritsFrom != null) {
1049 BitArray inherited = InheritsFrom.Vector;
1051 if (index < inherited.Count)
1052 return inherited [index];
1061 throw new ArgumentOutOfRangeException ();
1063 // Only copy the vector if we're actually modifying it.
1065 if (this [index] != value) {
1066 initialize_vector ();
1068 vector [index] = value;
1074 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1075 // copy of the bit vector.
1077 public static explicit operator BitArray (MyBitVector vector)
1079 vector.initialize_vector ();
1080 return vector.Vector;
1084 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1085 // different size than the current one.
1087 public void Or (MyBitVector new_vector)
1089 BitArray new_array = new_vector.Vector;
1091 initialize_vector ();
1094 if (vector.Count < new_array.Count)
1095 upper = vector.Count;
1097 upper = new_array.Count;
1099 for (int i = 0; i < upper; i++)
1100 vector [i] = vector [i] | new_array [i];
1104 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1105 // a different size than the current one.
1107 public void And (MyBitVector new_vector)
1109 BitArray new_array = new_vector.Vector;
1111 initialize_vector ();
1114 if (vector.Count < new_array.Count)
1115 lower = upper = vector.Count;
1117 lower = new_array.Count;
1118 upper = vector.Count;
1121 for (int i = 0; i < lower; i++)
1122 vector [i] = vector [i] & new_array [i];
1124 for (int i = lower; i < upper; i++)
1129 // This does a deep copy of the bit vector.
1131 public MyBitVector Clone ()
1133 MyBitVector retval = new MyBitVector (Count);
1135 retval.Vector = Vector;
1144 else if (!is_dirty && (InheritsFrom != null))
1145 return InheritsFrom.Vector;
1147 initialize_vector ();
1153 initialize_vector ();
1155 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1156 vector [i] = value [i];
1160 void initialize_vector ()
1165 vector = new BitArray (Count, false);
1166 if (InheritsFrom != null)
1167 Vector = InheritsFrom.Vector;
1172 public override string ToString ()
1174 StringBuilder sb = new StringBuilder ("MyBitVector (");
1176 BitArray vector = Vector;
1180 sb.Append ("INHERITED - ");
1181 for (int i = 0; i < vector.Count; i++) {
1184 sb.Append (vector [i]);
1188 return sb.ToString ();
1193 // The type of a FlowBranching.
1195 public enum FlowBranchingType {
1196 // Normal (conditional or toplevel) block.
1213 // A new instance of this class is created every time a new block is resolved
1214 // and if there's branching in the block's control flow.
1216 public class FlowBranching {
1218 // The type of this flow branching.
1220 public readonly FlowBranchingType Type;
1223 // The block this branching is contained in. This may be null if it's not
1224 // a top-level block and it doesn't declare any local variables.
1226 public readonly Block Block;
1229 // The parent of this branching or null if this is the top-block.
1231 public readonly FlowBranching Parent;
1234 // Start-Location of this flow branching.
1236 public readonly Location Location;
1239 // A list of UsageVectors. A new vector is added each time control flow may
1240 // take a different path.
1242 public ArrayList Siblings;
1247 InternalParameters param_info;
1249 MyStructInfo[] struct_params;
1251 ArrayList finally_vectors;
1253 static int next_id = 0;
1257 // Performs an `And' operation on the FlowReturns status
1258 // (for instance, a block only returns ALWAYS if all its siblings
1261 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1263 if (b == FlowReturns.UNREACHABLE)
1267 case FlowReturns.NEVER:
1268 if (b == FlowReturns.NEVER)
1269 return FlowReturns.NEVER;
1271 return FlowReturns.SOMETIMES;
1273 case FlowReturns.SOMETIMES:
1274 return FlowReturns.SOMETIMES;
1276 case FlowReturns.ALWAYS:
1277 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1278 return FlowReturns.ALWAYS;
1280 return FlowReturns.SOMETIMES;
1282 case FlowReturns.EXCEPTION:
1283 if (b == FlowReturns.EXCEPTION)
1284 return FlowReturns.EXCEPTION;
1285 else if (b == FlowReturns.ALWAYS)
1286 return FlowReturns.ALWAYS;
1288 return FlowReturns.SOMETIMES;
1295 // The vector contains a BitArray with information about which local variables
1296 // and parameters are already initialized at the current code position.
1298 public class UsageVector {
1300 // If this is true, then the usage vector has been modified and must be
1301 // merged when we're done with this branching.
1303 public bool IsDirty;
1306 // The number of parameters in this block.
1308 public readonly int CountParameters;
1311 // The number of locals in this block.
1313 public readonly int CountLocals;
1316 // If not null, then we inherit our state from this vector and do a
1317 // copy-on-write. If null, then we're the first sibling in a top-level
1318 // block and inherit from the empty vector.
1320 public readonly UsageVector InheritsFrom;
1325 MyBitVector locals, parameters;
1326 FlowReturns real_returns, real_breaks;
1327 bool breaks_set, is_finally;
1329 static int next_id = 0;
1333 // Normally, you should not use any of these constructors.
1335 public UsageVector (UsageVector parent, int num_params, int num_locals)
1337 this.InheritsFrom = parent;
1338 this.CountParameters = num_params;
1339 this.CountLocals = num_locals;
1340 this.real_returns = FlowReturns.NEVER;
1341 this.real_breaks = FlowReturns.NEVER;
1343 if (parent != null) {
1344 locals = new MyBitVector (parent.locals, CountLocals);
1346 parameters = new MyBitVector (parent.parameters, num_params);
1348 locals = new MyBitVector (null, CountLocals);
1350 parameters = new MyBitVector (null, num_params);
1356 public UsageVector (UsageVector parent)
1357 : this (parent, parent.CountParameters, parent.CountLocals)
1361 // This does a deep copy of the usage vector.
1363 public UsageVector Clone ()
1365 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1367 retval.locals = locals.Clone ();
1368 if (parameters != null)
1369 retval.parameters = parameters.Clone ();
1370 retval.real_returns = real_returns;
1371 retval.real_breaks = real_breaks;
1377 // State of parameter `number'.
1379 public bool this [int number]
1384 else if (number == 0)
1385 throw new ArgumentException ();
1387 return parameters [number - 1];
1393 else if (number == 0)
1394 throw new ArgumentException ();
1396 parameters [number - 1] = value;
1401 // State of the local variable `vi'.
1402 // If the local variable is a struct, use a non-zero `field_idx'
1403 // to check an individual field in it.
1405 public bool this [VariableInfo vi, int field_idx]
1408 if (vi.Number == -1)
1410 else if (vi.Number == 0)
1411 throw new ArgumentException ();
1413 return locals [vi.Number + field_idx - 1];
1417 if (vi.Number == -1)
1419 else if (vi.Number == 0)
1420 throw new ArgumentException ();
1422 locals [vi.Number + field_idx - 1] = value;
1427 // Specifies when the current block returns.
1429 public FlowReturns Returns {
1431 return real_returns;
1435 real_returns = value;
1440 // Specifies whether control may return to our containing block
1441 // before reaching the end of this block. This happens if there
1442 // is a break/continue/goto/return in it.
1444 public FlowReturns Breaks {
1450 real_breaks = value;
1456 // Merge a child branching.
1458 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1460 MyBitVector new_locals = null;
1461 MyBitVector new_params = null;
1463 FlowReturns new_returns = FlowReturns.NEVER;
1464 FlowReturns new_breaks = FlowReturns.NEVER;
1465 bool new_returns_set = false, new_breaks_set = false;
1468 Report.Debug (1, "MERGING CHILDREN", branching, this);
1470 foreach (UsageVector child in children) {
1471 Report.Debug (1, " MERGING CHILD", child, child.is_finally);
1473 if (!child.is_finally) {
1474 // If Returns is already set, perform an
1475 // `And' operation on it, otherwise just set just.
1476 if (!new_returns_set) {
1477 new_returns = child.Returns;
1478 new_returns_set = true;
1480 new_returns = AndFlowReturns (
1481 new_returns, child.Returns);
1483 // If Breaks is already set, perform an
1484 // `And' operation on it, otherwise just set just.
1485 if (!new_breaks_set) {
1486 new_breaks = child.Breaks;
1487 new_breaks_set = true;
1489 new_breaks = AndFlowReturns (
1490 new_breaks, child.Breaks);
1492 // Check whether control may reach the end of this sibling.
1493 // This happens unless we either always return or always break.
1494 if ((child.Returns == FlowReturns.EXCEPTION) ||
1495 (child.Returns == FlowReturns.ALWAYS) ||
1496 ((branching.Type != FlowBranchingType.SWITCH_SECTION) &&
1497 (branching.Type != FlowBranchingType.LOOP_BLOCK) &&
1498 (child.Breaks == FlowReturns.ALWAYS)))
1505 // Ignore unreachable children.
1506 if (child.Returns == FlowReturns.UNREACHABLE)
1509 // A local variable is initialized after a flow branching if it
1510 // has been initialized in all its branches which do neither
1511 // always return or always throw an exception.
1513 // If a branch may return, but does not always return, then we
1514 // can treat it like a never-returning branch here: control will
1515 // only reach the code position after the branching if we did not
1518 // It's important to distinguish between always and sometimes
1519 // returning branches here:
1522 // 2 if (something) {
1526 // 6 Console.WriteLine (a);
1528 // The if block in lines 3-4 always returns, so we must not look
1529 // at the initialization of `a' in line 4 - thus it'll still be
1530 // uninitialized in line 6.
1532 // On the other hand, the following is allowed:
1539 // 6 Console.WriteLine (a);
1541 // Here, `a' is initialized in line 3 and we must not look at
1542 // line 5 since it always returns.
1544 if (child.is_finally) {
1545 if (new_locals == null)
1546 new_locals = locals.Clone ();
1547 new_locals.Or (child.locals);
1548 } else if (!breaks) {
1549 if (new_locals != null)
1550 new_locals.And (child.locals);
1552 new_locals = locals.Clone ();
1553 new_locals.Or (child.locals);
1557 // An `out' parameter must be assigned in all branches which do
1558 // not always throw an exception.
1559 if (!child.is_finally && (child.Returns != FlowReturns.EXCEPTION)) {
1560 if (parameters != null) {
1561 if (new_params != null)
1562 new_params.And (child.parameters);
1564 new_params = parameters.Clone ();
1565 new_params.Or (child.parameters);
1570 // If we always return, check whether all `out' parameters have
1572 if ((child.Returns == FlowReturns.ALWAYS) && (child.parameters != null)) {
1573 branching.CheckOutParameters (
1574 child.parameters, branching.Location);
1578 Returns = new_returns;
1581 // We've now either reached the point after the branching or we will
1582 // never get there since we always return or always throw an exception.
1584 // If we can reach the point after the branching, mark all locals and
1585 // parameters as initialized which have been initialized in all branches
1586 // we need to look at (see above).
1589 bool or_locals = (Returns == FlowReturns.NEVER) ||
1590 (Returns == FlowReturns.SOMETIMES);
1591 if ((branching.Type != FlowBranchingType.SWITCH_SECTION) &&
1592 (branching.Type != FlowBranchingType.LOOP_BLOCK))
1593 or_locals &= ((Breaks == FlowReturns.NEVER) ||
1594 (Breaks == FlowReturns.SOMETIMES));
1596 if ((new_locals != null) && or_locals) {
1597 locals.Or (new_locals);
1600 if ((new_params != null) && (Breaks == FlowReturns.NEVER))
1601 parameters.Or (new_params);
1604 // If we may have returned (this only happens if there was a reachable
1605 // `return' statement in one of the branches), then we may return to our
1606 // parent block before reaching the end of the block, so set `Breaks'.
1608 if ((Returns != FlowReturns.NEVER) && (Returns != FlowReturns.SOMETIMES)) {
1609 // real_breaks = Returns;
1610 // breaks_set = true;
1611 } else if (branching.Type == FlowBranchingType.BLOCK) {
1613 // If this is not a loop or switch block, `break' actually breaks.
1617 Breaks = new_breaks;
1620 Breaks = AndFlowReturns (Breaks, new_breaks);
1623 if (new_returns == FlowReturns.EXCEPTION)
1624 Breaks = FlowReturns.UNREACHABLE;
1626 Report.Debug (1, "MERGING CHILDREN DONE", new_params, new_locals,
1627 new_returns, new_breaks, this);
1633 // Tells control flow analysis that the current code position may be reached with
1634 // a forward jump from any of the origins listed in `origin_vectors' which is a
1635 // list of UsageVectors.
1637 // This is used when resolving forward gotos - in the following example, the
1638 // variable `a' is uninitialized in line 8 becase this line may be reached via
1639 // the goto in line 4:
1649 // 8 Console.WriteLine (a);
1652 public void MergeJumpOrigins (ICollection origin_vectors)
1654 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1656 real_breaks = FlowReturns.NEVER;
1659 foreach (UsageVector vector in origin_vectors) {
1660 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1662 locals.And (vector.locals);
1663 if (parameters != null)
1664 parameters.And (vector.parameters);
1665 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1668 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1672 // This is used at the beginning of a finally block if there were
1673 // any return statements in the try block or one of the catch blocks.
1675 public void MergeFinallyOrigins (ICollection finally_vectors)
1677 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1679 real_breaks = FlowReturns.NEVER;
1682 foreach (UsageVector vector in finally_vectors) {
1683 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1685 if (parameters != null)
1686 parameters.And (vector.parameters);
1687 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1692 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1696 // Performs an `or' operation on the locals and the parameters.
1698 public void Or (UsageVector new_vector)
1700 locals.Or (new_vector.locals);
1701 if (parameters != null)
1702 parameters.Or (new_vector.parameters);
1706 // Performs an `and' operation on the locals.
1708 public void AndLocals (UsageVector new_vector)
1710 locals.And (new_vector.locals);
1714 // Returns a deep copy of the parameters.
1716 public MyBitVector Parameters {
1718 if (parameters != null)
1719 return parameters.Clone ();
1726 // Returns a deep copy of the locals.
1728 public MyBitVector Locals {
1730 return locals.Clone ();
1738 public override string ToString ()
1740 StringBuilder sb = new StringBuilder ();
1742 sb.Append ("Vector (");
1745 sb.Append (Returns);
1748 if (parameters != null) {
1750 sb.Append (parameters);
1756 return sb.ToString ();
1760 FlowBranching (FlowBranchingType type, Location loc)
1762 this.Siblings = new ArrayList ();
1764 this.Location = loc;
1770 // Creates a new flow branching for `block'.
1771 // This is used from Block.Resolve to create the top-level branching of
1774 public FlowBranching (Block block, InternalParameters ip, Location loc)
1775 : this (FlowBranchingType.BLOCK, loc)
1780 int count = (ip != null) ? ip.Count : 0;
1783 param_map = new int [count];
1784 struct_params = new MyStructInfo [count];
1787 for (int i = 0; i < count; i++) {
1788 Parameter.Modifier mod = param_info.ParameterModifier (i);
1790 if ((mod & Parameter.Modifier.OUT) == 0)
1793 param_map [i] = ++num_params;
1795 Type param_type = param_info.ParameterType (i);
1797 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1798 if (struct_params [i] != null)
1799 num_params += struct_params [i].Count;
1802 Siblings = new ArrayList ();
1803 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1807 // Creates a new flow branching which is contained in `parent'.
1808 // You should only pass non-null for the `block' argument if this block
1809 // introduces any new variables - in this case, we need to create a new
1810 // usage vector with a different size than our parent's one.
1812 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1813 Block block, Location loc)
1819 if (parent != null) {
1820 param_info = parent.param_info;
1821 param_map = parent.param_map;
1822 struct_params = parent.struct_params;
1823 num_params = parent.num_params;
1828 vector = new UsageVector (parent.CurrentUsageVector, num_params,
1829 Block.CountVariables);
1831 vector = new UsageVector (Parent.CurrentUsageVector);
1833 Siblings.Add (vector);
1836 case FlowBranchingType.EXCEPTION:
1837 finally_vectors = new ArrayList ();
1846 // Returns the branching's current usage vector.
1848 public UsageVector CurrentUsageVector
1851 return (UsageVector) Siblings [Siblings.Count - 1];
1856 // Creates a sibling of the current usage vector.
1858 public void CreateSibling ()
1860 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
1862 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
1866 // Creates a sibling for a `finally' block.
1868 public void CreateSiblingForFinally ()
1870 if (Type != FlowBranchingType.EXCEPTION)
1871 throw new NotSupportedException ();
1875 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
1879 // Check whether all `out' parameters have been assigned.
1881 public void CheckOutParameters (MyBitVector parameters, Location loc)
1886 for (int i = 0; i < param_map.Length; i++) {
1887 int index = param_map [i];
1892 if (parameters [index - 1])
1895 // If it's a struct, we must ensure that all its fields have
1896 // been assigned. If the struct has any non-public fields, this
1897 // can only be done by assigning the whole struct.
1899 MyStructInfo struct_info = struct_params [index - 1];
1900 if ((struct_info == null) || struct_info.HasNonPublicFields) {
1902 177, loc, "The out parameter `" +
1903 param_info.ParameterName (i) + "' must be " +
1904 "assigned before control leave the current method.");
1910 for (int j = 0; j < struct_info.Count; j++) {
1911 if (!parameters [index + j]) {
1913 177, loc, "The out parameter `" +
1914 param_info.ParameterName (i) + "' must be " +
1915 "assigned before control leave the current method.");
1924 // Merge a child branching.
1926 public FlowReturns MergeChild (FlowBranching child)
1928 return CurrentUsageVector.MergeChildren (child, child.Siblings);
1932 // Does the toplevel merging.
1934 public FlowReturns MergeTopBlock ()
1936 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
1937 throw new NotSupportedException ();
1939 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
1941 vector.MergeChildren (this, Siblings);
1944 Siblings.Add (vector);
1946 Report.Debug (1, "MERGING TOP BLOCK", vector);
1948 if (vector.Returns != FlowReturns.EXCEPTION)
1949 CheckOutParameters (CurrentUsageVector.Parameters, Location);
1951 return vector.Returns;
1954 public bool InTryBlock ()
1956 if (finally_vectors != null)
1958 else if (Parent != null)
1959 return Parent.InTryBlock ();
1964 public void AddFinallyVector (UsageVector vector)
1966 if (finally_vectors != null) {
1967 finally_vectors.Add (vector.Clone ());
1972 Parent.AddFinallyVector (vector);
1974 throw new NotSupportedException ();
1977 public bool IsVariableAssigned (VariableInfo vi)
1979 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1982 return CurrentUsageVector [vi, 0];
1985 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
1987 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1990 return CurrentUsageVector [vi, field_idx];
1993 public void SetVariableAssigned (VariableInfo vi)
1995 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
1998 CurrentUsageVector [vi, 0] = true;
2001 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2003 if (CurrentUsageVector.Breaks == FlowReturns.UNREACHABLE)
2006 CurrentUsageVector [vi, field_idx] = true;
2009 public bool IsParameterAssigned (int number)
2011 int index = param_map [number];
2016 if (CurrentUsageVector [index])
2019 // Parameter is not assigned, so check whether it's a struct.
2020 // If it's either not a struct or a struct which non-public
2021 // fields, return false.
2022 MyStructInfo struct_info = struct_params [number];
2023 if ((struct_info == null) || struct_info.HasNonPublicFields)
2026 // Ok, so each field must be assigned.
2027 for (int i = 0; i < struct_info.Count; i++)
2028 if (!CurrentUsageVector [index + i])
2034 public bool IsParameterAssigned (int number, string field_name)
2036 int index = param_map [number];
2041 int field_idx = struct_params [number] [field_name];
2043 return CurrentUsageVector [index + field_idx];
2046 public void SetParameterAssigned (int number)
2048 if (param_map [number] == 0)
2051 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
2052 CurrentUsageVector [param_map [number]] = true;
2055 public void SetParameterAssigned (int number, string field_name)
2057 int index = param_map [number];
2062 int field_idx = struct_params [number] [field_name];
2064 if (CurrentUsageVector.Breaks == FlowReturns.NEVER)
2065 CurrentUsageVector [index + field_idx] = true;
2068 public override string ToString ()
2070 StringBuilder sb = new StringBuilder ("FlowBranching (");
2075 if (Block != null) {
2077 sb.Append (Block.ID);
2079 sb.Append (Block.StartLocation);
2082 sb.Append (Siblings.Count);
2084 sb.Append (CurrentUsageVector);
2086 return sb.ToString ();
2090 public class MyStructInfo {
2091 public readonly Type Type;
2092 public readonly FieldInfo[] Fields;
2093 public readonly FieldInfo[] NonPublicFields;
2094 public readonly int Count;
2095 public readonly int CountNonPublic;
2096 public readonly bool HasNonPublicFields;
2098 private static Hashtable field_type_hash = new Hashtable ();
2099 private Hashtable field_hash;
2101 // Private constructor. To save memory usage, we only need to create one instance
2102 // of this class per struct type.
2103 private MyStructInfo (Type type)
2107 if (type is TypeBuilder) {
2108 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2110 ArrayList fields = tc.Fields;
2111 if (fields != null) {
2112 foreach (Field field in fields) {
2113 if ((field.ModFlags & Modifiers.STATIC) != 0)
2115 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2122 Fields = new FieldInfo [Count];
2123 NonPublicFields = new FieldInfo [CountNonPublic];
2125 Count = CountNonPublic = 0;
2126 if (fields != null) {
2127 foreach (Field field in fields) {
2128 if ((field.ModFlags & Modifiers.STATIC) != 0)
2130 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2131 Fields [Count++] = field.FieldBuilder;
2133 NonPublicFields [CountNonPublic++] =
2139 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2140 Count = Fields.Length;
2142 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2143 CountNonPublic = NonPublicFields.Length;
2146 Count += NonPublicFields.Length;
2149 field_hash = new Hashtable ();
2150 foreach (FieldInfo field in Fields)
2151 field_hash.Add (field.Name, ++number);
2153 if (NonPublicFields.Length != 0)
2154 HasNonPublicFields = true;
2156 foreach (FieldInfo field in NonPublicFields)
2157 field_hash.Add (field.Name, ++number);
2160 public int this [string name] {
2162 if (field_hash.Contains (name))
2163 return (int) field_hash [name];
2169 public FieldInfo this [int index] {
2171 if (index >= Fields.Length)
2172 return NonPublicFields [index - Fields.Length];
2174 return Fields [index];
2178 public static MyStructInfo GetStructInfo (Type type)
2180 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2183 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2186 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2190 info = new MyStructInfo (type);
2191 field_type_hash.Add (type, info);
2195 public static MyStructInfo GetStructInfo (TypeContainer tc)
2197 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2201 info = new MyStructInfo (tc.TypeBuilder);
2202 field_type_hash.Add (tc.TypeBuilder, info);
2207 public class VariableInfo : IVariable {
2208 public Expression Type;
2209 public LocalBuilder LocalBuilder;
2210 public Type VariableType;
2211 public readonly string Name;
2212 public readonly Location Location;
2213 public readonly int Block;
2218 public bool Assigned;
2219 public bool ReadOnly;
2221 public VariableInfo (Expression type, string name, int block, Location l)
2226 LocalBuilder = null;
2230 public VariableInfo (TypeContainer tc, int block, Location l)
2232 VariableType = tc.TypeBuilder;
2233 struct_info = MyStructInfo.GetStructInfo (tc);
2235 LocalBuilder = null;
2239 MyStructInfo struct_info;
2240 public MyStructInfo StructInfo {
2246 public bool IsAssigned (EmitContext ec, Location loc)
2248 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2251 MyStructInfo struct_info = StructInfo;
2252 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2253 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2254 ec.CurrentBranching.SetVariableAssigned (this);
2258 int count = struct_info.Count;
2260 for (int i = 0; i < count; i++) {
2261 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2263 Report.Error (165, loc,
2264 "Use of unassigned local variable `" +
2266 ec.CurrentBranching.SetVariableAssigned (this);
2270 FieldInfo field = struct_info [i];
2271 Report.Error (171, loc,
2272 "Field `" + TypeManager.CSharpName (VariableType) +
2273 "." + field.Name + "' must be fully initialized " +
2274 "before control leaves the constructor");
2282 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2284 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2285 (struct_info == null))
2288 int field_idx = StructInfo [name];
2292 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2293 Report.Error (170, loc,
2294 "Use of possibly unassigned field `" + name + "'");
2295 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2302 public void SetAssigned (EmitContext ec)
2304 if (ec.DoFlowAnalysis)
2305 ec.CurrentBranching.SetVariableAssigned (this);
2308 public void SetFieldAssigned (EmitContext ec, string name)
2310 if (ec.DoFlowAnalysis && (struct_info != null))
2311 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2314 public bool Resolve (DeclSpace decl)
2316 if (struct_info != null)
2319 if (VariableType == null)
2320 VariableType = decl.ResolveType (Type, false, Location);
2322 if (VariableType == null)
2325 struct_info = MyStructInfo.GetStructInfo (VariableType);
2330 public void MakePinned ()
2332 TypeManager.MakePinned (LocalBuilder);
2335 public override string ToString ()
2337 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2342 /// Block represents a C# block.
2346 /// This class is used in a number of places: either to represent
2347 /// explicit blocks that the programmer places or implicit blocks.
2349 /// Implicit blocks are used as labels or to introduce variable
2352 public class Block : Statement {
2353 public readonly Block Parent;
2354 public readonly bool Implicit;
2355 public readonly Location StartLocation;
2356 public Location EndLocation;
2359 // The statements in this block
2361 ArrayList statements;
2364 // An array of Blocks. We keep track of children just
2365 // to generate the local variable declarations.
2367 // Statements and child statements are handled through the
2373 // Labels. (label, block) pairs.
2378 // Keeps track of (name, type) pairs
2380 Hashtable variables;
2383 // Keeps track of constants
2384 Hashtable constants;
2387 // Maps variable names to ILGenerator.LocalBuilders
2389 Hashtable local_builders;
2397 public Block (Block parent)
2398 : this (parent, false, Location.Null, Location.Null)
2401 public Block (Block parent, bool implicit_block)
2402 : this (parent, implicit_block, Location.Null, Location.Null)
2405 public Block (Block parent, bool implicit_block, Parameters parameters)
2406 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2409 public Block (Block parent, Location start, Location end)
2410 : this (parent, false, start, end)
2413 public Block (Block parent, Parameters parameters, Location start, Location end)
2414 : this (parent, false, parameters, start, end)
2417 public Block (Block parent, bool implicit_block, Location start, Location end)
2418 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2422 public Block (Block parent, bool implicit_block, Parameters parameters,
2423 Location start, Location end)
2426 parent.AddChild (this);
2428 this.Parent = parent;
2429 this.Implicit = implicit_block;
2430 this.parameters = parameters;
2431 this.StartLocation = start;
2432 this.EndLocation = end;
2435 statements = new ArrayList ();
2444 void AddChild (Block b)
2446 if (children == null)
2447 children = new ArrayList ();
2452 public void SetEndLocation (Location loc)
2458 /// Adds a label to the current block.
2462 /// false if the name already exists in this block. true
2466 public bool AddLabel (string name, LabeledStatement target)
2469 labels = new Hashtable ();
2470 if (labels.Contains (name))
2473 labels.Add (name, target);
2477 public LabeledStatement LookupLabel (string name)
2479 if (labels != null){
2480 if (labels.Contains (name))
2481 return ((LabeledStatement) labels [name]);
2485 return Parent.LookupLabel (name);
2490 VariableInfo this_variable = null;
2493 // Returns the "this" instance variable of this block.
2494 // See AddThisVariable() for more information.
2496 public VariableInfo ThisVariable {
2498 if (this_variable != null)
2499 return this_variable;
2500 else if (Parent != null)
2501 return Parent.ThisVariable;
2507 Hashtable child_variable_names;
2510 // Marks a variable with name @name as being used in a child block.
2511 // If a variable name has been used in a child block, it's illegal to
2512 // declare a variable with the same name in the current block.
2514 public void AddChildVariableName (string name)
2516 if (child_variable_names == null)
2517 child_variable_names = new Hashtable ();
2519 if (!child_variable_names.Contains (name))
2520 child_variable_names.Add (name, true);
2524 // Marks all variables from block @block and all its children as being
2525 // used in a child block.
2527 public void AddChildVariableNames (Block block)
2529 if (block.Variables != null) {
2530 foreach (string name in block.Variables.Keys)
2531 AddChildVariableName (name);
2534 foreach (Block child in block.children) {
2535 if (child.Variables != null) {
2536 foreach (string name in child.Variables.Keys)
2537 AddChildVariableName (name);
2543 // Checks whether a variable name has already been used in a child block.
2545 public bool IsVariableNameUsedInChildBlock (string name)
2547 if (child_variable_names == null)
2550 return child_variable_names.Contains (name);
2554 // This is used by non-static `struct' constructors which do not have an
2555 // initializer - in this case, the constructor must initialize all of the
2556 // struct's fields. To do this, we add a "this" variable and use the flow
2557 // analysis code to ensure that it's been fully initialized before control
2558 // leaves the constructor.
2560 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2562 if (this_variable != null)
2563 return this_variable;
2565 this_variable = new VariableInfo (tc, ID, l);
2567 if (variables == null)
2568 variables = new Hashtable ();
2569 variables.Add ("this", this_variable);
2571 return this_variable;
2574 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2576 if (variables == null)
2577 variables = new Hashtable ();
2579 VariableInfo vi = GetVariableInfo (name);
2582 Report.Error (136, l, "A local variable named `" + name + "' " +
2583 "cannot be declared in this scope since it would " +
2584 "give a different meaning to `" + name + "', which " +
2585 "is already used in a `parent or current' scope to " +
2586 "denote something else");
2588 Report.Error (128, l, "A local variable `" + name + "' is already " +
2589 "defined in this scope");
2593 if (IsVariableNameUsedInChildBlock (name)) {
2594 Report.Error (136, l, "A local variable named `" + name + "' " +
2595 "cannot be declared in this scope since it would " +
2596 "give a different meaning to `" + name + "', which " +
2597 "is already used in a `child' scope to denote something " +
2604 Parameter p = pars.GetParameterByName (name, out idx);
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");
2615 vi = new VariableInfo (type, name, ID, l);
2617 variables.Add (name, vi);
2619 if (variables_initialized)
2620 throw new Exception ();
2622 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2626 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2628 if (AddVariable (type, name, pars, l) == null)
2631 if (constants == null)
2632 constants = new Hashtable ();
2634 constants.Add (name, value);
2638 public Hashtable Variables {
2644 public VariableInfo GetVariableInfo (string name)
2646 if (variables != null) {
2648 temp = variables [name];
2651 return (VariableInfo) temp;
2656 return Parent.GetVariableInfo (name);
2661 public Expression GetVariableType (string name)
2663 VariableInfo vi = GetVariableInfo (name);
2671 public Expression GetConstantExpression (string name)
2673 if (constants != null) {
2675 temp = constants [name];
2678 return (Expression) temp;
2682 return Parent.GetConstantExpression (name);
2688 /// True if the variable named @name has been defined
2691 public bool IsVariableDefined (string name)
2693 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2694 if (variables != null) {
2695 if (variables.Contains (name))
2700 return Parent.IsVariableDefined (name);
2706 /// True if the variable named @name is a constant
2708 public bool IsConstant (string name)
2710 Expression e = null;
2712 e = GetConstantExpression (name);
2718 /// Use to fetch the statement associated with this label
2720 public Statement this [string name] {
2722 return (Statement) labels [name];
2726 Parameters parameters = null;
2727 public Parameters Parameters {
2730 return Parent.Parameters;
2737 /// A list of labels that were not used within this block
2739 public string [] GetUnreferenced ()
2741 // FIXME: Implement me
2745 public void AddStatement (Statement s)
2762 bool variables_initialized = false;
2763 int count_variables = 0, first_variable = 0;
2765 void UpdateVariableInfo (EmitContext ec)
2767 DeclSpace ds = ec.DeclSpace;
2772 first_variable += Parent.CountVariables;
2774 count_variables = first_variable;
2775 if (variables != null) {
2776 foreach (VariableInfo vi in variables.Values) {
2777 if (!vi.Resolve (ds)) {
2782 vi.Number = ++count_variables;
2784 if (vi.StructInfo != null)
2785 count_variables += vi.StructInfo.Count;
2789 variables_initialized = true;
2794 // The number of local variables in this block
2796 public int CountVariables
2799 if (!variables_initialized)
2800 throw new Exception ();
2802 return count_variables;
2807 /// Emits the variable declarations and labels.
2810 /// tc: is our typecontainer (to resolve type references)
2811 /// ig: is the code generator:
2812 /// toplevel: the toplevel block. This is used for checking
2813 /// that no two labels with the same name are used.
2815 public void EmitMeta (EmitContext ec, Block toplevel)
2817 DeclSpace ds = ec.DeclSpace;
2818 ILGenerator ig = ec.ig;
2820 if (!variables_initialized)
2821 UpdateVariableInfo (ec);
2824 // Process this block variables
2826 if (variables != null){
2827 local_builders = new Hashtable ();
2829 foreach (DictionaryEntry de in variables){
2830 string name = (string) de.Key;
2831 VariableInfo vi = (VariableInfo) de.Value;
2833 if (vi.VariableType == null)
2836 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
2838 if (CodeGen.SymbolWriter != null)
2839 vi.LocalBuilder.SetLocalSymInfo (name);
2841 if (constants == null)
2844 Expression cv = (Expression) constants [name];
2848 Expression e = cv.Resolve (ec);
2852 if (!(e is Constant)){
2853 Report.Error (133, vi.Location,
2854 "The expression being assigned to `" +
2855 name + "' must be constant (" + e + ")");
2859 constants.Remove (name);
2860 constants.Add (name, e);
2865 // Now, handle the children
2867 if (children != null){
2868 foreach (Block b in children)
2869 b.EmitMeta (ec, toplevel);
2873 public void UsageWarning ()
2877 if (variables != null){
2878 foreach (DictionaryEntry de in variables){
2879 VariableInfo vi = (VariableInfo) de.Value;
2884 name = (string) de.Key;
2888 219, vi.Location, "The variable `" + name +
2889 "' is assigned but its value is never used");
2892 168, vi.Location, "The variable `" +
2894 "' is declared but never used");
2899 if (children != null)
2900 foreach (Block b in children)
2904 public override bool Resolve (EmitContext ec)
2906 Block prev_block = ec.CurrentBlock;
2909 ec.CurrentBlock = this;
2910 ec.StartFlowBranching (this);
2912 Report.Debug (1, "RESOLVE BLOCK", StartLocation);
2914 if (!variables_initialized)
2915 UpdateVariableInfo (ec);
2917 foreach (Statement s in statements){
2918 if (s.Resolve (ec) == false)
2922 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation);
2924 FlowReturns returns = ec.EndFlowBranching ();
2925 ec.CurrentBlock = prev_block;
2927 // If we're a non-static `struct' constructor which doesn't have an
2928 // initializer, then we must initialize all of the struct's fields.
2929 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
2930 !this_variable.IsAssigned (ec, loc))
2933 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2934 foreach (LabeledStatement label in labels.Values)
2935 if (!label.HasBeenReferenced)
2936 Report.Warning (164, label.Location,
2937 "This label has not been referenced");
2943 public override bool Emit (EmitContext ec)
2945 bool is_ret = false, this_ret = false;
2946 Block prev_block = ec.CurrentBlock;
2947 bool warning_shown = false;
2949 ec.CurrentBlock = this;
2951 if (CodeGen.SymbolWriter != null) {
2952 ec.Mark (StartLocation);
2954 foreach (Statement s in statements) {
2957 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2958 warning_shown = true;
2959 Warning_DeadCodeFound (s.loc);
2962 this_ret = s.Emit (ec);
2967 ec.Mark (EndLocation);
2969 foreach (Statement s in statements){
2970 if (is_ret && !warning_shown && !(s is EmptyStatement)){
2971 warning_shown = true;
2972 Warning_DeadCodeFound (s.loc);
2975 this_ret = s.Emit (ec);
2981 ec.CurrentBlock = prev_block;
2986 public class SwitchLabel {
2989 public Location loc;
2990 public Label ILLabel;
2991 public Label ILLabelCode;
2994 // if expr == null, then it is the default case.
2996 public SwitchLabel (Expression expr, Location l)
3002 public Expression Label {
3008 public object Converted {
3015 // Resolves the expression, reduces it to a literal if possible
3016 // and then converts it to the requested type.
3018 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3020 ILLabel = ec.ig.DefineLabel ();
3021 ILLabelCode = ec.ig.DefineLabel ();
3026 Expression e = label.Resolve (ec);
3031 if (!(e is Constant)){
3032 Console.WriteLine ("Value is: " + label);
3033 Report.Error (150, loc, "A constant value is expected");
3037 if (e is StringConstant || e is NullLiteral){
3038 if (required_type == TypeManager.string_type){
3040 ILLabel = ec.ig.DefineLabel ();
3045 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3046 if (converted == null)
3053 public class SwitchSection {
3054 // An array of SwitchLabels.
3055 public readonly ArrayList Labels;
3056 public readonly Block Block;
3058 public SwitchSection (ArrayList labels, Block block)
3065 public class Switch : Statement {
3066 public readonly ArrayList Sections;
3067 public Expression Expr;
3070 /// Maps constants whose type type SwitchType to their SwitchLabels.
3072 public Hashtable Elements;
3075 /// The governing switch type
3077 public Type SwitchType;
3083 Label default_target;
3084 Expression new_expr;
3087 // The types allowed to be implicitly cast from
3088 // on the governing type
3090 static Type [] allowed_types;
3092 public Switch (Expression e, ArrayList sects, Location l)
3099 public bool GotDefault {
3105 public Label DefaultTarget {
3107 return default_target;
3112 // Determines the governing type for a switch. The returned
3113 // expression might be the expression from the switch, or an
3114 // expression that includes any potential conversions to the
3115 // integral types or to string.
3117 Expression SwitchGoverningType (EmitContext ec, Type t)
3119 if (t == TypeManager.int32_type ||
3120 t == TypeManager.uint32_type ||
3121 t == TypeManager.char_type ||
3122 t == TypeManager.byte_type ||
3123 t == TypeManager.sbyte_type ||
3124 t == TypeManager.ushort_type ||
3125 t == TypeManager.short_type ||
3126 t == TypeManager.uint64_type ||
3127 t == TypeManager.int64_type ||
3128 t == TypeManager.string_type ||
3129 t == TypeManager.bool_type ||
3130 t.IsSubclassOf (TypeManager.enum_type))
3133 if (allowed_types == null){
3134 allowed_types = new Type [] {
3135 TypeManager.sbyte_type,
3136 TypeManager.byte_type,
3137 TypeManager.short_type,
3138 TypeManager.ushort_type,
3139 TypeManager.int32_type,
3140 TypeManager.uint32_type,
3141 TypeManager.int64_type,
3142 TypeManager.uint64_type,
3143 TypeManager.char_type,
3144 TypeManager.bool_type,
3145 TypeManager.string_type
3150 // Try to find a *user* defined implicit conversion.
3152 // If there is no implicit conversion, or if there are multiple
3153 // conversions, we have to report an error
3155 Expression converted = null;
3156 foreach (Type tt in allowed_types){
3159 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3163 if (converted != null){
3164 Report.Error (-12, loc, "More than one conversion to an integral " +
3165 " type exists for type `" +
3166 TypeManager.CSharpName (Expr.Type)+"'");
3174 void error152 (string n)
3177 152, "The label `" + n + ":' " +
3178 "is already present on this switch statement");
3182 // Performs the basic sanity checks on the switch statement
3183 // (looks for duplicate keys and non-constant expressions).
3185 // It also returns a hashtable with the keys that we will later
3186 // use to compute the switch tables
3188 bool CheckSwitch (EmitContext ec)
3192 Elements = new Hashtable ();
3194 got_default = false;
3196 if (TypeManager.IsEnumType (SwitchType)){
3197 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3199 compare_type = SwitchType;
3201 foreach (SwitchSection ss in Sections){
3202 foreach (SwitchLabel sl in ss.Labels){
3203 if (!sl.ResolveAndReduce (ec, SwitchType)){
3208 if (sl.Label == null){
3210 error152 ("default");
3217 object key = sl.Converted;
3219 if (key is Constant)
3220 key = ((Constant) key).GetValue ();
3223 key = NullLiteral.Null;
3225 string lname = null;
3226 if (compare_type == TypeManager.uint64_type){
3227 ulong v = (ulong) key;
3229 if (Elements.Contains (v))
3230 lname = v.ToString ();
3232 Elements.Add (v, sl);
3233 } else if (compare_type == TypeManager.int64_type){
3234 long v = (long) key;
3236 if (Elements.Contains (v))
3237 lname = v.ToString ();
3239 Elements.Add (v, sl);
3240 } else if (compare_type == TypeManager.uint32_type){
3241 uint v = (uint) key;
3243 if (Elements.Contains (v))
3244 lname = v.ToString ();
3246 Elements.Add (v, sl);
3247 } else if (compare_type == TypeManager.char_type){
3248 char v = (char) key;
3250 if (Elements.Contains (v))
3251 lname = v.ToString ();
3253 Elements.Add (v, sl);
3254 } else if (compare_type == TypeManager.byte_type){
3255 byte v = (byte) key;
3257 if (Elements.Contains (v))
3258 lname = v.ToString ();
3260 Elements.Add (v, sl);
3261 } else if (compare_type == TypeManager.sbyte_type){
3262 sbyte v = (sbyte) key;
3264 if (Elements.Contains (v))
3265 lname = v.ToString ();
3267 Elements.Add (v, sl);
3268 } else if (compare_type == TypeManager.short_type){
3269 short v = (short) key;
3271 if (Elements.Contains (v))
3272 lname = v.ToString ();
3274 Elements.Add (v, sl);
3275 } else if (compare_type == TypeManager.ushort_type){
3276 ushort v = (ushort) key;
3278 if (Elements.Contains (v))
3279 lname = v.ToString ();
3281 Elements.Add (v, sl);
3282 } else if (compare_type == TypeManager.string_type){
3283 if (key is NullLiteral){
3284 if (Elements.Contains (NullLiteral.Null))
3287 Elements.Add (NullLiteral.Null, null);
3289 string s = (string) key;
3291 if (Elements.Contains (s))
3294 Elements.Add (s, sl);
3296 } else if (compare_type == TypeManager.int32_type) {
3299 if (Elements.Contains (v))
3300 lname = v.ToString ();
3302 Elements.Add (v, sl);
3303 } else if (compare_type == TypeManager.bool_type) {
3304 bool v = (bool) key;
3306 if (Elements.Contains (v))
3307 lname = v.ToString ();
3309 Elements.Add (v, sl);
3313 throw new Exception ("Unknown switch type!" +
3314 SwitchType + " " + compare_type);
3318 error152 ("case + " + lname);
3329 void EmitObjectInteger (ILGenerator ig, object k)
3332 IntConstant.EmitInt (ig, (int) k);
3333 else if (k is Constant) {
3334 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3337 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3340 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3342 IntConstant.EmitInt (ig, (int) (long) k);
3343 ig.Emit (OpCodes.Conv_I8);
3346 LongConstant.EmitLong (ig, (long) k);
3348 else if (k is ulong)
3350 if ((ulong) k < (1L<<32))
3352 IntConstant.EmitInt (ig, (int) (long) k);
3353 ig.Emit (OpCodes.Conv_U8);
3357 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3361 IntConstant.EmitInt (ig, (int) ((char) k));
3362 else if (k is sbyte)
3363 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3365 IntConstant.EmitInt (ig, (int) ((byte) k));
3366 else if (k is short)
3367 IntConstant.EmitInt (ig, (int) ((short) k));
3368 else if (k is ushort)
3369 IntConstant.EmitInt (ig, (int) ((ushort) k));
3371 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3373 throw new Exception ("Unhandled case");
3376 // structure used to hold blocks of keys while calculating table switch
3377 class KeyBlock : IComparable
3379 public KeyBlock (long _nFirst)
3381 nFirst = nLast = _nFirst;
3385 public ArrayList rgKeys = null;
3388 get { return (int) (nLast - nFirst + 1); }
3390 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3392 return kbLast.nLast - kbFirst.nFirst + 1;
3394 public int CompareTo (object obj)
3396 KeyBlock kb = (KeyBlock) obj;
3397 int nLength = Length;
3398 int nLengthOther = kb.Length;
3399 if (nLengthOther == nLength)
3400 return (int) (kb.nFirst - nFirst);
3401 return nLength - nLengthOther;
3406 /// This method emits code for a lookup-based switch statement (non-string)
3407 /// Basically it groups the cases into blocks that are at least half full,
3408 /// and then spits out individual lookup opcodes for each block.
3409 /// It emits the longest blocks first, and short blocks are just
3410 /// handled with direct compares.
3412 /// <param name="ec"></param>
3413 /// <param name="val"></param>
3414 /// <returns></returns>
3415 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3417 int cElements = Elements.Count;
3418 object [] rgKeys = new object [cElements];
3419 Elements.Keys.CopyTo (rgKeys, 0);
3420 Array.Sort (rgKeys);
3422 // initialize the block list with one element per key
3423 ArrayList rgKeyBlocks = new ArrayList ();
3424 foreach (object key in rgKeys)
3425 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3428 // iteratively merge the blocks while they are at least half full
3429 // there's probably a really cool way to do this with a tree...
3430 while (rgKeyBlocks.Count > 1)
3432 ArrayList rgKeyBlocksNew = new ArrayList ();
3433 kbCurr = (KeyBlock) rgKeyBlocks [0];
3434 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3436 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3437 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3440 kbCurr.nLast = kb.nLast;
3444 // start a new block
3445 rgKeyBlocksNew.Add (kbCurr);
3449 rgKeyBlocksNew.Add (kbCurr);
3450 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3452 rgKeyBlocks = rgKeyBlocksNew;
3455 // initialize the key lists
3456 foreach (KeyBlock kb in rgKeyBlocks)
3457 kb.rgKeys = new ArrayList ();
3459 // fill the key lists
3461 if (rgKeyBlocks.Count > 0) {
3462 kbCurr = (KeyBlock) rgKeyBlocks [0];
3463 foreach (object key in rgKeys)
3465 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3467 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3468 kbCurr.rgKeys.Add (key);
3472 // sort the blocks so we can tackle the largest ones first
3473 rgKeyBlocks.Sort ();
3475 // okay now we can start...
3476 ILGenerator ig = ec.ig;
3477 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3478 Label lblDefault = ig.DefineLabel ();
3480 Type typeKeys = null;
3481 if (rgKeys.Length > 0)
3482 typeKeys = rgKeys [0].GetType (); // used for conversions
3484 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3486 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3487 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3490 foreach (object key in kb.rgKeys)
3492 ig.Emit (OpCodes.Ldloc, val);
3493 EmitObjectInteger (ig, key);
3494 SwitchLabel sl = (SwitchLabel) Elements [key];
3495 ig.Emit (OpCodes.Beq, sl.ILLabel);
3500 // TODO: if all the keys in the block are the same and there are
3501 // no gaps/defaults then just use a range-check.
3502 if (SwitchType == TypeManager.int64_type ||
3503 SwitchType == TypeManager.uint64_type)
3505 // TODO: optimize constant/I4 cases
3507 // check block range (could be > 2^31)
3508 ig.Emit (OpCodes.Ldloc, val);
3509 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3510 ig.Emit (OpCodes.Blt, lblDefault);
3511 ig.Emit (OpCodes.Ldloc, val);
3512 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3513 ig.Emit (OpCodes.Bgt, lblDefault);
3516 ig.Emit (OpCodes.Ldloc, val);
3519 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3520 ig.Emit (OpCodes.Sub);
3522 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3527 ig.Emit (OpCodes.Ldloc, val);
3528 int nFirst = (int) kb.nFirst;
3531 IntConstant.EmitInt (ig, nFirst);
3532 ig.Emit (OpCodes.Sub);
3534 else if (nFirst < 0)
3536 IntConstant.EmitInt (ig, -nFirst);
3537 ig.Emit (OpCodes.Add);
3541 // first, build the list of labels for the switch
3543 int cJumps = kb.Length;
3544 Label [] rgLabels = new Label [cJumps];
3545 for (int iJump = 0; iJump < cJumps; iJump++)
3547 object key = kb.rgKeys [iKey];
3548 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3550 SwitchLabel sl = (SwitchLabel) Elements [key];
3551 rgLabels [iJump] = sl.ILLabel;
3555 rgLabels [iJump] = lblDefault;
3557 // emit the switch opcode
3558 ig.Emit (OpCodes.Switch, rgLabels);
3561 // mark the default for this block
3563 ig.MarkLabel (lblDefault);
3566 // TODO: find the default case and emit it here,
3567 // to prevent having to do the following jump.
3568 // make sure to mark other labels in the default section
3570 // the last default just goes to the end
3571 ig.Emit (OpCodes.Br, lblDefault);
3573 // now emit the code for the sections
3574 bool fFoundDefault = false;
3575 bool fAllReturn = true;
3576 foreach (SwitchSection ss in Sections)
3578 foreach (SwitchLabel sl in ss.Labels)
3580 ig.MarkLabel (sl.ILLabel);
3581 ig.MarkLabel (sl.ILLabelCode);
3582 if (sl.Label == null)
3584 ig.MarkLabel (lblDefault);
3585 fFoundDefault = true;
3589 bool returns = ss.Block.Emit (ec);
3590 if (!ec.Breaks && !returns)
3591 Report.Error (163, ((SwitchLabel) ss.Labels [0]).loc,
3592 "Control cannot fall through from one " +
3593 "case label to another");
3594 fAllReturn &= returns;
3595 //ig.Emit (OpCodes.Br, lblEnd);
3598 if (!fFoundDefault) {
3599 ig.MarkLabel (lblDefault);
3602 ig.MarkLabel (lblEnd);
3607 // This simple emit switch works, but does not take advantage of the
3609 // TODO: remove non-string logic from here
3610 // TODO: binary search strings?
3612 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3614 ILGenerator ig = ec.ig;
3615 Label end_of_switch = ig.DefineLabel ();
3616 Label next_test = ig.DefineLabel ();
3617 Label null_target = ig.DefineLabel ();
3618 bool default_found = false;
3619 bool first_test = true;
3620 bool pending_goto_end = false;
3621 bool all_return = true;
3622 bool is_string = false;
3626 // Special processing for strings: we cant compare
3629 if (SwitchType == TypeManager.string_type){
3630 ig.Emit (OpCodes.Ldloc, val);
3633 if (Elements.Contains (NullLiteral.Null)){
3634 ig.Emit (OpCodes.Brfalse, null_target);
3636 ig.Emit (OpCodes.Brfalse, default_target);
3638 ig.Emit (OpCodes.Ldloc, val);
3639 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3640 ig.Emit (OpCodes.Stloc, val);
3643 SwitchSection last_section;
3644 last_section = (SwitchSection) Sections [Sections.Count-1];
3646 foreach (SwitchSection ss in Sections){
3647 Label sec_begin = ig.DefineLabel ();
3649 if (pending_goto_end)
3650 ig.Emit (OpCodes.Br, end_of_switch);
3652 int label_count = ss.Labels.Count;
3654 foreach (SwitchLabel sl in ss.Labels){
3655 ig.MarkLabel (sl.ILLabel);
3658 ig.MarkLabel (next_test);
3659 next_test = ig.DefineLabel ();
3662 // If we are the default target
3664 if (sl.Label == null){
3665 ig.MarkLabel (default_target);
3666 default_found = true;
3668 object lit = sl.Converted;
3670 if (lit is NullLiteral){
3672 if (label_count == 1)
3673 ig.Emit (OpCodes.Br, next_test);
3678 StringConstant str = (StringConstant) lit;
3680 ig.Emit (OpCodes.Ldloc, val);
3681 ig.Emit (OpCodes.Ldstr, str.Value);
3682 if (label_count == 1)
3683 ig.Emit (OpCodes.Bne_Un, next_test);
3685 ig.Emit (OpCodes.Beq, sec_begin);
3687 ig.Emit (OpCodes.Ldloc, val);
3688 EmitObjectInteger (ig, lit);
3689 ig.Emit (OpCodes.Ceq);
3690 if (label_count == 1)
3691 ig.Emit (OpCodes.Brfalse, next_test);
3693 ig.Emit (OpCodes.Brtrue, sec_begin);
3697 if (label_count != 1 && ss != last_section)
3698 ig.Emit (OpCodes.Br, next_test);
3701 ig.MarkLabel (null_target);
3702 ig.MarkLabel (sec_begin);
3703 foreach (SwitchLabel sl in ss.Labels)
3704 ig.MarkLabel (sl.ILLabelCode);
3707 bool returns = ss.Block.Emit (ec);
3708 if (!ec.Breaks && !returns)
3709 Report.Error (163, ((SwitchLabel) ss.Labels [0]).loc,
3710 "Control cannot fall through from one " +
3711 "case label to another");
3713 pending_goto_end = false;
3716 pending_goto_end = true;
3720 if (!default_found){
3721 ig.MarkLabel (default_target);
3724 ig.MarkLabel (next_test);
3725 ig.MarkLabel (end_of_switch);
3730 public override bool Resolve (EmitContext ec)
3732 Expr = Expr.Resolve (ec);
3736 new_expr = SwitchGoverningType (ec, Expr.Type);
3737 if (new_expr == null){
3738 Report.Error (151, loc, "An integer type or string was expected for switch");
3743 SwitchType = new_expr.Type;
3745 if (!CheckSwitch (ec))
3748 Switch old_switch = ec.Switch;
3750 ec.Switch.SwitchType = SwitchType;
3752 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3755 foreach (SwitchSection ss in Sections){
3757 ec.CurrentBranching.CreateSibling ();
3761 if (ss.Block.Resolve (ec) != true)
3765 ec.EndFlowBranching ();
3766 ec.Switch = old_switch;
3771 public override bool Emit (EmitContext ec)
3773 // Store variable for comparission purposes
3774 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
3776 ec.ig.Emit (OpCodes.Stloc, value);
3778 ILGenerator ig = ec.ig;
3780 default_target = ig.DefineLabel ();
3783 // Setup the codegen context
3785 Label old_end = ec.LoopEnd;
3786 Switch old_switch = ec.Switch;
3788 ec.LoopEnd = ig.DefineLabel ();
3793 if (SwitchType == TypeManager.string_type)
3794 all_return = SimpleSwitchEmit (ec, value);
3796 all_return = TableSwitchEmit (ec, value);
3798 // Restore context state.
3799 ig.MarkLabel (ec.LoopEnd);
3802 // Restore the previous context
3804 ec.LoopEnd = old_end;
3805 ec.Switch = old_switch;
3811 public class Lock : Statement {
3813 Statement Statement;
3815 public Lock (Expression expr, Statement stmt, Location l)
3822 public override bool Resolve (EmitContext ec)
3824 expr = expr.Resolve (ec);
3825 return Statement.Resolve (ec) && expr != null;
3828 public override bool Emit (EmitContext ec)
3830 Type type = expr.Type;
3833 if (type.IsValueType){
3834 Report.Error (185, loc, "lock statement requires the expression to be " +
3835 " a reference type (type is: `" +
3836 TypeManager.CSharpName (type) + "'");
3840 ILGenerator ig = ec.ig;
3841 LocalBuilder temp = ig.DeclareLocal (type);
3844 ig.Emit (OpCodes.Dup);
3845 ig.Emit (OpCodes.Stloc, temp);
3846 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3849 Label end = ig.BeginExceptionBlock ();
3850 bool old_in_try = ec.InTry;
3852 Label finish = ig.DefineLabel ();
3853 val = Statement.Emit (ec);
3854 ec.InTry = old_in_try;
3855 // ig.Emit (OpCodes.Leave, finish);
3857 ig.MarkLabel (finish);
3860 ig.BeginFinallyBlock ();
3861 ig.Emit (OpCodes.Ldloc, temp);
3862 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3863 ig.EndExceptionBlock ();
3869 public class Unchecked : Statement {
3870 public readonly Block Block;
3872 public Unchecked (Block b)
3877 public override bool Resolve (EmitContext ec)
3879 return Block.Resolve (ec);
3882 public override bool Emit (EmitContext ec)
3884 bool previous_state = ec.CheckState;
3885 bool previous_state_const = ec.ConstantCheckState;
3888 ec.CheckState = false;
3889 ec.ConstantCheckState = false;
3890 val = Block.Emit (ec);
3891 ec.CheckState = previous_state;
3892 ec.ConstantCheckState = previous_state_const;
3898 public class Checked : Statement {
3899 public readonly Block Block;
3901 public Checked (Block b)
3906 public override bool Resolve (EmitContext ec)
3908 bool previous_state = ec.CheckState;
3909 bool previous_state_const = ec.ConstantCheckState;
3911 ec.CheckState = true;
3912 ec.ConstantCheckState = true;
3913 bool ret = Block.Resolve (ec);
3914 ec.CheckState = previous_state;
3915 ec.ConstantCheckState = previous_state_const;
3920 public override bool Emit (EmitContext ec)
3922 bool previous_state = ec.CheckState;
3923 bool previous_state_const = ec.ConstantCheckState;
3926 ec.CheckState = true;
3927 ec.ConstantCheckState = true;
3928 val = Block.Emit (ec);
3929 ec.CheckState = previous_state;
3930 ec.ConstantCheckState = previous_state_const;
3936 public class Unsafe : Statement {
3937 public readonly Block Block;
3939 public Unsafe (Block b)
3944 public override bool Resolve (EmitContext ec)
3946 bool previous_state = ec.InUnsafe;
3950 val = Block.Resolve (ec);
3951 ec.InUnsafe = previous_state;
3956 public override bool Emit (EmitContext ec)
3958 bool previous_state = ec.InUnsafe;
3962 val = Block.Emit (ec);
3963 ec.InUnsafe = previous_state;
3972 public class Fixed : Statement {
3974 ArrayList declarators;
3975 Statement statement;
3980 public bool is_object;
3981 public VariableInfo vi;
3982 public Expression expr;
3983 public Expression converted;
3986 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3989 declarators = decls;
3994 public override bool Resolve (EmitContext ec)
3996 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3997 if (expr_type == null)
4000 data = new FixedData [declarators.Count];
4003 foreach (Pair p in declarators){
4004 VariableInfo vi = (VariableInfo) p.First;
4005 Expression e = (Expression) p.Second;
4010 // The rules for the possible declarators are pretty wise,
4011 // but the production on the grammar is more concise.
4013 // So we have to enforce these rules here.
4015 // We do not resolve before doing the case 1 test,
4016 // because the grammar is explicit in that the token &
4017 // is present, so we need to test for this particular case.
4021 // Case 1: & object.
4023 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4024 Expression child = ((Unary) e).Expr;
4027 if (child is ParameterReference || child is LocalVariableReference){
4030 "No need to use fixed statement for parameters or " +
4031 "local variable declarations (address is already " +
4040 child = ((Unary) e).Expr;
4042 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4045 data [i].is_object = true;
4047 data [i].converted = null;
4061 if (e.Type.IsArray){
4062 Type array_type = e.Type.GetElementType ();
4066 // Provided that array_type is unmanaged,
4068 if (!TypeManager.VerifyUnManaged (array_type, loc))
4072 // and T* is implicitly convertible to the
4073 // pointer type given in the fixed statement.
4075 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4077 Expression converted = Expression.ConvertImplicitRequired (
4078 ec, array_ptr, vi.VariableType, loc);
4079 if (converted == null)
4082 data [i].is_object = false;
4084 data [i].converted = converted;
4094 if (e.Type == TypeManager.string_type){
4095 data [i].is_object = false;
4097 data [i].converted = null;
4103 return statement.Resolve (ec);
4106 public override bool Emit (EmitContext ec)
4108 ILGenerator ig = ec.ig;
4110 bool is_ret = false;
4112 for (int i = 0; i < data.Length; i++) {
4113 VariableInfo vi = data [i].vi;
4116 // Case 1: & object.
4118 if (data [i].is_object) {
4120 // Store pointer in pinned location
4122 data [i].expr.Emit (ec);
4123 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4125 is_ret = statement.Emit (ec);
4127 // Clear the pinned variable.
4128 ig.Emit (OpCodes.Ldc_I4_0);
4129 ig.Emit (OpCodes.Conv_U);
4130 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4138 if (data [i].expr.Type.IsArray){
4140 // Store pointer in pinned location
4142 data [i].converted.Emit (ec);
4144 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4146 is_ret = statement.Emit (ec);
4148 // Clear the pinned variable.
4149 ig.Emit (OpCodes.Ldc_I4_0);
4150 ig.Emit (OpCodes.Conv_U);
4151 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4159 if (data [i].expr.Type == TypeManager.string_type){
4160 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4161 TypeManager.MakePinned (pinned_string);
4163 data [i].expr.Emit (ec);
4164 ig.Emit (OpCodes.Stloc, pinned_string);
4166 Expression sptr = new StringPtr (pinned_string, loc);
4167 Expression converted = Expression.ConvertImplicitRequired (
4168 ec, sptr, vi.VariableType, loc);
4170 if (converted == null)
4173 converted.Emit (ec);
4174 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4176 is_ret = statement.Emit (ec);
4178 // Clear the pinned variable
4179 ig.Emit (OpCodes.Ldnull);
4180 ig.Emit (OpCodes.Stloc, pinned_string);
4188 public class Catch {
4189 public readonly string Name;
4190 public readonly Block Block;
4191 public readonly Location Location;
4193 Expression type_expr;
4196 public Catch (Expression type, string name, Block block, Location l)
4204 public Type CatchType {
4210 public bool IsGeneral {
4212 return type_expr == null;
4216 public bool Resolve (EmitContext ec)
4218 if (type_expr != null) {
4219 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4223 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4224 Report.Error (155, Location,
4225 "The type caught or thrown must be derived " +
4226 "from System.Exception");
4232 if (!Block.Resolve (ec))
4239 public class Try : Statement {
4240 public readonly Block Fini, Block;
4241 public readonly ArrayList Specific;
4242 public readonly Catch General;
4245 // specific, general and fini might all be null.
4247 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4249 if (specific == null && general == null){
4250 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4254 this.Specific = specific;
4255 this.General = general;
4260 public override bool Resolve (EmitContext ec)
4264 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4266 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4268 bool old_in_try = ec.InTry;
4271 if (!Block.Resolve (ec))
4274 ec.InTry = old_in_try;
4276 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4278 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4280 foreach (Catch c in Specific){
4281 ec.CurrentBranching.CreateSibling ();
4282 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4284 if (c.Name != null) {
4285 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4287 throw new Exception ();
4292 bool old_in_catch = ec.InCatch;
4295 if (!c.Resolve (ec))
4298 ec.InCatch = old_in_catch;
4300 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4302 if ((current.Returns == FlowReturns.NEVER) ||
4303 (current.Returns == FlowReturns.SOMETIMES)) {
4304 vector.AndLocals (current);
4308 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4310 if (General != null){
4311 ec.CurrentBranching.CreateSibling ();
4312 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4314 bool old_in_catch = ec.InCatch;
4317 if (!General.Resolve (ec))
4320 ec.InCatch = old_in_catch;
4322 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4324 if ((current.Returns == FlowReturns.NEVER) ||
4325 (current.Returns == FlowReturns.SOMETIMES)) {
4326 vector.AndLocals (current);
4330 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4333 ec.CurrentBranching.CreateSiblingForFinally ();
4334 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4336 bool old_in_finally = ec.InFinally;
4337 ec.InFinally = true;
4339 if (!Fini.Resolve (ec))
4342 ec.InFinally = old_in_finally;
4345 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4347 FlowReturns returns = ec.EndFlowBranching ();
4349 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4351 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4352 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4355 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4357 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4362 public override bool Emit (EmitContext ec)
4364 ILGenerator ig = ec.ig;
4366 Label finish = ig.DefineLabel ();;
4370 end = ig.BeginExceptionBlock ();
4371 bool old_in_try = ec.InTry;
4373 returns = Block.Emit (ec);
4374 ec.InTry = old_in_try;
4377 // System.Reflection.Emit provides this automatically:
4378 // ig.Emit (OpCodes.Leave, finish);
4380 bool old_in_catch = ec.InCatch;
4382 DeclSpace ds = ec.DeclSpace;
4384 foreach (Catch c in Specific){
4387 ig.BeginCatchBlock (c.CatchType);
4389 if (c.Name != null){
4390 vi = c.Block.GetVariableInfo (c.Name);
4392 throw new Exception ("Variable does not exist in this block");
4394 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4396 ig.Emit (OpCodes.Pop);
4398 if (!c.Block.Emit (ec))
4402 if (General != null){
4403 ig.BeginCatchBlock (TypeManager.object_type);
4404 ig.Emit (OpCodes.Pop);
4405 if (!General.Block.Emit (ec))
4408 ec.InCatch = old_in_catch;
4410 ig.MarkLabel (finish);
4412 ig.BeginFinallyBlock ();
4413 bool old_in_finally = ec.InFinally;
4414 ec.InFinally = true;
4416 ec.InFinally = old_in_finally;
4419 ig.EndExceptionBlock ();
4422 if (!returns || ec.InTry || ec.InCatch)
4425 // Unfortunately, System.Reflection.Emit automatically emits a leave
4426 // to the end of the finally block. This is a problem if `returns'
4427 // is true since we may jump to a point after the end of the method.
4428 // As a workaround, emit an explicit ret here.
4430 if (ec.ReturnType != null)
4431 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4432 ec.ig.Emit (OpCodes.Ret);
4439 // FIXME: We still do not support the expression variant of the using
4442 public class Using : Statement {
4443 object expression_or_block;
4444 Statement Statement;
4449 Expression [] converted_vars;
4450 ExpressionStatement [] assign;
4452 public Using (object expression_or_block, Statement stmt, Location l)
4454 this.expression_or_block = expression_or_block;
4460 // Resolves for the case of using using a local variable declaration.
4462 bool ResolveLocalVariableDecls (EmitContext ec)
4464 bool need_conv = false;
4465 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4468 if (expr_type == null)
4472 // The type must be an IDisposable or an implicit conversion
4475 converted_vars = new Expression [var_list.Count];
4476 assign = new ExpressionStatement [var_list.Count];
4477 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4478 foreach (DictionaryEntry e in var_list){
4479 Expression var = (Expression) e.Key;
4481 var = var.ResolveLValue (ec, new EmptyExpression ());
4485 converted_vars [i] = Expression.ConvertImplicit (
4486 ec, var, TypeManager.idisposable_type, loc);
4488 if (converted_vars [i] == null)
4496 foreach (DictionaryEntry e in var_list){
4497 LocalVariableReference var = (LocalVariableReference) e.Key;
4498 Expression new_expr = (Expression) e.Value;
4501 a = new Assign (var, new_expr, loc);
4507 converted_vars [i] = var;
4508 assign [i] = (ExpressionStatement) a;
4515 bool ResolveExpression (EmitContext ec)
4517 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4518 conv = Expression.ConvertImplicit (
4519 ec, expr, TypeManager.idisposable_type, loc);
4529 // Emits the code for the case of using using a local variable declaration.
4531 bool EmitLocalVariableDecls (EmitContext ec)
4533 ILGenerator ig = ec.ig;
4536 bool old_in_try = ec.InTry;
4538 for (i = 0; i < assign.Length; i++) {
4539 assign [i].EmitStatement (ec);
4541 ig.BeginExceptionBlock ();
4543 Statement.Emit (ec);
4544 ec.InTry = old_in_try;
4546 bool old_in_finally = ec.InFinally;
4547 ec.InFinally = true;
4548 var_list.Reverse ();
4549 foreach (DictionaryEntry e in var_list){
4550 LocalVariableReference var = (LocalVariableReference) e.Key;
4551 Label skip = ig.DefineLabel ();
4554 ig.BeginFinallyBlock ();
4557 ig.Emit (OpCodes.Brfalse, skip);
4558 converted_vars [i].Emit (ec);
4559 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4560 ig.MarkLabel (skip);
4561 ig.EndExceptionBlock ();
4563 ec.InFinally = old_in_finally;
4568 bool EmitExpression (EmitContext ec)
4571 // Make a copy of the expression and operate on that.
4573 ILGenerator ig = ec.ig;
4574 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4579 ig.Emit (OpCodes.Stloc, local_copy);
4581 bool old_in_try = ec.InTry;
4583 ig.BeginExceptionBlock ();
4584 Statement.Emit (ec);
4585 ec.InTry = old_in_try;
4587 Label skip = ig.DefineLabel ();
4588 bool old_in_finally = ec.InFinally;
4589 ig.BeginFinallyBlock ();
4590 ig.Emit (OpCodes.Ldloc, local_copy);
4591 ig.Emit (OpCodes.Brfalse, skip);
4592 ig.Emit (OpCodes.Ldloc, local_copy);
4593 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4594 ig.MarkLabel (skip);
4595 ec.InFinally = old_in_finally;
4596 ig.EndExceptionBlock ();
4601 public override bool Resolve (EmitContext ec)
4603 if (expression_or_block is DictionaryEntry){
4604 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4605 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4607 if (!ResolveLocalVariableDecls (ec))
4610 } else if (expression_or_block is Expression){
4611 expr = (Expression) expression_or_block;
4613 expr = expr.Resolve (ec);
4617 expr_type = expr.Type;
4619 if (!ResolveExpression (ec))
4623 return Statement.Resolve (ec);
4626 public override bool Emit (EmitContext ec)
4628 if (expression_or_block is DictionaryEntry)
4629 return EmitLocalVariableDecls (ec);
4630 else if (expression_or_block is Expression)
4631 return EmitExpression (ec);
4638 /// Implementation of the foreach C# statement
4640 public class Foreach : Statement {
4642 LocalVariableReference variable;
4644 Statement statement;
4645 ForeachHelperMethods hm;
4646 Expression empty, conv;
4647 Type array_type, element_type;
4650 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4651 Statement stmt, Location l)
4654 this.variable = var;
4660 public override bool Resolve (EmitContext ec)
4662 expr = expr.Resolve (ec);
4666 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4667 if (var_type == null)
4671 // We need an instance variable. Not sure this is the best
4672 // way of doing this.
4674 // FIXME: When we implement propertyaccess, will those turn
4675 // out to return values in ExprClass? I think they should.
4677 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4678 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4679 error1579 (expr.Type);
4683 if (expr.Type.IsArray) {
4684 array_type = expr.Type;
4685 element_type = array_type.GetElementType ();
4687 empty = new EmptyExpression (element_type);
4689 hm = ProbeCollectionType (ec, expr.Type);
4691 error1579 (expr.Type);
4695 array_type = expr.Type;
4696 element_type = hm.element_type;
4698 empty = new EmptyExpression (hm.element_type);
4702 // FIXME: maybe we can apply the same trick we do in the
4703 // array handling to avoid creating empty and conv in some cases.
4705 // Although it is not as important in this case, as the type
4706 // will not likely be object (what the enumerator will return).
4708 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4712 if (variable.ResolveLValue (ec, empty) == null)
4715 if (!statement.Resolve (ec))
4722 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4724 static MethodInfo FetchMethodMoveNext (Type t)
4726 MemberList move_next_list;
4728 move_next_list = TypeContainer.FindMembers (
4729 t, MemberTypes.Method,
4730 BindingFlags.Public | BindingFlags.Instance,
4731 Type.FilterName, "MoveNext");
4732 if (move_next_list.Count == 0)
4735 foreach (MemberInfo m in move_next_list){
4736 MethodInfo mi = (MethodInfo) m;
4739 args = TypeManager.GetArgumentTypes (mi);
4740 if (args != null && args.Length == 0){
4741 if (mi.ReturnType == TypeManager.bool_type)
4749 // Retrieves a `public T get_Current ()' method from the Type `t'
4751 static MethodInfo FetchMethodGetCurrent (Type t)
4753 MemberList move_next_list;
4755 move_next_list = TypeContainer.FindMembers (
4756 t, MemberTypes.Method,
4757 BindingFlags.Public | BindingFlags.Instance,
4758 Type.FilterName, "get_Current");
4759 if (move_next_list.Count == 0)
4762 foreach (MemberInfo m in move_next_list){
4763 MethodInfo mi = (MethodInfo) m;
4766 args = TypeManager.GetArgumentTypes (mi);
4767 if (args != null && args.Length == 0)
4774 // This struct records the helper methods used by the Foreach construct
4776 class ForeachHelperMethods {
4777 public EmitContext ec;
4778 public MethodInfo get_enumerator;
4779 public MethodInfo move_next;
4780 public MethodInfo get_current;
4781 public Type element_type;
4782 public Type enumerator_type;
4783 public bool is_disposable;
4785 public ForeachHelperMethods (EmitContext ec)
4788 this.element_type = TypeManager.object_type;
4789 this.enumerator_type = TypeManager.ienumerator_type;
4790 this.is_disposable = true;
4794 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4799 if (!(m is MethodInfo))
4802 if (m.Name != "GetEnumerator")
4805 MethodInfo mi = (MethodInfo) m;
4806 Type [] args = TypeManager.GetArgumentTypes (mi);
4808 if (args.Length != 0)
4811 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4812 EmitContext ec = hm.ec;
4815 // Check whether GetEnumerator is accessible to us
4817 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
4819 Type declaring = mi.DeclaringType;
4820 if (prot == MethodAttributes.Private){
4821 if (declaring != ec.ContainerType)
4823 } else if (prot == MethodAttributes.FamANDAssem){
4824 // If from a different assembly, false
4825 if (!(mi is MethodBuilder))
4828 // Are we being invoked from the same class, or from a derived method?
4830 if (ec.ContainerType != declaring){
4831 if (!ec.ContainerType.IsSubclassOf (declaring))
4834 } else if (prot == MethodAttributes.FamORAssem){
4835 if (!(mi is MethodBuilder ||
4836 ec.ContainerType == declaring ||
4837 ec.ContainerType.IsSubclassOf (declaring)))
4839 } if (prot == MethodAttributes.Family){
4840 if (!(ec.ContainerType == declaring ||
4841 ec.ContainerType.IsSubclassOf (declaring)))
4846 // Ok, we can access it, now make sure that we can do something
4847 // with this `GetEnumerator'
4850 if (mi.ReturnType == TypeManager.ienumerator_type ||
4851 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
4852 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
4853 hm.move_next = TypeManager.bool_movenext_void;
4854 hm.get_current = TypeManager.object_getcurrent_void;
4859 // Ok, so they dont return an IEnumerable, we will have to
4860 // find if they support the GetEnumerator pattern.
4862 Type return_type = mi.ReturnType;
4864 hm.move_next = FetchMethodMoveNext (return_type);
4865 if (hm.move_next == null)
4867 hm.get_current = FetchMethodGetCurrent (return_type);
4868 if (hm.get_current == null)
4871 hm.element_type = hm.get_current.ReturnType;
4872 hm.enumerator_type = return_type;
4873 hm.is_disposable = TypeManager.ImplementsInterface (
4874 hm.enumerator_type, TypeManager.idisposable_type);
4880 /// This filter is used to find the GetEnumerator method
4881 /// on which IEnumerator operates
4883 static MemberFilter FilterEnumerator;
4887 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4890 void error1579 (Type t)
4892 Report.Error (1579, loc,
4893 "foreach statement cannot operate on variables of type `" +
4894 t.FullName + "' because that class does not provide a " +
4895 " GetEnumerator method or it is inaccessible");
4898 static bool TryType (Type t, ForeachHelperMethods hm)
4902 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4903 BindingFlags.Public | BindingFlags.NonPublic |
4904 BindingFlags.Instance,
4905 FilterEnumerator, hm);
4910 hm.get_enumerator = (MethodInfo) mi [0];
4915 // Looks for a usable GetEnumerator in the Type, and if found returns
4916 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4918 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4920 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
4922 if (TryType (t, hm))
4926 // Now try to find the method in the interfaces
4929 Type [] ifaces = t.GetInterfaces ();
4931 foreach (Type i in ifaces){
4932 if (TryType (i, hm))
4937 // Since TypeBuilder.GetInterfaces only returns the interface
4938 // types for this type, we have to keep looping, but once
4939 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4940 // done, because it returns all the types
4942 if ((t is TypeBuilder))
4952 // FIXME: possible optimization.
4953 // We might be able to avoid creating `empty' if the type is the sam
4955 bool EmitCollectionForeach (EmitContext ec)
4957 ILGenerator ig = ec.ig;
4958 LocalBuilder enumerator, disposable;
4960 enumerator = ig.DeclareLocal (hm.enumerator_type);
4961 if (hm.is_disposable)
4962 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
4967 // Instantiate the enumerator
4969 if (expr.Type.IsValueType){
4970 if (expr is IMemoryLocation){
4971 IMemoryLocation ml = (IMemoryLocation) expr;
4973 ml.AddressOf (ec, AddressOp.Load);
4975 throw new Exception ("Expr " + expr + " of type " + expr.Type +
4976 " does not implement IMemoryLocation");
4977 ig.Emit (OpCodes.Call, hm.get_enumerator);
4980 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4982 ig.Emit (OpCodes.Stloc, enumerator);
4985 // Protect the code in a try/finalize block, so that
4986 // if the beast implement IDisposable, we get rid of it
4989 bool old_in_try = ec.InTry;
4991 if (hm.is_disposable) {
4992 l = ig.BeginExceptionBlock ();
4996 Label end_try = ig.DefineLabel ();
4998 ig.MarkLabel (ec.LoopBegin);
4999 ig.Emit (OpCodes.Ldloc, enumerator);
5000 ig.Emit (OpCodes.Callvirt, hm.move_next);
5001 ig.Emit (OpCodes.Brfalse, end_try);
5002 ig.Emit (OpCodes.Ldloc, enumerator);
5003 ig.Emit (OpCodes.Callvirt, hm.get_current);
5004 variable.EmitAssign (ec, conv);
5005 statement.Emit (ec);
5006 ig.Emit (OpCodes.Br, ec.LoopBegin);
5007 ig.MarkLabel (end_try);
5008 ec.InTry = old_in_try;
5010 // The runtime provides this for us.
5011 // ig.Emit (OpCodes.Leave, end);
5014 // Now the finally block
5016 if (hm.is_disposable) {
5017 Label end_finally = ig.DefineLabel ();
5018 bool old_in_finally = ec.InFinally;
5019 ec.InFinally = true;
5020 ig.BeginFinallyBlock ();
5022 ig.Emit (OpCodes.Ldloc, enumerator);
5023 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5024 ig.Emit (OpCodes.Stloc, disposable);
5025 ig.Emit (OpCodes.Ldloc, disposable);
5026 ig.Emit (OpCodes.Brfalse, end_finally);
5027 ig.Emit (OpCodes.Ldloc, disposable);
5028 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5029 ig.MarkLabel (end_finally);
5030 ec.InFinally = old_in_finally;
5032 // The runtime generates this anyways.
5033 // ig.Emit (OpCodes.Endfinally);
5035 ig.EndExceptionBlock ();
5038 ig.MarkLabel (ec.LoopEnd);
5043 // FIXME: possible optimization.
5044 // We might be able to avoid creating `empty' if the type is the sam
5046 bool EmitArrayForeach (EmitContext ec)
5048 int rank = array_type.GetArrayRank ();
5049 ILGenerator ig = ec.ig;
5051 LocalBuilder copy = ig.DeclareLocal (array_type);
5054 // Make our copy of the array
5057 ig.Emit (OpCodes.Stloc, copy);
5060 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5064 ig.Emit (OpCodes.Ldc_I4_0);
5065 ig.Emit (OpCodes.Stloc, counter);
5066 test = ig.DefineLabel ();
5067 ig.Emit (OpCodes.Br, test);
5069 loop = ig.DefineLabel ();
5070 ig.MarkLabel (loop);
5072 ig.Emit (OpCodes.Ldloc, copy);
5073 ig.Emit (OpCodes.Ldloc, counter);
5074 ArrayAccess.EmitLoadOpcode (ig, var_type);
5076 variable.EmitAssign (ec, conv);
5078 statement.Emit (ec);
5080 ig.MarkLabel (ec.LoopBegin);
5081 ig.Emit (OpCodes.Ldloc, counter);
5082 ig.Emit (OpCodes.Ldc_I4_1);
5083 ig.Emit (OpCodes.Add);
5084 ig.Emit (OpCodes.Stloc, counter);
5086 ig.MarkLabel (test);
5087 ig.Emit (OpCodes.Ldloc, counter);
5088 ig.Emit (OpCodes.Ldloc, copy);
5089 ig.Emit (OpCodes.Ldlen);
5090 ig.Emit (OpCodes.Conv_I4);
5091 ig.Emit (OpCodes.Blt, loop);
5093 LocalBuilder [] dim_len = new LocalBuilder [rank];
5094 LocalBuilder [] dim_count = new LocalBuilder [rank];
5095 Label [] loop = new Label [rank];
5096 Label [] test = new Label [rank];
5099 for (dim = 0; dim < rank; dim++){
5100 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5101 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5102 test [dim] = ig.DefineLabel ();
5103 loop [dim] = ig.DefineLabel ();
5106 for (dim = 0; dim < rank; dim++){
5107 ig.Emit (OpCodes.Ldloc, copy);
5108 IntLiteral.EmitInt (ig, dim);
5109 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5110 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5113 for (dim = 0; dim < rank; dim++){
5114 ig.Emit (OpCodes.Ldc_I4_0);
5115 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5116 ig.Emit (OpCodes.Br, test [dim]);
5117 ig.MarkLabel (loop [dim]);
5120 ig.Emit (OpCodes.Ldloc, copy);
5121 for (dim = 0; dim < rank; dim++)
5122 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5125 // FIXME: Maybe we can cache the computation of `get'?
5127 Type [] args = new Type [rank];
5130 for (int i = 0; i < rank; i++)
5131 args [i] = TypeManager.int32_type;
5133 ModuleBuilder mb = CodeGen.ModuleBuilder;
5134 get = mb.GetArrayMethod (
5136 CallingConventions.HasThis| CallingConventions.Standard,
5138 ig.Emit (OpCodes.Call, get);
5139 variable.EmitAssign (ec, conv);
5140 statement.Emit (ec);
5141 ig.MarkLabel (ec.LoopBegin);
5142 for (dim = rank - 1; dim >= 0; dim--){
5143 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5144 ig.Emit (OpCodes.Ldc_I4_1);
5145 ig.Emit (OpCodes.Add);
5146 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5148 ig.MarkLabel (test [dim]);
5149 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5150 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5151 ig.Emit (OpCodes.Blt, loop [dim]);
5154 ig.MarkLabel (ec.LoopEnd);
5159 public override bool Emit (EmitContext ec)
5163 ILGenerator ig = ec.ig;
5165 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5166 bool old_inloop = ec.InLoop;
5167 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5168 ec.LoopBegin = ig.DefineLabel ();
5169 ec.LoopEnd = ig.DefineLabel ();
5171 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5174 ret_val = EmitCollectionForeach (ec);
5176 ret_val = EmitArrayForeach (ec);
5178 ec.LoopBegin = old_begin;
5179 ec.LoopEnd = old_end;
5180 ec.InLoop = old_inloop;
5181 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;