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, 2003 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 protected abstract bool DoEmit (EmitContext ec);
39 /// Return value indicates whether all code paths emitted return.
41 public virtual bool Emit (EmitContext ec)
48 /// Encapsulates the emission of a boolean test and jumping to a
51 /// This will emit the bool expression in `bool_expr' and if
52 /// `target_is_for_true' is true, then the code will generate a
53 /// brtrue to the target. Otherwise a brfalse.
55 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
56 Label target, bool target_is_for_true)
58 ILGenerator ig = ec.ig;
61 if (bool_expr is Unary){
62 Unary u = (Unary) bool_expr;
64 if (u.Oper == Unary.Operator.LogicalNot){
67 u.EmitLogicalNot (ec);
69 } else if (bool_expr is Binary){
70 Binary b = (Binary) bool_expr;
72 if (b.EmitBranchable (ec, target, target_is_for_true))
79 if (target_is_for_true){
81 ig.Emit (OpCodes.Brfalse, target);
83 ig.Emit (OpCodes.Brtrue, target);
86 ig.Emit (OpCodes.Brtrue, target);
88 ig.Emit (OpCodes.Brfalse, target);
92 public static void Warning_DeadCodeFound (Location loc)
94 Report.Warning (162, loc, "Unreachable code detected");
98 public class EmptyStatement : Statement {
99 public override bool Resolve (EmitContext ec)
104 protected override bool DoEmit (EmitContext ec)
110 public class If : Statement {
112 public Statement TrueStatement;
113 public Statement FalseStatement;
115 public If (Expression expr, Statement trueStatement, Location l)
118 TrueStatement = trueStatement;
122 public If (Expression expr,
123 Statement trueStatement,
124 Statement falseStatement,
128 TrueStatement = trueStatement;
129 FalseStatement = falseStatement;
133 public override bool Resolve (EmitContext ec)
135 Report.Debug (1, "START IF BLOCK", loc);
137 expr = Expression.ResolveBoolean (ec, expr, loc);
142 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
144 if (!TrueStatement.Resolve (ec)) {
145 ec.KillFlowBranching ();
149 ec.CurrentBranching.CreateSibling ();
151 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
152 ec.KillFlowBranching ();
156 ec.EndFlowBranching ();
158 Report.Debug (1, "END IF BLOCK", loc);
163 protected override bool DoEmit (EmitContext ec)
165 ILGenerator ig = ec.ig;
166 Label false_target = ig.DefineLabel ();
168 bool is_true_ret, is_false_ret;
171 // Dead code elimination
173 if (expr is BoolConstant){
174 bool take = ((BoolConstant) expr).Value;
177 if (FalseStatement != null){
178 Warning_DeadCodeFound (FalseStatement.loc);
180 return TrueStatement.Emit (ec);
182 Warning_DeadCodeFound (TrueStatement.loc);
183 if (FalseStatement != null)
184 return FalseStatement.Emit (ec);
188 EmitBoolExpression (ec, expr, false_target, false);
190 is_true_ret = TrueStatement.Emit (ec);
191 is_false_ret = is_true_ret;
193 if (FalseStatement != null){
194 bool branch_emitted = false;
196 end = ig.DefineLabel ();
198 ig.Emit (OpCodes.Br, end);
199 branch_emitted = true;
202 ig.MarkLabel (false_target);
203 is_false_ret = FalseStatement.Emit (ec);
208 ig.MarkLabel (false_target);
209 is_false_ret = false;
212 return is_true_ret && is_false_ret;
216 public class Do : Statement {
217 public Expression expr;
218 public readonly Statement EmbeddedStatement;
219 bool infinite, may_return;
221 public Do (Statement statement, Expression boolExpr, Location l)
224 EmbeddedStatement = statement;
228 public override bool Resolve (EmitContext ec)
232 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
234 if (!EmbeddedStatement.Resolve (ec))
237 expr = Expression.ResolveBoolean (ec, expr, loc);
240 else if (expr is BoolConstant){
241 bool res = ((BoolConstant) expr).Value;
247 ec.CurrentBranching.Infinite = infinite;
248 FlowReturns returns = ec.EndFlowBranching ();
249 may_return = returns != FlowReturns.NEVER;
254 protected override bool DoEmit (EmitContext ec)
256 ILGenerator ig = ec.ig;
257 Label loop = ig.DefineLabel ();
258 Label old_begin = ec.LoopBegin;
259 Label old_end = ec.LoopEnd;
260 bool old_inloop = ec.InLoop;
261 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
263 ec.LoopBegin = ig.DefineLabel ();
264 ec.LoopEnd = ig.DefineLabel ();
266 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
269 EmbeddedStatement.Emit (ec);
270 ig.MarkLabel (ec.LoopBegin);
273 // Dead code elimination
275 if (expr is BoolConstant){
276 bool res = ((BoolConstant) expr).Value;
279 ec.ig.Emit (OpCodes.Br, loop);
281 EmitBoolExpression (ec, expr, loop, true);
283 ig.MarkLabel (ec.LoopEnd);
285 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
286 ec.LoopBegin = old_begin;
287 ec.LoopEnd = old_end;
288 ec.InLoop = old_inloop;
291 return may_return == false;
297 public class While : Statement {
298 public Expression expr;
299 public readonly Statement Statement;
300 bool may_return, empty, infinite;
302 public While (Expression boolExpr, Statement statement, Location l)
304 this.expr = boolExpr;
305 Statement = statement;
309 public override bool Resolve (EmitContext ec)
313 expr = Expression.ResolveBoolean (ec, expr, loc);
317 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
320 // Inform whether we are infinite or not
322 if (expr is BoolConstant){
323 BoolConstant bc = (BoolConstant) expr;
325 if (bc.Value == false){
326 Warning_DeadCodeFound (Statement.loc);
332 // We are not infinite, so the loop may or may not be executed.
334 ec.CurrentBranching.CreateSibling ();
337 if (!Statement.Resolve (ec))
341 ec.KillFlowBranching ();
343 ec.CurrentBranching.Infinite = infinite;
344 FlowReturns returns = ec.EndFlowBranching ();
345 may_return = returns != FlowReturns.NEVER;
351 protected override bool DoEmit (EmitContext ec)
356 ILGenerator ig = ec.ig;
357 Label old_begin = ec.LoopBegin;
358 Label old_end = ec.LoopEnd;
359 bool old_inloop = ec.InLoop;
360 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
363 ec.LoopBegin = ig.DefineLabel ();
364 ec.LoopEnd = ig.DefineLabel ();
366 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
369 // Inform whether we are infinite or not
371 if (expr is BoolConstant){
372 BoolConstant bc = (BoolConstant) expr;
374 ig.MarkLabel (ec.LoopBegin);
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 = may_return == false;
383 ig.MarkLabel (ec.LoopEnd);
385 Label while_loop = ig.DefineLabel ();
387 ig.Emit (OpCodes.Br, ec.LoopBegin);
388 ig.MarkLabel (while_loop);
392 ig.MarkLabel (ec.LoopBegin);
394 EmitBoolExpression (ec, expr, while_loop, true);
395 ig.MarkLabel (ec.LoopEnd);
400 ec.LoopBegin = old_begin;
401 ec.LoopEnd = old_end;
402 ec.InLoop = old_inloop;
403 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
409 public class For : Statement {
411 readonly Statement InitStatement;
412 readonly Statement Increment;
413 readonly Statement Statement;
414 bool may_return, infinite, empty;
416 public For (Statement initStatement,
422 InitStatement = initStatement;
424 Increment = increment;
425 Statement = statement;
429 public override bool Resolve (EmitContext ec)
433 if (InitStatement != null){
434 if (!InitStatement.Resolve (ec))
439 Test = Expression.ResolveBoolean (ec, Test, loc);
442 else if (Test is BoolConstant){
443 BoolConstant bc = (BoolConstant) Test;
445 if (bc.Value == false){
446 Warning_DeadCodeFound (Statement.loc);
454 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
456 ec.CurrentBranching.CreateSibling ();
458 if (!Statement.Resolve (ec))
461 if (Increment != null){
462 if (!Increment.Resolve (ec))
467 ec.KillFlowBranching ();
469 ec.CurrentBranching.Infinite = infinite;
470 FlowReturns returns = ec.EndFlowBranching ();
471 may_return = returns != FlowReturns.NEVER;
477 protected override bool DoEmit (EmitContext ec)
482 ILGenerator ig = ec.ig;
483 Label old_begin = ec.LoopBegin;
484 Label old_end = ec.LoopEnd;
485 bool old_inloop = ec.InLoop;
486 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
487 Label loop = ig.DefineLabel ();
488 Label test = ig.DefineLabel ();
490 if (InitStatement != null)
491 if (! (InitStatement is EmptyStatement))
492 InitStatement.Emit (ec);
494 ec.LoopBegin = ig.DefineLabel ();
495 ec.LoopEnd = ig.DefineLabel ();
497 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
499 ig.Emit (OpCodes.Br, test);
503 ig.MarkLabel (ec.LoopBegin);
504 if (!(Increment is EmptyStatement))
509 // If test is null, there is no test, and we are just
514 // The Resolve code already catches the case for Test == BoolConstant (false)
515 // so we know that this is true
517 if (Test is BoolConstant)
518 ig.Emit (OpCodes.Br, loop);
520 EmitBoolExpression (ec, Test, loop, true);
522 ig.Emit (OpCodes.Br, loop);
523 ig.MarkLabel (ec.LoopEnd);
525 ec.LoopBegin = old_begin;
526 ec.LoopEnd = old_end;
527 ec.InLoop = old_inloop;
528 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
531 // Inform whether we are infinite or not
534 if (Test is BoolConstant){
535 BoolConstant bc = (BoolConstant) Test;
538 return may_return == false;
542 return may_return == false;
546 public class StatementExpression : Statement {
547 ExpressionStatement expr;
549 public StatementExpression (ExpressionStatement expr, Location l)
555 public override bool Resolve (EmitContext ec)
557 expr = expr.ResolveStatement (ec);
561 protected override bool DoEmit (EmitContext ec)
563 ILGenerator ig = ec.ig;
565 expr.EmitStatement (ec);
570 public override string ToString ()
572 return "StatementExpression (" + expr + ")";
577 /// Implements the return statement
579 public class Return : Statement {
580 public Expression Expr;
582 public Return (Expression expr, Location l)
588 public override bool Resolve (EmitContext ec)
591 Expr = Expr.Resolve (ec);
597 Report.Error (-206, loc, "Return statement not allowed inside iterators");
601 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
603 if (ec.CurrentBranching.InTryBlock ())
604 ec.CurrentBranching.AddFinallyVector (vector);
606 vector.CheckOutParameters (ec.CurrentBranching);
608 vector.Returns = FlowReturns.ALWAYS;
609 vector.Breaks = FlowReturns.ALWAYS;
613 protected override bool DoEmit (EmitContext ec)
616 Report.Error (157, loc, "Control can not leave the body of the finally block");
620 if (ec.ReturnType == null){
622 Report.Error (127, loc, "Return with a value not allowed here");
627 Report.Error (126, loc, "An object of type `" +
628 TypeManager.CSharpName (ec.ReturnType) + "' is " +
629 "expected for the return statement");
633 if (Expr.Type != ec.ReturnType)
634 Expr = Convert.ImplicitConversionRequired (
635 ec, Expr, ec.ReturnType, loc);
642 if (ec.InTry || ec.InCatch)
643 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
646 if (ec.InTry || ec.InCatch) {
647 if (!ec.HasReturnLabel) {
648 ec.ReturnLabel = ec.ig.DefineLabel ();
649 ec.HasReturnLabel = true;
651 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
653 ec.ig.Emit (OpCodes.Ret);
654 ec.NeedExplicitReturn = false;
661 public class Goto : Statement {
664 LabeledStatement label;
666 public override bool Resolve (EmitContext ec)
668 label = block.LookupLabel (target);
672 "No such label `" + target + "' in this scope");
676 // If this is a forward goto.
677 if (!label.IsDefined)
678 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
680 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
681 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.ALWAYS;
686 public Goto (Block parent_block, string label, Location l)
688 block = parent_block;
693 public string Target {
699 protected override bool DoEmit (EmitContext ec)
701 Label l = label.LabelTarget (ec);
702 ec.ig.Emit (OpCodes.Br, l);
708 public class LabeledStatement : Statement {
709 public readonly Location Location;
717 public LabeledStatement (string label_name, Location l)
719 this.label_name = label_name;
723 public Label LabelTarget (EmitContext ec)
727 label = ec.ig.DefineLabel ();
733 public bool IsDefined {
739 public bool HasBeenReferenced {
745 public void AddUsageVector (FlowBranching.UsageVector vector)
748 vectors = new ArrayList ();
750 vectors.Add (vector.Clone ());
753 public override bool Resolve (EmitContext ec)
756 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
758 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
759 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
767 protected override bool DoEmit (EmitContext ec)
770 ec.ig.MarkLabel (label);
778 /// `goto default' statement
780 public class GotoDefault : Statement {
782 public GotoDefault (Location l)
787 public override bool Resolve (EmitContext ec)
789 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
790 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.ALWAYS;
794 protected override bool DoEmit (EmitContext ec)
796 if (ec.Switch == null){
797 Report.Error (153, loc, "goto default is only valid in a switch statement");
801 if (!ec.Switch.GotDefault){
802 Report.Error (159, loc, "No default target on switch statement");
805 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
811 /// `goto case' statement
813 public class GotoCase : Statement {
817 public GotoCase (Expression e, Location l)
823 public override bool Resolve (EmitContext ec)
825 if (ec.Switch == null){
826 Report.Error (153, loc, "goto case is only valid in a switch statement");
830 expr = expr.Resolve (ec);
834 if (!(expr is Constant)){
835 Report.Error (159, loc, "Target expression for goto case is not constant");
839 object val = Expression.ConvertIntLiteral (
840 (Constant) expr, ec.Switch.SwitchType, loc);
845 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
850 "No such label 'case " + val + "': for the goto case");
854 label = sl.ILLabelCode;
856 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
857 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.ALWAYS;
861 protected override bool DoEmit (EmitContext ec)
863 ec.ig.Emit (OpCodes.Br, label);
868 public class Throw : Statement {
871 public Throw (Expression expr, Location l)
877 public override bool Resolve (EmitContext ec)
880 expr = expr.Resolve (ec);
884 ExprClass eclass = expr.eclass;
886 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
887 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
888 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
894 if ((t != TypeManager.exception_type) &&
895 !t.IsSubclassOf (TypeManager.exception_type) &&
896 !(expr is NullLiteral)) {
897 Report.Error (155, loc,
898 "The type caught or thrown must be derived " +
899 "from System.Exception");
904 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
905 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
909 protected override bool DoEmit (EmitContext ec)
913 ec.ig.Emit (OpCodes.Rethrow);
917 "A throw statement with no argument is only " +
918 "allowed in a catch clause");
925 ec.ig.Emit (OpCodes.Throw);
931 public class Break : Statement {
933 public Break (Location l)
938 public override bool Resolve (EmitContext ec)
940 ec.CurrentBranching.MayLeaveLoop = true;
941 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
945 protected override bool DoEmit (EmitContext ec)
947 ILGenerator ig = ec.ig;
949 if (ec.InLoop == false && ec.Switch == null){
950 Report.Error (139, loc, "No enclosing loop or switch to continue to");
954 if (ec.InTry || ec.InCatch)
955 ig.Emit (OpCodes.Leave, ec.LoopEnd);
957 ig.Emit (OpCodes.Br, ec.LoopEnd);
963 public class Continue : Statement {
965 public Continue (Location l)
970 public override bool Resolve (EmitContext ec)
972 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
976 protected override bool DoEmit (EmitContext ec)
978 Label begin = ec.LoopBegin;
981 Report.Error (139, loc, "No enclosing loop to continue to");
986 // UGH: Non trivial. This Br might cross a try/catch boundary
990 // try { ... } catch { continue; }
994 // try {} catch { while () { continue; }}
996 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
997 ec.ig.Emit (OpCodes.Leave, begin);
998 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
999 throw new Exception ("Should never happen");
1001 ec.ig.Emit (OpCodes.Br, begin);
1007 // This is used in the control flow analysis code to specify whether the
1008 // current code block may return to its enclosing block before reaching
1011 public enum FlowReturns {
1012 // It can never return.
1015 // This means that the block contains a conditional return statement
1019 // The code always returns, ie. there's an unconditional return / break
1023 // The code always throws an exception.
1026 // The current code block is unreachable. This happens if it's immediately
1027 // following a FlowReturns.ALWAYS block.
1032 // This is a special bit vector which can inherit from another bit vector doing a
1033 // copy-on-write strategy. The inherited vector may have a smaller size than the
1036 public class MyBitVector {
1037 public readonly int Count;
1038 public readonly MyBitVector InheritsFrom;
1043 public MyBitVector (int Count)
1044 : this (null, Count)
1047 public MyBitVector (MyBitVector InheritsFrom, int Count)
1049 this.InheritsFrom = InheritsFrom;
1054 // Checks whether this bit vector has been modified. After setting this to true,
1055 // we won't use the inherited vector anymore, but our own copy of it.
1057 public bool IsDirty {
1064 initialize_vector ();
1069 // Get/set bit `index' in the bit vector.
1071 public bool this [int index]
1075 throw new ArgumentOutOfRangeException ();
1077 // We're doing a "copy-on-write" strategy here; as long
1078 // as nobody writes to the array, we can use our parent's
1079 // copy instead of duplicating the vector.
1082 return vector [index];
1083 else if (InheritsFrom != null) {
1084 BitArray inherited = InheritsFrom.Vector;
1086 if (index < inherited.Count)
1087 return inherited [index];
1096 throw new ArgumentOutOfRangeException ();
1098 // Only copy the vector if we're actually modifying it.
1100 if (this [index] != value) {
1101 initialize_vector ();
1103 vector [index] = value;
1109 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1110 // copy of the bit vector.
1112 public static explicit operator BitArray (MyBitVector vector)
1114 vector.initialize_vector ();
1115 return vector.Vector;
1119 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1120 // different size than the current one.
1122 public void Or (MyBitVector new_vector)
1124 BitArray new_array = new_vector.Vector;
1126 initialize_vector ();
1129 if (vector.Count < new_array.Count)
1130 upper = vector.Count;
1132 upper = new_array.Count;
1134 for (int i = 0; i < upper; i++)
1135 vector [i] = vector [i] | new_array [i];
1139 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1140 // a different size than the current one.
1142 public void And (MyBitVector new_vector)
1144 BitArray new_array = new_vector.Vector;
1146 initialize_vector ();
1149 if (vector.Count < new_array.Count)
1150 lower = upper = vector.Count;
1152 lower = new_array.Count;
1153 upper = vector.Count;
1156 for (int i = 0; i < lower; i++)
1157 vector [i] = vector [i] & new_array [i];
1159 for (int i = lower; i < upper; i++)
1164 // This does a deep copy of the bit vector.
1166 public MyBitVector Clone ()
1168 MyBitVector retval = new MyBitVector (Count);
1170 retval.Vector = Vector;
1179 else if (!is_dirty && (InheritsFrom != null))
1180 return InheritsFrom.Vector;
1182 initialize_vector ();
1188 initialize_vector ();
1190 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1191 vector [i] = value [i];
1195 void initialize_vector ()
1200 vector = new BitArray (Count, false);
1201 if (InheritsFrom != null)
1202 Vector = InheritsFrom.Vector;
1207 public override string ToString ()
1209 StringBuilder sb = new StringBuilder ("MyBitVector (");
1211 BitArray vector = Vector;
1215 sb.Append ("INHERITED - ");
1216 for (int i = 0; i < vector.Count; i++) {
1219 sb.Append (vector [i]);
1223 return sb.ToString ();
1227 public class LocalInfo {
1228 public Expression Type;
1231 // Most of the time a variable will be stored in a LocalBuilder
1233 // But sometimes, it will be stored in a field. The context of the field will
1234 // be stored in the EmitContext
1237 public LocalBuilder LocalBuilder;
1238 public FieldBuilder FieldBuilder;
1240 public Type VariableType;
1241 public readonly string Name;
1242 public readonly Location Location;
1243 public readonly Block Block;
1245 public VariableInfo VariableInfo;
1248 public bool Assigned;
1249 public bool ReadOnly;
1252 public LocalInfo (Expression type, string name, Block block, Location l)
1257 LocalBuilder = null;
1261 public LocalInfo (TypeContainer tc, Block block, Location l)
1263 VariableType = tc.TypeBuilder;
1265 LocalBuilder = null;
1269 public bool IsThisAssigned (EmitContext ec, Location loc)
1271 VariableInfo vi = Block.GetVariableInfo (this);
1273 throw new Exception ();
1275 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (vi))
1278 return vi.TypeInfo.IsFullyInitialized (ec.CurrentBranching, vi, loc);
1281 public bool Resolve (DeclSpace decl)
1283 if (VariableType == null)
1284 VariableType = decl.ResolveType (Type, false, Location);
1286 if (VariableType == null)
1292 public void MakePinned ()
1294 TypeManager.MakePinned (LocalBuilder);
1298 public bool IsFixed {
1300 if (is_fixed || TypeManager.IsValueType (VariableType))
1307 public override string ToString ()
1309 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1310 Name, Type, VariableInfo, Location);
1315 /// Block represents a C# block.
1319 /// This class is used in a number of places: either to represent
1320 /// explicit blocks that the programmer places or implicit blocks.
1322 /// Implicit blocks are used as labels or to introduce variable
1325 public class Block : Statement {
1326 public readonly Block Parent;
1327 public readonly Location StartLocation;
1328 public Location EndLocation = Location.Null;
1331 public enum Flags : byte {
1335 VariablesInitialized = 8,
1340 public bool Implicit {
1342 return (flags & Flags.Implicit) != 0;
1346 public bool Unchecked {
1348 return (flags & Flags.Unchecked) != 0;
1351 flags |= Flags.Unchecked;
1356 // The statements in this block
1358 ArrayList statements;
1361 // An array of Blocks. We keep track of children just
1362 // to generate the local variable declarations.
1364 // Statements and child statements are handled through the
1370 // Labels. (label, block) pairs.
1375 // Keeps track of (name, type) pairs
1377 Hashtable variables;
1380 // Keeps track of constants
1381 Hashtable constants;
1384 // If this is a switch section, the enclosing switch block.
1392 public Block (Block parent)
1393 : this (parent, (Flags) 0, Location.Null, Location.Null)
1396 public Block (Block parent, Flags flags)
1397 : this (parent, flags, Location.Null, Location.Null)
1400 public Block (Block parent, Flags flags, Parameters parameters)
1401 : this (parent, flags, parameters, Location.Null, Location.Null)
1404 public Block (Block parent, Location start, Location end)
1405 : this (parent, (Flags) 0, start, end)
1408 public Block (Block parent, Parameters parameters, Location start, Location end)
1409 : this (parent, (Flags) 0, parameters, start, end)
1412 public Block (Block parent, Flags flags, Location start, Location end)
1413 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1416 public Block (Block parent, Flags flags, Parameters parameters,
1417 Location start, Location end)
1420 parent.AddChild (this);
1422 this.Parent = parent;
1424 this.parameters = parameters;
1425 this.StartLocation = start;
1426 this.EndLocation = end;
1429 statements = new ArrayList ();
1432 public Block CreateSwitchBlock (Location start)
1434 Block new_block = new Block (this, start, start);
1435 new_block.switch_block = this;
1445 void AddChild (Block b)
1447 if (children == null)
1448 children = new ArrayList ();
1453 public void SetEndLocation (Location loc)
1459 /// Adds a label to the current block.
1463 /// false if the name already exists in this block. true
1467 public bool AddLabel (string name, LabeledStatement target)
1469 if (switch_block != null)
1470 return switch_block.AddLabel (name, target);
1473 labels = new Hashtable ();
1474 if (labels.Contains (name))
1477 labels.Add (name, target);
1481 public LabeledStatement LookupLabel (string name)
1483 if (switch_block != null)
1484 return switch_block.LookupLabel (name);
1486 if (labels != null){
1487 if (labels.Contains (name))
1488 return ((LabeledStatement) labels [name]);
1492 return Parent.LookupLabel (name);
1497 LocalInfo this_variable = null;
1500 // Returns the "this" instance variable of this block.
1501 // See AddThisVariable() for more information.
1503 public LocalInfo ThisVariable {
1505 if (this_variable != null)
1506 return this_variable;
1507 else if (Parent != null)
1508 return Parent.ThisVariable;
1514 Hashtable child_variable_names;
1517 // Marks a variable with name @name as being used in a child block.
1518 // If a variable name has been used in a child block, it's illegal to
1519 // declare a variable with the same name in the current block.
1521 public void AddChildVariableName (string name)
1523 if (child_variable_names == null)
1524 child_variable_names = new Hashtable ();
1526 if (!child_variable_names.Contains (name))
1527 child_variable_names.Add (name, true);
1531 // Marks all variables from block @block and all its children as being
1532 // used in a child block.
1534 public void AddChildVariableNames (Block block)
1536 if (block.Variables != null) {
1537 foreach (string name in block.Variables.Keys)
1538 AddChildVariableName (name);
1541 if (block.children != null) {
1542 foreach (Block child in block.children)
1543 AddChildVariableNames (child);
1546 if (block.child_variable_names != null) {
1547 foreach (string name in block.child_variable_names.Keys)
1548 AddChildVariableName (name);
1553 // Checks whether a variable name has already been used in a child block.
1555 public bool IsVariableNameUsedInChildBlock (string name)
1557 if (child_variable_names == null)
1560 return child_variable_names.Contains (name);
1564 // This is used by non-static `struct' constructors which do not have an
1565 // initializer - in this case, the constructor must initialize all of the
1566 // struct's fields. To do this, we add a "this" variable and use the flow
1567 // analysis code to ensure that it's been fully initialized before control
1568 // leaves the constructor.
1570 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1572 if (this_variable != null)
1573 return this_variable;
1575 if (variables == null)
1576 variables = new Hashtable ();
1578 this_variable = new LocalInfo (tc, this, l);
1580 variables.Add ("this", this_variable);
1582 return this_variable;
1585 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1587 if (variables == null)
1588 variables = new Hashtable ();
1590 LocalInfo vi = GetLocalInfo (name);
1592 if (vi.Block != this)
1593 Report.Error (136, l, "A local variable named `" + name + "' " +
1594 "cannot be declared in this scope since it would " +
1595 "give a different meaning to `" + name + "', which " +
1596 "is already used in a `parent or current' scope to " +
1597 "denote something else");
1599 Report.Error (128, l, "A local variable `" + name + "' is already " +
1600 "defined in this scope");
1604 if (IsVariableNameUsedInChildBlock (name)) {
1605 Report.Error (136, l, "A local variable named `" + name + "' " +
1606 "cannot be declared in this scope since it would " +
1607 "give a different meaning to `" + name + "', which " +
1608 "is already used in a `child' scope to denote something " +
1615 Parameter p = pars.GetParameterByName (name, out idx);
1617 Report.Error (136, l, "A local variable named `" + name + "' " +
1618 "cannot be declared in this scope since it would " +
1619 "give a different meaning to `" + name + "', which " +
1620 "is already used in a `parent or current' scope to " +
1621 "denote something else");
1626 vi = new LocalInfo (type, name, this, l);
1628 variables.Add (name, vi);
1630 if ((flags & Flags.VariablesInitialized) != 0)
1631 throw new Exception ();
1633 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1637 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1639 if (AddVariable (type, name, pars, l) == null)
1642 if (constants == null)
1643 constants = new Hashtable ();
1645 constants.Add (name, value);
1649 public Hashtable Variables {
1655 public LocalInfo GetLocalInfo (string name)
1657 if (variables != null) {
1659 temp = variables [name];
1662 return (LocalInfo) temp;
1667 return Parent.GetLocalInfo (name);
1672 public VariableInfo GetVariableInfo (LocalInfo li)
1674 return li.VariableInfo;
1677 public Expression GetVariableType (string name)
1679 LocalInfo vi = GetLocalInfo (name);
1687 public Expression GetConstantExpression (string name)
1689 if (constants != null) {
1691 temp = constants [name];
1694 return (Expression) temp;
1698 return Parent.GetConstantExpression (name);
1704 /// True if the variable named @name is a constant
1706 public bool IsConstant (string name)
1708 Expression e = null;
1710 e = GetConstantExpression (name);
1716 /// Use to fetch the statement associated with this label
1718 public Statement this [string name] {
1720 return (Statement) labels [name];
1724 Parameters parameters = null;
1725 public Parameters Parameters {
1728 return Parent.Parameters;
1735 /// A list of labels that were not used within this block
1737 public string [] GetUnreferenced ()
1739 // FIXME: Implement me
1743 public void AddStatement (Statement s)
1746 flags |= Flags.BlockUsed;
1751 return (flags & Flags.BlockUsed) != 0;
1757 flags |= Flags.BlockUsed;
1760 VariableMap param_map, local_map;
1762 public VariableMap ParameterMap {
1764 if ((flags & Flags.VariablesInitialized) == 0)
1765 throw new Exception ();
1771 public VariableMap LocalMap {
1773 if ((flags & Flags.VariablesInitialized) == 0)
1774 throw new Exception ();
1781 /// Emits the variable declarations and labels.
1784 /// tc: is our typecontainer (to resolve type references)
1785 /// ig: is the code generator:
1787 public void EmitMeta (EmitContext ec, InternalParameters ip)
1789 DeclSpace ds = ec.DeclSpace;
1790 ILGenerator ig = ec.ig;
1793 // Compute the VariableMap's.
1795 // Unfortunately, we don't know the type when adding variables with
1796 // AddVariable(), so we need to compute this info here.
1800 if (variables != null) {
1801 foreach (LocalInfo li in variables.Values)
1802 li.Resolve (ec.DeclSpace);
1804 locals = new LocalInfo [variables.Count];
1805 variables.Values.CopyTo (locals, 0);
1807 locals = new LocalInfo [0];
1810 local_map = new VariableMap (Parent.LocalMap, locals);
1812 local_map = new VariableMap (locals);
1814 param_map = new VariableMap (ip);
1815 flags |= Flags.VariablesInitialized;
1817 bool old_check_state = ec.ConstantCheckState;
1818 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1819 bool remap_locals = ec.RemapToProxy;
1822 // Process this block variables
1824 if (variables != null){
1825 foreach (DictionaryEntry de in variables){
1826 string name = (string) de.Key;
1827 LocalInfo vi = (LocalInfo) de.Value;
1829 if (vi.VariableType == null)
1832 Type variable_type = vi.VariableType;
1834 if (variable_type.IsPointer){
1836 // Am not really convinced that this test is required (Microsoft does it)
1837 // but the fact is that you would not be able to use the pointer variable
1840 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1846 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1848 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1850 if (constants == null)
1853 Expression cv = (Expression) constants [name];
1857 ec.CurrentBlock = this;
1858 Expression e = cv.Resolve (ec);
1862 if (!(e is Constant)){
1863 Report.Error (133, vi.Location,
1864 "The expression being assigned to `" +
1865 name + "' must be constant (" + e + ")");
1869 constants.Remove (name);
1870 constants.Add (name, e);
1873 ec.ConstantCheckState = old_check_state;
1876 // Now, handle the children
1878 if (children != null){
1879 foreach (Block b in children)
1880 b.EmitMeta (ec, ip);
1884 public void UsageWarning ()
1888 if (variables != null){
1889 foreach (DictionaryEntry de in variables){
1890 LocalInfo vi = (LocalInfo) de.Value;
1895 name = (string) de.Key;
1899 219, vi.Location, "The variable `" + name +
1900 "' is assigned but its value is never used");
1903 168, vi.Location, "The variable `" +
1905 "' is declared but never used");
1910 if (children != null)
1911 foreach (Block b in children)
1915 public override bool Resolve (EmitContext ec)
1917 Block prev_block = ec.CurrentBlock;
1920 ec.CurrentBlock = this;
1921 ec.StartFlowBranching (this);
1923 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1925 ArrayList new_statements = new ArrayList ();
1926 bool unreachable = false, warning_shown = false;
1928 foreach (Statement s in statements){
1929 if (unreachable && !(s is LabeledStatement)) {
1930 if (!warning_shown && !(s is EmptyStatement)) {
1931 warning_shown = true;
1932 Warning_DeadCodeFound (s.loc);
1938 if (s.Resolve (ec) == false) {
1943 if (s is LabeledStatement)
1944 unreachable = false;
1946 unreachable = ! ec.CurrentBranching.IsReachable ();
1948 new_statements.Add (s);
1951 statements = new_statements;
1953 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
1955 FlowReturns returns = ec.EndFlowBranching ();
1956 ec.CurrentBlock = prev_block;
1958 // If we're a non-static `struct' constructor which doesn't have an
1959 // initializer, then we must initialize all of the struct's fields.
1960 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
1961 !this_variable.IsThisAssigned (ec, loc))
1964 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1965 foreach (LabeledStatement label in labels.Values)
1966 if (!label.HasBeenReferenced)
1967 Report.Warning (164, label.Location,
1968 "This label has not been referenced");
1971 if ((returns == FlowReturns.ALWAYS) ||
1972 (returns == FlowReturns.EXCEPTION) ||
1973 (returns == FlowReturns.UNREACHABLE))
1974 flags |= Flags.HasRet;
1979 protected override bool DoEmit (EmitContext ec)
1981 foreach (Statement s in statements)
1984 return (flags & Flags.HasRet) != 0;
1987 public override bool Emit (EmitContext ec)
1989 Block prev_block = ec.CurrentBlock;
1991 ec.CurrentBlock = this;
1993 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1994 bool is_lexical_block = !Implicit && (Parent != null);
1996 if (emit_debug_info) {
1997 if (is_lexical_block)
1998 ec.ig.BeginScope ();
2000 if (variables != null) {
2001 foreach (DictionaryEntry de in variables) {
2002 string name = (string) de.Key;
2003 LocalInfo vi = (LocalInfo) de.Value;
2005 if (vi.LocalBuilder == null)
2008 vi.LocalBuilder.SetLocalSymInfo (name);
2013 ec.Mark (StartLocation, true);
2014 bool retval = DoEmit (ec);
2015 ec.Mark (EndLocation, true);
2017 if (emit_debug_info && is_lexical_block)
2020 ec.CurrentBlock = prev_block;
2026 public class SwitchLabel {
2029 public Location loc;
2030 public Label ILLabel;
2031 public Label ILLabelCode;
2034 // if expr == null, then it is the default case.
2036 public SwitchLabel (Expression expr, Location l)
2042 public Expression Label {
2048 public object Converted {
2055 // Resolves the expression, reduces it to a literal if possible
2056 // and then converts it to the requested type.
2058 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2060 ILLabel = ec.ig.DefineLabel ();
2061 ILLabelCode = ec.ig.DefineLabel ();
2066 Expression e = label.Resolve (ec);
2071 if (!(e is Constant)){
2072 Report.Error (150, loc, "A constant value is expected, got: " + e);
2076 if (e is StringConstant || e is NullLiteral){
2077 if (required_type == TypeManager.string_type){
2079 ILLabel = ec.ig.DefineLabel ();
2084 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2085 if (converted == null)
2092 public class SwitchSection {
2093 // An array of SwitchLabels.
2094 public readonly ArrayList Labels;
2095 public readonly Block Block;
2097 public SwitchSection (ArrayList labels, Block block)
2104 public class Switch : Statement {
2105 public readonly ArrayList Sections;
2106 public Expression Expr;
2109 /// Maps constants whose type type SwitchType to their SwitchLabels.
2111 public Hashtable Elements;
2114 /// The governing switch type
2116 public Type SwitchType;
2122 Label default_target;
2123 Expression new_expr;
2126 // The types allowed to be implicitly cast from
2127 // on the governing type
2129 static Type [] allowed_types;
2131 public Switch (Expression e, ArrayList sects, Location l)
2138 public bool GotDefault {
2144 public Label DefaultTarget {
2146 return default_target;
2151 // Determines the governing type for a switch. The returned
2152 // expression might be the expression from the switch, or an
2153 // expression that includes any potential conversions to the
2154 // integral types or to string.
2156 Expression SwitchGoverningType (EmitContext ec, Type t)
2158 if (t == TypeManager.int32_type ||
2159 t == TypeManager.uint32_type ||
2160 t == TypeManager.char_type ||
2161 t == TypeManager.byte_type ||
2162 t == TypeManager.sbyte_type ||
2163 t == TypeManager.ushort_type ||
2164 t == TypeManager.short_type ||
2165 t == TypeManager.uint64_type ||
2166 t == TypeManager.int64_type ||
2167 t == TypeManager.string_type ||
2168 t == TypeManager.bool_type ||
2169 t.IsSubclassOf (TypeManager.enum_type))
2172 if (allowed_types == null){
2173 allowed_types = new Type [] {
2174 TypeManager.sbyte_type,
2175 TypeManager.byte_type,
2176 TypeManager.short_type,
2177 TypeManager.ushort_type,
2178 TypeManager.int32_type,
2179 TypeManager.uint32_type,
2180 TypeManager.int64_type,
2181 TypeManager.uint64_type,
2182 TypeManager.char_type,
2183 TypeManager.bool_type,
2184 TypeManager.string_type
2189 // Try to find a *user* defined implicit conversion.
2191 // If there is no implicit conversion, or if there are multiple
2192 // conversions, we have to report an error
2194 Expression converted = null;
2195 foreach (Type tt in allowed_types){
2198 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2202 if (converted != null){
2203 Report.Error (-12, loc, "More than one conversion to an integral " +
2204 " type exists for type `" +
2205 TypeManager.CSharpName (Expr.Type)+"'");
2213 void error152 (string n)
2216 152, "The label `" + n + ":' " +
2217 "is already present on this switch statement");
2221 // Performs the basic sanity checks on the switch statement
2222 // (looks for duplicate keys and non-constant expressions).
2224 // It also returns a hashtable with the keys that we will later
2225 // use to compute the switch tables
2227 bool CheckSwitch (EmitContext ec)
2231 Elements = new Hashtable ();
2233 got_default = false;
2235 if (TypeManager.IsEnumType (SwitchType)){
2236 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2238 compare_type = SwitchType;
2240 foreach (SwitchSection ss in Sections){
2241 foreach (SwitchLabel sl in ss.Labels){
2242 if (!sl.ResolveAndReduce (ec, SwitchType)){
2247 if (sl.Label == null){
2249 error152 ("default");
2256 object key = sl.Converted;
2258 if (key is Constant)
2259 key = ((Constant) key).GetValue ();
2262 key = NullLiteral.Null;
2264 string lname = null;
2265 if (compare_type == TypeManager.uint64_type){
2266 ulong v = (ulong) key;
2268 if (Elements.Contains (v))
2269 lname = v.ToString ();
2271 Elements.Add (v, sl);
2272 } else if (compare_type == TypeManager.int64_type){
2273 long v = (long) key;
2275 if (Elements.Contains (v))
2276 lname = v.ToString ();
2278 Elements.Add (v, sl);
2279 } else if (compare_type == TypeManager.uint32_type){
2280 uint v = (uint) key;
2282 if (Elements.Contains (v))
2283 lname = v.ToString ();
2285 Elements.Add (v, sl);
2286 } else if (compare_type == TypeManager.char_type){
2287 char v = (char) key;
2289 if (Elements.Contains (v))
2290 lname = v.ToString ();
2292 Elements.Add (v, sl);
2293 } else if (compare_type == TypeManager.byte_type){
2294 byte v = (byte) key;
2296 if (Elements.Contains (v))
2297 lname = v.ToString ();
2299 Elements.Add (v, sl);
2300 } else if (compare_type == TypeManager.sbyte_type){
2301 sbyte v = (sbyte) key;
2303 if (Elements.Contains (v))
2304 lname = v.ToString ();
2306 Elements.Add (v, sl);
2307 } else if (compare_type == TypeManager.short_type){
2308 short v = (short) key;
2310 if (Elements.Contains (v))
2311 lname = v.ToString ();
2313 Elements.Add (v, sl);
2314 } else if (compare_type == TypeManager.ushort_type){
2315 ushort v = (ushort) key;
2317 if (Elements.Contains (v))
2318 lname = v.ToString ();
2320 Elements.Add (v, sl);
2321 } else if (compare_type == TypeManager.string_type){
2322 if (key is NullLiteral){
2323 if (Elements.Contains (NullLiteral.Null))
2326 Elements.Add (NullLiteral.Null, null);
2328 string s = (string) key;
2330 if (Elements.Contains (s))
2333 Elements.Add (s, sl);
2335 } else if (compare_type == TypeManager.int32_type) {
2338 if (Elements.Contains (v))
2339 lname = v.ToString ();
2341 Elements.Add (v, sl);
2342 } else if (compare_type == TypeManager.bool_type) {
2343 bool v = (bool) key;
2345 if (Elements.Contains (v))
2346 lname = v.ToString ();
2348 Elements.Add (v, sl);
2352 throw new Exception ("Unknown switch type!" +
2353 SwitchType + " " + compare_type);
2357 error152 ("case + " + lname);
2368 void EmitObjectInteger (ILGenerator ig, object k)
2371 IntConstant.EmitInt (ig, (int) k);
2372 else if (k is Constant) {
2373 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2376 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2379 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2381 IntConstant.EmitInt (ig, (int) (long) k);
2382 ig.Emit (OpCodes.Conv_I8);
2385 LongConstant.EmitLong (ig, (long) k);
2387 else if (k is ulong)
2389 if ((ulong) k < (1L<<32))
2391 IntConstant.EmitInt (ig, (int) (long) k);
2392 ig.Emit (OpCodes.Conv_U8);
2396 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2400 IntConstant.EmitInt (ig, (int) ((char) k));
2401 else if (k is sbyte)
2402 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2404 IntConstant.EmitInt (ig, (int) ((byte) k));
2405 else if (k is short)
2406 IntConstant.EmitInt (ig, (int) ((short) k));
2407 else if (k is ushort)
2408 IntConstant.EmitInt (ig, (int) ((ushort) k));
2410 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2412 throw new Exception ("Unhandled case");
2415 // structure used to hold blocks of keys while calculating table switch
2416 class KeyBlock : IComparable
2418 public KeyBlock (long _nFirst)
2420 nFirst = nLast = _nFirst;
2424 public ArrayList rgKeys = null;
2427 get { return (int) (nLast - nFirst + 1); }
2429 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2431 return kbLast.nLast - kbFirst.nFirst + 1;
2433 public int CompareTo (object obj)
2435 KeyBlock kb = (KeyBlock) obj;
2436 int nLength = Length;
2437 int nLengthOther = kb.Length;
2438 if (nLengthOther == nLength)
2439 return (int) (kb.nFirst - nFirst);
2440 return nLength - nLengthOther;
2445 /// This method emits code for a lookup-based switch statement (non-string)
2446 /// Basically it groups the cases into blocks that are at least half full,
2447 /// and then spits out individual lookup opcodes for each block.
2448 /// It emits the longest blocks first, and short blocks are just
2449 /// handled with direct compares.
2451 /// <param name="ec"></param>
2452 /// <param name="val"></param>
2453 /// <returns></returns>
2454 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
2456 int cElements = Elements.Count;
2457 object [] rgKeys = new object [cElements];
2458 Elements.Keys.CopyTo (rgKeys, 0);
2459 Array.Sort (rgKeys);
2461 // initialize the block list with one element per key
2462 ArrayList rgKeyBlocks = new ArrayList ();
2463 foreach (object key in rgKeys)
2464 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2467 // iteratively merge the blocks while they are at least half full
2468 // there's probably a really cool way to do this with a tree...
2469 while (rgKeyBlocks.Count > 1)
2471 ArrayList rgKeyBlocksNew = new ArrayList ();
2472 kbCurr = (KeyBlock) rgKeyBlocks [0];
2473 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2475 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2476 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2479 kbCurr.nLast = kb.nLast;
2483 // start a new block
2484 rgKeyBlocksNew.Add (kbCurr);
2488 rgKeyBlocksNew.Add (kbCurr);
2489 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2491 rgKeyBlocks = rgKeyBlocksNew;
2494 // initialize the key lists
2495 foreach (KeyBlock kb in rgKeyBlocks)
2496 kb.rgKeys = new ArrayList ();
2498 // fill the key lists
2500 if (rgKeyBlocks.Count > 0) {
2501 kbCurr = (KeyBlock) rgKeyBlocks [0];
2502 foreach (object key in rgKeys)
2504 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2505 System.Convert.ToInt64 (key) > kbCurr.nLast;
2507 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2508 kbCurr.rgKeys.Add (key);
2512 // sort the blocks so we can tackle the largest ones first
2513 rgKeyBlocks.Sort ();
2515 // okay now we can start...
2516 ILGenerator ig = ec.ig;
2517 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2518 Label lblDefault = ig.DefineLabel ();
2520 Type typeKeys = null;
2521 if (rgKeys.Length > 0)
2522 typeKeys = rgKeys [0].GetType (); // used for conversions
2524 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2526 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2527 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2530 foreach (object key in kb.rgKeys)
2532 ig.Emit (OpCodes.Ldloc, val);
2533 EmitObjectInteger (ig, key);
2534 SwitchLabel sl = (SwitchLabel) Elements [key];
2535 ig.Emit (OpCodes.Beq, sl.ILLabel);
2540 // TODO: if all the keys in the block are the same and there are
2541 // no gaps/defaults then just use a range-check.
2542 if (SwitchType == TypeManager.int64_type ||
2543 SwitchType == TypeManager.uint64_type)
2545 // TODO: optimize constant/I4 cases
2547 // check block range (could be > 2^31)
2548 ig.Emit (OpCodes.Ldloc, val);
2549 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2550 ig.Emit (OpCodes.Blt, lblDefault);
2551 ig.Emit (OpCodes.Ldloc, val);
2552 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2553 ig.Emit (OpCodes.Bgt, lblDefault);
2556 ig.Emit (OpCodes.Ldloc, val);
2559 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2560 ig.Emit (OpCodes.Sub);
2562 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2567 ig.Emit (OpCodes.Ldloc, val);
2568 int nFirst = (int) kb.nFirst;
2571 IntConstant.EmitInt (ig, nFirst);
2572 ig.Emit (OpCodes.Sub);
2574 else if (nFirst < 0)
2576 IntConstant.EmitInt (ig, -nFirst);
2577 ig.Emit (OpCodes.Add);
2581 // first, build the list of labels for the switch
2583 int cJumps = kb.Length;
2584 Label [] rgLabels = new Label [cJumps];
2585 for (int iJump = 0; iJump < cJumps; iJump++)
2587 object key = kb.rgKeys [iKey];
2588 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2590 SwitchLabel sl = (SwitchLabel) Elements [key];
2591 rgLabels [iJump] = sl.ILLabel;
2595 rgLabels [iJump] = lblDefault;
2597 // emit the switch opcode
2598 ig.Emit (OpCodes.Switch, rgLabels);
2601 // mark the default for this block
2603 ig.MarkLabel (lblDefault);
2606 // TODO: find the default case and emit it here,
2607 // to prevent having to do the following jump.
2608 // make sure to mark other labels in the default section
2610 // the last default just goes to the end
2611 ig.Emit (OpCodes.Br, lblDefault);
2613 // now emit the code for the sections
2614 bool fFoundDefault = false;
2615 bool fAllReturn = true;
2616 foreach (SwitchSection ss in Sections)
2618 foreach (SwitchLabel sl in ss.Labels)
2620 ig.MarkLabel (sl.ILLabel);
2621 ig.MarkLabel (sl.ILLabelCode);
2622 if (sl.Label == null)
2624 ig.MarkLabel (lblDefault);
2625 fFoundDefault = true;
2628 bool returns = ss.Block.Emit (ec);
2629 fAllReturn &= returns;
2630 //ig.Emit (OpCodes.Br, lblEnd);
2633 if (!fFoundDefault) {
2634 ig.MarkLabel (lblDefault);
2637 ig.MarkLabel (lblEnd);
2642 // This simple emit switch works, but does not take advantage of the
2644 // TODO: remove non-string logic from here
2645 // TODO: binary search strings?
2647 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2649 ILGenerator ig = ec.ig;
2650 Label end_of_switch = ig.DefineLabel ();
2651 Label next_test = ig.DefineLabel ();
2652 Label null_target = ig.DefineLabel ();
2653 bool default_found = false;
2654 bool first_test = true;
2655 bool pending_goto_end = false;
2656 bool all_return = true;
2659 ig.Emit (OpCodes.Ldloc, val);
2661 if (Elements.Contains (NullLiteral.Null)){
2662 ig.Emit (OpCodes.Brfalse, null_target);
2664 ig.Emit (OpCodes.Brfalse, default_target);
2666 ig.Emit (OpCodes.Ldloc, val);
2667 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2668 ig.Emit (OpCodes.Stloc, val);
2670 int section_count = Sections.Count;
2671 for (int section = 0; section < section_count; section++){
2672 SwitchSection ss = (SwitchSection) Sections [section];
2673 Label sec_begin = ig.DefineLabel ();
2675 if (pending_goto_end)
2676 ig.Emit (OpCodes.Br, end_of_switch);
2678 int label_count = ss.Labels.Count;
2680 for (int label = 0; label < label_count; label++){
2681 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2682 ig.MarkLabel (sl.ILLabel);
2685 ig.MarkLabel (next_test);
2686 next_test = ig.DefineLabel ();
2689 // If we are the default target
2691 if (sl.Label == null){
2692 ig.MarkLabel (default_target);
2693 default_found = true;
2695 object lit = sl.Converted;
2697 if (lit is NullLiteral){
2699 if (label_count == 1)
2700 ig.Emit (OpCodes.Br, next_test);
2704 StringConstant str = (StringConstant) lit;
2706 ig.Emit (OpCodes.Ldloc, val);
2707 ig.Emit (OpCodes.Ldstr, str.Value);
2708 if (label_count == 1)
2709 ig.Emit (OpCodes.Bne_Un, next_test);
2711 if (label+1 == label_count)
2712 ig.Emit (OpCodes.Bne_Un, next_test);
2714 ig.Emit (OpCodes.Beq, sec_begin);
2719 ig.MarkLabel (null_target);
2720 ig.MarkLabel (sec_begin);
2721 foreach (SwitchLabel sl in ss.Labels)
2722 ig.MarkLabel (sl.ILLabelCode);
2724 bool returns = ss.Block.Emit (ec);
2726 pending_goto_end = false;
2729 pending_goto_end = true;
2733 if (!default_found){
2734 ig.MarkLabel (default_target);
2737 ig.MarkLabel (next_test);
2738 ig.MarkLabel (end_of_switch);
2743 public override bool Resolve (EmitContext ec)
2745 Expr = Expr.Resolve (ec);
2749 new_expr = SwitchGoverningType (ec, Expr.Type);
2750 if (new_expr == null){
2751 Report.Error (151, loc, "An integer type or string was expected for switch");
2756 SwitchType = new_expr.Type;
2758 if (!CheckSwitch (ec))
2761 Switch old_switch = ec.Switch;
2763 ec.Switch.SwitchType = SwitchType;
2765 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2768 foreach (SwitchSection ss in Sections){
2770 ec.CurrentBranching.CreateSibling ();
2774 if (ss.Block.Resolve (ec) != true)
2780 ec.CurrentBranching.CreateSibling ();
2782 ec.EndFlowBranching ();
2783 ec.Switch = old_switch;
2788 protected override bool DoEmit (EmitContext ec)
2790 // Store variable for comparission purposes
2791 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2793 ec.ig.Emit (OpCodes.Stloc, value);
2795 ILGenerator ig = ec.ig;
2797 default_target = ig.DefineLabel ();
2800 // Setup the codegen context
2802 Label old_end = ec.LoopEnd;
2803 Switch old_switch = ec.Switch;
2805 ec.LoopEnd = ig.DefineLabel ();
2810 if (SwitchType == TypeManager.string_type)
2811 all_return = SimpleSwitchEmit (ec, value);
2813 all_return = TableSwitchEmit (ec, value);
2815 // Restore context state.
2816 ig.MarkLabel (ec.LoopEnd);
2819 // Restore the previous context
2821 ec.LoopEnd = old_end;
2822 ec.Switch = old_switch;
2828 public class Lock : Statement {
2830 Statement Statement;
2832 public Lock (Expression expr, Statement stmt, Location l)
2839 public override bool Resolve (EmitContext ec)
2841 expr = expr.Resolve (ec);
2842 return Statement.Resolve (ec) && expr != null;
2845 protected override bool DoEmit (EmitContext ec)
2847 Type type = expr.Type;
2850 if (type.IsValueType){
2851 Report.Error (185, loc, "lock statement requires the expression to be " +
2852 " a reference type (type is: `" +
2853 TypeManager.CSharpName (type) + "'");
2857 ILGenerator ig = ec.ig;
2858 LocalBuilder temp = ig.DeclareLocal (type);
2861 ig.Emit (OpCodes.Dup);
2862 ig.Emit (OpCodes.Stloc, temp);
2863 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2866 Label end = ig.BeginExceptionBlock ();
2867 bool old_in_try = ec.InTry;
2869 Label finish = ig.DefineLabel ();
2870 val = Statement.Emit (ec);
2871 ec.InTry = old_in_try;
2872 // ig.Emit (OpCodes.Leave, finish);
2874 ig.MarkLabel (finish);
2877 ig.BeginFinallyBlock ();
2878 ig.Emit (OpCodes.Ldloc, temp);
2879 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2880 ig.EndExceptionBlock ();
2886 public class Unchecked : Statement {
2887 public readonly Block Block;
2889 public Unchecked (Block b)
2895 public override bool Resolve (EmitContext ec)
2897 bool previous_state = ec.CheckState;
2898 bool previous_state_const = ec.ConstantCheckState;
2900 ec.CheckState = false;
2901 ec.ConstantCheckState = false;
2902 bool ret = Block.Resolve (ec);
2903 ec.CheckState = previous_state;
2904 ec.ConstantCheckState = previous_state_const;
2909 protected override bool DoEmit (EmitContext ec)
2911 bool previous_state = ec.CheckState;
2912 bool previous_state_const = ec.ConstantCheckState;
2915 ec.CheckState = false;
2916 ec.ConstantCheckState = false;
2917 val = Block.Emit (ec);
2918 ec.CheckState = previous_state;
2919 ec.ConstantCheckState = previous_state_const;
2925 public class Checked : Statement {
2926 public readonly Block Block;
2928 public Checked (Block b)
2931 b.Unchecked = false;
2934 public override bool Resolve (EmitContext ec)
2936 bool previous_state = ec.CheckState;
2937 bool previous_state_const = ec.ConstantCheckState;
2939 ec.CheckState = true;
2940 ec.ConstantCheckState = true;
2941 bool ret = Block.Resolve (ec);
2942 ec.CheckState = previous_state;
2943 ec.ConstantCheckState = previous_state_const;
2948 protected override bool DoEmit (EmitContext ec)
2950 bool previous_state = ec.CheckState;
2951 bool previous_state_const = ec.ConstantCheckState;
2954 ec.CheckState = true;
2955 ec.ConstantCheckState = true;
2956 val = Block.Emit (ec);
2957 ec.CheckState = previous_state;
2958 ec.ConstantCheckState = previous_state_const;
2964 public class Unsafe : Statement {
2965 public readonly Block Block;
2967 public Unsafe (Block b)
2972 public override bool Resolve (EmitContext ec)
2974 bool previous_state = ec.InUnsafe;
2978 val = Block.Resolve (ec);
2979 ec.InUnsafe = previous_state;
2984 protected override bool DoEmit (EmitContext ec)
2986 bool previous_state = ec.InUnsafe;
2990 val = Block.Emit (ec);
2991 ec.InUnsafe = previous_state;
3000 public class Fixed : Statement {
3002 ArrayList declarators;
3003 Statement statement;
3008 public bool is_object;
3009 public LocalInfo vi;
3010 public Expression expr;
3011 public Expression converted;
3014 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3017 declarators = decls;
3022 public override bool Resolve (EmitContext ec)
3025 Expression.UnsafeError (loc);
3029 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
3030 if (expr_type == null)
3033 if (ec.RemapToProxy){
3034 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3038 data = new FixedData [declarators.Count];
3040 if (!expr_type.IsPointer){
3041 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3046 foreach (Pair p in declarators){
3047 LocalInfo vi = (LocalInfo) p.First;
3048 Expression e = (Expression) p.Second;
3050 vi.VariableInfo = null;
3053 // The rules for the possible declarators are pretty wise,
3054 // but the production on the grammar is more concise.
3056 // So we have to enforce these rules here.
3058 // We do not resolve before doing the case 1 test,
3059 // because the grammar is explicit in that the token &
3060 // is present, so we need to test for this particular case.
3064 // Case 1: & object.
3066 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3067 Expression child = ((Unary) e).Expr;
3070 if (child is ParameterReference || child is LocalVariableReference){
3073 "No need to use fixed statement for parameters or " +
3074 "local variable declarations (address is already " +
3079 ec.InFixedInitializer = true;
3081 ec.InFixedInitializer = false;
3085 child = ((Unary) e).Expr;
3087 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3090 data [i].is_object = true;
3092 data [i].converted = null;
3099 ec.InFixedInitializer = true;
3101 ec.InFixedInitializer = false;
3108 if (e.Type.IsArray){
3109 Type array_type = TypeManager.GetElementType (e.Type);
3113 // Provided that array_type is unmanaged,
3115 if (!TypeManager.VerifyUnManaged (array_type, loc))
3119 // and T* is implicitly convertible to the
3120 // pointer type given in the fixed statement.
3122 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3124 Expression converted = Convert.ImplicitConversionRequired (
3125 ec, array_ptr, vi.VariableType, loc);
3126 if (converted == null)
3129 data [i].is_object = false;
3131 data [i].converted = converted;
3141 if (e.Type == TypeManager.string_type){
3142 data [i].is_object = false;
3144 data [i].converted = null;
3150 return statement.Resolve (ec);
3153 protected override bool DoEmit (EmitContext ec)
3155 ILGenerator ig = ec.ig;
3157 bool is_ret = false;
3158 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3160 for (int i = 0; i < data.Length; i++) {
3161 LocalInfo vi = data [i].vi;
3164 // Case 1: & object.
3166 if (data [i].is_object) {
3168 // Store pointer in pinned location
3170 data [i].expr.Emit (ec);
3171 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3172 clear_list [i] = vi.LocalBuilder;
3179 if (data [i].expr.Type.IsArray){
3181 // Store pointer in pinned location
3183 data [i].converted.Emit (ec);
3185 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3186 clear_list [i] = vi.LocalBuilder;
3193 if (data [i].expr.Type == TypeManager.string_type){
3194 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3195 TypeManager.MakePinned (pinned_string);
3196 clear_list [i] = pinned_string;
3198 data [i].expr.Emit (ec);
3199 ig.Emit (OpCodes.Stloc, pinned_string);
3201 Expression sptr = new StringPtr (pinned_string, loc);
3202 Expression converted = Convert.ImplicitConversionRequired (
3203 ec, sptr, vi.VariableType, loc);
3205 if (converted == null)
3208 converted.Emit (ec);
3209 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3213 is_ret = statement.Emit (ec);
3218 // Clear the pinned variable
3220 for (int i = 0; i < data.Length; i++) {
3221 LocalInfo vi = data [i].vi;
3223 if (data [i].is_object || data [i].expr.Type.IsArray) {
3224 ig.Emit (OpCodes.Ldc_I4_0);
3225 ig.Emit (OpCodes.Conv_U);
3226 ig.Emit (OpCodes.Stloc, clear_list [i]);
3227 } else if (data [i].expr.Type == TypeManager.string_type){
3228 ig.Emit (OpCodes.Ldnull);
3229 ig.Emit (OpCodes.Stloc, clear_list [i]);
3237 public class Catch {
3238 public readonly string Name;
3239 public readonly Block Block;
3240 public readonly Location Location;
3242 Expression type_expr;
3245 public Catch (Expression type, string name, Block block, Location l)
3253 public Type CatchType {
3259 public bool IsGeneral {
3261 return type_expr == null;
3265 public bool Resolve (EmitContext ec)
3267 if (type_expr != null) {
3268 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3272 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3273 Report.Error (155, Location,
3274 "The type caught or thrown must be derived " +
3275 "from System.Exception");
3281 if (!Block.Resolve (ec))
3288 public class Try : Statement {
3289 public readonly Block Fini, Block;
3290 public readonly ArrayList Specific;
3291 public readonly Catch General;
3294 // specific, general and fini might all be null.
3296 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3298 if (specific == null && general == null){
3299 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3303 this.Specific = specific;
3304 this.General = general;
3309 public override bool Resolve (EmitContext ec)
3313 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3315 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3317 bool old_in_try = ec.InTry;
3320 if (!Block.Resolve (ec))
3323 ec.InTry = old_in_try;
3325 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3327 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3329 foreach (Catch c in Specific){
3330 ec.CurrentBranching.CreateSibling ();
3331 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3333 if (c.Name != null) {
3334 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3336 throw new Exception ();
3338 vi.VariableInfo = null;
3341 bool old_in_catch = ec.InCatch;
3344 if (!c.Resolve (ec))
3347 ec.InCatch = old_in_catch;
3349 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3351 if (!current.AlwaysReturns && !current.AlwaysBreaks)
3352 vector.AndLocals (current);
3354 vector.Or (current);
3357 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3359 if (General != null){
3360 ec.CurrentBranching.CreateSibling ();
3361 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3363 bool old_in_catch = ec.InCatch;
3366 if (!General.Resolve (ec))
3369 ec.InCatch = old_in_catch;
3371 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
3373 if (!current.AlwaysReturns && !current.AlwaysBreaks)
3374 vector.AndLocals (current);
3376 vector.Or (current);
3379 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3383 ec.CurrentBranching.CreateSiblingForFinally ();
3384 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3386 bool old_in_finally = ec.InFinally;
3387 ec.InFinally = true;
3389 if (!Fini.Resolve (ec))
3392 ec.InFinally = old_in_finally;
3395 FlowReturns returns = ec.EndFlowBranching ();
3397 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3399 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
3401 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
3402 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
3405 ec.CurrentBranching.CurrentUsageVector.Or (vector);
3407 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
3409 if (returns != FlowReturns.ALWAYS) {
3410 // Unfortunately, System.Reflection.Emit automatically emits a leave
3411 // to the end of the finally block. This is a problem if `returns'
3412 // is true since we may jump to a point after the end of the method.
3413 // As a workaround, emit an explicit ret here.
3414 ec.NeedExplicitReturn = true;
3420 protected override bool DoEmit (EmitContext ec)
3422 ILGenerator ig = ec.ig;
3424 Label finish = ig.DefineLabel ();;
3428 end = ig.BeginExceptionBlock ();
3429 bool old_in_try = ec.InTry;
3431 returns = Block.Emit (ec);
3432 ec.InTry = old_in_try;
3435 // System.Reflection.Emit provides this automatically:
3436 // ig.Emit (OpCodes.Leave, finish);
3438 bool old_in_catch = ec.InCatch;
3440 DeclSpace ds = ec.DeclSpace;
3442 foreach (Catch c in Specific){
3445 ig.BeginCatchBlock (c.CatchType);
3447 if (c.Name != null){
3448 vi = c.Block.GetLocalInfo (c.Name);
3450 throw new Exception ("Variable does not exist in this block");
3452 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3454 ig.Emit (OpCodes.Pop);
3456 if (!c.Block.Emit (ec))
3460 if (General != null){
3461 ig.BeginCatchBlock (TypeManager.object_type);
3462 ig.Emit (OpCodes.Pop);
3463 if (!General.Block.Emit (ec))
3466 ec.InCatch = old_in_catch;
3468 ig.MarkLabel (finish);
3470 ig.BeginFinallyBlock ();
3471 bool old_in_finally = ec.InFinally;
3472 ec.InFinally = true;
3474 ec.InFinally = old_in_finally;
3477 ig.EndExceptionBlock ();
3484 public class Using : Statement {
3485 object expression_or_block;
3486 Statement Statement;
3491 Expression [] converted_vars;
3492 ExpressionStatement [] assign;
3494 public Using (object expression_or_block, Statement stmt, Location l)
3496 this.expression_or_block = expression_or_block;
3502 // Resolves for the case of using using a local variable declaration.
3504 bool ResolveLocalVariableDecls (EmitContext ec)
3506 bool need_conv = false;
3507 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3510 if (expr_type == null)
3514 // The type must be an IDisposable or an implicit conversion
3517 converted_vars = new Expression [var_list.Count];
3518 assign = new ExpressionStatement [var_list.Count];
3519 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3520 foreach (DictionaryEntry e in var_list){
3521 Expression var = (Expression) e.Key;
3523 var = var.ResolveLValue (ec, new EmptyExpression ());
3527 converted_vars [i] = Convert.ImplicitConversionRequired (
3528 ec, var, TypeManager.idisposable_type, loc);
3530 if (converted_vars [i] == null)
3538 foreach (DictionaryEntry e in var_list){
3539 LocalVariableReference var = (LocalVariableReference) e.Key;
3540 Expression new_expr = (Expression) e.Value;
3543 a = new Assign (var, new_expr, loc);
3549 converted_vars [i] = var;
3550 assign [i] = (ExpressionStatement) a;
3557 bool ResolveExpression (EmitContext ec)
3559 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3560 conv = Convert.ImplicitConversionRequired (
3561 ec, expr, TypeManager.idisposable_type, loc);
3571 // Emits the code for the case of using using a local variable declaration.
3573 bool EmitLocalVariableDecls (EmitContext ec)
3575 ILGenerator ig = ec.ig;
3578 bool old_in_try = ec.InTry;
3580 for (i = 0; i < assign.Length; i++) {
3581 assign [i].EmitStatement (ec);
3583 ig.BeginExceptionBlock ();
3585 Statement.Emit (ec);
3586 ec.InTry = old_in_try;
3588 bool old_in_finally = ec.InFinally;
3589 ec.InFinally = true;
3590 var_list.Reverse ();
3591 foreach (DictionaryEntry e in var_list){
3592 LocalVariableReference var = (LocalVariableReference) e.Key;
3593 Label skip = ig.DefineLabel ();
3596 ig.BeginFinallyBlock ();
3599 ig.Emit (OpCodes.Brfalse, skip);
3600 converted_vars [i].Emit (ec);
3601 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3602 ig.MarkLabel (skip);
3603 ig.EndExceptionBlock ();
3605 ec.InFinally = old_in_finally;
3610 bool EmitExpression (EmitContext ec)
3613 // Make a copy of the expression and operate on that.
3615 ILGenerator ig = ec.ig;
3616 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3621 ig.Emit (OpCodes.Stloc, local_copy);
3623 bool old_in_try = ec.InTry;
3625 ig.BeginExceptionBlock ();
3626 Statement.Emit (ec);
3627 ec.InTry = old_in_try;
3629 Label skip = ig.DefineLabel ();
3630 bool old_in_finally = ec.InFinally;
3631 ig.BeginFinallyBlock ();
3632 ig.Emit (OpCodes.Ldloc, local_copy);
3633 ig.Emit (OpCodes.Brfalse, skip);
3634 ig.Emit (OpCodes.Ldloc, local_copy);
3635 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3636 ig.MarkLabel (skip);
3637 ec.InFinally = old_in_finally;
3638 ig.EndExceptionBlock ();
3643 public override bool Resolve (EmitContext ec)
3645 if (expression_or_block is DictionaryEntry){
3646 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3647 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3649 if (!ResolveLocalVariableDecls (ec))
3652 } else if (expression_or_block is Expression){
3653 expr = (Expression) expression_or_block;
3655 expr = expr.Resolve (ec);
3659 expr_type = expr.Type;
3661 if (!ResolveExpression (ec))
3665 return Statement.Resolve (ec);
3668 protected override bool DoEmit (EmitContext ec)
3670 if (expression_or_block is DictionaryEntry)
3671 return EmitLocalVariableDecls (ec);
3672 else if (expression_or_block is Expression)
3673 return EmitExpression (ec);
3680 /// Implementation of the foreach C# statement
3682 public class Foreach : Statement {
3684 Expression variable;
3686 Statement statement;
3687 ForeachHelperMethods hm;
3688 Expression empty, conv;
3689 Type array_type, element_type;
3692 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3693 Statement stmt, Location l)
3696 this.variable = var;
3702 public override bool Resolve (EmitContext ec)
3704 expr = expr.Resolve (ec);
3708 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3709 if (var_type == null)
3713 // We need an instance variable. Not sure this is the best
3714 // way of doing this.
3716 // FIXME: When we implement propertyaccess, will those turn
3717 // out to return values in ExprClass? I think they should.
3719 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3720 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3721 error1579 (expr.Type);
3725 if (expr.Type.IsArray) {
3726 array_type = expr.Type;
3727 element_type = TypeManager.GetElementType (array_type);
3729 empty = new EmptyExpression (element_type);
3731 hm = ProbeCollectionType (ec, expr.Type);
3733 error1579 (expr.Type);
3737 array_type = expr.Type;
3738 element_type = hm.element_type;
3740 empty = new EmptyExpression (hm.element_type);
3743 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
3744 ec.CurrentBranching.CreateSibling ();
3748 // FIXME: maybe we can apply the same trick we do in the
3749 // array handling to avoid creating empty and conv in some cases.
3751 // Although it is not as important in this case, as the type
3752 // will not likely be object (what the enumerator will return).
3754 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3758 variable = variable.ResolveLValue (ec, empty);
3759 if (variable == null)
3762 if (!statement.Resolve (ec))
3765 FlowReturns returns = ec.EndFlowBranching ();
3771 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3773 static MethodInfo FetchMethodMoveNext (Type t)
3775 MemberList move_next_list;
3777 move_next_list = TypeContainer.FindMembers (
3778 t, MemberTypes.Method,
3779 BindingFlags.Public | BindingFlags.Instance,
3780 Type.FilterName, "MoveNext");
3781 if (move_next_list.Count == 0)
3784 foreach (MemberInfo m in move_next_list){
3785 MethodInfo mi = (MethodInfo) m;
3788 args = TypeManager.GetArgumentTypes (mi);
3789 if (args != null && args.Length == 0){
3790 if (mi.ReturnType == TypeManager.bool_type)
3798 // Retrieves a `public T get_Current ()' method from the Type `t'
3800 static MethodInfo FetchMethodGetCurrent (Type t)
3802 MemberList move_next_list;
3804 move_next_list = TypeContainer.FindMembers (
3805 t, MemberTypes.Method,
3806 BindingFlags.Public | BindingFlags.Instance,
3807 Type.FilterName, "get_Current");
3808 if (move_next_list.Count == 0)
3811 foreach (MemberInfo m in move_next_list){
3812 MethodInfo mi = (MethodInfo) m;
3815 args = TypeManager.GetArgumentTypes (mi);
3816 if (args != null && args.Length == 0)
3823 // This struct records the helper methods used by the Foreach construct
3825 class ForeachHelperMethods {
3826 public EmitContext ec;
3827 public MethodInfo get_enumerator;
3828 public MethodInfo move_next;
3829 public MethodInfo get_current;
3830 public Type element_type;
3831 public Type enumerator_type;
3832 public bool is_disposable;
3834 public ForeachHelperMethods (EmitContext ec)
3837 this.element_type = TypeManager.object_type;
3838 this.enumerator_type = TypeManager.ienumerator_type;
3839 this.is_disposable = true;
3843 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3848 if (!(m is MethodInfo))
3851 if (m.Name != "GetEnumerator")
3854 MethodInfo mi = (MethodInfo) m;
3855 Type [] args = TypeManager.GetArgumentTypes (mi);
3857 if (args.Length != 0)
3860 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3861 EmitContext ec = hm.ec;
3864 // Check whether GetEnumerator is accessible to us
3866 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3868 Type declaring = mi.DeclaringType;
3869 if (prot == MethodAttributes.Private){
3870 if (declaring != ec.ContainerType)
3872 } else if (prot == MethodAttributes.FamANDAssem){
3873 // If from a different assembly, false
3874 if (!(mi is MethodBuilder))
3877 // Are we being invoked from the same class, or from a derived method?
3879 if (ec.ContainerType != declaring){
3880 if (!ec.ContainerType.IsSubclassOf (declaring))
3883 } else if (prot == MethodAttributes.FamORAssem){
3884 if (!(mi is MethodBuilder ||
3885 ec.ContainerType == declaring ||
3886 ec.ContainerType.IsSubclassOf (declaring)))
3888 } if (prot == MethodAttributes.Family){
3889 if (!(ec.ContainerType == declaring ||
3890 ec.ContainerType.IsSubclassOf (declaring)))
3894 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3896 // Apply the same optimization as MS: skip the GetEnumerator
3897 // returning an IEnumerator, and use the one returning a
3898 // CharEnumerator instead. This allows us to avoid the
3899 // try-finally block and the boxing.
3904 // Ok, we can access it, now make sure that we can do something
3905 // with this `GetEnumerator'
3908 if (mi.ReturnType == TypeManager.ienumerator_type ||
3909 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
3910 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
3911 if (declaring != TypeManager.string_type) {
3912 hm.move_next = TypeManager.bool_movenext_void;
3913 hm.get_current = TypeManager.object_getcurrent_void;
3919 // Ok, so they dont return an IEnumerable, we will have to
3920 // find if they support the GetEnumerator pattern.
3922 Type return_type = mi.ReturnType;
3924 hm.move_next = FetchMethodMoveNext (return_type);
3925 if (hm.move_next == null)
3927 hm.get_current = FetchMethodGetCurrent (return_type);
3928 if (hm.get_current == null)
3931 hm.element_type = hm.get_current.ReturnType;
3932 hm.enumerator_type = return_type;
3933 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3934 TypeManager.ImplementsInterface (
3935 hm.enumerator_type, TypeManager.idisposable_type);
3941 /// This filter is used to find the GetEnumerator method
3942 /// on which IEnumerator operates
3944 static MemberFilter FilterEnumerator;
3948 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3951 void error1579 (Type t)
3953 Report.Error (1579, loc,
3954 "foreach statement cannot operate on variables of type `" +
3955 t.FullName + "' because that class does not provide a " +
3956 " GetEnumerator method or it is inaccessible");
3959 static bool TryType (Type t, ForeachHelperMethods hm)
3963 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3964 BindingFlags.Public | BindingFlags.NonPublic |
3965 BindingFlags.Instance,
3966 FilterEnumerator, hm);
3971 hm.get_enumerator = (MethodInfo) mi [0];
3976 // Looks for a usable GetEnumerator in the Type, and if found returns
3977 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3979 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3981 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3983 if (TryType (t, hm))
3987 // Now try to find the method in the interfaces
3990 Type [] ifaces = t.GetInterfaces ();
3992 foreach (Type i in ifaces){
3993 if (TryType (i, hm))
3998 // Since TypeBuilder.GetInterfaces only returns the interface
3999 // types for this type, we have to keep looping, but once
4000 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4001 // done, because it returns all the types
4003 if ((t is TypeBuilder))
4013 // FIXME: possible optimization.
4014 // We might be able to avoid creating `empty' if the type is the sam
4016 bool EmitCollectionForeach (EmitContext ec)
4018 ILGenerator ig = ec.ig;
4019 VariableStorage enumerator, disposable;
4021 enumerator = new VariableStorage (ec, hm.enumerator_type);
4022 if (hm.is_disposable)
4023 disposable = new VariableStorage (ec, TypeManager.idisposable_type);
4027 enumerator.EmitThis ();
4029 // Instantiate the enumerator
4031 if (expr.Type.IsValueType){
4032 if (expr is IMemoryLocation){
4033 IMemoryLocation ml = (IMemoryLocation) expr;
4035 ml.AddressOf (ec, AddressOp.Load);
4037 throw new Exception ("Expr " + expr + " of type " + expr.Type +
4038 " does not implement IMemoryLocation");
4039 ig.Emit (OpCodes.Call, hm.get_enumerator);
4042 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4044 enumerator.EmitStore ();
4047 // Protect the code in a try/finalize block, so that
4048 // if the beast implement IDisposable, we get rid of it
4051 bool old_in_try = ec.InTry;
4053 if (hm.is_disposable) {
4054 l = ig.BeginExceptionBlock ();
4058 Label end_try = ig.DefineLabel ();
4060 ig.MarkLabel (ec.LoopBegin);
4061 enumerator.EmitLoad ();
4062 ig.Emit (OpCodes.Callvirt, hm.move_next);
4063 ig.Emit (OpCodes.Brfalse, end_try);
4067 enumerator.EmitLoad ();
4068 ig.Emit (OpCodes.Callvirt, hm.get_current);
4072 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4074 ((IAssignMethod)variable).EmitAssign (ec, conv);
4076 statement.Emit (ec);
4077 ig.Emit (OpCodes.Br, ec.LoopBegin);
4078 ig.MarkLabel (end_try);
4079 ec.InTry = old_in_try;
4081 // The runtime provides this for us.
4082 // ig.Emit (OpCodes.Leave, end);
4085 // Now the finally block
4087 if (hm.is_disposable) {
4088 Label end_finally = ig.DefineLabel ();
4089 bool old_in_finally = ec.InFinally;
4090 ec.InFinally = true;
4091 ig.BeginFinallyBlock ();
4093 disposable.EmitThis ();
4094 enumerator.EmitThis ();
4095 enumerator.EmitLoad ();
4096 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4097 disposable.EmitStore ();
4098 disposable.EmitLoad ();
4099 ig.Emit (OpCodes.Brfalse, end_finally);
4100 disposable.EmitThis ();
4101 disposable.EmitLoad ();
4102 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4103 ig.MarkLabel (end_finally);
4104 ec.InFinally = old_in_finally;
4106 // The runtime generates this anyways.
4107 // ig.Emit (OpCodes.Endfinally);
4109 ig.EndExceptionBlock ();
4112 ig.MarkLabel (ec.LoopEnd);
4117 // FIXME: possible optimization.
4118 // We might be able to avoid creating `empty' if the type is the sam
4120 bool EmitArrayForeach (EmitContext ec)
4122 int rank = array_type.GetArrayRank ();
4123 ILGenerator ig = ec.ig;
4125 VariableStorage copy = new VariableStorage (ec, array_type);
4128 // Make our copy of the array
4135 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4139 counter.EmitThis ();
4140 ig.Emit (OpCodes.Ldc_I4_0);
4141 counter.EmitStore ();
4142 test = ig.DefineLabel ();
4143 ig.Emit (OpCodes.Br, test);
4145 loop = ig.DefineLabel ();
4146 ig.MarkLabel (loop);
4153 counter.EmitThis ();
4154 counter.EmitLoad ();
4157 // Load the value, we load the value using the underlying type,
4158 // then we use the variable.EmitAssign to load using the proper cast.
4160 ArrayAccess.EmitLoadOpcode (ig, element_type);
4163 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4165 ((IAssignMethod)variable).EmitAssign (ec, conv);
4167 statement.Emit (ec);
4169 ig.MarkLabel (ec.LoopBegin);
4170 counter.EmitThis ();
4171 counter.EmitThis ();
4172 counter.EmitLoad ();
4173 ig.Emit (OpCodes.Ldc_I4_1);
4174 ig.Emit (OpCodes.Add);
4175 counter.EmitStore ();
4177 ig.MarkLabel (test);
4178 counter.EmitThis ();
4179 counter.EmitLoad ();
4182 ig.Emit (OpCodes.Ldlen);
4183 ig.Emit (OpCodes.Conv_I4);
4184 ig.Emit (OpCodes.Blt, loop);
4186 VariableStorage [] dim_len = new VariableStorage [rank];
4187 VariableStorage [] dim_count = new VariableStorage [rank];
4188 Label [] loop = new Label [rank];
4189 Label [] test = new Label [rank];
4192 for (dim = 0; dim < rank; dim++){
4193 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4194 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4195 test [dim] = ig.DefineLabel ();
4196 loop [dim] = ig.DefineLabel ();
4199 for (dim = 0; dim < rank; dim++){
4200 dim_len [dim].EmitThis ();
4203 IntLiteral.EmitInt (ig, dim);
4204 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4205 dim_len [dim].EmitStore ();
4209 for (dim = 0; dim < rank; dim++){
4210 dim_count [dim].EmitThis ();
4211 ig.Emit (OpCodes.Ldc_I4_0);
4212 dim_count [dim].EmitStore ();
4213 ig.Emit (OpCodes.Br, test [dim]);
4214 ig.MarkLabel (loop [dim]);
4221 for (dim = 0; dim < rank; dim++){
4222 dim_count [dim].EmitThis ();
4223 dim_count [dim].EmitLoad ();
4227 // FIXME: Maybe we can cache the computation of `get'?
4229 Type [] args = new Type [rank];
4232 for (int i = 0; i < rank; i++)
4233 args [i] = TypeManager.int32_type;
4235 ModuleBuilder mb = CodeGen.ModuleBuilder;
4236 get = mb.GetArrayMethod (
4238 CallingConventions.HasThis| CallingConventions.Standard,
4240 ig.Emit (OpCodes.Call, get);
4243 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4245 ((IAssignMethod)variable).EmitAssign (ec, conv);
4246 statement.Emit (ec);
4247 ig.MarkLabel (ec.LoopBegin);
4248 for (dim = rank - 1; dim >= 0; dim--){
4249 dim_count [dim].EmitThis ();
4250 dim_count [dim].EmitThis ();
4251 dim_count [dim].EmitLoad ();
4252 ig.Emit (OpCodes.Ldc_I4_1);
4253 ig.Emit (OpCodes.Add);
4254 dim_count [dim].EmitStore ();
4256 ig.MarkLabel (test [dim]);
4257 dim_count [dim].EmitThis ();
4258 dim_count [dim].EmitLoad ();
4259 dim_len [dim].EmitThis ();
4260 dim_len [dim].EmitLoad ();
4261 ig.Emit (OpCodes.Blt, loop [dim]);
4264 ig.MarkLabel (ec.LoopEnd);
4269 protected override bool DoEmit (EmitContext ec)
4273 ILGenerator ig = ec.ig;
4275 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4276 bool old_inloop = ec.InLoop;
4277 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4278 ec.LoopBegin = ig.DefineLabel ();
4279 ec.LoopEnd = ig.DefineLabel ();
4281 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4284 ret_val = EmitCollectionForeach (ec);
4286 ret_val = EmitArrayForeach (ec);
4288 ec.LoopBegin = old_begin;
4289 ec.LoopEnd = old_end;
4290 ec.InLoop = old_inloop;
4291 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;