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 protected abstract bool DoEmit (EmitContext ec);
39 /// Return value indicates whether all code paths emitted return.
41 public virtual bool Emit (EmitContext ec)
44 Report.Debug (8, "MARK", this, loc);
48 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
54 if (e.Type != TypeManager.bool_type){
55 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type, Location.Null);
60 31, loc, "Can not convert the expression to a boolean");
69 /// Encapsulates the emission of a boolean test and jumping to a
72 /// This will emit the bool expression in `bool_expr' and if
73 /// `target_is_for_true' is true, then the code will generate a
74 /// brtrue to the target. Otherwise a brfalse.
76 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
77 Label target, bool target_is_for_true)
79 ILGenerator ig = ec.ig;
82 if (bool_expr is Unary){
83 Unary u = (Unary) bool_expr;
85 if (u.Oper == Unary.Operator.LogicalNot){
88 u.EmitLogicalNot (ec);
90 } else if (bool_expr is Binary){
91 Binary b = (Binary) bool_expr;
93 if (b.EmitBranchable (ec, target, target_is_for_true))
100 if (target_is_for_true){
102 ig.Emit (OpCodes.Brfalse, target);
104 ig.Emit (OpCodes.Brtrue, target);
107 ig.Emit (OpCodes.Brtrue, target);
109 ig.Emit (OpCodes.Brfalse, target);
113 public static void Warning_DeadCodeFound (Location loc)
115 Report.Warning (162, loc, "Unreachable code detected");
119 public class EmptyStatement : Statement {
120 public override bool Resolve (EmitContext ec)
125 protected override bool DoEmit (EmitContext ec)
131 public class If : Statement {
133 public Statement TrueStatement;
134 public Statement FalseStatement;
136 public If (Expression expr, Statement trueStatement, Location l)
139 TrueStatement = trueStatement;
143 public If (Expression expr,
144 Statement trueStatement,
145 Statement falseStatement,
149 TrueStatement = trueStatement;
150 FalseStatement = falseStatement;
154 public override bool Resolve (EmitContext ec)
156 Report.Debug (1, "START IF BLOCK", loc);
158 expr = ResolveBoolean (ec, expr, loc);
163 ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
165 if (!TrueStatement.Resolve (ec)) {
166 ec.KillFlowBranching ();
170 ec.CurrentBranching.CreateSibling ();
172 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
173 ec.KillFlowBranching ();
177 ec.EndFlowBranching ();
179 Report.Debug (1, "END IF BLOCK", loc);
184 protected override bool DoEmit (EmitContext ec)
186 ILGenerator ig = ec.ig;
187 Label false_target = ig.DefineLabel ();
189 bool is_true_ret, is_false_ret;
192 // Dead code elimination
194 if (expr is BoolConstant){
195 bool take = ((BoolConstant) expr).Value;
198 if (FalseStatement != null){
199 Warning_DeadCodeFound (FalseStatement.loc);
201 return TrueStatement.Emit (ec);
203 Warning_DeadCodeFound (TrueStatement.loc);
204 if (FalseStatement != null)
205 return FalseStatement.Emit (ec);
209 EmitBoolExpression (ec, expr, false_target, false);
211 is_true_ret = TrueStatement.Emit (ec);
212 is_false_ret = is_true_ret;
214 if (FalseStatement != null){
215 bool branch_emitted = false;
217 end = ig.DefineLabel ();
219 ig.Emit (OpCodes.Br, end);
220 branch_emitted = true;
223 ig.MarkLabel (false_target);
224 is_false_ret = FalseStatement.Emit (ec);
229 ig.MarkLabel (false_target);
230 is_false_ret = false;
233 return is_true_ret && is_false_ret;
237 public enum DoOptions {
244 public class Do : Statement {
245 public Expression expr;
246 public readonly Statement EmbeddedStatement;
247 //public DoOptions type;
248 public DoOptions test;
249 bool infinite, may_return;
252 public Do (Statement statement, Expression boolExpr, DoOptions do_test, Location l)
255 EmbeddedStatement = statement;
261 public override bool Resolve (EmitContext ec)
265 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
267 if (!EmbeddedStatement.Resolve (ec))
270 expr = ResolveBoolean (ec, expr, loc);
273 else if (expr is BoolConstant){
274 bool res = ((BoolConstant) expr).Value;
280 ec.CurrentBranching.Infinite = infinite;
281 FlowReturns returns = ec.EndFlowBranching ();
282 may_return = returns != FlowReturns.NEVER;
287 protected override bool DoEmit (EmitContext ec)
289 ILGenerator ig = ec.ig;
290 Label loop = ig.DefineLabel ();
291 Label old_begin = ec.LoopBegin;
292 Label old_end = ec.LoopEnd;
293 bool old_inloop = ec.InLoop;
294 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
296 ec.LoopBegin = ig.DefineLabel ();
297 ec.LoopEnd = ig.DefineLabel ();
299 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
301 if (test == DoOptions.TEST_AFTER) {
303 EmbeddedStatement.Emit (ec);
304 ig.MarkLabel (ec.LoopBegin);
307 // Dead code elimination
309 if (expr is BoolConstant){
310 bool res = ((BoolConstant) expr).Value;
313 ec.ig.Emit (OpCodes.Br, loop);
315 EmitBoolExpression (ec, expr, loop, true);
317 ig.MarkLabel (ec.LoopEnd);
322 ig.MarkLabel (ec.LoopBegin);
325 // Dead code elimination
327 if (expr is BoolConstant){
328 bool res = ((BoolConstant) expr).Value;
331 ec.ig.Emit (OpCodes.Br, ec.LoopEnd);
333 EmitBoolExpression (ec, expr, ec.LoopEnd, true);
335 EmbeddedStatement.Emit (ec);
336 ec.ig.Emit (OpCodes.Br, loop);
337 ig.MarkLabel (ec.LoopEnd);
339 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
340 ec.LoopBegin = old_begin;
341 ec.LoopEnd = old_end;
342 ec.InLoop = old_inloop;
345 return may_return == false;
351 public class While : Statement {
352 public Expression expr;
353 public readonly Statement Statement;
354 bool may_return, empty, infinite;
356 public While (Expression boolExpr, Statement statement, Location l)
358 this.expr = boolExpr;
359 Statement = statement;
363 public override bool Resolve (EmitContext ec)
367 expr = ResolveBoolean (ec, expr, loc);
371 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
374 // Inform whether we are infinite or not
376 if (expr is BoolConstant){
377 BoolConstant bc = (BoolConstant) expr;
379 if (bc.Value == false){
380 Warning_DeadCodeFound (Statement.loc);
386 // We are not infinite, so the loop may or may not be executed.
388 ec.CurrentBranching.CreateSibling ();
391 if (!Statement.Resolve (ec))
395 ec.KillFlowBranching ();
397 ec.CurrentBranching.Infinite = infinite;
398 FlowReturns returns = ec.EndFlowBranching ();
399 may_return = returns != FlowReturns.NEVER;
405 protected override bool DoEmit (EmitContext ec)
410 ILGenerator ig = ec.ig;
411 Label old_begin = ec.LoopBegin;
412 Label old_end = ec.LoopEnd;
413 bool old_inloop = ec.InLoop;
414 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
417 ec.LoopBegin = ig.DefineLabel ();
418 ec.LoopEnd = ig.DefineLabel ();
420 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
423 // Inform whether we are infinite or not
425 if (expr is BoolConstant){
426 BoolConstant bc = (BoolConstant) expr;
428 ig.MarkLabel (ec.LoopBegin);
430 ig.Emit (OpCodes.Br, ec.LoopBegin);
433 // Inform that we are infinite (ie, `we return'), only
434 // if we do not `break' inside the code.
436 ret = may_return == false;
437 ig.MarkLabel (ec.LoopEnd);
439 Label while_loop = ig.DefineLabel ();
441 ig.Emit (OpCodes.Br, ec.LoopBegin);
442 ig.MarkLabel (while_loop);
446 ig.MarkLabel (ec.LoopBegin);
448 EmitBoolExpression (ec, expr, while_loop, true);
449 ig.MarkLabel (ec.LoopEnd);
454 ec.LoopBegin = old_begin;
455 ec.LoopEnd = old_end;
456 ec.InLoop = old_inloop;
457 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
463 public class For : Statement {
465 readonly Statement InitStatement;
466 readonly Statement Increment;
467 readonly Statement Statement;
468 bool may_return, infinite, empty;
470 public For (Statement initStatement,
476 InitStatement = initStatement;
478 Increment = increment;
479 Statement = statement;
484 public override bool Resolve (EmitContext ec)
488 if (InitStatement != null){
489 if (!InitStatement.Resolve (ec))
494 Test = ResolveBoolean (ec, Test, loc);
497 else if (Test is BoolConstant){
498 BoolConstant bc = (BoolConstant) Test;
500 if (bc.Value == false){
501 Warning_DeadCodeFound (Statement.loc);
509 if (Increment != null){
510 if (!Increment.Resolve (ec))
514 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
516 ec.CurrentBranching.CreateSibling ();
518 if (!Statement.Resolve (ec))
522 ec.KillFlowBranching ();
524 ec.CurrentBranching.Infinite = infinite;
525 FlowReturns returns = ec.EndFlowBranching ();
526 may_return = returns != FlowReturns.NEVER;
532 protected override bool DoEmit (EmitContext ec)
537 ILGenerator ig = ec.ig;
538 Label old_begin = ec.LoopBegin;
539 Label old_end = ec.LoopEnd;
540 bool old_inloop = ec.InLoop;
541 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
542 Label loop = ig.DefineLabel ();
543 Label test = ig.DefineLabel ();
545 if (InitStatement != null)
546 if (! (InitStatement is EmptyStatement))
547 InitStatement.Emit (ec);
549 ec.LoopBegin = ig.DefineLabel ();
550 ec.LoopEnd = ig.DefineLabel ();
552 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
554 ig.Emit (OpCodes.Br, test);
558 ig.MarkLabel (ec.LoopBegin);
559 if (!(Increment is EmptyStatement))
564 // If test is null, there is no test, and we are just
568 EmitBoolExpression (ec, Test, loop, true);
570 ig.Emit (OpCodes.Br, loop);
571 ig.MarkLabel (ec.LoopEnd);
573 ec.LoopBegin = old_begin;
574 ec.LoopEnd = old_end;
575 ec.InLoop = old_inloop;
576 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
579 // Inform whether we are infinite or not
582 if (Test is BoolConstant){
583 BoolConstant bc = (BoolConstant) Test;
586 return may_return == false;
590 return may_return == false;
594 public class StatementExpression : Statement {
595 public Expression expr;
597 public StatementExpression (ExpressionStatement expr, Location l)
603 public override bool Resolve (EmitContext ec)
605 expr = (Expression) expr.Resolve (ec);
609 protected override bool DoEmit (EmitContext ec)
611 ILGenerator ig = ec.ig;
613 if (expr is ExpressionStatement)
614 ((ExpressionStatement) expr).EmitStatement (ec);
617 ig.Emit (OpCodes.Pop);
623 public override string ToString ()
625 return "StatementExpression (" + expr + ")";
630 /// Implements the return statement
632 public class Return : Statement {
633 public Expression Expr;
635 public Return (Expression expr, Location l)
641 public override bool Resolve (EmitContext ec)
644 Expr = Expr.Resolve (ec);
649 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
651 if (ec.CurrentBranching.InTryBlock ())
652 ec.CurrentBranching.AddFinallyVector (vector);
654 vector.CheckOutParameters (ec.CurrentBranching);
656 vector.Returns = FlowReturns.ALWAYS;
657 vector.Breaks = FlowReturns.ALWAYS;
661 protected override bool DoEmit (EmitContext ec)
664 Report.Error (157,loc,"Control can not leave the body of the finally block");
668 if (ec.ReturnType == null){
670 Report.Error (127, loc, "Return with a value not allowed here");
675 Report.Error (126, loc, "An object of type `" +
676 TypeManager.CSharpName (ec.ReturnType) + "' is " +
677 "expected for the return statement");
681 if (Expr.Type != ec.ReturnType)
682 Expr = Expression.ConvertImplicitRequired (
683 ec, Expr, ec.ReturnType, loc);
690 if (ec.InTry || ec.InCatch)
691 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
694 if (ec.InTry || ec.InCatch) {
695 if (!ec.HasReturnLabel) {
696 ec.ReturnLabel = ec.ig.DefineLabel ();
697 ec.HasReturnLabel = true;
699 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
701 ec.ig.Emit (OpCodes.Ret);
707 public class Goto : Statement {
710 LabeledStatement label;
712 public override bool Resolve (EmitContext ec)
714 label = block.LookupLabel (target);
718 "No such label `" + target + "' in this scope");
722 // If this is a forward goto.
723 if (!label.IsDefined)
724 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
726 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
731 public Goto (Block parent_block, string label, Location l)
733 block = parent_block;
738 public string Target {
744 protected override bool DoEmit (EmitContext ec)
746 Label l = label.LabelTarget (ec);
747 ec.ig.Emit (OpCodes.Br, l);
753 public class LabeledStatement : Statement {
754 public readonly Location Location;
762 public LabeledStatement (string label_name, Location l)
764 this.label_name = label_name;
768 public Label LabelTarget (EmitContext ec)
772 label = ec.ig.DefineLabel ();
778 public bool IsDefined {
784 public bool HasBeenReferenced {
790 public void AddUsageVector (FlowBranching.UsageVector vector)
793 vectors = new ArrayList ();
795 vectors.Add (vector.Clone ());
798 public override bool Resolve (EmitContext ec)
801 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
803 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
804 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
812 protected override bool DoEmit (EmitContext ec)
815 ec.ig.MarkLabel (label);
823 /// `goto default' statement
825 public class GotoDefault : Statement {
827 public GotoDefault (Location l)
832 public override bool Resolve (EmitContext ec)
834 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
838 protected override bool DoEmit (EmitContext ec)
840 if (ec.Switch == null){
841 Report.Error (153, loc, "goto default is only valid in a switch statement");
845 if (!ec.Switch.GotDefault){
846 Report.Error (159, loc, "No default target on switch statement");
849 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
855 /// `goto case' statement
857 public class GotoCase : Statement {
861 public GotoCase (Expression e, Location l)
867 public override bool Resolve (EmitContext ec)
869 if (ec.Switch == null){
870 Report.Error (153, loc, "goto case is only valid in a switch statement");
874 expr = expr.Resolve (ec);
878 if (!(expr is Constant)){
879 Report.Error (159, loc, "Target expression for goto case is not constant");
883 object val = Expression.ConvertIntLiteral (
884 (Constant) expr, ec.Switch.SwitchType, loc);
889 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
894 "No such label 'case " + val + "': for the goto case");
897 label = sl.ILLabelCode;
899 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
903 protected override bool DoEmit (EmitContext ec)
905 ec.ig.Emit (OpCodes.Br, label);
910 public class Throw : Statement {
913 public Throw (Expression expr, Location l)
919 public override bool Resolve (EmitContext ec)
922 expr = expr.Resolve (ec);
926 ExprClass eclass = expr.eclass;
928 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
929 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
930 expr.Error118 ("value, variable, property or indexer access ");
936 if ((t != TypeManager.exception_type) &&
937 !t.IsSubclassOf (TypeManager.exception_type) &&
938 !(expr is NullLiteral)) {
939 Report.Error (155, loc,
940 "The type caught or thrown must be derived " +
941 "from System.Exception");
946 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
947 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
951 protected override bool DoEmit (EmitContext ec)
955 ec.ig.Emit (OpCodes.Rethrow);
959 "A throw statement with no argument is only " +
960 "allowed in a catch clause");
967 ec.ig.Emit (OpCodes.Throw);
973 public class Break : Statement {
975 public Break (Location l)
980 public override bool Resolve (EmitContext ec)
982 ec.CurrentBranching.MayLeaveLoop = true;
983 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
987 protected override bool DoEmit (EmitContext ec)
989 ILGenerator ig = ec.ig;
991 if (ec.InLoop == false && ec.Switch == null){
992 Report.Error (139, loc, "No enclosing loop or switch to continue to");
996 if (ec.InTry || ec.InCatch)
997 ig.Emit (OpCodes.Leave, ec.LoopEnd);
999 ig.Emit (OpCodes.Br, ec.LoopEnd);
1005 public enum ExitType {
1016 public class Exit : Statement {
1017 public readonly ExitType type;
1018 public Exit (ExitType t, Location l)
1024 public override bool Resolve (EmitContext ec)
1026 ec.CurrentBranching.MayLeaveLoop = true;
1027 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1031 protected override bool DoEmit (EmitContext ec)
1033 ILGenerator ig = ec.ig;
1035 if (ec.InLoop == false && ec.Switch == null){
1036 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1040 if (ec.InTry || ec.InCatch)
1041 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1043 ig.Emit (OpCodes.Br, ec.LoopEnd);
1049 public class Continue : Statement {
1051 public Continue (Location l)
1056 public override bool Resolve (EmitContext ec)
1058 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1062 protected override bool DoEmit (EmitContext ec)
1064 Label begin = ec.LoopBegin;
1067 Report.Error (139, loc, "No enclosing loop to continue to");
1072 // UGH: Non trivial. This Br might cross a try/catch boundary
1076 // try { ... } catch { continue; }
1080 // try {} catch { while () { continue; }}
1082 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1083 ec.ig.Emit (OpCodes.Leave, begin);
1084 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1085 throw new Exception ("Should never happen");
1087 ec.ig.Emit (OpCodes.Br, begin);
1093 // This is used in the control flow analysis code to specify whether the
1094 // current code block may return to its enclosing block before reaching
1097 public enum FlowReturns {
1098 // It can never return.
1101 // This means that the block contains a conditional return statement
1105 // The code always returns, ie. there's an unconditional return / break
1109 // The code always throws an exception.
1112 // The current code block is unreachable. This happens if it's immediately
1113 // following a FlowReturns.ALWAYS block.
1118 // This is a special bit vector which can inherit from another bit vector doing a
1119 // copy-on-write strategy. The inherited vector may have a smaller size than the
1122 public class MyBitVector {
1123 public readonly int Count;
1124 public readonly MyBitVector InheritsFrom;
1129 public MyBitVector (int Count)
1130 : this (null, Count)
1133 public MyBitVector (MyBitVector InheritsFrom, int Count)
1135 this.InheritsFrom = InheritsFrom;
1140 // Checks whether this bit vector has been modified. After setting this to true,
1141 // we won't use the inherited vector anymore, but our own copy of it.
1143 public bool IsDirty {
1150 initialize_vector ();
1155 // Get/set bit `index' in the bit vector.
1157 public bool this [int index]
1161 throw new ArgumentOutOfRangeException ();
1163 // We're doing a "copy-on-write" strategy here; as long
1164 // as nobody writes to the array, we can use our parent's
1165 // copy instead of duplicating the vector.
1168 return vector [index];
1169 else if (InheritsFrom != null) {
1170 BitArray inherited = InheritsFrom.Vector;
1172 if (index < inherited.Count)
1173 return inherited [index];
1182 throw new ArgumentOutOfRangeException ();
1184 // Only copy the vector if we're actually modifying it.
1186 if (this [index] != value) {
1187 initialize_vector ();
1189 vector [index] = value;
1195 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1196 // copy of the bit vector.
1198 public static explicit operator BitArray (MyBitVector vector)
1200 vector.initialize_vector ();
1201 return vector.Vector;
1205 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1206 // different size than the current one.
1208 public void Or (MyBitVector new_vector)
1210 BitArray new_array = new_vector.Vector;
1212 initialize_vector ();
1215 if (vector.Count < new_array.Count)
1216 upper = vector.Count;
1218 upper = new_array.Count;
1220 for (int i = 0; i < upper; i++)
1221 vector [i] = vector [i] | new_array [i];
1225 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1226 // a different size than the current one.
1228 public void And (MyBitVector new_vector)
1230 BitArray new_array = new_vector.Vector;
1232 initialize_vector ();
1235 if (vector.Count < new_array.Count)
1236 lower = upper = vector.Count;
1238 lower = new_array.Count;
1239 upper = vector.Count;
1242 for (int i = 0; i < lower; i++)
1243 vector [i] = vector [i] & new_array [i];
1245 for (int i = lower; i < upper; i++)
1250 // This does a deep copy of the bit vector.
1252 public MyBitVector Clone ()
1254 MyBitVector retval = new MyBitVector (Count);
1256 retval.Vector = Vector;
1265 else if (!is_dirty && (InheritsFrom != null))
1266 return InheritsFrom.Vector;
1268 initialize_vector ();
1274 initialize_vector ();
1276 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1277 vector [i] = value [i];
1281 void initialize_vector ()
1286 vector = new BitArray (Count, false);
1287 if (InheritsFrom != null)
1288 Vector = InheritsFrom.Vector;
1293 public override string ToString ()
1295 StringBuilder sb = new StringBuilder ("MyBitVector (");
1297 BitArray vector = Vector;
1301 sb.Append ("INHERITED - ");
1302 for (int i = 0; i < vector.Count; i++) {
1305 sb.Append (vector [i]);
1309 return sb.ToString ();
1314 // The type of a FlowBranching.
1316 public enum FlowBranchingType {
1317 // Normal (conditional or toplevel) block.
1334 // A new instance of this class is created every time a new block is resolved
1335 // and if there's branching in the block's control flow.
1337 public class FlowBranching {
1339 // The type of this flow branching.
1341 public readonly FlowBranchingType Type;
1344 // The block this branching is contained in. This may be null if it's not
1345 // a top-level block and it doesn't declare any local variables.
1347 public readonly Block Block;
1350 // The parent of this branching or null if this is the top-block.
1352 public readonly FlowBranching Parent;
1355 // Start-Location of this flow branching.
1357 public readonly Location Location;
1360 // A list of UsageVectors. A new vector is added each time control flow may
1361 // take a different path.
1363 public ArrayList Siblings;
1366 // If this is an infinite loop.
1368 public bool Infinite;
1371 // If we may leave the current loop.
1373 public bool MayLeaveLoop;
1378 InternalParameters param_info;
1380 MyStructInfo[] struct_params;
1382 ArrayList finally_vectors;
1384 static int next_id = 0;
1388 // Performs an `And' operation on the FlowReturns status
1389 // (for instance, a block only returns ALWAYS if all its siblings
1392 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1394 if (b == FlowReturns.UNREACHABLE)
1398 case FlowReturns.NEVER:
1399 if (b == FlowReturns.NEVER)
1400 return FlowReturns.NEVER;
1402 return FlowReturns.SOMETIMES;
1404 case FlowReturns.SOMETIMES:
1405 return FlowReturns.SOMETIMES;
1407 case FlowReturns.ALWAYS:
1408 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1409 return FlowReturns.ALWAYS;
1411 return FlowReturns.SOMETIMES;
1413 case FlowReturns.EXCEPTION:
1414 if (b == FlowReturns.EXCEPTION)
1415 return FlowReturns.EXCEPTION;
1416 else if (b == FlowReturns.ALWAYS)
1417 return FlowReturns.ALWAYS;
1419 return FlowReturns.SOMETIMES;
1426 // The vector contains a BitArray with information about which local variables
1427 // and parameters are already initialized at the current code position.
1429 public class UsageVector {
1431 // If this is true, then the usage vector has been modified and must be
1432 // merged when we're done with this branching.
1434 public bool IsDirty;
1437 // The number of parameters in this block.
1439 public readonly int CountParameters;
1442 // The number of locals in this block.
1444 public readonly int CountLocals;
1447 // If not null, then we inherit our state from this vector and do a
1448 // copy-on-write. If null, then we're the first sibling in a top-level
1449 // block and inherit from the empty vector.
1451 public readonly UsageVector InheritsFrom;
1456 MyBitVector locals, parameters;
1457 FlowReturns real_returns, real_breaks;
1460 static int next_id = 0;
1464 // Normally, you should not use any of these constructors.
1466 public UsageVector (UsageVector parent, int num_params, int num_locals)
1468 this.InheritsFrom = parent;
1469 this.CountParameters = num_params;
1470 this.CountLocals = num_locals;
1471 this.real_returns = FlowReturns.NEVER;
1472 this.real_breaks = FlowReturns.NEVER;
1474 if (parent != null) {
1475 locals = new MyBitVector (parent.locals, CountLocals);
1477 parameters = new MyBitVector (parent.parameters, num_params);
1478 real_returns = parent.Returns;
1479 real_breaks = parent.Breaks;
1481 locals = new MyBitVector (null, CountLocals);
1483 parameters = new MyBitVector (null, num_params);
1489 public UsageVector (UsageVector parent)
1490 : this (parent, parent.CountParameters, parent.CountLocals)
1494 // This does a deep copy of the usage vector.
1496 public UsageVector Clone ()
1498 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1500 retval.locals = locals.Clone ();
1501 if (parameters != null)
1502 retval.parameters = parameters.Clone ();
1503 retval.real_returns = real_returns;
1504 retval.real_breaks = real_breaks;
1510 // State of parameter `number'.
1512 public bool this [int number]
1517 else if (number == 0)
1518 throw new ArgumentException ();
1520 return parameters [number - 1];
1526 else if (number == 0)
1527 throw new ArgumentException ();
1529 parameters [number - 1] = value;
1534 // State of the local variable `vi'.
1535 // If the local variable is a struct, use a non-zero `field_idx'
1536 // to check an individual field in it.
1538 public bool this [VariableInfo vi, int field_idx]
1541 if (vi.Number == -1)
1543 else if (vi.Number == 0)
1544 throw new ArgumentException ();
1546 return locals [vi.Number + field_idx - 1];
1550 if (vi.Number == -1)
1552 else if (vi.Number == 0)
1553 throw new ArgumentException ();
1555 locals [vi.Number + field_idx - 1] = value;
1560 // Specifies when the current block returns.
1561 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1562 // end of the method (so that we don't need to emit a return statement).
1563 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1564 // value will never be used.
1566 public FlowReturns Returns {
1568 return real_returns;
1572 real_returns = value;
1577 // Specifies whether control may return to our containing block
1578 // before reaching the end of this block. This happens if there
1579 // is a break/continue/goto/return in it.
1580 // This can also be used to find out whether the statement immediately
1581 // following the current block may be reached or not.
1583 public FlowReturns Breaks {
1589 real_breaks = value;
1593 public bool AlwaysBreaks {
1595 return (Breaks == FlowReturns.ALWAYS) ||
1596 (Breaks == FlowReturns.EXCEPTION) ||
1597 (Breaks == FlowReturns.UNREACHABLE);
1601 public bool MayBreak {
1603 return Breaks != FlowReturns.NEVER;
1607 public bool AlwaysReturns {
1609 return (Returns == FlowReturns.ALWAYS) ||
1610 (Returns == FlowReturns.EXCEPTION);
1614 public bool MayReturn {
1616 return (Returns == FlowReturns.SOMETIMES) ||
1617 (Returns == FlowReturns.ALWAYS);
1622 // Merge a child branching.
1624 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1626 MyBitVector new_locals = null;
1627 MyBitVector new_params = null;
1629 FlowReturns new_returns = FlowReturns.NEVER;
1630 FlowReturns new_breaks = FlowReturns.NEVER;
1631 bool new_returns_set = false, new_breaks_set = false;
1633 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1634 this, children.Count);
1636 foreach (UsageVector child in children) {
1637 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1639 if (!child.is_finally) {
1640 if (child.Breaks != FlowReturns.UNREACHABLE) {
1641 // If Returns is already set, perform an
1642 // `And' operation on it, otherwise just set just.
1643 if (!new_returns_set) {
1644 new_returns = child.Returns;
1645 new_returns_set = true;
1647 new_returns = AndFlowReturns (
1648 new_returns, child.Returns);
1651 // If Breaks is already set, perform an
1652 // `And' operation on it, otherwise just set just.
1653 if (!new_breaks_set) {
1654 new_breaks = child.Breaks;
1655 new_breaks_set = true;
1657 new_breaks = AndFlowReturns (
1658 new_breaks, child.Breaks);
1661 // Ignore unreachable children.
1662 if (child.Returns == FlowReturns.UNREACHABLE)
1665 // A local variable is initialized after a flow branching if it
1666 // has been initialized in all its branches which do neither
1667 // always return or always throw an exception.
1669 // If a branch may return, but does not always return, then we
1670 // can treat it like a never-returning branch here: control will
1671 // only reach the code position after the branching if we did not
1674 // It's important to distinguish between always and sometimes
1675 // returning branches here:
1678 // 2 if (something) {
1682 // 6 Console.WriteLine (a);
1684 // The if block in lines 3-4 always returns, so we must not look
1685 // at the initialization of `a' in line 4 - thus it'll still be
1686 // uninitialized in line 6.
1688 // On the other hand, the following is allowed:
1695 // 6 Console.WriteLine (a);
1697 // Here, `a' is initialized in line 3 and we must not look at
1698 // line 5 since it always returns.
1700 if (child.is_finally) {
1701 if (new_locals == null)
1702 new_locals = locals.Clone ();
1703 new_locals.Or (child.locals);
1705 if (parameters != null) {
1706 if (new_params == null)
1707 new_params = parameters.Clone ();
1708 new_params.Or (child.parameters);
1712 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1713 if (new_locals != null)
1714 new_locals.And (child.locals);
1716 new_locals = locals.Clone ();
1717 new_locals.Or (child.locals);
1719 } else if (children.Count == 1) {
1720 new_locals = locals.Clone ();
1721 new_locals.Or (child.locals);
1724 // An `out' parameter must be assigned in all branches which do
1725 // not always throw an exception.
1726 if (parameters != null) {
1727 if (child.Breaks != FlowReturns.EXCEPTION) {
1728 if (new_params != null)
1729 new_params.And (child.parameters);
1731 new_params = parameters.Clone ();
1732 new_params.Or (child.parameters);
1734 } else if (children.Count == 1) {
1735 new_params = parameters.Clone ();
1736 new_params.Or (child.parameters);
1742 Returns = new_returns;
1743 if ((branching.Type == FlowBranchingType.BLOCK) ||
1744 (branching.Type == FlowBranchingType.EXCEPTION) ||
1745 (new_breaks == FlowReturns.UNREACHABLE) ||
1746 (new_breaks == FlowReturns.EXCEPTION))
1747 Breaks = new_breaks;
1748 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1749 Breaks = new_returns;
1750 else if (branching.Type == FlowBranchingType.SWITCH){
1751 if (new_breaks == FlowReturns.ALWAYS)
1752 Breaks = FlowReturns.ALWAYS;
1756 // We've now either reached the point after the branching or we will
1757 // never get there since we always return or always throw an exception.
1759 // If we can reach the point after the branching, mark all locals and
1760 // parameters as initialized which have been initialized in all branches
1761 // we need to look at (see above).
1764 if (((new_breaks != FlowReturns.ALWAYS) &&
1765 (new_breaks != FlowReturns.EXCEPTION) &&
1766 (new_breaks != FlowReturns.UNREACHABLE)) ||
1767 (children.Count == 1)) {
1768 if (new_locals != null)
1769 locals.Or (new_locals);
1771 if (new_params != null)
1772 parameters.Or (new_params);
1775 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1776 new_params, new_locals, new_returns, new_breaks,
1777 branching.Infinite, branching.MayLeaveLoop, this);
1779 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1780 if ((new_breaks != FlowReturns.ALWAYS) &&
1781 (new_breaks != FlowReturns.EXCEPTION) &&
1782 (new_breaks != FlowReturns.UNREACHABLE))
1783 Report.Error (163, branching.Location,
1784 "Control cannot fall through from one " +
1785 "case label to another");
1788 if (branching.Infinite && !branching.MayLeaveLoop) {
1789 Report.Debug (1, "INFINITE", new_returns, new_breaks,
1790 Returns, Breaks, this);
1792 // We're actually infinite.
1793 if (new_returns == FlowReturns.NEVER) {
1794 Breaks = FlowReturns.UNREACHABLE;
1795 return FlowReturns.UNREACHABLE;
1798 // If we're an infinite loop and do not break, the code after
1799 // the loop can never be reached. However, if we may return
1800 // from the loop, then we do always return (or stay in the loop
1802 if ((new_returns == FlowReturns.SOMETIMES) ||
1803 (new_returns == FlowReturns.ALWAYS)) {
1804 Returns = FlowReturns.ALWAYS;
1805 return FlowReturns.ALWAYS;
1813 // Tells control flow analysis that the current code position may be reached with
1814 // a forward jump from any of the origins listed in `origin_vectors' which is a
1815 // list of UsageVectors.
1817 // This is used when resolving forward gotos - in the following example, the
1818 // variable `a' is uninitialized in line 8 becase this line may be reached via
1819 // the goto in line 4:
1829 // 8 Console.WriteLine (a);
1832 public void MergeJumpOrigins (ICollection origin_vectors)
1834 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1836 real_breaks = FlowReturns.NEVER;
1837 real_returns = FlowReturns.NEVER;
1839 foreach (UsageVector vector in origin_vectors) {
1840 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1842 locals.And (vector.locals);
1843 if (parameters != null)
1844 parameters.And (vector.parameters);
1845 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1846 Returns = AndFlowReturns (Returns, vector.Returns);
1849 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1853 // This is used at the beginning of a finally block if there were
1854 // any return statements in the try block or one of the catch blocks.
1856 public void MergeFinallyOrigins (ICollection finally_vectors)
1858 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1860 real_breaks = FlowReturns.NEVER;
1862 foreach (UsageVector vector in finally_vectors) {
1863 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1865 if (parameters != null)
1866 parameters.And (vector.parameters);
1867 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1872 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1875 public void CheckOutParameters (FlowBranching branching)
1877 if (parameters != null)
1878 branching.CheckOutParameters (parameters, branching.Location);
1882 // Performs an `or' operation on the locals and the parameters.
1884 public void Or (UsageVector new_vector)
1886 locals.Or (new_vector.locals);
1887 if (parameters != null)
1888 parameters.Or (new_vector.parameters);
1892 // Performs an `and' operation on the locals.
1894 public void AndLocals (UsageVector new_vector)
1896 locals.And (new_vector.locals);
1900 // Returns a deep copy of the parameters.
1902 public MyBitVector Parameters {
1904 if (parameters != null)
1905 return parameters.Clone ();
1912 // Returns a deep copy of the locals.
1914 public MyBitVector Locals {
1916 return locals.Clone ();
1924 public override string ToString ()
1926 StringBuilder sb = new StringBuilder ();
1928 sb.Append ("Vector (");
1931 sb.Append (Returns);
1934 if (parameters != null) {
1936 sb.Append (parameters);
1942 return sb.ToString ();
1946 FlowBranching (FlowBranchingType type, Location loc)
1948 this.Siblings = new ArrayList ();
1950 this.Location = loc;
1956 // Creates a new flow branching for `block'.
1957 // This is used from Block.Resolve to create the top-level branching of
1960 public FlowBranching (Block block, InternalParameters ip, Location loc)
1961 : this (FlowBranchingType.BLOCK, loc)
1966 int count = (ip != null) ? ip.Count : 0;
1969 param_map = new int [count];
1970 struct_params = new MyStructInfo [count];
1973 for (int i = 0; i < count; i++) {
1974 Parameter.Modifier mod = param_info.ParameterModifier (i);
1976 if ((mod & Parameter.Modifier.OUT) == 0)
1979 param_map [i] = ++num_params;
1981 Type param_type = param_info.ParameterType (i);
1983 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1984 if (struct_params [i] != null)
1985 num_params += struct_params [i].Count;
1988 Siblings = new ArrayList ();
1989 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1993 // Creates a new flow branching which is contained in `parent'.
1994 // You should only pass non-null for the `block' argument if this block
1995 // introduces any new variables - in this case, we need to create a new
1996 // usage vector with a different size than our parent's one.
1998 public FlowBranching (FlowBranching parent, FlowBranchingType type,
1999 Block block, Location loc)
2005 if (parent != null) {
2006 param_info = parent.param_info;
2007 param_map = parent.param_map;
2008 struct_params = parent.struct_params;
2009 num_params = parent.num_params;
2014 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2015 Block.CountVariables);
2017 vector = new UsageVector (Parent.CurrentUsageVector);
2019 Siblings.Add (vector);
2022 case FlowBranchingType.EXCEPTION:
2023 finally_vectors = new ArrayList ();
2032 // Returns the branching's current usage vector.
2034 public UsageVector CurrentUsageVector
2037 return (UsageVector) Siblings [Siblings.Count - 1];
2042 // Creates a sibling of the current usage vector.
2044 public void CreateSibling ()
2046 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2048 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2052 // Creates a sibling for a `finally' block.
2054 public void CreateSiblingForFinally ()
2056 if (Type != FlowBranchingType.EXCEPTION)
2057 throw new NotSupportedException ();
2061 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2065 // Check whether all `out' parameters have been assigned.
2067 public void CheckOutParameters (MyBitVector parameters, Location loc)
2072 for (int i = 0; i < param_map.Length; i++) {
2073 int index = param_map [i];
2078 if (parameters [index - 1])
2081 // If it's a struct, we must ensure that all its fields have
2082 // been assigned. If the struct has any non-public fields, this
2083 // can only be done by assigning the whole struct.
2085 MyStructInfo struct_info = struct_params [index - 1];
2086 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2088 177, loc, "The out parameter `" +
2089 param_info.ParameterName (i) + "' must be " +
2090 "assigned before control leave the current method.");
2096 for (int j = 0; j < struct_info.Count; j++) {
2097 if (!parameters [index + j]) {
2099 177, loc, "The out parameter `" +
2100 param_info.ParameterName (i) + "' must be " +
2101 "assigned before control leave the current method.");
2110 // Merge a child branching.
2112 public FlowReturns MergeChild (FlowBranching child)
2114 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2116 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2117 MayLeaveLoop |= child.MayLeaveLoop;
2119 MayLeaveLoop = false;
2125 // Does the toplevel merging.
2127 public FlowReturns MergeTopBlock ()
2129 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2130 throw new NotSupportedException ();
2132 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2134 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2136 vector.MergeChildren (this, Siblings);
2139 Siblings.Add (vector);
2141 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2143 if (vector.Breaks != FlowReturns.EXCEPTION) {
2144 if (!vector.AlwaysBreaks)
2145 CheckOutParameters (CurrentUsageVector.Parameters, Location);
2146 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2148 return FlowReturns.EXCEPTION;
2151 public bool InTryBlock ()
2153 if (finally_vectors != null)
2155 else if (Parent != null)
2156 return Parent.InTryBlock ();
2161 public void AddFinallyVector (UsageVector vector)
2163 if (finally_vectors != null) {
2164 finally_vectors.Add (vector.Clone ());
2169 Parent.AddFinallyVector (vector);
2171 throw new NotSupportedException ();
2174 public bool IsVariableAssigned (VariableInfo vi)
2176 if (CurrentUsageVector.AlwaysBreaks)
2179 return CurrentUsageVector [vi, 0];
2182 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2184 if (CurrentUsageVector.AlwaysBreaks)
2187 return CurrentUsageVector [vi, field_idx];
2190 public void SetVariableAssigned (VariableInfo vi)
2192 if (CurrentUsageVector.AlwaysBreaks)
2195 CurrentUsageVector [vi, 0] = true;
2198 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2200 if (CurrentUsageVector.AlwaysBreaks)
2203 CurrentUsageVector [vi, field_idx] = true;
2206 public bool IsParameterAssigned (int number)
2208 int index = param_map [number];
2213 if (CurrentUsageVector [index])
2216 // Parameter is not assigned, so check whether it's a struct.
2217 // If it's either not a struct or a struct which non-public
2218 // fields, return false.
2219 MyStructInfo struct_info = struct_params [number];
2220 if ((struct_info == null) || struct_info.HasNonPublicFields)
2223 // Ok, so each field must be assigned.
2224 for (int i = 0; i < struct_info.Count; i++)
2225 if (!CurrentUsageVector [index + i])
2231 public bool IsParameterAssigned (int number, string field_name)
2233 int index = param_map [number];
2238 MyStructInfo info = (MyStructInfo) struct_params [number];
2242 int field_idx = info [field_name];
2244 return CurrentUsageVector [index + field_idx];
2247 public void SetParameterAssigned (int number)
2249 if (param_map [number] == 0)
2252 if (!CurrentUsageVector.AlwaysBreaks)
2253 CurrentUsageVector [param_map [number]] = true;
2256 public void SetParameterAssigned (int number, string field_name)
2258 int index = param_map [number];
2263 MyStructInfo info = (MyStructInfo) struct_params [number];
2267 int field_idx = info [field_name];
2269 if (!CurrentUsageVector.AlwaysBreaks)
2270 CurrentUsageVector [index + field_idx] = true;
2273 public bool IsReachable ()
2278 case FlowBranchingType.SWITCH_SECTION:
2279 // The code following a switch block is reachable unless the switch
2280 // block always returns.
2281 reachable = !CurrentUsageVector.AlwaysReturns;
2284 case FlowBranchingType.LOOP_BLOCK:
2285 // The code following a loop is reachable unless the loop always
2286 // returns or it's an infinite loop without any `break's in it.
2287 reachable = !CurrentUsageVector.AlwaysReturns &&
2288 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2292 // The code following a block or exception is reachable unless the
2293 // block either always returns or always breaks.
2294 reachable = !CurrentUsageVector.AlwaysBreaks &&
2295 !CurrentUsageVector.AlwaysReturns;
2299 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2300 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2305 public override string ToString ()
2307 StringBuilder sb = new StringBuilder ("FlowBranching (");
2312 if (Block != null) {
2314 sb.Append (Block.ID);
2316 sb.Append (Block.StartLocation);
2319 sb.Append (Siblings.Count);
2321 sb.Append (CurrentUsageVector);
2323 return sb.ToString ();
2327 public class MyStructInfo {
2328 public readonly Type Type;
2329 public readonly FieldInfo[] Fields;
2330 public readonly FieldInfo[] NonPublicFields;
2331 public readonly int Count;
2332 public readonly int CountNonPublic;
2333 public readonly bool HasNonPublicFields;
2335 private static Hashtable field_type_hash = new Hashtable ();
2336 private Hashtable field_hash;
2338 // Private constructor. To save memory usage, we only need to create one instance
2339 // of this class per struct type.
2340 private MyStructInfo (Type type)
2344 if (type is TypeBuilder) {
2345 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2347 ArrayList fields = tc.Fields;
2348 if (fields != null) {
2349 foreach (Field field in fields) {
2350 if ((field.ModFlags & Modifiers.STATIC) != 0)
2352 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2359 Fields = new FieldInfo [Count];
2360 NonPublicFields = new FieldInfo [CountNonPublic];
2362 Count = CountNonPublic = 0;
2363 if (fields != null) {
2364 foreach (Field field in fields) {
2365 if ((field.ModFlags & Modifiers.STATIC) != 0)
2367 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2368 Fields [Count++] = field.FieldBuilder;
2370 NonPublicFields [CountNonPublic++] =
2376 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2377 Count = Fields.Length;
2379 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2380 CountNonPublic = NonPublicFields.Length;
2383 Count += NonPublicFields.Length;
2386 field_hash = new Hashtable ();
2387 foreach (FieldInfo field in Fields)
2388 field_hash.Add (field.Name, ++number);
2390 if (NonPublicFields.Length != 0)
2391 HasNonPublicFields = true;
2393 foreach (FieldInfo field in NonPublicFields)
2394 field_hash.Add (field.Name, ++number);
2397 public int this [string name] {
2399 if (field_hash.Contains (name))
2400 return (int) field_hash [name];
2406 public FieldInfo this [int index] {
2408 if (index >= Fields.Length)
2409 return NonPublicFields [index - Fields.Length];
2411 return Fields [index];
2415 public static MyStructInfo GetStructInfo (Type type)
2417 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2420 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2423 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2427 info = new MyStructInfo (type);
2428 field_type_hash.Add (type, info);
2432 public static MyStructInfo GetStructInfo (TypeContainer tc)
2434 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2438 info = new MyStructInfo (tc.TypeBuilder);
2439 field_type_hash.Add (tc.TypeBuilder, info);
2444 public class VariableInfo : IVariable {
2445 public Expression Type;
2446 public LocalBuilder LocalBuilder;
2447 public Type VariableType;
2448 public readonly string Name;
2449 public readonly Location Location;
2450 public readonly int Block;
2455 public bool Assigned;
2456 public bool ReadOnly;
2458 public VariableInfo (Expression type, string name, int block, Location l)
2463 LocalBuilder = null;
2467 public VariableInfo (TypeContainer tc, int block, Location l)
2469 VariableType = tc.TypeBuilder;
2470 struct_info = MyStructInfo.GetStructInfo (tc);
2472 LocalBuilder = null;
2476 MyStructInfo struct_info;
2477 public MyStructInfo StructInfo {
2483 public bool IsAssigned (EmitContext ec, Location loc)
2484 {/* FIXME: we shouldn't just skip this!!!
2485 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2488 MyStructInfo struct_info = StructInfo;
2489 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2490 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2491 ec.CurrentBranching.SetVariableAssigned (this);
2495 int count = struct_info.Count;
2497 for (int i = 0; i < count; i++) {
2498 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2500 Report.Error (165, loc,
2501 "Use of unassigned local variable `" +
2503 ec.CurrentBranching.SetVariableAssigned (this);
2507 FieldInfo field = struct_info [i];
2508 Report.Error (171, loc,
2509 "Field `" + TypeManager.CSharpName (VariableType) +
2510 "." + field.Name + "' must be fully initialized " +
2511 "before control leaves the constructor");
2519 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2521 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2522 (struct_info == null))
2525 int field_idx = StructInfo [name];
2529 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2530 Report.Error (170, loc,
2531 "Use of possibly unassigned field `" + name + "'");
2532 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2539 public void SetAssigned (EmitContext ec)
2541 if (ec.DoFlowAnalysis)
2542 ec.CurrentBranching.SetVariableAssigned (this);
2545 public void SetFieldAssigned (EmitContext ec, string name)
2547 if (ec.DoFlowAnalysis && (struct_info != null))
2548 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2551 public bool Resolve (DeclSpace decl)
2553 if (struct_info != null)
2556 if (VariableType == null)
2557 VariableType = decl.ResolveType (Type, false, Location);
2559 if (VariableType == null)
2562 struct_info = MyStructInfo.GetStructInfo (VariableType);
2567 public void MakePinned ()
2569 TypeManager.MakePinned (LocalBuilder);
2572 public override string ToString ()
2574 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2579 /// Block represents a C# block.
2583 /// This class is used in a number of places: either to represent
2584 /// explicit blocks that the programmer places or implicit blocks.
2586 /// Implicit blocks are used as labels or to introduce variable
2589 public class Block : Statement {
2590 public readonly Block Parent;
2591 public readonly bool Implicit;
2592 public readonly Location StartLocation;
2593 public Location EndLocation;
2596 // The statements in this block
2598 public ArrayList statements;
2601 // An array of Blocks. We keep track of children just
2602 // to generate the local variable declarations.
2604 // Statements and child statements are handled through the
2610 // Labels. (label, block) pairs.
2612 CaseInsensitiveHashtable labels;
2615 // Keeps track of (name, type) pairs
2617 CaseInsensitiveHashtable variables;
2620 // Keeps track of constants
2621 CaseInsensitiveHashtable constants;
2624 // Maps variable names to ILGenerator.LocalBuilders
2626 CaseInsensitiveHashtable local_builders;
2634 public Block (Block parent)
2635 : this (parent, false, Location.Null, Location.Null)
2638 public Block (Block parent, bool implicit_block)
2639 : this (parent, implicit_block, Location.Null, Location.Null)
2642 public Block (Block parent, bool implicit_block, Parameters parameters)
2643 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2646 public Block (Block parent, Location start, Location end)
2647 : this (parent, false, start, end)
2650 public Block (Block parent, Parameters parameters, Location start, Location end)
2651 : this (parent, false, parameters, start, end)
2654 public Block (Block parent, bool implicit_block, Location start, Location end)
2655 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2659 public Block (Block parent, bool implicit_block, Parameters parameters,
2660 Location start, Location end)
2663 parent.AddChild (this);
2665 this.Parent = parent;
2666 this.Implicit = implicit_block;
2667 this.parameters = parameters;
2668 this.StartLocation = start;
2669 this.EndLocation = end;
2672 statements = new ArrayList ();
2681 void AddChild (Block b)
2683 if (children == null)
2684 children = new ArrayList ();
2689 public void SetEndLocation (Location loc)
2695 /// Adds a label to the current block.
2699 /// false if the name already exists in this block. true
2703 public bool AddLabel (string name, LabeledStatement target)
2706 labels = new CaseInsensitiveHashtable ();
2707 if (labels.Contains (name))
2710 labels.Add (name, target);
2714 public LabeledStatement LookupLabel (string name)
2716 if (labels != null){
2717 if (labels.Contains (name))
2718 return ((LabeledStatement) labels [name]);
2722 return Parent.LookupLabel (name);
2727 VariableInfo this_variable = null;
2730 // Returns the "this" instance variable of this block.
2731 // See AddThisVariable() for more information.
2733 public VariableInfo ThisVariable {
2735 if (this_variable != null)
2736 return this_variable;
2737 else if (Parent != null)
2738 return Parent.ThisVariable;
2744 Hashtable child_variable_names;
2747 // Marks a variable with name @name as being used in a child block.
2748 // If a variable name has been used in a child block, it's illegal to
2749 // declare a variable with the same name in the current block.
2751 public void AddChildVariableName (string name)
2753 if (child_variable_names == null)
2754 child_variable_names = new CaseInsensitiveHashtable ();
2756 if (!child_variable_names.Contains (name))
2757 child_variable_names.Add (name, true);
2761 // Marks all variables from block @block and all its children as being
2762 // used in a child block.
2764 public void AddChildVariableNames (Block block)
2766 if (block.Variables != null) {
2767 foreach (string name in block.Variables.Keys)
2768 AddChildVariableName (name);
2771 foreach (Block child in block.children) {
2772 if (child.Variables != null) {
2773 foreach (string name in child.Variables.Keys)
2774 AddChildVariableName (name);
2780 // Checks whether a variable name has already been used in a child block.
2782 public bool IsVariableNameUsedInChildBlock (string name)
2784 if (child_variable_names == null)
2787 return child_variable_names.Contains (name);
2791 // This is used by non-static `struct' constructors which do not have an
2792 // initializer - in this case, the constructor must initialize all of the
2793 // struct's fields. To do this, we add a "this" variable and use the flow
2794 // analysis code to ensure that it's been fully initialized before control
2795 // leaves the constructor.
2797 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2799 if (this_variable != null)
2800 return this_variable;
2802 this_variable = new VariableInfo (tc, ID, l);
2804 if (variables == null)
2805 variables = new CaseInsensitiveHashtable ();
2806 variables.Add ("this", this_variable);
2808 return this_variable;
2811 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2813 if (variables == null)
2814 variables = new CaseInsensitiveHashtable ();
2816 VariableInfo vi = GetVariableInfo (name);
2819 Report.Error (136, l, "A local variable named `" + name + "' " +
2820 "cannot be declared in this scope since it would " +
2821 "give a different meaning to `" + name + "', which " +
2822 "is already used in a `parent or current' scope to " +
2823 "denote something else");
2825 Report.Error (128, l, "A local variable `" + name + "' is already " +
2826 "defined in this scope");
2830 if (IsVariableNameUsedInChildBlock (name)) {
2831 Report.Error (136, l, "A local variable named `" + name + "' " +
2832 "cannot be declared in this scope since it would " +
2833 "give a different meaning to `" + name + "', which " +
2834 "is already used in a `child' scope to denote something " +
2841 Parameter p = pars.GetParameterByName (name, out idx);
2843 Report.Error (136, l, "A local variable named `" + name + "' " +
2844 "cannot be declared in this scope since it would " +
2845 "give a different meaning to `" + name + "', which " +
2846 "is already used in a `parent or current' scope to " +
2847 "denote something else");
2852 vi = new VariableInfo (type, name, ID, l);
2854 variables.Add (name, vi);
2856 if (variables_initialized)
2857 throw new Exception ();
2859 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2863 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2865 if (AddVariable (type, name, pars, l) == null)
2868 if (constants == null)
2869 constants = new CaseInsensitiveHashtable ();
2871 constants.Add (name, value);
2875 public Hashtable Variables {
2881 public VariableInfo GetVariableInfo (string name)
2883 if (variables != null) {
2885 temp = variables [name];
2888 return (VariableInfo) temp;
2893 return Parent.GetVariableInfo (name);
2898 public Expression GetVariableType (string name)
2900 VariableInfo vi = GetVariableInfo (name);
2908 public Expression GetConstantExpression (string name)
2910 if (constants != null) {
2912 temp = constants [name];
2915 return (Expression) temp;
2919 return Parent.GetConstantExpression (name);
2925 /// True if the variable named @name has been defined
2928 public bool IsVariableDefined (string name)
2930 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2931 if (variables != null) {
2932 if (variables.Contains (name))
2937 return Parent.IsVariableDefined (name);
2943 /// True if the variable named @name is a constant
2945 public bool IsConstant (string name)
2947 Expression e = null;
2949 e = GetConstantExpression (name);
2955 /// Use to fetch the statement associated with this label
2957 public Statement this [string name] {
2959 return (Statement) labels [name];
2963 Parameters parameters = null;
2964 public Parameters Parameters {
2967 return Parent.Parameters;
2974 /// A list of labels that were not used within this block
2976 public string [] GetUnreferenced ()
2978 // FIXME: Implement me
2982 public void AddStatement (Statement s)
2999 bool variables_initialized = false;
3000 int count_variables = 0, first_variable = 0;
3002 void UpdateVariableInfo (EmitContext ec)
3004 DeclSpace ds = ec.DeclSpace;
3009 first_variable += Parent.CountVariables;
3011 count_variables = first_variable;
3012 if (variables != null) {
3013 foreach (VariableInfo vi in variables.Values) {
3014 if (!vi.Resolve (ds)) {
3019 vi.Number = ++count_variables;
3021 if (vi.StructInfo != null)
3022 count_variables += vi.StructInfo.Count;
3026 variables_initialized = true;
3031 // The number of local variables in this block
3033 public int CountVariables
3036 if (!variables_initialized)
3037 throw new Exception ();
3039 return count_variables;
3044 /// Emits the variable declarations and labels.
3047 /// tc: is our typecontainer (to resolve type references)
3048 /// ig: is the code generator:
3049 /// toplevel: the toplevel block. This is used for checking
3050 /// that no two labels with the same name are used.
3052 public void EmitMeta (EmitContext ec, Block toplevel)
3054 DeclSpace ds = ec.DeclSpace;
3055 ILGenerator ig = ec.ig;
3057 if (!variables_initialized)
3058 UpdateVariableInfo (ec);
3061 // Process this block variables
3063 if (variables != null){
3064 local_builders = new CaseInsensitiveHashtable ();
3066 foreach (DictionaryEntry de in variables){
3067 string name = (string) de.Key;
3068 VariableInfo vi = (VariableInfo) de.Value;
3070 if (vi.VariableType == null)
3073 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3075 if (CodeGen.SymbolWriter != null)
3076 vi.LocalBuilder.SetLocalSymInfo (name);
3078 if (constants == null)
3081 Expression cv = (Expression) constants [name];
3085 Expression e = cv.Resolve (ec);
3089 if (!(e is Constant)){
3090 Report.Error (133, vi.Location,
3091 "The expression being assigned to `" +
3092 name + "' must be constant (" + e + ")");
3096 constants.Remove (name);
3097 constants.Add (name, e);
3102 // Now, handle the children
3104 if (children != null){
3105 foreach (Block b in children)
3106 b.EmitMeta (ec, toplevel);
3110 public void UsageWarning ()
3114 if (variables != null){
3115 foreach (DictionaryEntry de in variables){
3116 VariableInfo vi = (VariableInfo) de.Value;
3121 name = (string) de.Key;
3125 219, vi.Location, "The variable `" + name +
3126 "' is assigned but its value is never used");
3129 168, vi.Location, "The variable `" +
3131 "' is declared but never used");
3136 if (children != null)
3137 foreach (Block b in children)
3141 bool has_ret = false;
3143 public override bool Resolve (EmitContext ec)
3145 Block prev_block = ec.CurrentBlock;
3148 ec.CurrentBlock = this;
3149 ec.StartFlowBranching (this);
3151 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3153 if (!variables_initialized)
3154 UpdateVariableInfo (ec);
3156 ArrayList new_statements = new ArrayList ();
3157 bool unreachable = false, warning_shown = false;
3159 foreach (Statement s in statements){
3160 if (unreachable && !(s is LabeledStatement)) {
3161 if (!warning_shown && !(s is EmptyStatement)) {
3162 warning_shown = true;
3163 Warning_DeadCodeFound (s.loc);
3169 if (s.Resolve (ec) == false) {
3174 if (s is LabeledStatement)
3175 unreachable = false;
3177 unreachable = ! ec.CurrentBranching.IsReachable ();
3179 new_statements.Add (s);
3182 statements = new_statements;
3184 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3186 FlowReturns returns = ec.EndFlowBranching ();
3187 ec.CurrentBlock = prev_block;
3189 // If we're a non-static `struct' constructor which doesn't have an
3190 // initializer, then we must initialize all of the struct's fields.
3191 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3192 !this_variable.IsAssigned (ec, loc))
3195 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3196 foreach (LabeledStatement label in labels.Values)
3197 if (!label.HasBeenReferenced)
3198 Report.Warning (164, label.Location,
3199 "This label has not been referenced");
3202 if ((returns == FlowReturns.ALWAYS) ||
3203 (returns == FlowReturns.EXCEPTION) ||
3204 (returns == FlowReturns.UNREACHABLE))
3210 protected override bool DoEmit (EmitContext ec)
3212 Block prev_block = ec.CurrentBlock;
3214 ec.CurrentBlock = this;
3216 ec.Mark (StartLocation);
3217 foreach (Statement s in statements)
3220 ec.Mark (EndLocation);
3222 ec.CurrentBlock = prev_block;
3227 public class SwitchLabel {
3230 public Location loc;
3231 public Label ILLabel;
3232 public Label ILLabelCode;
3235 // if expr == null, then it is the default case.
3237 public SwitchLabel (Expression expr, Location l)
3243 public Expression Label {
3249 public object Converted {
3256 // Resolves the expression, reduces it to a literal if possible
3257 // and then converts it to the requested type.
3259 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3261 ILLabel = ec.ig.DefineLabel ();
3262 ILLabelCode = ec.ig.DefineLabel ();
3267 Expression e = label.Resolve (ec);
3272 if (!(e is Constant)){
3273 Console.WriteLine ("Value is: " + label);
3274 Report.Error (150, loc, "A constant value is expected");
3278 if (e is StringConstant || e is NullLiteral){
3279 if (required_type == TypeManager.string_type){
3281 ILLabel = ec.ig.DefineLabel ();
3286 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3287 if (converted == null)
3294 public class SwitchSection {
3295 // An array of SwitchLabels.
3296 public readonly ArrayList Labels;
3297 public readonly Block Block;
3299 public SwitchSection (ArrayList labels, Block block)
3306 public class Switch : Statement {
3307 public readonly ArrayList Sections;
3308 public Expression Expr;
3311 /// Maps constants whose type type SwitchType to their SwitchLabels.
3313 public Hashtable Elements;
3316 /// The governing switch type
3318 public Type SwitchType;
3324 Label default_target;
3325 Expression new_expr;
3328 // The types allowed to be implicitly cast from
3329 // on the governing type
3331 static Type [] allowed_types;
3333 public Switch (Expression e, ArrayList sects, Location l)
3340 public bool GotDefault {
3346 public Label DefaultTarget {
3348 return default_target;
3353 // Determines the governing type for a switch. The returned
3354 // expression might be the expression from the switch, or an
3355 // expression that includes any potential conversions to the
3356 // integral types or to string.
3358 Expression SwitchGoverningType (EmitContext ec, Type t)
3360 if (t == TypeManager.int32_type ||
3361 t == TypeManager.uint32_type ||
3362 t == TypeManager.char_type ||
3363 t == TypeManager.byte_type ||
3364 t == TypeManager.sbyte_type ||
3365 t == TypeManager.ushort_type ||
3366 t == TypeManager.short_type ||
3367 t == TypeManager.uint64_type ||
3368 t == TypeManager.int64_type ||
3369 t == TypeManager.string_type ||
3370 t == TypeManager.bool_type ||
3371 t.IsSubclassOf (TypeManager.enum_type))
3374 if (allowed_types == null){
3375 allowed_types = new Type [] {
3376 TypeManager.sbyte_type,
3377 TypeManager.byte_type,
3378 TypeManager.short_type,
3379 TypeManager.ushort_type,
3380 TypeManager.int32_type,
3381 TypeManager.uint32_type,
3382 TypeManager.int64_type,
3383 TypeManager.uint64_type,
3384 TypeManager.char_type,
3385 TypeManager.bool_type,
3386 TypeManager.string_type
3391 // Try to find a *user* defined implicit conversion.
3393 // If there is no implicit conversion, or if there are multiple
3394 // conversions, we have to report an error
3396 Expression converted = null;
3397 foreach (Type tt in allowed_types){
3400 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3404 if (converted != null){
3405 Report.Error (-12, loc, "More than one conversion to an integral " +
3406 " type exists for type `" +
3407 TypeManager.CSharpName (Expr.Type)+"'");
3415 void error152 (string n)
3418 152, "The label `" + n + ":' " +
3419 "is already present on this switch statement");
3423 // Performs the basic sanity checks on the switch statement
3424 // (looks for duplicate keys and non-constant expressions).
3426 // It also returns a hashtable with the keys that we will later
3427 // use to compute the switch tables
3429 bool CheckSwitch (EmitContext ec)
3433 Elements = new CaseInsensitiveHashtable ();
3435 got_default = false;
3437 if (TypeManager.IsEnumType (SwitchType)){
3438 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3440 compare_type = SwitchType;
3442 foreach (SwitchSection ss in Sections){
3443 foreach (SwitchLabel sl in ss.Labels){
3444 if (!sl.ResolveAndReduce (ec, SwitchType)){
3449 if (sl.Label == null){
3451 error152 ("default");
3458 object key = sl.Converted;
3460 if (key is Constant)
3461 key = ((Constant) key).GetValue ();
3464 key = NullLiteral.Null;
3466 string lname = null;
3467 if (compare_type == TypeManager.uint64_type){
3468 ulong v = (ulong) key;
3470 if (Elements.Contains (v))
3471 lname = v.ToString ();
3473 Elements.Add (v, sl);
3474 } else if (compare_type == TypeManager.int64_type){
3475 long v = (long) key;
3477 if (Elements.Contains (v))
3478 lname = v.ToString ();
3480 Elements.Add (v, sl);
3481 } else if (compare_type == TypeManager.uint32_type){
3482 uint v = (uint) key;
3484 if (Elements.Contains (v))
3485 lname = v.ToString ();
3487 Elements.Add (v, sl);
3488 } else if (compare_type == TypeManager.char_type){
3489 char v = (char) key;
3491 if (Elements.Contains (v))
3492 lname = v.ToString ();
3494 Elements.Add (v, sl);
3495 } else if (compare_type == TypeManager.byte_type){
3496 byte v = (byte) key;
3498 if (Elements.Contains (v))
3499 lname = v.ToString ();
3501 Elements.Add (v, sl);
3502 } else if (compare_type == TypeManager.sbyte_type){
3503 sbyte v = (sbyte) key;
3505 if (Elements.Contains (v))
3506 lname = v.ToString ();
3508 Elements.Add (v, sl);
3509 } else if (compare_type == TypeManager.short_type){
3510 short v = (short) key;
3512 if (Elements.Contains (v))
3513 lname = v.ToString ();
3515 Elements.Add (v, sl);
3516 } else if (compare_type == TypeManager.ushort_type){
3517 ushort v = (ushort) key;
3519 if (Elements.Contains (v))
3520 lname = v.ToString ();
3522 Elements.Add (v, sl);
3523 } else if (compare_type == TypeManager.string_type){
3524 if (key is NullLiteral){
3525 if (Elements.Contains (NullLiteral.Null))
3528 Elements.Add (NullLiteral.Null, null);
3530 string s = (string) key;
3532 if (Elements.Contains (s))
3535 Elements.Add (s, sl);
3537 } else if (compare_type == TypeManager.int32_type) {
3540 if (Elements.Contains (v))
3541 lname = v.ToString ();
3543 Elements.Add (v, sl);
3544 } else if (compare_type == TypeManager.bool_type) {
3545 bool v = (bool) key;
3547 if (Elements.Contains (v))
3548 lname = v.ToString ();
3550 Elements.Add (v, sl);
3554 throw new Exception ("Unknown switch type!" +
3555 SwitchType + " " + compare_type);
3559 error152 ("case + " + lname);
3570 void EmitObjectInteger (ILGenerator ig, object k)
3573 IntConstant.EmitInt (ig, (int) k);
3574 else if (k is Constant) {
3575 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3578 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3581 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3583 IntConstant.EmitInt (ig, (int) (long) k);
3584 ig.Emit (OpCodes.Conv_I8);
3587 LongConstant.EmitLong (ig, (long) k);
3589 else if (k is ulong)
3591 if ((ulong) k < (1L<<32))
3593 IntConstant.EmitInt (ig, (int) (long) k);
3594 ig.Emit (OpCodes.Conv_U8);
3598 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3602 IntConstant.EmitInt (ig, (int) ((char) k));
3603 else if (k is sbyte)
3604 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3606 IntConstant.EmitInt (ig, (int) ((byte) k));
3607 else if (k is short)
3608 IntConstant.EmitInt (ig, (int) ((short) k));
3609 else if (k is ushort)
3610 IntConstant.EmitInt (ig, (int) ((ushort) k));
3612 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3614 throw new Exception ("Unhandled case");
3617 // structure used to hold blocks of keys while calculating table switch
3618 class KeyBlock : IComparable
3620 public KeyBlock (long _nFirst)
3622 nFirst = nLast = _nFirst;
3626 public ArrayList rgKeys = null;
3629 get { return (int) (nLast - nFirst + 1); }
3631 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3633 return kbLast.nLast - kbFirst.nFirst + 1;
3635 public int CompareTo (object obj)
3637 KeyBlock kb = (KeyBlock) obj;
3638 int nLength = Length;
3639 int nLengthOther = kb.Length;
3640 if (nLengthOther == nLength)
3641 return (int) (kb.nFirst - nFirst);
3642 return nLength - nLengthOther;
3647 /// This method emits code for a lookup-based switch statement (non-string)
3648 /// Basically it groups the cases into blocks that are at least half full,
3649 /// and then spits out individual lookup opcodes for each block.
3650 /// It emits the longest blocks first, and short blocks are just
3651 /// handled with direct compares.
3653 /// <param name="ec"></param>
3654 /// <param name="val"></param>
3655 /// <returns></returns>
3656 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3658 int cElements = Elements.Count;
3659 object [] rgKeys = new object [cElements];
3660 Elements.Keys.CopyTo (rgKeys, 0);
3661 Array.Sort (rgKeys);
3663 // initialize the block list with one element per key
3664 ArrayList rgKeyBlocks = new ArrayList ();
3665 foreach (object key in rgKeys)
3666 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3669 // iteratively merge the blocks while they are at least half full
3670 // there's probably a really cool way to do this with a tree...
3671 while (rgKeyBlocks.Count > 1)
3673 ArrayList rgKeyBlocksNew = new ArrayList ();
3674 kbCurr = (KeyBlock) rgKeyBlocks [0];
3675 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3677 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3678 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3681 kbCurr.nLast = kb.nLast;
3685 // start a new block
3686 rgKeyBlocksNew.Add (kbCurr);
3690 rgKeyBlocksNew.Add (kbCurr);
3691 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3693 rgKeyBlocks = rgKeyBlocksNew;
3696 // initialize the key lists
3697 foreach (KeyBlock kb in rgKeyBlocks)
3698 kb.rgKeys = new ArrayList ();
3700 // fill the key lists
3702 if (rgKeyBlocks.Count > 0) {
3703 kbCurr = (KeyBlock) rgKeyBlocks [0];
3704 foreach (object key in rgKeys)
3706 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3708 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3709 kbCurr.rgKeys.Add (key);
3713 // sort the blocks so we can tackle the largest ones first
3714 rgKeyBlocks.Sort ();
3716 // okay now we can start...
3717 ILGenerator ig = ec.ig;
3718 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3719 Label lblDefault = ig.DefineLabel ();
3721 Type typeKeys = null;
3722 if (rgKeys.Length > 0)
3723 typeKeys = rgKeys [0].GetType (); // used for conversions
3725 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3727 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3728 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3731 foreach (object key in kb.rgKeys)
3733 ig.Emit (OpCodes.Ldloc, val);
3734 EmitObjectInteger (ig, key);
3735 SwitchLabel sl = (SwitchLabel) Elements [key];
3736 ig.Emit (OpCodes.Beq, sl.ILLabel);
3741 // TODO: if all the keys in the block are the same and there are
3742 // no gaps/defaults then just use a range-check.
3743 if (SwitchType == TypeManager.int64_type ||
3744 SwitchType == TypeManager.uint64_type)
3746 // TODO: optimize constant/I4 cases
3748 // check block range (could be > 2^31)
3749 ig.Emit (OpCodes.Ldloc, val);
3750 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3751 ig.Emit (OpCodes.Blt, lblDefault);
3752 ig.Emit (OpCodes.Ldloc, val);
3753 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3754 ig.Emit (OpCodes.Bgt, lblDefault);
3757 ig.Emit (OpCodes.Ldloc, val);
3760 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3761 ig.Emit (OpCodes.Sub);
3763 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3768 ig.Emit (OpCodes.Ldloc, val);
3769 int nFirst = (int) kb.nFirst;
3772 IntConstant.EmitInt (ig, nFirst);
3773 ig.Emit (OpCodes.Sub);
3775 else if (nFirst < 0)
3777 IntConstant.EmitInt (ig, -nFirst);
3778 ig.Emit (OpCodes.Add);
3782 // first, build the list of labels for the switch
3784 int cJumps = kb.Length;
3785 Label [] rgLabels = new Label [cJumps];
3786 for (int iJump = 0; iJump < cJumps; iJump++)
3788 object key = kb.rgKeys [iKey];
3789 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3791 SwitchLabel sl = (SwitchLabel) Elements [key];
3792 rgLabels [iJump] = sl.ILLabel;
3796 rgLabels [iJump] = lblDefault;
3798 // emit the switch opcode
3799 ig.Emit (OpCodes.Switch, rgLabels);
3802 // mark the default for this block
3804 ig.MarkLabel (lblDefault);
3807 // TODO: find the default case and emit it here,
3808 // to prevent having to do the following jump.
3809 // make sure to mark other labels in the default section
3811 // the last default just goes to the end
3812 ig.Emit (OpCodes.Br, lblDefault);
3814 // now emit the code for the sections
3815 bool fFoundDefault = false;
3816 bool fAllReturn = true;
3817 foreach (SwitchSection ss in Sections)
3819 foreach (SwitchLabel sl in ss.Labels)
3821 ig.MarkLabel (sl.ILLabel);
3822 ig.MarkLabel (sl.ILLabelCode);
3823 if (sl.Label == null)
3825 ig.MarkLabel (lblDefault);
3826 fFoundDefault = true;
3829 bool returns = ss.Block.Emit (ec);
3830 fAllReturn &= returns;
3831 //ig.Emit (OpCodes.Br, lblEnd);
3834 if (!fFoundDefault) {
3835 ig.MarkLabel (lblDefault);
3838 ig.MarkLabel (lblEnd);
3843 // This simple emit switch works, but does not take advantage of the
3845 // TODO: remove non-string logic from here
3846 // TODO: binary search strings?
3848 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3850 ILGenerator ig = ec.ig;
3851 Label end_of_switch = ig.DefineLabel ();
3852 Label next_test = ig.DefineLabel ();
3853 Label null_target = ig.DefineLabel ();
3854 bool default_found = false;
3855 bool first_test = true;
3856 bool pending_goto_end = false;
3857 bool all_return = true;
3858 bool is_string = false;
3862 // Special processing for strings: we cant compare
3865 if (SwitchType == TypeManager.string_type){
3866 ig.Emit (OpCodes.Ldloc, val);
3869 if (Elements.Contains (NullLiteral.Null)){
3870 ig.Emit (OpCodes.Brfalse, null_target);
3872 ig.Emit (OpCodes.Brfalse, default_target);
3874 ig.Emit (OpCodes.Ldloc, val);
3875 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3876 ig.Emit (OpCodes.Stloc, val);
3879 foreach (SwitchSection ss in Sections){
3880 Label sec_begin = ig.DefineLabel ();
3882 if (pending_goto_end)
3883 ig.Emit (OpCodes.Br, end_of_switch);
3885 int label_count = ss.Labels.Count;
3887 foreach (SwitchLabel sl in ss.Labels){
3888 ig.MarkLabel (sl.ILLabel);
3891 ig.MarkLabel (next_test);
3892 next_test = ig.DefineLabel ();
3895 // If we are the default target
3897 if (sl.Label == null){
3898 ig.MarkLabel (default_target);
3899 default_found = true;
3901 object lit = sl.Converted;
3903 if (lit is NullLiteral){
3905 if (label_count == 1)
3906 ig.Emit (OpCodes.Br, next_test);
3911 StringConstant str = (StringConstant) lit;
3913 ig.Emit (OpCodes.Ldloc, val);
3914 ig.Emit (OpCodes.Ldstr, str.Value);
3915 if (label_count == 1)
3916 ig.Emit (OpCodes.Bne_Un, next_test);
3918 ig.Emit (OpCodes.Beq, sec_begin);
3920 ig.Emit (OpCodes.Ldloc, val);
3921 EmitObjectInteger (ig, lit);
3922 ig.Emit (OpCodes.Ceq);
3923 if (label_count == 1)
3924 ig.Emit (OpCodes.Brfalse, next_test);
3926 ig.Emit (OpCodes.Brtrue, sec_begin);
3930 if (label_count != 1)
3931 ig.Emit (OpCodes.Br, next_test);
3934 ig.MarkLabel (null_target);
3935 ig.MarkLabel (sec_begin);
3936 foreach (SwitchLabel sl in ss.Labels)
3937 ig.MarkLabel (sl.ILLabelCode);
3939 bool returns = ss.Block.Emit (ec);
3941 pending_goto_end = false;
3944 pending_goto_end = true;
3948 if (!default_found){
3949 ig.MarkLabel (default_target);
3952 ig.MarkLabel (next_test);
3953 ig.MarkLabel (end_of_switch);
3958 public override bool Resolve (EmitContext ec)
3960 Expr = Expr.Resolve (ec);
3964 new_expr = SwitchGoverningType (ec, Expr.Type);
3965 if (new_expr == null){
3966 Report.Error (151, loc, "An integer type or string was expected for switch");
3971 SwitchType = new_expr.Type;
3973 if (!CheckSwitch (ec))
3976 Switch old_switch = ec.Switch;
3978 ec.Switch.SwitchType = SwitchType;
3980 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3983 foreach (SwitchSection ss in Sections){
3985 ec.CurrentBranching.CreateSibling ();
3989 if (ss.Block.Resolve (ec) != true)
3995 ec.CurrentBranching.CreateSibling ();
3997 ec.EndFlowBranching ();
3998 ec.Switch = old_switch;
4003 protected override bool DoEmit (EmitContext ec)
4005 // Store variable for comparission purposes
4006 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
4008 ec.ig.Emit (OpCodes.Stloc, value);
4010 ILGenerator ig = ec.ig;
4012 default_target = ig.DefineLabel ();
4015 // Setup the codegen context
4017 Label old_end = ec.LoopEnd;
4018 Switch old_switch = ec.Switch;
4020 ec.LoopEnd = ig.DefineLabel ();
4025 if (SwitchType == TypeManager.string_type)
4026 all_return = SimpleSwitchEmit (ec, value);
4028 all_return = TableSwitchEmit (ec, value);
4030 // Restore context state.
4031 ig.MarkLabel (ec.LoopEnd);
4034 // Restore the previous context
4036 ec.LoopEnd = old_end;
4037 ec.Switch = old_switch;
4043 public class Lock : Statement {
4045 Statement Statement;
4047 public Lock (Expression expr, Statement stmt, Location l)
4054 public override bool Resolve (EmitContext ec)
4056 expr = expr.Resolve (ec);
4057 return Statement.Resolve (ec) && expr != null;
4060 protected override bool DoEmit (EmitContext ec)
4062 Type type = expr.Type;
4065 if (type.IsValueType){
4066 Report.Error (185, loc, "lock statement requires the expression to be " +
4067 " a reference type (type is: `" +
4068 TypeManager.CSharpName (type) + "'");
4072 ILGenerator ig = ec.ig;
4073 LocalBuilder temp = ig.DeclareLocal (type);
4076 ig.Emit (OpCodes.Dup);
4077 ig.Emit (OpCodes.Stloc, temp);
4078 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4081 Label end = ig.BeginExceptionBlock ();
4082 bool old_in_try = ec.InTry;
4084 Label finish = ig.DefineLabel ();
4085 val = Statement.Emit (ec);
4086 ec.InTry = old_in_try;
4087 // ig.Emit (OpCodes.Leave, finish);
4089 ig.MarkLabel (finish);
4092 ig.BeginFinallyBlock ();
4093 ig.Emit (OpCodes.Ldloc, temp);
4094 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4095 ig.EndExceptionBlock ();
4101 public class Unchecked : Statement {
4102 public readonly Block Block;
4104 public Unchecked (Block b)
4109 public override bool Resolve (EmitContext ec)
4111 return Block.Resolve (ec);
4114 protected override bool DoEmit (EmitContext ec)
4116 bool previous_state = ec.CheckState;
4117 bool previous_state_const = ec.ConstantCheckState;
4120 ec.CheckState = false;
4121 ec.ConstantCheckState = false;
4122 val = Block.Emit (ec);
4123 ec.CheckState = previous_state;
4124 ec.ConstantCheckState = previous_state_const;
4130 public class Checked : Statement {
4131 public readonly Block Block;
4133 public Checked (Block b)
4138 public override bool Resolve (EmitContext ec)
4140 bool previous_state = ec.CheckState;
4141 bool previous_state_const = ec.ConstantCheckState;
4143 ec.CheckState = true;
4144 ec.ConstantCheckState = true;
4145 bool ret = Block.Resolve (ec);
4146 ec.CheckState = previous_state;
4147 ec.ConstantCheckState = previous_state_const;
4152 protected override bool DoEmit (EmitContext ec)
4154 bool previous_state = ec.CheckState;
4155 bool previous_state_const = ec.ConstantCheckState;
4158 ec.CheckState = true;
4159 ec.ConstantCheckState = true;
4160 val = Block.Emit (ec);
4161 ec.CheckState = previous_state;
4162 ec.ConstantCheckState = previous_state_const;
4168 public class Unsafe : Statement {
4169 public readonly Block Block;
4171 public Unsafe (Block b)
4176 public override bool Resolve (EmitContext ec)
4178 bool previous_state = ec.InUnsafe;
4182 val = Block.Resolve (ec);
4183 ec.InUnsafe = previous_state;
4188 protected override bool DoEmit (EmitContext ec)
4190 bool previous_state = ec.InUnsafe;
4194 val = Block.Emit (ec);
4195 ec.InUnsafe = previous_state;
4204 public class Fixed : Statement {
4206 ArrayList declarators;
4207 Statement statement;
4212 public bool is_object;
4213 public VariableInfo vi;
4214 public Expression expr;
4215 public Expression converted;
4218 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4221 declarators = decls;
4226 public override bool Resolve (EmitContext ec)
4228 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4229 if (expr_type == null)
4232 data = new FixedData [declarators.Count];
4235 foreach (Pair p in declarators){
4236 VariableInfo vi = (VariableInfo) p.First;
4237 Expression e = (Expression) p.Second;
4242 // The rules for the possible declarators are pretty wise,
4243 // but the production on the grammar is more concise.
4245 // So we have to enforce these rules here.
4247 // We do not resolve before doing the case 1 test,
4248 // because the grammar is explicit in that the token &
4249 // is present, so we need to test for this particular case.
4253 // Case 1: & object.
4255 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4256 Expression child = ((Unary) e).Expr;
4259 if (child is ParameterReference || child is LocalVariableReference){
4262 "No need to use fixed statement for parameters or " +
4263 "local variable declarations (address is already " +
4272 child = ((Unary) e).Expr;
4274 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4277 data [i].is_object = true;
4279 data [i].converted = null;
4293 if (e.Type.IsArray){
4294 Type array_type = e.Type.GetElementType ();
4298 // Provided that array_type is unmanaged,
4300 if (!TypeManager.VerifyUnManaged (array_type, loc))
4304 // and T* is implicitly convertible to the
4305 // pointer type given in the fixed statement.
4307 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4309 Expression converted = Expression.ConvertImplicitRequired (
4310 ec, array_ptr, vi.VariableType, loc);
4311 if (converted == null)
4314 data [i].is_object = false;
4316 data [i].converted = converted;
4326 if (e.Type == TypeManager.string_type){
4327 data [i].is_object = false;
4329 data [i].converted = null;
4335 return statement.Resolve (ec);
4338 protected override bool DoEmit (EmitContext ec)
4340 ILGenerator ig = ec.ig;
4342 bool is_ret = false;
4344 for (int i = 0; i < data.Length; i++) {
4345 VariableInfo vi = data [i].vi;
4348 // Case 1: & object.
4350 if (data [i].is_object) {
4352 // Store pointer in pinned location
4354 data [i].expr.Emit (ec);
4355 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4357 is_ret = statement.Emit (ec);
4359 // Clear the pinned variable.
4360 ig.Emit (OpCodes.Ldc_I4_0);
4361 ig.Emit (OpCodes.Conv_U);
4362 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4370 if (data [i].expr.Type.IsArray){
4372 // Store pointer in pinned location
4374 data [i].converted.Emit (ec);
4376 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4378 is_ret = statement.Emit (ec);
4380 // Clear the pinned variable.
4381 ig.Emit (OpCodes.Ldc_I4_0);
4382 ig.Emit (OpCodes.Conv_U);
4383 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4391 if (data [i].expr.Type == TypeManager.string_type){
4392 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4393 TypeManager.MakePinned (pinned_string);
4395 data [i].expr.Emit (ec);
4396 ig.Emit (OpCodes.Stloc, pinned_string);
4398 Expression sptr = new StringPtr (pinned_string, loc);
4399 Expression converted = Expression.ConvertImplicitRequired (
4400 ec, sptr, vi.VariableType, loc);
4402 if (converted == null)
4405 converted.Emit (ec);
4406 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4408 is_ret = statement.Emit (ec);
4410 // Clear the pinned variable
4411 ig.Emit (OpCodes.Ldnull);
4412 ig.Emit (OpCodes.Stloc, pinned_string);
4420 public class Catch {
4421 public readonly string Name;
4422 public readonly Block Block;
4423 public readonly Location Location;
4425 Expression type_expr;
4428 public Catch (Expression type, string name, Block block, Location l)
4436 public Type CatchType {
4442 public bool IsGeneral {
4444 return type_expr == null;
4448 public bool Resolve (EmitContext ec)
4450 if (type_expr != null) {
4451 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4455 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4456 Report.Error (155, Location,
4457 "The type caught or thrown must be derived " +
4458 "from System.Exception");
4464 if (!Block.Resolve (ec))
4471 public class Try : Statement {
4472 public readonly Block Fini, Block;
4473 public readonly ArrayList Specific;
4474 public readonly Catch General;
4477 // specific, general and fini might all be null.
4479 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4481 if (specific == null && general == null){
4482 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4486 this.Specific = specific;
4487 this.General = general;
4492 public override bool Resolve (EmitContext ec)
4496 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4498 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4500 bool old_in_try = ec.InTry;
4503 if (!Block.Resolve (ec))
4506 ec.InTry = old_in_try;
4508 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4510 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4512 foreach (Catch c in Specific){
4513 ec.CurrentBranching.CreateSibling ();
4514 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4516 if (c.Name != null) {
4517 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4519 throw new Exception ();
4524 bool old_in_catch = ec.InCatch;
4527 if (!c.Resolve (ec))
4530 ec.InCatch = old_in_catch;
4532 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4534 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4535 vector.AndLocals (current);
4538 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4540 if (General != null){
4541 ec.CurrentBranching.CreateSibling ();
4542 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4544 bool old_in_catch = ec.InCatch;
4547 if (!General.Resolve (ec))
4550 ec.InCatch = old_in_catch;
4552 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4554 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4555 vector.AndLocals (current);
4558 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4561 ec.CurrentBranching.CreateSiblingForFinally ();
4562 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4564 bool old_in_finally = ec.InFinally;
4565 ec.InFinally = true;
4567 if (!Fini.Resolve (ec))
4570 ec.InFinally = old_in_finally;
4573 FlowReturns returns = ec.EndFlowBranching ();
4575 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4577 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4579 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4580 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4583 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4585 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4590 protected override bool DoEmit (EmitContext ec)
4592 ILGenerator ig = ec.ig;
4594 Label finish = ig.DefineLabel ();;
4598 end = ig.BeginExceptionBlock ();
4599 bool old_in_try = ec.InTry;
4601 returns = Block.Emit (ec);
4602 ec.InTry = old_in_try;
4605 // System.Reflection.Emit provides this automatically:
4606 // ig.Emit (OpCodes.Leave, finish);
4608 bool old_in_catch = ec.InCatch;
4610 DeclSpace ds = ec.DeclSpace;
4612 foreach (Catch c in Specific){
4615 ig.BeginCatchBlock (c.CatchType);
4617 if (c.Name != null){
4618 vi = c.Block.GetVariableInfo (c.Name);
4620 throw new Exception ("Variable does not exist in this block");
4622 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4624 ig.Emit (OpCodes.Pop);
4626 if (!c.Block.Emit (ec))
4630 if (General != null){
4631 ig.BeginCatchBlock (TypeManager.object_type);
4632 ig.Emit (OpCodes.Pop);
4633 if (!General.Block.Emit (ec))
4636 ec.InCatch = old_in_catch;
4638 ig.MarkLabel (finish);
4640 ig.BeginFinallyBlock ();
4641 bool old_in_finally = ec.InFinally;
4642 ec.InFinally = true;
4644 ec.InFinally = old_in_finally;
4647 ig.EndExceptionBlock ();
4650 if (!returns || ec.InTry || ec.InCatch)
4653 // Unfortunately, System.Reflection.Emit automatically emits a leave
4654 // to the end of the finally block. This is a problem if `returns'
4655 // is true since we may jump to a point after the end of the method.
4656 // As a workaround, emit an explicit ret here.
4658 if (ec.ReturnType != null)
4659 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4660 ec.ig.Emit (OpCodes.Ret);
4666 public class Using : Statement {
4667 object expression_or_block;
4668 Statement Statement;
4673 Expression [] converted_vars;
4674 ExpressionStatement [] assign;
4676 public Using (object expression_or_block, Statement stmt, Location l)
4678 this.expression_or_block = expression_or_block;
4684 // Resolves for the case of using using a local variable declaration.
4686 bool ResolveLocalVariableDecls (EmitContext ec)
4688 bool need_conv = false;
4689 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4692 if (expr_type == null)
4696 // The type must be an IDisposable or an implicit conversion
4699 converted_vars = new Expression [var_list.Count];
4700 assign = new ExpressionStatement [var_list.Count];
4701 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4702 foreach (DictionaryEntry e in var_list){
4703 Expression var = (Expression) e.Key;
4705 var = var.ResolveLValue (ec, new EmptyExpression ());
4709 converted_vars [i] = Expression.ConvertImplicitRequired (
4710 ec, var, TypeManager.idisposable_type, loc);
4712 if (converted_vars [i] == null)
4720 foreach (DictionaryEntry e in var_list){
4721 LocalVariableReference var = (LocalVariableReference) e.Key;
4722 Expression new_expr = (Expression) e.Value;
4725 a = new Assign (var, new_expr, loc);
4731 converted_vars [i] = var;
4732 assign [i] = (ExpressionStatement) a;
4739 bool ResolveExpression (EmitContext ec)
4741 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4742 conv = Expression.ConvertImplicitRequired (
4743 ec, expr, TypeManager.idisposable_type, loc);
4753 // Emits the code for the case of using using a local variable declaration.
4755 bool EmitLocalVariableDecls (EmitContext ec)
4757 ILGenerator ig = ec.ig;
4760 bool old_in_try = ec.InTry;
4762 for (i = 0; i < assign.Length; i++) {
4763 assign [i].EmitStatement (ec);
4765 ig.BeginExceptionBlock ();
4767 Statement.Emit (ec);
4768 ec.InTry = old_in_try;
4770 bool old_in_finally = ec.InFinally;
4771 ec.InFinally = true;
4772 var_list.Reverse ();
4773 foreach (DictionaryEntry e in var_list){
4774 LocalVariableReference var = (LocalVariableReference) e.Key;
4775 Label skip = ig.DefineLabel ();
4778 ig.BeginFinallyBlock ();
4781 ig.Emit (OpCodes.Brfalse, skip);
4782 converted_vars [i].Emit (ec);
4783 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4784 ig.MarkLabel (skip);
4785 ig.EndExceptionBlock ();
4787 ec.InFinally = old_in_finally;
4792 bool EmitExpression (EmitContext ec)
4795 // Make a copy of the expression and operate on that.
4797 ILGenerator ig = ec.ig;
4798 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4803 ig.Emit (OpCodes.Stloc, local_copy);
4805 bool old_in_try = ec.InTry;
4807 ig.BeginExceptionBlock ();
4808 Statement.Emit (ec);
4809 ec.InTry = old_in_try;
4811 Label skip = ig.DefineLabel ();
4812 bool old_in_finally = ec.InFinally;
4813 ig.BeginFinallyBlock ();
4814 ig.Emit (OpCodes.Ldloc, local_copy);
4815 ig.Emit (OpCodes.Brfalse, skip);
4816 ig.Emit (OpCodes.Ldloc, local_copy);
4817 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4818 ig.MarkLabel (skip);
4819 ec.InFinally = old_in_finally;
4820 ig.EndExceptionBlock ();
4825 public override bool Resolve (EmitContext ec)
4827 if (expression_or_block is DictionaryEntry){
4828 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4829 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4831 if (!ResolveLocalVariableDecls (ec))
4834 } else if (expression_or_block is Expression){
4835 expr = (Expression) expression_or_block;
4837 expr = expr.Resolve (ec);
4841 expr_type = expr.Type;
4843 if (!ResolveExpression (ec))
4847 return Statement.Resolve (ec);
4850 protected override bool DoEmit (EmitContext ec)
4852 if (expression_or_block is DictionaryEntry)
4853 return EmitLocalVariableDecls (ec);
4854 else if (expression_or_block is Expression)
4855 return EmitExpression (ec);
4862 /// Implementation of the foreach C# statement
4864 public class Foreach : Statement {
4866 LocalVariableReference variable;
4868 Statement statement;
4869 ForeachHelperMethods hm;
4870 Expression empty, conv;
4871 Type array_type, element_type;
4874 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4875 Statement stmt, Location l)
4882 VariableInfo vi = var.VariableInfo;
4883 this.type = vi.Type;
4885 this.variable = var;
4891 public override bool Resolve (EmitContext ec)
4893 expr = expr.Resolve (ec);
4897 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4898 if (var_type == null)
4902 // We need an instance variable. Not sure this is the best
4903 // way of doing this.
4905 // FIXME: When we implement propertyaccess, will those turn
4906 // out to return values in ExprClass? I think they should.
4908 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4909 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4910 error1579 (expr.Type);
4914 if (expr.Type.IsArray) {
4915 array_type = expr.Type;
4916 element_type = array_type.GetElementType ();
4918 empty = new EmptyExpression (element_type);
4920 hm = ProbeCollectionType (ec, expr.Type);
4922 error1579 (expr.Type);
4926 array_type = expr.Type;
4927 element_type = hm.element_type;
4929 empty = new EmptyExpression (hm.element_type);
4932 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4933 ec.CurrentBranching.CreateSibling ();
4937 // FIXME: maybe we can apply the same trick we do in the
4938 // array handling to avoid creating empty and conv in some cases.
4940 // Although it is not as important in this case, as the type
4941 // will not likely be object (what the enumerator will return).
4943 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4947 if (variable.ResolveLValue (ec, empty) == null)
4950 if (!statement.Resolve (ec))
4953 FlowReturns returns = ec.EndFlowBranching ();
4959 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4961 static MethodInfo FetchMethodMoveNext (Type t)
4963 MemberList move_next_list;
4965 move_next_list = TypeContainer.FindMembers (
4966 t, MemberTypes.Method,
4967 BindingFlags.Public | BindingFlags.Instance,
4968 Type.FilterName, "MoveNext");
4969 if (move_next_list.Count == 0)
4972 foreach (MemberInfo m in move_next_list){
4973 MethodInfo mi = (MethodInfo) m;
4976 args = TypeManager.GetArgumentTypes (mi);
4977 if (args != null && args.Length == 0){
4978 if (mi.ReturnType == TypeManager.bool_type)
4986 // Retrieves a `public T get_Current ()' method from the Type `t'
4988 static MethodInfo FetchMethodGetCurrent (Type t)
4990 MemberList move_next_list;
4992 move_next_list = TypeContainer.FindMembers (
4993 t, MemberTypes.Method,
4994 BindingFlags.Public | BindingFlags.Instance,
4995 Type.FilterName, "get_Current");
4996 if (move_next_list.Count == 0)
4999 foreach (MemberInfo m in move_next_list){
5000 MethodInfo mi = (MethodInfo) m;
5003 args = TypeManager.GetArgumentTypes (mi);
5004 if (args != null && args.Length == 0)
5011 // This struct records the helper methods used by the Foreach construct
5013 class ForeachHelperMethods {
5014 public EmitContext ec;
5015 public MethodInfo get_enumerator;
5016 public MethodInfo move_next;
5017 public MethodInfo get_current;
5018 public Type element_type;
5019 public Type enumerator_type;
5020 public bool is_disposable;
5022 public ForeachHelperMethods (EmitContext ec)
5025 this.element_type = TypeManager.object_type;
5026 this.enumerator_type = TypeManager.ienumerator_type;
5027 this.is_disposable = true;
5031 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5036 if (!(m is MethodInfo))
5039 if (m.Name != "GetEnumerator")
5042 MethodInfo mi = (MethodInfo) m;
5043 Type [] args = TypeManager.GetArgumentTypes (mi);
5045 if (args.Length != 0)
5048 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5049 EmitContext ec = hm.ec;
5052 // Check whether GetEnumerator is accessible to us
5054 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5056 Type declaring = mi.DeclaringType;
5057 if (prot == MethodAttributes.Private){
5058 if (declaring != ec.ContainerType)
5060 } else if (prot == MethodAttributes.FamANDAssem){
5061 // If from a different assembly, false
5062 if (!(mi is MethodBuilder))
5065 // Are we being invoked from the same class, or from a derived method?
5067 if (ec.ContainerType != declaring){
5068 if (!ec.ContainerType.IsSubclassOf (declaring))
5071 } else if (prot == MethodAttributes.FamORAssem){
5072 if (!(mi is MethodBuilder ||
5073 ec.ContainerType == declaring ||
5074 ec.ContainerType.IsSubclassOf (declaring)))
5076 } if (prot == MethodAttributes.Family){
5077 if (!(ec.ContainerType == declaring ||
5078 ec.ContainerType.IsSubclassOf (declaring)))
5083 // Ok, we can access it, now make sure that we can do something
5084 // with this `GetEnumerator'
5087 if (mi.ReturnType == TypeManager.ienumerator_type ||
5088 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5089 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5090 hm.move_next = TypeManager.bool_movenext_void;
5091 hm.get_current = TypeManager.object_getcurrent_void;
5096 // Ok, so they dont return an IEnumerable, we will have to
5097 // find if they support the GetEnumerator pattern.
5099 Type return_type = mi.ReturnType;
5101 hm.move_next = FetchMethodMoveNext (return_type);
5102 if (hm.move_next == null)
5104 hm.get_current = FetchMethodGetCurrent (return_type);
5105 if (hm.get_current == null)
5108 hm.element_type = hm.get_current.ReturnType;
5109 hm.enumerator_type = return_type;
5110 hm.is_disposable = TypeManager.ImplementsInterface (
5111 hm.enumerator_type, TypeManager.idisposable_type);
5117 /// This filter is used to find the GetEnumerator method
5118 /// on which IEnumerator operates
5120 static MemberFilter FilterEnumerator;
5124 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5127 void error1579 (Type t)
5129 Report.Error (1579, loc,
5130 "foreach statement cannot operate on variables of type `" +
5131 t.FullName + "' because that class does not provide a " +
5132 " GetEnumerator method or it is inaccessible");
5135 static bool TryType (Type t, ForeachHelperMethods hm)
5139 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5140 BindingFlags.Public | BindingFlags.NonPublic |
5141 BindingFlags.Instance,
5142 FilterEnumerator, hm);
5147 hm.get_enumerator = (MethodInfo) mi [0];
5152 // Looks for a usable GetEnumerator in the Type, and if found returns
5153 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5155 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5157 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5159 if (TryType (t, hm))
5163 // Now try to find the method in the interfaces
5166 Type [] ifaces = t.GetInterfaces ();
5168 foreach (Type i in ifaces){
5169 if (TryType (i, hm))
5174 // Since TypeBuilder.GetInterfaces only returns the interface
5175 // types for this type, we have to keep looping, but once
5176 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5177 // done, because it returns all the types
5179 if ((t is TypeBuilder))
5189 // FIXME: possible optimization.
5190 // We might be able to avoid creating `empty' if the type is the sam
5192 bool EmitCollectionForeach (EmitContext ec)
5194 ILGenerator ig = ec.ig;
5195 LocalBuilder enumerator, disposable;
5197 enumerator = ig.DeclareLocal (hm.enumerator_type);
5198 if (hm.is_disposable)
5199 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5204 // Instantiate the enumerator
5206 if (expr.Type.IsValueType){
5207 if (expr is IMemoryLocation){
5208 IMemoryLocation ml = (IMemoryLocation) expr;
5210 ml.AddressOf (ec, AddressOp.Load);
5212 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5213 " does not implement IMemoryLocation");
5214 ig.Emit (OpCodes.Call, hm.get_enumerator);
5217 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5219 ig.Emit (OpCodes.Stloc, enumerator);
5222 // Protect the code in a try/finalize block, so that
5223 // if the beast implement IDisposable, we get rid of it
5226 bool old_in_try = ec.InTry;
5228 if (hm.is_disposable) {
5229 l = ig.BeginExceptionBlock ();
5233 Label end_try = ig.DefineLabel ();
5235 ig.MarkLabel (ec.LoopBegin);
5236 ig.Emit (OpCodes.Ldloc, enumerator);
5237 ig.Emit (OpCodes.Callvirt, hm.move_next);
5238 ig.Emit (OpCodes.Brfalse, end_try);
5239 ig.Emit (OpCodes.Ldloc, enumerator);
5240 ig.Emit (OpCodes.Callvirt, hm.get_current);
5241 variable.EmitAssign (ec, conv);
5242 statement.Emit (ec);
5243 ig.Emit (OpCodes.Br, ec.LoopBegin);
5244 ig.MarkLabel (end_try);
5245 ec.InTry = old_in_try;
5247 // The runtime provides this for us.
5248 // ig.Emit (OpCodes.Leave, end);
5251 // Now the finally block
5253 if (hm.is_disposable) {
5254 Label end_finally = ig.DefineLabel ();
5255 bool old_in_finally = ec.InFinally;
5256 ec.InFinally = true;
5257 ig.BeginFinallyBlock ();
5259 ig.Emit (OpCodes.Ldloc, enumerator);
5260 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5261 ig.Emit (OpCodes.Stloc, disposable);
5262 ig.Emit (OpCodes.Ldloc, disposable);
5263 ig.Emit (OpCodes.Brfalse, end_finally);
5264 ig.Emit (OpCodes.Ldloc, disposable);
5265 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5266 ig.MarkLabel (end_finally);
5267 ec.InFinally = old_in_finally;
5269 // The runtime generates this anyways.
5270 // ig.Emit (OpCodes.Endfinally);
5272 ig.EndExceptionBlock ();
5275 ig.MarkLabel (ec.LoopEnd);
5280 // FIXME: possible optimization.
5281 // We might be able to avoid creating `empty' if the type is the sam
5283 bool EmitArrayForeach (EmitContext ec)
5285 int rank = array_type.GetArrayRank ();
5286 ILGenerator ig = ec.ig;
5288 LocalBuilder copy = ig.DeclareLocal (array_type);
5291 // Make our copy of the array
5294 ig.Emit (OpCodes.Stloc, copy);
5297 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5301 ig.Emit (OpCodes.Ldc_I4_0);
5302 ig.Emit (OpCodes.Stloc, counter);
5303 test = ig.DefineLabel ();
5304 ig.Emit (OpCodes.Br, test);
5306 loop = ig.DefineLabel ();
5307 ig.MarkLabel (loop);
5309 ig.Emit (OpCodes.Ldloc, copy);
5310 ig.Emit (OpCodes.Ldloc, counter);
5311 ArrayAccess.EmitLoadOpcode (ig, var_type);
5313 variable.EmitAssign (ec, conv);
5315 statement.Emit (ec);
5317 ig.MarkLabel (ec.LoopBegin);
5318 ig.Emit (OpCodes.Ldloc, counter);
5319 ig.Emit (OpCodes.Ldc_I4_1);
5320 ig.Emit (OpCodes.Add);
5321 ig.Emit (OpCodes.Stloc, counter);
5323 ig.MarkLabel (test);
5324 ig.Emit (OpCodes.Ldloc, counter);
5325 ig.Emit (OpCodes.Ldloc, copy);
5326 ig.Emit (OpCodes.Ldlen);
5327 ig.Emit (OpCodes.Conv_I4);
5328 ig.Emit (OpCodes.Blt, loop);
5330 LocalBuilder [] dim_len = new LocalBuilder [rank];
5331 LocalBuilder [] dim_count = new LocalBuilder [rank];
5332 Label [] loop = new Label [rank];
5333 Label [] test = new Label [rank];
5336 for (dim = 0; dim < rank; dim++){
5337 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5338 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5339 test [dim] = ig.DefineLabel ();
5340 loop [dim] = ig.DefineLabel ();
5343 for (dim = 0; dim < rank; dim++){
5344 ig.Emit (OpCodes.Ldloc, copy);
5345 IntLiteral.EmitInt (ig, dim);
5346 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5347 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5350 for (dim = 0; dim < rank; dim++){
5351 ig.Emit (OpCodes.Ldc_I4_0);
5352 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5353 ig.Emit (OpCodes.Br, test [dim]);
5354 ig.MarkLabel (loop [dim]);
5357 ig.Emit (OpCodes.Ldloc, copy);
5358 for (dim = 0; dim < rank; dim++)
5359 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5362 // FIXME: Maybe we can cache the computation of `get'?
5364 Type [] args = new Type [rank];
5367 for (int i = 0; i < rank; i++)
5368 args [i] = TypeManager.int32_type;
5370 ModuleBuilder mb = CodeGen.ModuleBuilder;
5371 get = mb.GetArrayMethod (
5373 CallingConventions.HasThis| CallingConventions.Standard,
5375 ig.Emit (OpCodes.Call, get);
5376 variable.EmitAssign (ec, conv);
5377 statement.Emit (ec);
5378 ig.MarkLabel (ec.LoopBegin);
5379 for (dim = rank - 1; dim >= 0; dim--){
5380 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5381 ig.Emit (OpCodes.Ldc_I4_1);
5382 ig.Emit (OpCodes.Add);
5383 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5385 ig.MarkLabel (test [dim]);
5386 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5387 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5388 ig.Emit (OpCodes.Blt, loop [dim]);
5391 ig.MarkLabel (ec.LoopEnd);
5396 protected override bool DoEmit (EmitContext ec)
5400 ILGenerator ig = ec.ig;
5402 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5403 bool old_inloop = ec.InLoop;
5404 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5405 ec.LoopBegin = ig.DefineLabel ();
5406 ec.LoopEnd = ig.DefineLabel ();
5408 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5411 ret_val = EmitCollectionForeach (ec);
5413 ret_val = EmitArrayForeach (ec);
5415 ec.LoopBegin = old_begin;
5416 ec.LoopEnd = old_end;
5417 ec.InLoop = old_inloop;
5418 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5425 /// AddHandler statement
5427 public class AddHandler : Statement {
5429 Expression EvtHandler;
5430 Expression EvtTarget;
5432 public AddHandler (Expression evt_id, Expression evt_handler,
5433 Expression evt_target, Location l)
5436 EvtHandler = evt_handler;
5437 EvtTarget = evt_target;
5439 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5442 public override bool Resolve (EmitContext ec)
5444 EvtId = EvtId.Resolve(ec);
5445 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5446 EvtTarget = EvtTarget.Resolve (ec,ResolveFlags.VariableOrValue);
5447 if (EvtId == null || (!(EvtId is EventExpr))) {
5448 Report.Error (999, "'AddHandler' statement needs an event designator.");
5452 if (EvtHandler == null)
5454 Report.Error (999, "'AddHandler' statement needs an event handler.");
5457 //EventExpr ee = (EventExpr) EvtId;
5458 //MethodGroupExpr me = (MethodGroupExpr) EvtHandler;
5459 //bool b = EvtId.Type.IsSubclassOf (TypeManager.delegate_type);
5460 //ee.EventInfo.AddEventHandler(EvtTarget, new System.Delegate())
5464 protected override bool DoEmit (EmitContext ec)
5467 ArrayList args = new ArrayList();
5468 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5471 // The even type was already resolved to a delegate, so
5472 // we must un-resolve its name to generate a type expression
5473 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5474 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5476 // which we can use to declare a new event handler
5478 d = new New (dtype, args, Location.Null);
5480 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5482 // we resolve it all and emit the code
5494 public class RedimClause {
5495 public Expression Expr;
5496 public ArrayList NewIndexes;
5498 public RedimClause (Expression e, ArrayList args)
5505 public class ReDim : Statement {
5506 ArrayList RedimTargets;
5510 private StatementExpression ReDimExpr;
5512 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5515 RedimTargets = targets;
5516 Preserve = opt_preserve;
5519 public override bool Resolve (EmitContext ec)
5521 Expression RedimTarget;
5522 ArrayList NewIndexes;
5524 foreach (RedimClause rc in RedimTargets) {
5525 RedimTarget = rc.Expr;
5526 NewIndexes = rc.NewIndexes;
5528 RedimTarget = RedimTarget.Resolve (ec);
5529 if (!RedimTarget.Type.IsArray)
5530 Report.Error (49, "'ReDim' statement requires an array");
5532 ArrayList args = new ArrayList();
5533 foreach (Argument a in NewIndexes) {
5534 if (a.Resolve(ec, loc))
5538 for (int x = 0; x < args.Count; x++) {
5539 args[x] = new Binary (Binary.Operator.Addition,
5540 (Expression) args[x], new IntLiteral (1), Location.Null);
5544 if (RedimTarget.Type.GetArrayRank() != args.Count)
5545 Report.Error (415, "'ReDim' cannot change the number of dimensions of an array.");
5547 BaseType = RedimTarget.Type.GetElementType();
5548 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5549 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
5552 // TODO: Generate call to copying code, which has to make lots of verifications
5553 //PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5554 //ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5555 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5558 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5559 ReDimExpr.Resolve(ec);
5564 protected override bool DoEmit (EmitContext ec)
5572 public class Erase : Statement {
5573 Expression EraseTarget;
5575 private StatementExpression EraseExpr;
5577 public Erase (Expression expr, Location l)
5583 public override bool Resolve (EmitContext ec)
5585 EraseTarget = EraseTarget.Resolve (ec);
5586 if (!EraseTarget.Type.IsArray)
5587 Report.Error (49, "'Erase' statement requires an array");
5589 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5590 EraseExpr.Resolve(ec);
5595 protected override bool DoEmit (EmitContext ec)