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.MonoBASIC {
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.MonoBASIC_Name (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 (type != ExitType.SUB && type != ExitType.FUNCTION && type != ExitType.PROPERTY) {
1036 if (ec.InLoop == false && ec.Switch == null){
1037 Report.Error (139, loc, "No enclosing loop or switch to exit from");
1041 if (ec.InTry || ec.InCatch)
1042 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1044 ig.Emit (OpCodes.Br, ec.LoopEnd);
1047 Report.Error (157,loc,"Control can not leave the body of the finally block");
1051 if (ec.InTry || ec.InCatch) {
1052 if (!ec.HasReturnLabel) {
1053 ec.ReturnLabel = ec.ig.DefineLabel ();
1054 ec.HasReturnLabel = true;
1056 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
1058 ec.ig.Emit (OpCodes.Ret);
1067 public class Continue : Statement {
1069 public Continue (Location l)
1074 public override bool Resolve (EmitContext ec)
1076 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1080 protected override bool DoEmit (EmitContext ec)
1082 Label begin = ec.LoopBegin;
1085 Report.Error (139, loc, "No enclosing loop to continue to");
1090 // UGH: Non trivial. This Br might cross a try/catch boundary
1094 // try { ... } catch { continue; }
1098 // try {} catch { while () { continue; }}
1100 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1101 ec.ig.Emit (OpCodes.Leave, begin);
1102 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1103 throw new Exception ("Should never happen");
1105 ec.ig.Emit (OpCodes.Br, begin);
1111 // This is used in the control flow analysis code to specify whether the
1112 // current code block may return to its enclosing block before reaching
1115 public enum FlowReturns {
1116 // It can never return.
1119 // This means that the block contains a conditional return statement
1123 // The code always returns, ie. there's an unconditional return / break
1127 // The code always throws an exception.
1130 // The current code block is unreachable. This happens if it's immediately
1131 // following a FlowReturns.ALWAYS block.
1136 // This is a special bit vector which can inherit from another bit vector doing a
1137 // copy-on-write strategy. The inherited vector may have a smaller size than the
1140 public class MyBitVector {
1141 public readonly int Count;
1142 public readonly MyBitVector InheritsFrom;
1147 public MyBitVector (int Count)
1148 : this (null, Count)
1151 public MyBitVector (MyBitVector InheritsFrom, int Count)
1153 this.InheritsFrom = InheritsFrom;
1158 // Checks whether this bit vector has been modified. After setting this to true,
1159 // we won't use the inherited vector anymore, but our own copy of it.
1161 public bool IsDirty {
1168 initialize_vector ();
1173 // Get/set bit `index' in the bit vector.
1175 public bool this [int index]
1179 throw new ArgumentOutOfRangeException ();
1181 // We're doing a "copy-on-write" strategy here; as long
1182 // as nobody writes to the array, we can use our parent's
1183 // copy instead of duplicating the vector.
1186 return vector [index];
1187 else if (InheritsFrom != null) {
1188 BitArray inherited = InheritsFrom.Vector;
1190 if (index < inherited.Count)
1191 return inherited [index];
1200 throw new ArgumentOutOfRangeException ();
1202 // Only copy the vector if we're actually modifying it.
1204 if (this [index] != value) {
1205 initialize_vector ();
1207 vector [index] = value;
1213 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1214 // copy of the bit vector.
1216 public static explicit operator BitArray (MyBitVector vector)
1218 vector.initialize_vector ();
1219 return vector.Vector;
1223 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1224 // different size than the current one.
1226 public void Or (MyBitVector new_vector)
1228 BitArray new_array = new_vector.Vector;
1230 initialize_vector ();
1233 if (vector.Count < new_array.Count)
1234 upper = vector.Count;
1236 upper = new_array.Count;
1238 for (int i = 0; i < upper; i++)
1239 vector [i] = vector [i] | new_array [i];
1243 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1244 // a different size than the current one.
1246 public void And (MyBitVector new_vector)
1248 BitArray new_array = new_vector.Vector;
1250 initialize_vector ();
1253 if (vector.Count < new_array.Count)
1254 lower = upper = vector.Count;
1256 lower = new_array.Count;
1257 upper = vector.Count;
1260 for (int i = 0; i < lower; i++)
1261 vector [i] = vector [i] & new_array [i];
1263 for (int i = lower; i < upper; i++)
1268 // This does a deep copy of the bit vector.
1270 public MyBitVector Clone ()
1272 MyBitVector retval = new MyBitVector (Count);
1274 retval.Vector = Vector;
1283 else if (!is_dirty && (InheritsFrom != null))
1284 return InheritsFrom.Vector;
1286 initialize_vector ();
1292 initialize_vector ();
1294 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1295 vector [i] = value [i];
1299 void initialize_vector ()
1304 vector = new BitArray (Count, false);
1305 if (InheritsFrom != null)
1306 Vector = InheritsFrom.Vector;
1311 public override string ToString ()
1313 StringBuilder sb = new StringBuilder ("MyBitVector (");
1315 BitArray vector = Vector;
1319 sb.Append ("INHERITED - ");
1320 for (int i = 0; i < vector.Count; i++) {
1323 sb.Append (vector [i]);
1327 return sb.ToString ();
1332 // The type of a FlowBranching.
1334 public enum FlowBranchingType {
1335 // Normal (conditional or toplevel) block.
1352 // A new instance of this class is created every time a new block is resolved
1353 // and if there's branching in the block's control flow.
1355 public class FlowBranching {
1357 // The type of this flow branching.
1359 public readonly FlowBranchingType Type;
1362 // The block this branching is contained in. This may be null if it's not
1363 // a top-level block and it doesn't declare any local variables.
1365 public readonly Block Block;
1368 // The parent of this branching or null if this is the top-block.
1370 public readonly FlowBranching Parent;
1373 // Start-Location of this flow branching.
1375 public readonly Location Location;
1378 // A list of UsageVectors. A new vector is added each time control flow may
1379 // take a different path.
1381 public ArrayList Siblings;
1384 // If this is an infinite loop.
1386 public bool Infinite;
1389 // If we may leave the current loop.
1391 public bool MayLeaveLoop;
1396 InternalParameters param_info;
1398 MyStructInfo[] struct_params;
1400 ArrayList finally_vectors;
1402 static int next_id = 0;
1406 // Performs an `And' operation on the FlowReturns status
1407 // (for instance, a block only returns ALWAYS if all its siblings
1410 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1412 if (b == FlowReturns.UNREACHABLE)
1416 case FlowReturns.NEVER:
1417 if (b == FlowReturns.NEVER)
1418 return FlowReturns.NEVER;
1420 return FlowReturns.SOMETIMES;
1422 case FlowReturns.SOMETIMES:
1423 return FlowReturns.SOMETIMES;
1425 case FlowReturns.ALWAYS:
1426 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1427 return FlowReturns.ALWAYS;
1429 return FlowReturns.SOMETIMES;
1431 case FlowReturns.EXCEPTION:
1432 if (b == FlowReturns.EXCEPTION)
1433 return FlowReturns.EXCEPTION;
1434 else if (b == FlowReturns.ALWAYS)
1435 return FlowReturns.ALWAYS;
1437 return FlowReturns.SOMETIMES;
1444 // The vector contains a BitArray with information about which local variables
1445 // and parameters are already initialized at the current code position.
1447 public class UsageVector {
1449 // If this is true, then the usage vector has been modified and must be
1450 // merged when we're done with this branching.
1452 public bool IsDirty;
1455 // The number of parameters in this block.
1457 public readonly int CountParameters;
1460 // The number of locals in this block.
1462 public readonly int CountLocals;
1465 // If not null, then we inherit our state from this vector and do a
1466 // copy-on-write. If null, then we're the first sibling in a top-level
1467 // block and inherit from the empty vector.
1469 public readonly UsageVector InheritsFrom;
1474 MyBitVector locals, parameters;
1475 FlowReturns real_returns, real_breaks;
1478 static int next_id = 0;
1482 // Normally, you should not use any of these constructors.
1484 public UsageVector (UsageVector parent, int num_params, int num_locals)
1486 this.InheritsFrom = parent;
1487 this.CountParameters = num_params;
1488 this.CountLocals = num_locals;
1489 this.real_returns = FlowReturns.NEVER;
1490 this.real_breaks = FlowReturns.NEVER;
1492 if (parent != null) {
1493 locals = new MyBitVector (parent.locals, CountLocals);
1495 parameters = new MyBitVector (parent.parameters, num_params);
1496 real_returns = parent.Returns;
1497 real_breaks = parent.Breaks;
1499 locals = new MyBitVector (null, CountLocals);
1501 parameters = new MyBitVector (null, num_params);
1507 public UsageVector (UsageVector parent)
1508 : this (parent, parent.CountParameters, parent.CountLocals)
1512 // This does a deep copy of the usage vector.
1514 public UsageVector Clone ()
1516 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1518 retval.locals = locals.Clone ();
1519 if (parameters != null)
1520 retval.parameters = parameters.Clone ();
1521 retval.real_returns = real_returns;
1522 retval.real_breaks = real_breaks;
1528 // State of parameter `number'.
1530 public bool this [int number]
1535 else if (number == 0)
1536 throw new ArgumentException ();
1538 return parameters [number - 1];
1544 else if (number == 0)
1545 throw new ArgumentException ();
1547 parameters [number - 1] = value;
1552 // State of the local variable `vi'.
1553 // If the local variable is a struct, use a non-zero `field_idx'
1554 // to check an individual field in it.
1556 public bool this [VariableInfo vi, int field_idx]
1559 if (vi.Number == -1)
1561 else if (vi.Number == 0)
1562 throw new ArgumentException ();
1564 return locals [vi.Number + field_idx - 1];
1568 if (vi.Number == -1)
1570 else if (vi.Number == 0)
1571 throw new ArgumentException ();
1573 locals [vi.Number + field_idx - 1] = value;
1578 // Specifies when the current block returns.
1579 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1580 // end of the method (so that we don't need to emit a return statement).
1581 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1582 // value will never be used.
1584 public FlowReturns Returns {
1586 return real_returns;
1590 real_returns = value;
1595 // Specifies whether control may return to our containing block
1596 // before reaching the end of this block. This happens if there
1597 // is a break/continue/goto/return in it.
1598 // This can also be used to find out whether the statement immediately
1599 // following the current block may be reached or not.
1601 public FlowReturns Breaks {
1607 real_breaks = value;
1611 public bool AlwaysBreaks {
1613 return (Breaks == FlowReturns.ALWAYS) ||
1614 (Breaks == FlowReturns.EXCEPTION) ||
1615 (Breaks == FlowReturns.UNREACHABLE);
1619 public bool MayBreak {
1621 return Breaks != FlowReturns.NEVER;
1625 public bool AlwaysReturns {
1627 return (Returns == FlowReturns.ALWAYS) ||
1628 (Returns == FlowReturns.EXCEPTION);
1632 public bool MayReturn {
1634 return (Returns == FlowReturns.SOMETIMES) ||
1635 (Returns == FlowReturns.ALWAYS);
1640 // Merge a child branching.
1642 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1644 MyBitVector new_locals = null;
1645 MyBitVector new_params = null;
1647 FlowReturns new_returns = FlowReturns.NEVER;
1648 FlowReturns new_breaks = FlowReturns.NEVER;
1649 bool new_returns_set = false, new_breaks_set = false;
1651 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1652 this, children.Count);
1654 foreach (UsageVector child in children) {
1655 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1657 if (!child.is_finally) {
1658 if (child.Breaks != FlowReturns.UNREACHABLE) {
1659 // If Returns is already set, perform an
1660 // `And' operation on it, otherwise just set just.
1661 if (!new_returns_set) {
1662 new_returns = child.Returns;
1663 new_returns_set = true;
1665 new_returns = AndFlowReturns (
1666 new_returns, child.Returns);
1669 // If Breaks is already set, perform an
1670 // `And' operation on it, otherwise just set just.
1671 if (!new_breaks_set) {
1672 new_breaks = child.Breaks;
1673 new_breaks_set = true;
1675 new_breaks = AndFlowReturns (
1676 new_breaks, child.Breaks);
1679 // Ignore unreachable children.
1680 if (child.Returns == FlowReturns.UNREACHABLE)
1683 // A local variable is initialized after a flow branching if it
1684 // has been initialized in all its branches which do neither
1685 // always return or always throw an exception.
1687 // If a branch may return, but does not always return, then we
1688 // can treat it like a never-returning branch here: control will
1689 // only reach the code position after the branching if we did not
1692 // It's important to distinguish between always and sometimes
1693 // returning branches here:
1696 // 2 if (something) {
1700 // 6 Console.WriteLine (a);
1702 // The if block in lines 3-4 always returns, so we must not look
1703 // at the initialization of `a' in line 4 - thus it'll still be
1704 // uninitialized in line 6.
1706 // On the other hand, the following is allowed:
1713 // 6 Console.WriteLine (a);
1715 // Here, `a' is initialized in line 3 and we must not look at
1716 // line 5 since it always returns.
1718 if (child.is_finally) {
1719 if (new_locals == null)
1720 new_locals = locals.Clone ();
1721 new_locals.Or (child.locals);
1723 if (parameters != null) {
1724 if (new_params == null)
1725 new_params = parameters.Clone ();
1726 new_params.Or (child.parameters);
1730 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1731 if (new_locals != null)
1732 new_locals.And (child.locals);
1734 new_locals = locals.Clone ();
1735 new_locals.Or (child.locals);
1737 } else if (children.Count == 1) {
1738 new_locals = locals.Clone ();
1739 new_locals.Or (child.locals);
1742 // An `out' parameter must be assigned in all branches which do
1743 // not always throw an exception.
1744 if (parameters != null) {
1745 if (child.Breaks != FlowReturns.EXCEPTION) {
1746 if (new_params != null)
1747 new_params.And (child.parameters);
1749 new_params = parameters.Clone ();
1750 new_params.Or (child.parameters);
1752 } else if (children.Count == 1) {
1753 new_params = parameters.Clone ();
1754 new_params.Or (child.parameters);
1760 Returns = new_returns;
1761 if ((branching.Type == FlowBranchingType.BLOCK) ||
1762 (branching.Type == FlowBranchingType.EXCEPTION) ||
1763 (new_breaks == FlowReturns.UNREACHABLE) ||
1764 (new_breaks == FlowReturns.EXCEPTION))
1765 Breaks = new_breaks;
1766 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1767 Breaks = new_returns;
1768 else if (branching.Type == FlowBranchingType.SWITCH){
1769 if (new_breaks == FlowReturns.ALWAYS)
1770 Breaks = FlowReturns.ALWAYS;
1774 // We've now either reached the point after the branching or we will
1775 // never get there since we always return or always throw an exception.
1777 // If we can reach the point after the branching, mark all locals and
1778 // parameters as initialized which have been initialized in all branches
1779 // we need to look at (see above).
1782 if (((new_breaks != FlowReturns.ALWAYS) &&
1783 (new_breaks != FlowReturns.EXCEPTION) &&
1784 (new_breaks != FlowReturns.UNREACHABLE)) ||
1785 (children.Count == 1)) {
1786 if (new_locals != null)
1787 locals.Or (new_locals);
1789 if (new_params != null)
1790 parameters.Or (new_params);
1793 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1794 new_params, new_locals, new_returns, new_breaks,
1795 branching.Infinite, branching.MayLeaveLoop, this);
1797 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1798 if ((new_breaks != FlowReturns.ALWAYS) &&
1799 (new_breaks != FlowReturns.EXCEPTION) &&
1800 (new_breaks != FlowReturns.UNREACHABLE))
1801 Report.Error (163, branching.Location,
1802 "Control cannot fall through from one " +
1803 "case label to another");
1806 if (branching.Infinite && !branching.MayLeaveLoop) {
1807 Report.Debug (1, "INFINITE", new_returns, new_breaks,
1808 Returns, Breaks, this);
1810 // We're actually infinite.
1811 if (new_returns == FlowReturns.NEVER) {
1812 Breaks = FlowReturns.UNREACHABLE;
1813 return FlowReturns.UNREACHABLE;
1816 // If we're an infinite loop and do not break, the code after
1817 // the loop can never be reached. However, if we may return
1818 // from the loop, then we do always return (or stay in the loop
1820 if ((new_returns == FlowReturns.SOMETIMES) ||
1821 (new_returns == FlowReturns.ALWAYS)) {
1822 Returns = FlowReturns.ALWAYS;
1823 return FlowReturns.ALWAYS;
1831 // Tells control flow analysis that the current code position may be reached with
1832 // a forward jump from any of the origins listed in `origin_vectors' which is a
1833 // list of UsageVectors.
1835 // This is used when resolving forward gotos - in the following example, the
1836 // variable `a' is uninitialized in line 8 becase this line may be reached via
1837 // the goto in line 4:
1847 // 8 Console.WriteLine (a);
1850 public void MergeJumpOrigins (ICollection origin_vectors)
1852 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1854 real_breaks = FlowReturns.NEVER;
1855 real_returns = FlowReturns.NEVER;
1857 foreach (UsageVector vector in origin_vectors) {
1858 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1860 locals.And (vector.locals);
1861 if (parameters != null)
1862 parameters.And (vector.parameters);
1863 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1864 Returns = AndFlowReturns (Returns, vector.Returns);
1867 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1871 // This is used at the beginning of a finally block if there were
1872 // any return statements in the try block or one of the catch blocks.
1874 public void MergeFinallyOrigins (ICollection finally_vectors)
1876 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1878 real_breaks = FlowReturns.NEVER;
1880 foreach (UsageVector vector in finally_vectors) {
1881 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1883 if (parameters != null)
1884 parameters.And (vector.parameters);
1885 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1890 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1893 public void CheckOutParameters (FlowBranching branching)
1895 if (parameters != null)
1896 branching.CheckOutParameters (parameters, branching.Location);
1900 // Performs an `or' operation on the locals and the parameters.
1902 public void Or (UsageVector new_vector)
1904 locals.Or (new_vector.locals);
1905 if (parameters != null)
1906 parameters.Or (new_vector.parameters);
1910 // Performs an `and' operation on the locals.
1912 public void AndLocals (UsageVector new_vector)
1914 locals.And (new_vector.locals);
1918 // Returns a deep copy of the parameters.
1920 public MyBitVector Parameters {
1922 if (parameters != null)
1923 return parameters.Clone ();
1930 // Returns a deep copy of the locals.
1932 public MyBitVector Locals {
1934 return locals.Clone ();
1942 public override string ToString ()
1944 StringBuilder sb = new StringBuilder ();
1946 sb.Append ("Vector (");
1949 sb.Append (Returns);
1952 if (parameters != null) {
1954 sb.Append (parameters);
1960 return sb.ToString ();
1964 FlowBranching (FlowBranchingType type, Location loc)
1966 this.Siblings = new ArrayList ();
1968 this.Location = loc;
1974 // Creates a new flow branching for `block'.
1975 // This is used from Block.Resolve to create the top-level branching of
1978 public FlowBranching (Block block, InternalParameters ip, Location loc)
1979 : this (FlowBranchingType.BLOCK, loc)
1984 int count = (ip != null) ? ip.Count : 0;
1987 param_map = new int [count];
1988 struct_params = new MyStructInfo [count];
1991 for (int i = 0; i < count; i++) {
1992 Parameter.Modifier mod = param_info.ParameterModifier (i);
1994 if ((mod & Parameter.Modifier.OUT) == 0)
1997 param_map [i] = ++num_params;
1999 Type param_type = param_info.ParameterType (i);
2001 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2002 if (struct_params [i] != null)
2003 num_params += struct_params [i].Count;
2006 Siblings = new ArrayList ();
2007 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2011 // Creates a new flow branching which is contained in `parent'.
2012 // You should only pass non-null for the `block' argument if this block
2013 // introduces any new variables - in this case, we need to create a new
2014 // usage vector with a different size than our parent's one.
2016 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2017 Block block, Location loc)
2023 if (parent != null) {
2024 param_info = parent.param_info;
2025 param_map = parent.param_map;
2026 struct_params = parent.struct_params;
2027 num_params = parent.num_params;
2032 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2033 Block.CountVariables);
2035 vector = new UsageVector (Parent.CurrentUsageVector);
2037 Siblings.Add (vector);
2040 case FlowBranchingType.EXCEPTION:
2041 finally_vectors = new ArrayList ();
2050 // Returns the branching's current usage vector.
2052 public UsageVector CurrentUsageVector
2055 return (UsageVector) Siblings [Siblings.Count - 1];
2060 // Creates a sibling of the current usage vector.
2062 public void CreateSibling ()
2064 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2066 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2070 // Creates a sibling for a `finally' block.
2072 public void CreateSiblingForFinally ()
2074 if (Type != FlowBranchingType.EXCEPTION)
2075 throw new NotSupportedException ();
2079 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2083 // Check whether all `out' parameters have been assigned.
2085 public void CheckOutParameters (MyBitVector parameters, Location loc)
2090 for (int i = 0; i < param_map.Length; i++) {
2091 int index = param_map [i];
2096 if (parameters [index - 1])
2099 // If it's a struct, we must ensure that all its fields have
2100 // been assigned. If the struct has any non-public fields, this
2101 // can only be done by assigning the whole struct.
2103 MyStructInfo struct_info = struct_params [index - 1];
2104 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2106 177, loc, "The out parameter `" +
2107 param_info.ParameterName (i) + "' must be " +
2108 "assigned before control leave the current method.");
2114 for (int j = 0; j < struct_info.Count; j++) {
2115 if (!parameters [index + j]) {
2117 177, loc, "The out parameter `" +
2118 param_info.ParameterName (i) + "' must be " +
2119 "assigned before control leave the current method.");
2128 // Merge a child branching.
2130 public FlowReturns MergeChild (FlowBranching child)
2132 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2134 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2135 MayLeaveLoop |= child.MayLeaveLoop;
2137 MayLeaveLoop = false;
2143 // Does the toplevel merging.
2145 public FlowReturns MergeTopBlock ()
2147 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2148 throw new NotSupportedException ();
2150 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2152 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2154 vector.MergeChildren (this, Siblings);
2157 Siblings.Add (vector);
2159 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2161 if (vector.Breaks != FlowReturns.EXCEPTION) {
2162 if (!vector.AlwaysBreaks)
2163 CheckOutParameters (CurrentUsageVector.Parameters, Location);
2164 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2166 return FlowReturns.EXCEPTION;
2169 public bool InTryBlock ()
2171 if (finally_vectors != null)
2173 else if (Parent != null)
2174 return Parent.InTryBlock ();
2179 public void AddFinallyVector (UsageVector vector)
2181 if (finally_vectors != null) {
2182 finally_vectors.Add (vector.Clone ());
2187 Parent.AddFinallyVector (vector);
2189 throw new NotSupportedException ();
2192 public bool IsVariableAssigned (VariableInfo vi)
2194 if (CurrentUsageVector.AlwaysBreaks)
2197 return CurrentUsageVector [vi, 0];
2200 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2202 if (CurrentUsageVector.AlwaysBreaks)
2205 return CurrentUsageVector [vi, field_idx];
2208 public void SetVariableAssigned (VariableInfo vi)
2210 if (CurrentUsageVector.AlwaysBreaks)
2213 CurrentUsageVector [vi, 0] = true;
2216 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2218 if (CurrentUsageVector.AlwaysBreaks)
2221 CurrentUsageVector [vi, field_idx] = true;
2224 public bool IsParameterAssigned (int number)
2226 int index = param_map [number];
2231 if (CurrentUsageVector [index])
2234 // Parameter is not assigned, so check whether it's a struct.
2235 // If it's either not a struct or a struct which non-public
2236 // fields, return false.
2237 MyStructInfo struct_info = struct_params [number];
2238 if ((struct_info == null) || struct_info.HasNonPublicFields)
2241 // Ok, so each field must be assigned.
2242 for (int i = 0; i < struct_info.Count; i++)
2243 if (!CurrentUsageVector [index + i])
2249 public bool IsParameterAssigned (int number, string field_name)
2251 int index = param_map [number];
2256 MyStructInfo info = (MyStructInfo) struct_params [number];
2260 int field_idx = info [field_name];
2262 return CurrentUsageVector [index + field_idx];
2265 public void SetParameterAssigned (int number)
2267 if (param_map [number] == 0)
2270 if (!CurrentUsageVector.AlwaysBreaks)
2271 CurrentUsageVector [param_map [number]] = true;
2274 public void SetParameterAssigned (int number, string field_name)
2276 int index = param_map [number];
2281 MyStructInfo info = (MyStructInfo) struct_params [number];
2285 int field_idx = info [field_name];
2287 if (!CurrentUsageVector.AlwaysBreaks)
2288 CurrentUsageVector [index + field_idx] = true;
2291 public bool IsReachable ()
2296 case FlowBranchingType.SWITCH_SECTION:
2297 // The code following a switch block is reachable unless the switch
2298 // block always returns.
2299 reachable = !CurrentUsageVector.AlwaysReturns;
2302 case FlowBranchingType.LOOP_BLOCK:
2303 // The code following a loop is reachable unless the loop always
2304 // returns or it's an infinite loop without any `break's in it.
2305 reachable = !CurrentUsageVector.AlwaysReturns &&
2306 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2310 // The code following a block or exception is reachable unless the
2311 // block either always returns or always breaks.
2312 reachable = !CurrentUsageVector.AlwaysBreaks &&
2313 !CurrentUsageVector.AlwaysReturns;
2317 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2318 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2323 public override string ToString ()
2325 StringBuilder sb = new StringBuilder ("FlowBranching (");
2330 if (Block != null) {
2332 sb.Append (Block.ID);
2334 sb.Append (Block.StartLocation);
2337 sb.Append (Siblings.Count);
2339 sb.Append (CurrentUsageVector);
2341 return sb.ToString ();
2345 public class MyStructInfo {
2346 public readonly Type Type;
2347 public readonly FieldInfo[] Fields;
2348 public readonly FieldInfo[] NonPublicFields;
2349 public readonly int Count;
2350 public readonly int CountNonPublic;
2351 public readonly bool HasNonPublicFields;
2353 private static Hashtable field_type_hash = new Hashtable ();
2354 private Hashtable field_hash;
2356 // Private constructor. To save memory usage, we only need to create one instance
2357 // of this class per struct type.
2358 private MyStructInfo (Type type)
2362 if (type is TypeBuilder) {
2363 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2365 ArrayList fields = tc.Fields;
2366 if (fields != null) {
2367 foreach (Field field in fields) {
2368 if ((field.ModFlags & Modifiers.STATIC) != 0)
2370 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2377 Fields = new FieldInfo [Count];
2378 NonPublicFields = new FieldInfo [CountNonPublic];
2380 Count = CountNonPublic = 0;
2381 if (fields != null) {
2382 foreach (Field field in fields) {
2383 if ((field.ModFlags & Modifiers.STATIC) != 0)
2385 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2386 Fields [Count++] = field.FieldBuilder;
2388 NonPublicFields [CountNonPublic++] =
2394 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2395 Count = Fields.Length;
2397 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2398 CountNonPublic = NonPublicFields.Length;
2401 Count += NonPublicFields.Length;
2404 field_hash = new Hashtable ();
2405 foreach (FieldInfo field in Fields)
2406 field_hash.Add (field.Name, ++number);
2408 if (NonPublicFields.Length != 0)
2409 HasNonPublicFields = true;
2411 foreach (FieldInfo field in NonPublicFields)
2412 field_hash.Add (field.Name, ++number);
2415 public int this [string name] {
2417 if (field_hash.Contains (name))
2418 return (int) field_hash [name];
2424 public FieldInfo this [int index] {
2426 if (index >= Fields.Length)
2427 return NonPublicFields [index - Fields.Length];
2429 return Fields [index];
2433 public static MyStructInfo GetStructInfo (Type type)
2435 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2438 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2441 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2445 info = new MyStructInfo (type);
2446 field_type_hash.Add (type, info);
2450 public static MyStructInfo GetStructInfo (TypeContainer tc)
2452 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2456 info = new MyStructInfo (tc.TypeBuilder);
2457 field_type_hash.Add (tc.TypeBuilder, info);
2462 public class VariableInfo : IVariable {
2463 public Expression Type;
2464 public LocalBuilder LocalBuilder;
2465 public Type VariableType;
2466 public readonly string Name;
2467 public readonly Location Location;
2468 public readonly int Block;
2473 public bool Assigned;
2474 public bool ReadOnly;
2476 public VariableInfo (Expression type, string name, int block, Location l)
2481 LocalBuilder = null;
2485 public VariableInfo (TypeContainer tc, int block, Location l)
2487 VariableType = tc.TypeBuilder;
2488 struct_info = MyStructInfo.GetStructInfo (tc);
2490 LocalBuilder = null;
2494 MyStructInfo struct_info;
2495 public MyStructInfo StructInfo {
2501 public bool IsAssigned (EmitContext ec, Location loc)
2502 {/* FIXME: we shouldn't just skip this!!!
2503 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2506 MyStructInfo struct_info = StructInfo;
2507 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2508 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2509 ec.CurrentBranching.SetVariableAssigned (this);
2513 int count = struct_info.Count;
2515 for (int i = 0; i < count; i++) {
2516 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2518 Report.Error (165, loc,
2519 "Use of unassigned local variable `" +
2521 ec.CurrentBranching.SetVariableAssigned (this);
2525 FieldInfo field = struct_info [i];
2526 Report.Error (171, loc,
2527 "Field `" + TypeManager.MonoBASIC_Name (VariableType) +
2528 "." + field.Name + "' must be fully initialized " +
2529 "before control leaves the constructor");
2537 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2539 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2540 (struct_info == null))
2543 int field_idx = StructInfo [name];
2547 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2548 Report.Error (170, loc,
2549 "Use of possibly unassigned field `" + name + "'");
2550 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2557 public void SetAssigned (EmitContext ec)
2559 if (ec.DoFlowAnalysis)
2560 ec.CurrentBranching.SetVariableAssigned (this);
2563 public void SetFieldAssigned (EmitContext ec, string name)
2565 if (ec.DoFlowAnalysis && (struct_info != null))
2566 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2569 public bool Resolve (DeclSpace decl)
2571 if (struct_info != null)
2574 if (VariableType == null)
2575 VariableType = decl.ResolveType (Type, false, Location);
2577 if (VariableType == null)
2580 struct_info = MyStructInfo.GetStructInfo (VariableType);
2585 public void MakePinned ()
2587 TypeManager.MakePinned (LocalBuilder);
2590 public override string ToString ()
2592 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2597 /// Block represents a C# block.
2601 /// This class is used in a number of places: either to represent
2602 /// explicit blocks that the programmer places or implicit blocks.
2604 /// Implicit blocks are used as labels or to introduce variable
2607 public class Block : Statement {
2608 public readonly Block Parent;
2609 public readonly bool Implicit;
2610 public readonly Location StartLocation;
2611 public Location EndLocation;
2614 // The statements in this block
2616 public ArrayList statements;
2619 // An array of Blocks. We keep track of children just
2620 // to generate the local variable declarations.
2622 // Statements and child statements are handled through the
2628 // Labels. (label, block) pairs.
2630 CaseInsensitiveHashtable labels;
2633 // Keeps track of (name, type) pairs
2635 CaseInsensitiveHashtable variables;
2638 // Keeps track of constants
2639 CaseInsensitiveHashtable constants;
2642 // Maps variable names to ILGenerator.LocalBuilders
2644 CaseInsensitiveHashtable local_builders;
2652 public Block (Block parent)
2653 : this (parent, false, Location.Null, Location.Null)
2656 public Block (Block parent, bool implicit_block)
2657 : this (parent, implicit_block, Location.Null, Location.Null)
2660 public Block (Block parent, bool implicit_block, Parameters parameters)
2661 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2664 public Block (Block parent, Location start, Location end)
2665 : this (parent, false, start, end)
2668 public Block (Block parent, Parameters parameters, Location start, Location end)
2669 : this (parent, false, parameters, start, end)
2672 public Block (Block parent, bool implicit_block, Location start, Location end)
2673 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2677 public Block (Block parent, bool implicit_block, Parameters parameters,
2678 Location start, Location end)
2681 parent.AddChild (this);
2683 this.Parent = parent;
2684 this.Implicit = implicit_block;
2685 this.parameters = parameters;
2686 this.StartLocation = start;
2687 this.EndLocation = end;
2690 statements = new ArrayList ();
2699 void AddChild (Block b)
2701 if (children == null)
2702 children = new ArrayList ();
2707 public void SetEndLocation (Location loc)
2713 /// Adds a label to the current block.
2717 /// false if the name already exists in this block. true
2721 public bool AddLabel (string name, LabeledStatement target)
2724 labels = new CaseInsensitiveHashtable ();
2725 if (labels.Contains (name))
2728 labels.Add (name, target);
2732 public LabeledStatement LookupLabel (string name)
2734 if (labels != null){
2735 if (labels.Contains (name))
2736 return ((LabeledStatement) labels [name]);
2740 return Parent.LookupLabel (name);
2745 VariableInfo this_variable = null;
2748 // Returns the "this" instance variable of this block.
2749 // See AddThisVariable() for more information.
2751 public VariableInfo ThisVariable {
2753 if (this_variable != null)
2754 return this_variable;
2755 else if (Parent != null)
2756 return Parent.ThisVariable;
2762 Hashtable child_variable_names;
2765 // Marks a variable with name @name as being used in a child block.
2766 // If a variable name has been used in a child block, it's illegal to
2767 // declare a variable with the same name in the current block.
2769 public void AddChildVariableName (string name)
2771 if (child_variable_names == null)
2772 child_variable_names = new CaseInsensitiveHashtable ();
2774 if (!child_variable_names.Contains (name))
2775 child_variable_names.Add (name, true);
2779 // Marks all variables from block @block and all its children as being
2780 // used in a child block.
2782 public void AddChildVariableNames (Block block)
2784 if (block.Variables != null) {
2785 foreach (string name in block.Variables.Keys)
2786 AddChildVariableName (name);
2789 foreach (Block child in block.children) {
2790 if (child.Variables != null) {
2791 foreach (string name in child.Variables.Keys)
2792 AddChildVariableName (name);
2798 // Checks whether a variable name has already been used in a child block.
2800 public bool IsVariableNameUsedInChildBlock (string name)
2802 if (child_variable_names == null)
2805 return child_variable_names.Contains (name);
2809 // This is used by non-static `struct' constructors which do not have an
2810 // initializer - in this case, the constructor must initialize all of the
2811 // struct's fields. To do this, we add a "this" variable and use the flow
2812 // analysis code to ensure that it's been fully initialized before control
2813 // leaves the constructor.
2815 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2817 if (this_variable != null)
2818 return this_variable;
2820 this_variable = new VariableInfo (tc, ID, l);
2822 if (variables == null)
2823 variables = new CaseInsensitiveHashtable ();
2824 variables.Add ("this", this_variable);
2826 return this_variable;
2829 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2831 if (variables == null)
2832 variables = new CaseInsensitiveHashtable ();
2834 VariableInfo vi = GetVariableInfo (name);
2837 Report.Error (136, l, "A local variable named `" + name + "' " +
2838 "cannot be declared in this scope since it would " +
2839 "give a different meaning to `" + name + "', which " +
2840 "is already used in a `parent or current' scope to " +
2841 "denote something else");
2843 Report.Error (128, l, "A local variable `" + name + "' is already " +
2844 "defined in this scope");
2848 if (IsVariableNameUsedInChildBlock (name)) {
2849 Report.Error (136, l, "A local variable named `" + name + "' " +
2850 "cannot be declared in this scope since it would " +
2851 "give a different meaning to `" + name + "', which " +
2852 "is already used in a `child' scope to denote something " +
2859 Parameter p = pars.GetParameterByName (name, out idx);
2861 Report.Error (136, l, "A local variable named `" + name + "' " +
2862 "cannot be declared in this scope since it would " +
2863 "give a different meaning to `" + name + "', which " +
2864 "is already used in a `parent or current' scope to " +
2865 "denote something else");
2870 vi = new VariableInfo (type, name, ID, l);
2872 variables.Add (name, vi);
2874 if (variables_initialized)
2875 throw new Exception ();
2877 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2881 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2883 if (AddVariable (type, name, pars, l) == null)
2886 if (constants == null)
2887 constants = new CaseInsensitiveHashtable ();
2889 constants.Add (name, value);
2893 public Hashtable Variables {
2899 public VariableInfo GetVariableInfo (string name)
2901 if (variables != null) {
2903 temp = variables [name];
2906 return (VariableInfo) temp;
2911 return Parent.GetVariableInfo (name);
2916 public Expression GetVariableType (string name)
2918 VariableInfo vi = GetVariableInfo (name);
2926 public Expression GetConstantExpression (string name)
2928 if (constants != null) {
2930 temp = constants [name];
2933 return (Expression) temp;
2937 return Parent.GetConstantExpression (name);
2943 /// True if the variable named @name has been defined
2946 public bool IsVariableDefined (string name)
2948 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2949 if (variables != null) {
2950 if (variables.Contains (name))
2955 return Parent.IsVariableDefined (name);
2961 /// True if the variable named @name is a constant
2963 public bool IsConstant (string name)
2965 Expression e = null;
2967 e = GetConstantExpression (name);
2973 /// Use to fetch the statement associated with this label
2975 public Statement this [string name] {
2977 return (Statement) labels [name];
2981 Parameters parameters = null;
2982 public Parameters Parameters {
2985 return Parent.Parameters;
2992 /// A list of labels that were not used within this block
2994 public string [] GetUnreferenced ()
2996 // FIXME: Implement me
3000 public void AddStatement (Statement s)
3017 bool variables_initialized = false;
3018 int count_variables = 0, first_variable = 0;
3020 void UpdateVariableInfo (EmitContext ec)
3022 DeclSpace ds = ec.DeclSpace;
3027 first_variable += Parent.CountVariables;
3029 count_variables = first_variable;
3030 if (variables != null) {
3031 foreach (VariableInfo vi in variables.Values) {
3032 if (!vi.Resolve (ds)) {
3037 vi.Number = ++count_variables;
3039 if (vi.StructInfo != null)
3040 count_variables += vi.StructInfo.Count;
3044 variables_initialized = true;
3049 // The number of local variables in this block
3051 public int CountVariables
3054 if (!variables_initialized)
3055 throw new Exception ();
3057 return count_variables;
3062 /// Emits the variable declarations and labels.
3065 /// tc: is our typecontainer (to resolve type references)
3066 /// ig: is the code generator:
3067 /// toplevel: the toplevel block. This is used for checking
3068 /// that no two labels with the same name are used.
3070 public void EmitMeta (EmitContext ec, Block toplevel)
3072 DeclSpace ds = ec.DeclSpace;
3073 ILGenerator ig = ec.ig;
3075 if (!variables_initialized)
3076 UpdateVariableInfo (ec);
3079 // Process this block variables
3081 if (variables != null){
3082 local_builders = new CaseInsensitiveHashtable ();
3084 foreach (DictionaryEntry de in variables){
3085 string name = (string) de.Key;
3086 VariableInfo vi = (VariableInfo) de.Value;
3088 if (vi.VariableType == null)
3091 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3093 if (CodeGen.SymbolWriter != null)
3094 vi.LocalBuilder.SetLocalSymInfo (name);
3096 if (constants == null)
3099 Expression cv = (Expression) constants [name];
3103 Expression e = cv.Resolve (ec);
3107 if (!(e is Constant)){
3108 Report.Error (133, vi.Location,
3109 "The expression being assigned to `" +
3110 name + "' must be constant (" + e + ")");
3114 constants.Remove (name);
3115 constants.Add (name, e);
3120 // Now, handle the children
3122 if (children != null){
3123 foreach (Block b in children)
3124 b.EmitMeta (ec, toplevel);
3128 public void UsageWarning ()
3132 if (variables != null){
3133 foreach (DictionaryEntry de in variables){
3134 VariableInfo vi = (VariableInfo) de.Value;
3139 name = (string) de.Key;
3143 219, vi.Location, "The variable `" + name +
3144 "' is assigned but its value is never used");
3147 168, vi.Location, "The variable `" +
3149 "' is declared but never used");
3154 if (children != null)
3155 foreach (Block b in children)
3159 bool has_ret = false;
3161 public override bool Resolve (EmitContext ec)
3163 Block prev_block = ec.CurrentBlock;
3166 ec.CurrentBlock = this;
3167 ec.StartFlowBranching (this);
3169 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3171 if (!variables_initialized)
3172 UpdateVariableInfo (ec);
3174 ArrayList new_statements = new ArrayList ();
3175 bool unreachable = false, warning_shown = false;
3177 foreach (Statement s in statements){
3178 if (unreachable && !(s is LabeledStatement)) {
3179 if (!warning_shown && !(s is EmptyStatement)) {
3180 warning_shown = true;
3181 Warning_DeadCodeFound (s.loc);
3187 if (s.Resolve (ec) == false) {
3192 if (s is LabeledStatement)
3193 unreachable = false;
3195 unreachable = ! ec.CurrentBranching.IsReachable ();
3197 new_statements.Add (s);
3200 statements = new_statements;
3202 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3204 FlowReturns returns = ec.EndFlowBranching ();
3205 ec.CurrentBlock = prev_block;
3207 // If we're a non-static `struct' constructor which doesn't have an
3208 // initializer, then we must initialize all of the struct's fields.
3209 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3210 !this_variable.IsAssigned (ec, loc))
3213 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3214 foreach (LabeledStatement label in labels.Values)
3215 if (!label.HasBeenReferenced)
3216 Report.Warning (164, label.Location,
3217 "This label has not been referenced");
3220 if ((returns == FlowReturns.ALWAYS) ||
3221 (returns == FlowReturns.EXCEPTION) ||
3222 (returns == FlowReturns.UNREACHABLE))
3228 protected override bool DoEmit (EmitContext ec)
3230 Block prev_block = ec.CurrentBlock;
3232 ec.CurrentBlock = this;
3234 ec.Mark (StartLocation);
3235 foreach (Statement s in statements)
3238 ec.Mark (EndLocation);
3240 ec.CurrentBlock = prev_block;
3245 public class SwitchLabel {
3248 public Location loc;
3249 public Label ILLabel;
3250 public Label ILLabelCode;
3253 // if expr == null, then it is the default case.
3255 public SwitchLabel (Expression expr, Location l)
3261 public Expression Label {
3267 public object Converted {
3274 // Resolves the expression, reduces it to a literal if possible
3275 // and then converts it to the requested type.
3277 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3279 ILLabel = ec.ig.DefineLabel ();
3280 ILLabelCode = ec.ig.DefineLabel ();
3285 Expression e = label.Resolve (ec);
3290 if (!(e is Constant)){
3291 Console.WriteLine ("Value is: " + label);
3292 Report.Error (150, loc, "A constant value is expected");
3296 if (e is StringConstant || e is NullLiteral){
3297 if (required_type == TypeManager.string_type){
3299 ILLabel = ec.ig.DefineLabel ();
3304 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3305 if (converted == null)
3312 public class SwitchSection {
3313 // An array of SwitchLabels.
3314 public readonly ArrayList Labels;
3315 public readonly Block Block;
3317 public SwitchSection (ArrayList labels, Block block)
3324 public class Switch : Statement {
3325 public readonly ArrayList Sections;
3326 public Expression Expr;
3329 /// Maps constants whose type type SwitchType to their SwitchLabels.
3331 public Hashtable Elements;
3334 /// The governing switch type
3336 public Type SwitchType;
3342 Label default_target;
3343 Expression new_expr;
3346 // The types allowed to be implicitly cast from
3347 // on the governing type
3349 static Type [] allowed_types;
3351 public Switch (Expression e, ArrayList sects, Location l)
3358 public bool GotDefault {
3364 public Label DefaultTarget {
3366 return default_target;
3371 // Determines the governing type for a switch. The returned
3372 // expression might be the expression from the switch, or an
3373 // expression that includes any potential conversions to the
3374 // integral types or to string.
3376 Expression SwitchGoverningType (EmitContext ec, Type t)
3378 if (t == TypeManager.int32_type ||
3379 t == TypeManager.uint32_type ||
3380 t == TypeManager.char_type ||
3381 t == TypeManager.byte_type ||
3382 t == TypeManager.sbyte_type ||
3383 t == TypeManager.ushort_type ||
3384 t == TypeManager.short_type ||
3385 t == TypeManager.uint64_type ||
3386 t == TypeManager.int64_type ||
3387 t == TypeManager.string_type ||
3388 t == TypeManager.bool_type ||
3389 t.IsSubclassOf (TypeManager.enum_type))
3392 if (allowed_types == null){
3393 allowed_types = new Type [] {
3394 TypeManager.sbyte_type,
3395 TypeManager.byte_type,
3396 TypeManager.short_type,
3397 TypeManager.ushort_type,
3398 TypeManager.int32_type,
3399 TypeManager.uint32_type,
3400 TypeManager.int64_type,
3401 TypeManager.uint64_type,
3402 TypeManager.char_type,
3403 TypeManager.bool_type,
3404 TypeManager.string_type
3409 // Try to find a *user* defined implicit conversion.
3411 // If there is no implicit conversion, or if there are multiple
3412 // conversions, we have to report an error
3414 Expression converted = null;
3415 foreach (Type tt in allowed_types){
3418 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3422 if (converted != null){
3423 Report.Error (-12, loc, "More than one conversion to an integral " +
3424 " type exists for type `" +
3425 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3433 void error152 (string n)
3436 152, "The label `" + n + ":' " +
3437 "is already present on this switch statement");
3441 // Performs the basic sanity checks on the switch statement
3442 // (looks for duplicate keys and non-constant expressions).
3444 // It also returns a hashtable with the keys that we will later
3445 // use to compute the switch tables
3447 bool CheckSwitch (EmitContext ec)
3451 Elements = new CaseInsensitiveHashtable ();
3453 got_default = false;
3455 if (TypeManager.IsEnumType (SwitchType)){
3456 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3458 compare_type = SwitchType;
3460 foreach (SwitchSection ss in Sections){
3461 foreach (SwitchLabel sl in ss.Labels){
3462 if (!sl.ResolveAndReduce (ec, SwitchType)){
3467 if (sl.Label == null){
3469 error152 ("default");
3476 object key = sl.Converted;
3478 if (key is Constant)
3479 key = ((Constant) key).GetValue ();
3482 key = NullLiteral.Null;
3484 string lname = null;
3485 if (compare_type == TypeManager.uint64_type){
3486 ulong v = (ulong) key;
3488 if (Elements.Contains (v))
3489 lname = v.ToString ();
3491 Elements.Add (v, sl);
3492 } else if (compare_type == TypeManager.int64_type){
3493 long v = (long) key;
3495 if (Elements.Contains (v))
3496 lname = v.ToString ();
3498 Elements.Add (v, sl);
3499 } else if (compare_type == TypeManager.uint32_type){
3500 uint v = (uint) key;
3502 if (Elements.Contains (v))
3503 lname = v.ToString ();
3505 Elements.Add (v, sl);
3506 } else if (compare_type == TypeManager.char_type){
3507 char v = (char) key;
3509 if (Elements.Contains (v))
3510 lname = v.ToString ();
3512 Elements.Add (v, sl);
3513 } else if (compare_type == TypeManager.byte_type){
3514 byte v = (byte) key;
3516 if (Elements.Contains (v))
3517 lname = v.ToString ();
3519 Elements.Add (v, sl);
3520 } else if (compare_type == TypeManager.sbyte_type){
3521 sbyte v = (sbyte) key;
3523 if (Elements.Contains (v))
3524 lname = v.ToString ();
3526 Elements.Add (v, sl);
3527 } else if (compare_type == TypeManager.short_type){
3528 short v = (short) key;
3530 if (Elements.Contains (v))
3531 lname = v.ToString ();
3533 Elements.Add (v, sl);
3534 } else if (compare_type == TypeManager.ushort_type){
3535 ushort v = (ushort) key;
3537 if (Elements.Contains (v))
3538 lname = v.ToString ();
3540 Elements.Add (v, sl);
3541 } else if (compare_type == TypeManager.string_type){
3542 if (key is NullLiteral){
3543 if (Elements.Contains (NullLiteral.Null))
3546 Elements.Add (NullLiteral.Null, null);
3548 string s = (string) key;
3550 if (Elements.Contains (s))
3553 Elements.Add (s, sl);
3555 } else if (compare_type == TypeManager.int32_type) {
3558 if (Elements.Contains (v))
3559 lname = v.ToString ();
3561 Elements.Add (v, sl);
3562 } else if (compare_type == TypeManager.bool_type) {
3563 bool v = (bool) key;
3565 if (Elements.Contains (v))
3566 lname = v.ToString ();
3568 Elements.Add (v, sl);
3572 throw new Exception ("Unknown switch type!" +
3573 SwitchType + " " + compare_type);
3577 error152 ("case + " + lname);
3588 void EmitObjectInteger (ILGenerator ig, object k)
3591 IntConstant.EmitInt (ig, (int) k);
3592 else if (k is Constant) {
3593 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3596 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3599 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3601 IntConstant.EmitInt (ig, (int) (long) k);
3602 ig.Emit (OpCodes.Conv_I8);
3605 LongConstant.EmitLong (ig, (long) k);
3607 else if (k is ulong)
3609 if ((ulong) k < (1L<<32))
3611 IntConstant.EmitInt (ig, (int) (long) k);
3612 ig.Emit (OpCodes.Conv_U8);
3616 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3620 IntConstant.EmitInt (ig, (int) ((char) k));
3621 else if (k is sbyte)
3622 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3624 IntConstant.EmitInt (ig, (int) ((byte) k));
3625 else if (k is short)
3626 IntConstant.EmitInt (ig, (int) ((short) k));
3627 else if (k is ushort)
3628 IntConstant.EmitInt (ig, (int) ((ushort) k));
3630 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3632 throw new Exception ("Unhandled case");
3635 // structure used to hold blocks of keys while calculating table switch
3636 class KeyBlock : IComparable
3638 public KeyBlock (long _nFirst)
3640 nFirst = nLast = _nFirst;
3644 public ArrayList rgKeys = null;
3647 get { return (int) (nLast - nFirst + 1); }
3649 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3651 return kbLast.nLast - kbFirst.nFirst + 1;
3653 public int CompareTo (object obj)
3655 KeyBlock kb = (KeyBlock) obj;
3656 int nLength = Length;
3657 int nLengthOther = kb.Length;
3658 if (nLengthOther == nLength)
3659 return (int) (kb.nFirst - nFirst);
3660 return nLength - nLengthOther;
3665 /// This method emits code for a lookup-based switch statement (non-string)
3666 /// Basically it groups the cases into blocks that are at least half full,
3667 /// and then spits out individual lookup opcodes for each block.
3668 /// It emits the longest blocks first, and short blocks are just
3669 /// handled with direct compares.
3671 /// <param name="ec"></param>
3672 /// <param name="val"></param>
3673 /// <returns></returns>
3674 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3676 int cElements = Elements.Count;
3677 object [] rgKeys = new object [cElements];
3678 Elements.Keys.CopyTo (rgKeys, 0);
3679 Array.Sort (rgKeys);
3681 // initialize the block list with one element per key
3682 ArrayList rgKeyBlocks = new ArrayList ();
3683 foreach (object key in rgKeys)
3684 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3687 // iteratively merge the blocks while they are at least half full
3688 // there's probably a really cool way to do this with a tree...
3689 while (rgKeyBlocks.Count > 1)
3691 ArrayList rgKeyBlocksNew = new ArrayList ();
3692 kbCurr = (KeyBlock) rgKeyBlocks [0];
3693 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3695 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3696 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3699 kbCurr.nLast = kb.nLast;
3703 // start a new block
3704 rgKeyBlocksNew.Add (kbCurr);
3708 rgKeyBlocksNew.Add (kbCurr);
3709 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3711 rgKeyBlocks = rgKeyBlocksNew;
3714 // initialize the key lists
3715 foreach (KeyBlock kb in rgKeyBlocks)
3716 kb.rgKeys = new ArrayList ();
3718 // fill the key lists
3720 if (rgKeyBlocks.Count > 0) {
3721 kbCurr = (KeyBlock) rgKeyBlocks [0];
3722 foreach (object key in rgKeys)
3724 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3726 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3727 kbCurr.rgKeys.Add (key);
3731 // sort the blocks so we can tackle the largest ones first
3732 rgKeyBlocks.Sort ();
3734 // okay now we can start...
3735 ILGenerator ig = ec.ig;
3736 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3737 Label lblDefault = ig.DefineLabel ();
3739 Type typeKeys = null;
3740 if (rgKeys.Length > 0)
3741 typeKeys = rgKeys [0].GetType (); // used for conversions
3743 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3745 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3746 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3749 foreach (object key in kb.rgKeys)
3751 ig.Emit (OpCodes.Ldloc, val);
3752 EmitObjectInteger (ig, key);
3753 SwitchLabel sl = (SwitchLabel) Elements [key];
3754 ig.Emit (OpCodes.Beq, sl.ILLabel);
3759 // TODO: if all the keys in the block are the same and there are
3760 // no gaps/defaults then just use a range-check.
3761 if (SwitchType == TypeManager.int64_type ||
3762 SwitchType == TypeManager.uint64_type)
3764 // TODO: optimize constant/I4 cases
3766 // check block range (could be > 2^31)
3767 ig.Emit (OpCodes.Ldloc, val);
3768 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3769 ig.Emit (OpCodes.Blt, lblDefault);
3770 ig.Emit (OpCodes.Ldloc, val);
3771 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3772 ig.Emit (OpCodes.Bgt, lblDefault);
3775 ig.Emit (OpCodes.Ldloc, val);
3778 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3779 ig.Emit (OpCodes.Sub);
3781 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3786 ig.Emit (OpCodes.Ldloc, val);
3787 int nFirst = (int) kb.nFirst;
3790 IntConstant.EmitInt (ig, nFirst);
3791 ig.Emit (OpCodes.Sub);
3793 else if (nFirst < 0)
3795 IntConstant.EmitInt (ig, -nFirst);
3796 ig.Emit (OpCodes.Add);
3800 // first, build the list of labels for the switch
3802 int cJumps = kb.Length;
3803 Label [] rgLabels = new Label [cJumps];
3804 for (int iJump = 0; iJump < cJumps; iJump++)
3806 object key = kb.rgKeys [iKey];
3807 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3809 SwitchLabel sl = (SwitchLabel) Elements [key];
3810 rgLabels [iJump] = sl.ILLabel;
3814 rgLabels [iJump] = lblDefault;
3816 // emit the switch opcode
3817 ig.Emit (OpCodes.Switch, rgLabels);
3820 // mark the default for this block
3822 ig.MarkLabel (lblDefault);
3825 // TODO: find the default case and emit it here,
3826 // to prevent having to do the following jump.
3827 // make sure to mark other labels in the default section
3829 // the last default just goes to the end
3830 ig.Emit (OpCodes.Br, lblDefault);
3832 // now emit the code for the sections
3833 bool fFoundDefault = false;
3834 bool fAllReturn = true;
3835 foreach (SwitchSection ss in Sections)
3837 foreach (SwitchLabel sl in ss.Labels)
3839 ig.MarkLabel (sl.ILLabel);
3840 ig.MarkLabel (sl.ILLabelCode);
3841 if (sl.Label == null)
3843 ig.MarkLabel (lblDefault);
3844 fFoundDefault = true;
3847 bool returns = ss.Block.Emit (ec);
3848 fAllReturn &= returns;
3849 //ig.Emit (OpCodes.Br, lblEnd);
3852 if (!fFoundDefault) {
3853 ig.MarkLabel (lblDefault);
3856 ig.MarkLabel (lblEnd);
3861 // This simple emit switch works, but does not take advantage of the
3863 // TODO: remove non-string logic from here
3864 // TODO: binary search strings?
3866 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3868 ILGenerator ig = ec.ig;
3869 Label end_of_switch = ig.DefineLabel ();
3870 Label next_test = ig.DefineLabel ();
3871 Label null_target = ig.DefineLabel ();
3872 bool default_found = false;
3873 bool first_test = true;
3874 bool pending_goto_end = false;
3875 bool all_return = true;
3876 bool is_string = false;
3880 // Special processing for strings: we cant compare
3883 if (SwitchType == TypeManager.string_type){
3884 ig.Emit (OpCodes.Ldloc, val);
3887 if (Elements.Contains (NullLiteral.Null)){
3888 ig.Emit (OpCodes.Brfalse, null_target);
3890 ig.Emit (OpCodes.Brfalse, default_target);
3892 ig.Emit (OpCodes.Ldloc, val);
3893 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3894 ig.Emit (OpCodes.Stloc, val);
3897 foreach (SwitchSection ss in Sections){
3898 Label sec_begin = ig.DefineLabel ();
3900 if (pending_goto_end)
3901 ig.Emit (OpCodes.Br, end_of_switch);
3903 int label_count = ss.Labels.Count;
3905 foreach (SwitchLabel sl in ss.Labels){
3906 ig.MarkLabel (sl.ILLabel);
3909 ig.MarkLabel (next_test);
3910 next_test = ig.DefineLabel ();
3913 // If we are the default target
3915 if (sl.Label == null){
3916 ig.MarkLabel (default_target);
3917 default_found = true;
3919 object lit = sl.Converted;
3921 if (lit is NullLiteral){
3923 if (label_count == 1)
3924 ig.Emit (OpCodes.Br, next_test);
3929 StringConstant str = (StringConstant) lit;
3931 ig.Emit (OpCodes.Ldloc, val);
3932 ig.Emit (OpCodes.Ldstr, str.Value);
3933 if (label_count == 1)
3934 ig.Emit (OpCodes.Bne_Un, next_test);
3936 ig.Emit (OpCodes.Beq, sec_begin);
3938 ig.Emit (OpCodes.Ldloc, val);
3939 EmitObjectInteger (ig, lit);
3940 ig.Emit (OpCodes.Ceq);
3941 if (label_count == 1)
3942 ig.Emit (OpCodes.Brfalse, next_test);
3944 ig.Emit (OpCodes.Brtrue, sec_begin);
3948 if (label_count != 1)
3949 ig.Emit (OpCodes.Br, next_test);
3952 ig.MarkLabel (null_target);
3953 ig.MarkLabel (sec_begin);
3954 foreach (SwitchLabel sl in ss.Labels)
3955 ig.MarkLabel (sl.ILLabelCode);
3957 bool returns = ss.Block.Emit (ec);
3959 pending_goto_end = false;
3962 pending_goto_end = true;
3966 if (!default_found){
3967 ig.MarkLabel (default_target);
3970 ig.MarkLabel (next_test);
3971 ig.MarkLabel (end_of_switch);
3976 public override bool Resolve (EmitContext ec)
3978 Expr = Expr.Resolve (ec);
3982 new_expr = SwitchGoverningType (ec, Expr.Type);
3983 if (new_expr == null){
3984 Report.Error (151, loc, "An integer type or string was expected for switch");
3989 SwitchType = new_expr.Type;
3991 if (!CheckSwitch (ec))
3994 Switch old_switch = ec.Switch;
3996 ec.Switch.SwitchType = SwitchType;
3998 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
4001 foreach (SwitchSection ss in Sections){
4003 ec.CurrentBranching.CreateSibling ();
4007 if (ss.Block.Resolve (ec) != true)
4013 ec.CurrentBranching.CreateSibling ();
4015 ec.EndFlowBranching ();
4016 ec.Switch = old_switch;
4021 protected override bool DoEmit (EmitContext ec)
4023 // Store variable for comparission purposes
4024 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
4026 ec.ig.Emit (OpCodes.Stloc, value);
4028 ILGenerator ig = ec.ig;
4030 default_target = ig.DefineLabel ();
4033 // Setup the codegen context
4035 Label old_end = ec.LoopEnd;
4036 Switch old_switch = ec.Switch;
4038 ec.LoopEnd = ig.DefineLabel ();
4043 if (SwitchType == TypeManager.string_type)
4044 all_return = SimpleSwitchEmit (ec, value);
4046 all_return = TableSwitchEmit (ec, value);
4048 // Restore context state.
4049 ig.MarkLabel (ec.LoopEnd);
4052 // Restore the previous context
4054 ec.LoopEnd = old_end;
4055 ec.Switch = old_switch;
4061 public class Lock : Statement {
4063 Statement Statement;
4065 public Lock (Expression expr, Statement stmt, Location l)
4072 public override bool Resolve (EmitContext ec)
4074 expr = expr.Resolve (ec);
4075 return Statement.Resolve (ec) && expr != null;
4078 protected override bool DoEmit (EmitContext ec)
4080 Type type = expr.Type;
4083 if (type.IsValueType){
4084 Report.Error (185, loc, "lock statement requires the expression to be " +
4085 " a reference type (type is: `" +
4086 TypeManager.MonoBASIC_Name (type) + "'");
4090 ILGenerator ig = ec.ig;
4091 LocalBuilder temp = ig.DeclareLocal (type);
4094 ig.Emit (OpCodes.Dup);
4095 ig.Emit (OpCodes.Stloc, temp);
4096 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4099 Label end = ig.BeginExceptionBlock ();
4100 bool old_in_try = ec.InTry;
4102 Label finish = ig.DefineLabel ();
4103 val = Statement.Emit (ec);
4104 ec.InTry = old_in_try;
4105 // ig.Emit (OpCodes.Leave, finish);
4107 ig.MarkLabel (finish);
4110 ig.BeginFinallyBlock ();
4111 ig.Emit (OpCodes.Ldloc, temp);
4112 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4113 ig.EndExceptionBlock ();
4119 public class Unchecked : Statement {
4120 public readonly Block Block;
4122 public Unchecked (Block b)
4127 public override bool Resolve (EmitContext ec)
4129 return Block.Resolve (ec);
4132 protected override bool DoEmit (EmitContext ec)
4134 bool previous_state = ec.CheckState;
4135 bool previous_state_const = ec.ConstantCheckState;
4138 ec.CheckState = false;
4139 ec.ConstantCheckState = false;
4140 val = Block.Emit (ec);
4141 ec.CheckState = previous_state;
4142 ec.ConstantCheckState = previous_state_const;
4148 public class Checked : Statement {
4149 public readonly Block Block;
4151 public Checked (Block b)
4156 public override bool Resolve (EmitContext ec)
4158 bool previous_state = ec.CheckState;
4159 bool previous_state_const = ec.ConstantCheckState;
4161 ec.CheckState = true;
4162 ec.ConstantCheckState = true;
4163 bool ret = Block.Resolve (ec);
4164 ec.CheckState = previous_state;
4165 ec.ConstantCheckState = previous_state_const;
4170 protected override bool DoEmit (EmitContext ec)
4172 bool previous_state = ec.CheckState;
4173 bool previous_state_const = ec.ConstantCheckState;
4176 ec.CheckState = true;
4177 ec.ConstantCheckState = true;
4178 val = Block.Emit (ec);
4179 ec.CheckState = previous_state;
4180 ec.ConstantCheckState = previous_state_const;
4186 public class Unsafe : Statement {
4187 public readonly Block Block;
4189 public Unsafe (Block b)
4194 public override bool Resolve (EmitContext ec)
4196 bool previous_state = ec.InUnsafe;
4200 val = Block.Resolve (ec);
4201 ec.InUnsafe = previous_state;
4206 protected override bool DoEmit (EmitContext ec)
4208 bool previous_state = ec.InUnsafe;
4212 val = Block.Emit (ec);
4213 ec.InUnsafe = previous_state;
4222 public class Fixed : Statement {
4224 ArrayList declarators;
4225 Statement statement;
4230 public bool is_object;
4231 public VariableInfo vi;
4232 public Expression expr;
4233 public Expression converted;
4236 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4239 declarators = decls;
4244 public override bool Resolve (EmitContext ec)
4246 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4247 if (expr_type == null)
4250 data = new FixedData [declarators.Count];
4253 foreach (Pair p in declarators){
4254 VariableInfo vi = (VariableInfo) p.First;
4255 Expression e = (Expression) p.Second;
4260 // The rules for the possible declarators are pretty wise,
4261 // but the production on the grammar is more concise.
4263 // So we have to enforce these rules here.
4265 // We do not resolve before doing the case 1 test,
4266 // because the grammar is explicit in that the token &
4267 // is present, so we need to test for this particular case.
4271 // Case 1: & object.
4273 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4274 Expression child = ((Unary) e).Expr;
4277 if (child is ParameterReference || child is LocalVariableReference){
4280 "No need to use fixed statement for parameters or " +
4281 "local variable declarations (address is already " +
4290 child = ((Unary) e).Expr;
4292 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4295 data [i].is_object = true;
4297 data [i].converted = null;
4311 if (e.Type.IsArray){
4312 Type array_type = e.Type.GetElementType ();
4316 // Provided that array_type is unmanaged,
4318 if (!TypeManager.VerifyUnManaged (array_type, loc))
4322 // and T* is implicitly convertible to the
4323 // pointer type given in the fixed statement.
4325 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4327 Expression converted = Expression.ConvertImplicitRequired (
4328 ec, array_ptr, vi.VariableType, loc);
4329 if (converted == null)
4332 data [i].is_object = false;
4334 data [i].converted = converted;
4344 if (e.Type == TypeManager.string_type){
4345 data [i].is_object = false;
4347 data [i].converted = null;
4353 return statement.Resolve (ec);
4356 protected override bool DoEmit (EmitContext ec)
4358 ILGenerator ig = ec.ig;
4360 bool is_ret = false;
4362 for (int i = 0; i < data.Length; i++) {
4363 VariableInfo vi = data [i].vi;
4366 // Case 1: & object.
4368 if (data [i].is_object) {
4370 // Store pointer in pinned location
4372 data [i].expr.Emit (ec);
4373 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4375 is_ret = statement.Emit (ec);
4377 // Clear the pinned variable.
4378 ig.Emit (OpCodes.Ldc_I4_0);
4379 ig.Emit (OpCodes.Conv_U);
4380 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4388 if (data [i].expr.Type.IsArray){
4390 // Store pointer in pinned location
4392 data [i].converted.Emit (ec);
4394 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4396 is_ret = statement.Emit (ec);
4398 // Clear the pinned variable.
4399 ig.Emit (OpCodes.Ldc_I4_0);
4400 ig.Emit (OpCodes.Conv_U);
4401 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4409 if (data [i].expr.Type == TypeManager.string_type){
4410 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4411 TypeManager.MakePinned (pinned_string);
4413 data [i].expr.Emit (ec);
4414 ig.Emit (OpCodes.Stloc, pinned_string);
4416 Expression sptr = new StringPtr (pinned_string, loc);
4417 Expression converted = Expression.ConvertImplicitRequired (
4418 ec, sptr, vi.VariableType, loc);
4420 if (converted == null)
4423 converted.Emit (ec);
4424 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4426 is_ret = statement.Emit (ec);
4428 // Clear the pinned variable
4429 ig.Emit (OpCodes.Ldnull);
4430 ig.Emit (OpCodes.Stloc, pinned_string);
4438 public class Catch {
4439 public readonly string Name;
4440 public readonly Block Block;
4441 public readonly Location Location;
4443 Expression type_expr;
4446 public Catch (Expression type, string name, Block block, Location l)
4454 public Type CatchType {
4460 public bool IsGeneral {
4462 return type_expr == null;
4466 public bool Resolve (EmitContext ec)
4468 if (type_expr != null) {
4469 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4473 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4474 Report.Error (155, Location,
4475 "The type caught or thrown must be derived " +
4476 "from System.Exception");
4482 if (!Block.Resolve (ec))
4489 public class Try : Statement {
4490 public readonly Block Fini, Block;
4491 public readonly ArrayList Specific;
4492 public readonly Catch General;
4495 // specific, general and fini might all be null.
4497 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4499 if (specific == null && general == null){
4500 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4504 this.Specific = specific;
4505 this.General = general;
4510 public override bool Resolve (EmitContext ec)
4514 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4516 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4518 bool old_in_try = ec.InTry;
4521 if (!Block.Resolve (ec))
4524 ec.InTry = old_in_try;
4526 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4528 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4530 foreach (Catch c in Specific){
4531 ec.CurrentBranching.CreateSibling ();
4532 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4534 if (c.Name != null) {
4535 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4537 throw new Exception ();
4542 bool old_in_catch = ec.InCatch;
4545 if (!c.Resolve (ec))
4548 ec.InCatch = old_in_catch;
4550 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4552 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4553 vector.AndLocals (current);
4556 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4558 if (General != null){
4559 ec.CurrentBranching.CreateSibling ();
4560 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4562 bool old_in_catch = ec.InCatch;
4565 if (!General.Resolve (ec))
4568 ec.InCatch = old_in_catch;
4570 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4572 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4573 vector.AndLocals (current);
4576 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4579 ec.CurrentBranching.CreateSiblingForFinally ();
4580 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4582 bool old_in_finally = ec.InFinally;
4583 ec.InFinally = true;
4585 if (!Fini.Resolve (ec))
4588 ec.InFinally = old_in_finally;
4591 FlowReturns returns = ec.EndFlowBranching ();
4593 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4595 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4597 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4598 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4601 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4603 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4608 protected override bool DoEmit (EmitContext ec)
4610 ILGenerator ig = ec.ig;
4612 Label finish = ig.DefineLabel ();;
4616 end = ig.BeginExceptionBlock ();
4617 bool old_in_try = ec.InTry;
4619 returns = Block.Emit (ec);
4620 ec.InTry = old_in_try;
4623 // System.Reflection.Emit provides this automatically:
4624 // ig.Emit (OpCodes.Leave, finish);
4626 bool old_in_catch = ec.InCatch;
4628 DeclSpace ds = ec.DeclSpace;
4630 foreach (Catch c in Specific){
4633 ig.BeginCatchBlock (c.CatchType);
4635 if (c.Name != null){
4636 vi = c.Block.GetVariableInfo (c.Name);
4638 throw new Exception ("Variable does not exist in this block");
4640 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4642 ig.Emit (OpCodes.Pop);
4644 if (!c.Block.Emit (ec))
4648 if (General != null){
4649 ig.BeginCatchBlock (TypeManager.object_type);
4650 ig.Emit (OpCodes.Pop);
4651 if (!General.Block.Emit (ec))
4654 ec.InCatch = old_in_catch;
4656 ig.MarkLabel (finish);
4658 ig.BeginFinallyBlock ();
4659 bool old_in_finally = ec.InFinally;
4660 ec.InFinally = true;
4662 ec.InFinally = old_in_finally;
4665 ig.EndExceptionBlock ();
4668 if (!returns || ec.InTry || ec.InCatch)
4671 // Unfortunately, System.Reflection.Emit automatically emits a leave
4672 // to the end of the finally block. This is a problem if `returns'
4673 // is true since we may jump to a point after the end of the method.
4674 // As a workaround, emit an explicit ret here.
4676 if (ec.ReturnType != null)
4677 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4678 ec.ig.Emit (OpCodes.Ret);
4684 public class Using : Statement {
4685 object expression_or_block;
4686 Statement Statement;
4691 Expression [] converted_vars;
4692 ExpressionStatement [] assign;
4694 public Using (object expression_or_block, Statement stmt, Location l)
4696 this.expression_or_block = expression_or_block;
4702 // Resolves for the case of using using a local variable declaration.
4704 bool ResolveLocalVariableDecls (EmitContext ec)
4706 bool need_conv = false;
4707 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4710 if (expr_type == null)
4714 // The type must be an IDisposable or an implicit conversion
4717 converted_vars = new Expression [var_list.Count];
4718 assign = new ExpressionStatement [var_list.Count];
4719 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4720 foreach (DictionaryEntry e in var_list){
4721 Expression var = (Expression) e.Key;
4723 var = var.ResolveLValue (ec, new EmptyExpression ());
4727 converted_vars [i] = Expression.ConvertImplicitRequired (
4728 ec, var, TypeManager.idisposable_type, loc);
4730 if (converted_vars [i] == null)
4738 foreach (DictionaryEntry e in var_list){
4739 LocalVariableReference var = (LocalVariableReference) e.Key;
4740 Expression new_expr = (Expression) e.Value;
4743 a = new Assign (var, new_expr, loc);
4749 converted_vars [i] = var;
4750 assign [i] = (ExpressionStatement) a;
4757 bool ResolveExpression (EmitContext ec)
4759 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4760 conv = Expression.ConvertImplicitRequired (
4761 ec, expr, TypeManager.idisposable_type, loc);
4771 // Emits the code for the case of using using a local variable declaration.
4773 bool EmitLocalVariableDecls (EmitContext ec)
4775 ILGenerator ig = ec.ig;
4778 bool old_in_try = ec.InTry;
4780 for (i = 0; i < assign.Length; i++) {
4781 assign [i].EmitStatement (ec);
4783 ig.BeginExceptionBlock ();
4785 Statement.Emit (ec);
4786 ec.InTry = old_in_try;
4788 bool old_in_finally = ec.InFinally;
4789 ec.InFinally = true;
4790 var_list.Reverse ();
4791 foreach (DictionaryEntry e in var_list){
4792 LocalVariableReference var = (LocalVariableReference) e.Key;
4793 Label skip = ig.DefineLabel ();
4796 ig.BeginFinallyBlock ();
4799 ig.Emit (OpCodes.Brfalse, skip);
4800 converted_vars [i].Emit (ec);
4801 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4802 ig.MarkLabel (skip);
4803 ig.EndExceptionBlock ();
4805 ec.InFinally = old_in_finally;
4810 bool EmitExpression (EmitContext ec)
4813 // Make a copy of the expression and operate on that.
4815 ILGenerator ig = ec.ig;
4816 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4821 ig.Emit (OpCodes.Stloc, local_copy);
4823 bool old_in_try = ec.InTry;
4825 ig.BeginExceptionBlock ();
4826 Statement.Emit (ec);
4827 ec.InTry = old_in_try;
4829 Label skip = ig.DefineLabel ();
4830 bool old_in_finally = ec.InFinally;
4831 ig.BeginFinallyBlock ();
4832 ig.Emit (OpCodes.Ldloc, local_copy);
4833 ig.Emit (OpCodes.Brfalse, skip);
4834 ig.Emit (OpCodes.Ldloc, local_copy);
4835 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4836 ig.MarkLabel (skip);
4837 ec.InFinally = old_in_finally;
4838 ig.EndExceptionBlock ();
4843 public override bool Resolve (EmitContext ec)
4845 if (expression_or_block is DictionaryEntry){
4846 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4847 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4849 if (!ResolveLocalVariableDecls (ec))
4852 } else if (expression_or_block is Expression){
4853 expr = (Expression) expression_or_block;
4855 expr = expr.Resolve (ec);
4859 expr_type = expr.Type;
4861 if (!ResolveExpression (ec))
4865 return Statement.Resolve (ec);
4868 protected override bool DoEmit (EmitContext ec)
4870 if (expression_or_block is DictionaryEntry)
4871 return EmitLocalVariableDecls (ec);
4872 else if (expression_or_block is Expression)
4873 return EmitExpression (ec);
4880 /// Implementation of the foreach C# statement
4882 public class Foreach : Statement {
4884 LocalVariableReference variable;
4886 Statement statement;
4887 ForeachHelperMethods hm;
4888 Expression empty, conv;
4889 Type array_type, element_type;
4892 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4893 Statement stmt, Location l)
4900 VariableInfo vi = var.VariableInfo;
4901 this.type = vi.Type;
4903 this.variable = var;
4909 public override bool Resolve (EmitContext ec)
4911 expr = expr.Resolve (ec);
4915 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4916 if (var_type == null)
4920 // We need an instance variable. Not sure this is the best
4921 // way of doing this.
4923 // FIXME: When we implement propertyaccess, will those turn
4924 // out to return values in ExprClass? I think they should.
4926 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4927 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4928 error1579 (expr.Type);
4932 if (expr.Type.IsArray) {
4933 array_type = expr.Type;
4934 element_type = array_type.GetElementType ();
4936 empty = new EmptyExpression (element_type);
4938 hm = ProbeCollectionType (ec, expr.Type);
4940 error1579 (expr.Type);
4944 array_type = expr.Type;
4945 element_type = hm.element_type;
4947 empty = new EmptyExpression (hm.element_type);
4950 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4951 ec.CurrentBranching.CreateSibling ();
4955 // FIXME: maybe we can apply the same trick we do in the
4956 // array handling to avoid creating empty and conv in some cases.
4958 // Although it is not as important in this case, as the type
4959 // will not likely be object (what the enumerator will return).
4961 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4965 if (variable.ResolveLValue (ec, empty) == null)
4968 if (!statement.Resolve (ec))
4971 FlowReturns returns = ec.EndFlowBranching ();
4977 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4979 static MethodInfo FetchMethodMoveNext (Type t)
4981 MemberList move_next_list;
4983 move_next_list = TypeContainer.FindMembers (
4984 t, MemberTypes.Method,
4985 BindingFlags.Public | BindingFlags.Instance,
4986 Type.FilterName, "MoveNext");
4987 if (move_next_list.Count == 0)
4990 foreach (MemberInfo m in move_next_list){
4991 MethodInfo mi = (MethodInfo) m;
4994 args = TypeManager.GetArgumentTypes (mi);
4995 if (args != null && args.Length == 0){
4996 if (mi.ReturnType == TypeManager.bool_type)
5004 // Retrieves a `public T get_Current ()' method from the Type `t'
5006 static MethodInfo FetchMethodGetCurrent (Type t)
5008 MemberList move_next_list;
5010 move_next_list = TypeContainer.FindMembers (
5011 t, MemberTypes.Method,
5012 BindingFlags.Public | BindingFlags.Instance,
5013 Type.FilterName, "get_Current");
5014 if (move_next_list.Count == 0)
5017 foreach (MemberInfo m in move_next_list){
5018 MethodInfo mi = (MethodInfo) m;
5021 args = TypeManager.GetArgumentTypes (mi);
5022 if (args != null && args.Length == 0)
5029 // This struct records the helper methods used by the Foreach construct
5031 class ForeachHelperMethods {
5032 public EmitContext ec;
5033 public MethodInfo get_enumerator;
5034 public MethodInfo move_next;
5035 public MethodInfo get_current;
5036 public Type element_type;
5037 public Type enumerator_type;
5038 public bool is_disposable;
5040 public ForeachHelperMethods (EmitContext ec)
5043 this.element_type = TypeManager.object_type;
5044 this.enumerator_type = TypeManager.ienumerator_type;
5045 this.is_disposable = true;
5049 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5054 if (!(m is MethodInfo))
5057 if (m.Name != "GetEnumerator")
5060 MethodInfo mi = (MethodInfo) m;
5061 Type [] args = TypeManager.GetArgumentTypes (mi);
5063 if (args.Length != 0)
5066 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5067 EmitContext ec = hm.ec;
5070 // Check whether GetEnumerator is accessible to us
5072 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5074 Type declaring = mi.DeclaringType;
5075 if (prot == MethodAttributes.Private){
5076 if (declaring != ec.ContainerType)
5078 } else if (prot == MethodAttributes.FamANDAssem){
5079 // If from a different assembly, false
5080 if (!(mi is MethodBuilder))
5083 // Are we being invoked from the same class, or from a derived method?
5085 if (ec.ContainerType != declaring){
5086 if (!ec.ContainerType.IsSubclassOf (declaring))
5089 } else if (prot == MethodAttributes.FamORAssem){
5090 if (!(mi is MethodBuilder ||
5091 ec.ContainerType == declaring ||
5092 ec.ContainerType.IsSubclassOf (declaring)))
5094 } if (prot == MethodAttributes.Family){
5095 if (!(ec.ContainerType == declaring ||
5096 ec.ContainerType.IsSubclassOf (declaring)))
5101 // Ok, we can access it, now make sure that we can do something
5102 // with this `GetEnumerator'
5105 if (mi.ReturnType == TypeManager.ienumerator_type ||
5106 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5107 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5108 hm.move_next = TypeManager.bool_movenext_void;
5109 hm.get_current = TypeManager.object_getcurrent_void;
5114 // Ok, so they dont return an IEnumerable, we will have to
5115 // find if they support the GetEnumerator pattern.
5117 Type return_type = mi.ReturnType;
5119 hm.move_next = FetchMethodMoveNext (return_type);
5120 if (hm.move_next == null)
5122 hm.get_current = FetchMethodGetCurrent (return_type);
5123 if (hm.get_current == null)
5126 hm.element_type = hm.get_current.ReturnType;
5127 hm.enumerator_type = return_type;
5128 hm.is_disposable = TypeManager.ImplementsInterface (
5129 hm.enumerator_type, TypeManager.idisposable_type);
5135 /// This filter is used to find the GetEnumerator method
5136 /// on which IEnumerator operates
5138 static MemberFilter FilterEnumerator;
5142 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5145 void error1579 (Type t)
5147 Report.Error (1579, loc,
5148 "foreach statement cannot operate on variables of type `" +
5149 t.FullName + "' because that class does not provide a " +
5150 " GetEnumerator method or it is inaccessible");
5153 static bool TryType (Type t, ForeachHelperMethods hm)
5157 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5158 BindingFlags.Public | BindingFlags.NonPublic |
5159 BindingFlags.Instance,
5160 FilterEnumerator, hm);
5165 hm.get_enumerator = (MethodInfo) mi [0];
5170 // Looks for a usable GetEnumerator in the Type, and if found returns
5171 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5173 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5175 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5177 if (TryType (t, hm))
5181 // Now try to find the method in the interfaces
5184 Type [] ifaces = t.GetInterfaces ();
5186 foreach (Type i in ifaces){
5187 if (TryType (i, hm))
5192 // Since TypeBuilder.GetInterfaces only returns the interface
5193 // types for this type, we have to keep looping, but once
5194 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5195 // done, because it returns all the types
5197 if ((t is TypeBuilder))
5207 // FIXME: possible optimization.
5208 // We might be able to avoid creating `empty' if the type is the sam
5210 bool EmitCollectionForeach (EmitContext ec)
5212 ILGenerator ig = ec.ig;
5213 LocalBuilder enumerator, disposable;
5215 enumerator = ig.DeclareLocal (hm.enumerator_type);
5216 if (hm.is_disposable)
5217 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5222 // Instantiate the enumerator
5224 if (expr.Type.IsValueType){
5225 if (expr is IMemoryLocation){
5226 IMemoryLocation ml = (IMemoryLocation) expr;
5228 ml.AddressOf (ec, AddressOp.Load);
5230 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5231 " does not implement IMemoryLocation");
5232 ig.Emit (OpCodes.Call, hm.get_enumerator);
5235 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5237 ig.Emit (OpCodes.Stloc, enumerator);
5240 // Protect the code in a try/finalize block, so that
5241 // if the beast implement IDisposable, we get rid of it
5244 bool old_in_try = ec.InTry;
5246 if (hm.is_disposable) {
5247 l = ig.BeginExceptionBlock ();
5251 Label end_try = ig.DefineLabel ();
5253 ig.MarkLabel (ec.LoopBegin);
5254 ig.Emit (OpCodes.Ldloc, enumerator);
5255 ig.Emit (OpCodes.Callvirt, hm.move_next);
5256 ig.Emit (OpCodes.Brfalse, end_try);
5257 ig.Emit (OpCodes.Ldloc, enumerator);
5258 ig.Emit (OpCodes.Callvirt, hm.get_current);
5259 variable.EmitAssign (ec, conv);
5260 statement.Emit (ec);
5261 ig.Emit (OpCodes.Br, ec.LoopBegin);
5262 ig.MarkLabel (end_try);
5263 ec.InTry = old_in_try;
5265 // The runtime provides this for us.
5266 // ig.Emit (OpCodes.Leave, end);
5269 // Now the finally block
5271 if (hm.is_disposable) {
5272 Label end_finally = ig.DefineLabel ();
5273 bool old_in_finally = ec.InFinally;
5274 ec.InFinally = true;
5275 ig.BeginFinallyBlock ();
5277 ig.Emit (OpCodes.Ldloc, enumerator);
5278 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5279 ig.Emit (OpCodes.Stloc, disposable);
5280 ig.Emit (OpCodes.Ldloc, disposable);
5281 ig.Emit (OpCodes.Brfalse, end_finally);
5282 ig.Emit (OpCodes.Ldloc, disposable);
5283 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5284 ig.MarkLabel (end_finally);
5285 ec.InFinally = old_in_finally;
5287 // The runtime generates this anyways.
5288 // ig.Emit (OpCodes.Endfinally);
5290 ig.EndExceptionBlock ();
5293 ig.MarkLabel (ec.LoopEnd);
5298 // FIXME: possible optimization.
5299 // We might be able to avoid creating `empty' if the type is the sam
5301 bool EmitArrayForeach (EmitContext ec)
5303 int rank = array_type.GetArrayRank ();
5304 ILGenerator ig = ec.ig;
5306 LocalBuilder copy = ig.DeclareLocal (array_type);
5309 // Make our copy of the array
5312 ig.Emit (OpCodes.Stloc, copy);
5315 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5319 ig.Emit (OpCodes.Ldc_I4_0);
5320 ig.Emit (OpCodes.Stloc, counter);
5321 test = ig.DefineLabel ();
5322 ig.Emit (OpCodes.Br, test);
5324 loop = ig.DefineLabel ();
5325 ig.MarkLabel (loop);
5327 ig.Emit (OpCodes.Ldloc, copy);
5328 ig.Emit (OpCodes.Ldloc, counter);
5329 ArrayAccess.EmitLoadOpcode (ig, var_type);
5331 variable.EmitAssign (ec, conv);
5333 statement.Emit (ec);
5335 ig.MarkLabel (ec.LoopBegin);
5336 ig.Emit (OpCodes.Ldloc, counter);
5337 ig.Emit (OpCodes.Ldc_I4_1);
5338 ig.Emit (OpCodes.Add);
5339 ig.Emit (OpCodes.Stloc, counter);
5341 ig.MarkLabel (test);
5342 ig.Emit (OpCodes.Ldloc, counter);
5343 ig.Emit (OpCodes.Ldloc, copy);
5344 ig.Emit (OpCodes.Ldlen);
5345 ig.Emit (OpCodes.Conv_I4);
5346 ig.Emit (OpCodes.Blt, loop);
5348 LocalBuilder [] dim_len = new LocalBuilder [rank];
5349 LocalBuilder [] dim_count = new LocalBuilder [rank];
5350 Label [] loop = new Label [rank];
5351 Label [] test = new Label [rank];
5354 for (dim = 0; dim < rank; dim++){
5355 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5356 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5357 test [dim] = ig.DefineLabel ();
5358 loop [dim] = ig.DefineLabel ();
5361 for (dim = 0; dim < rank; dim++){
5362 ig.Emit (OpCodes.Ldloc, copy);
5363 IntLiteral.EmitInt (ig, dim);
5364 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5365 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5368 for (dim = 0; dim < rank; dim++){
5369 ig.Emit (OpCodes.Ldc_I4_0);
5370 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5371 ig.Emit (OpCodes.Br, test [dim]);
5372 ig.MarkLabel (loop [dim]);
5375 ig.Emit (OpCodes.Ldloc, copy);
5376 for (dim = 0; dim < rank; dim++)
5377 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5380 // FIXME: Maybe we can cache the computation of `get'?
5382 Type [] args = new Type [rank];
5385 for (int i = 0; i < rank; i++)
5386 args [i] = TypeManager.int32_type;
5388 ModuleBuilder mb = CodeGen.ModuleBuilder;
5389 get = mb.GetArrayMethod (
5391 CallingConventions.HasThis| CallingConventions.Standard,
5393 ig.Emit (OpCodes.Call, get);
5394 variable.EmitAssign (ec, conv);
5395 statement.Emit (ec);
5396 ig.MarkLabel (ec.LoopBegin);
5397 for (dim = rank - 1; dim >= 0; dim--){
5398 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5399 ig.Emit (OpCodes.Ldc_I4_1);
5400 ig.Emit (OpCodes.Add);
5401 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5403 ig.MarkLabel (test [dim]);
5404 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5405 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5406 ig.Emit (OpCodes.Blt, loop [dim]);
5409 ig.MarkLabel (ec.LoopEnd);
5414 protected override bool DoEmit (EmitContext ec)
5418 ILGenerator ig = ec.ig;
5420 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5421 bool old_inloop = ec.InLoop;
5422 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5423 ec.LoopBegin = ig.DefineLabel ();
5424 ec.LoopEnd = ig.DefineLabel ();
5426 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5429 ret_val = EmitCollectionForeach (ec);
5431 ret_val = EmitArrayForeach (ec);
5433 ec.LoopBegin = old_begin;
5434 ec.LoopEnd = old_end;
5435 ec.InLoop = old_inloop;
5436 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5443 /// AddHandler statement
5445 public class AddHandler : Statement {
5447 Expression EvtHandler;
5448 Expression EvtTarget;
5450 public AddHandler (Expression evt_id, Expression evt_handler,
5451 Expression evt_target, Location l)
5454 EvtHandler = evt_handler;
5455 EvtTarget = evt_target;
5457 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5460 public override bool Resolve (EmitContext ec)
5462 EvtId = EvtId.Resolve(ec);
5463 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5464 EvtTarget = EvtTarget.Resolve (ec,ResolveFlags.VariableOrValue);
5465 if (EvtId == null || (!(EvtId is EventExpr))) {
5466 Report.Error (999, "'AddHandler' statement needs an event designator.");
5470 if (EvtHandler == null)
5472 Report.Error (999, "'AddHandler' statement needs an event handler.");
5475 //EventExpr ee = (EventExpr) EvtId;
5476 //MethodGroupExpr me = (MethodGroupExpr) EvtHandler;
5477 //bool b = EvtId.Type.IsSubclassOf (TypeManager.delegate_type);
5478 //ee.EventInfo.AddEventHandler(EvtTarget, new System.Delegate())
5482 protected override bool DoEmit (EmitContext ec)
5485 ArrayList args = new ArrayList();
5486 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5489 // The even type was already resolved to a delegate, so
5490 // we must un-resolve its name to generate a type expression
5491 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5492 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5494 // which we can use to declare a new event handler
5496 d = new New (dtype, args, Location.Null);
5498 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5500 // we resolve it all and emit the code
5512 public class RedimClause {
5513 public Expression Expr;
5514 public ArrayList NewIndexes;
5516 public RedimClause (Expression e, ArrayList args)
5523 public class ReDim : Statement {
5524 ArrayList RedimTargets;
5528 private StatementExpression ReDimExpr;
5530 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5533 RedimTargets = targets;
5534 Preserve = opt_preserve;
5537 public override bool Resolve (EmitContext ec)
5539 Expression RedimTarget;
5540 ArrayList NewIndexes;
5542 foreach (RedimClause rc in RedimTargets) {
5543 RedimTarget = rc.Expr;
5544 NewIndexes = rc.NewIndexes;
5546 RedimTarget = RedimTarget.Resolve (ec);
5547 if (!RedimTarget.Type.IsArray)
5548 Report.Error (49, "'ReDim' statement requires an array");
5550 ArrayList args = new ArrayList();
5551 foreach (Argument a in NewIndexes) {
5552 if (a.Resolve(ec, loc))
5556 for (int x = 0; x < args.Count; x++) {
5557 args[x] = new Binary (Binary.Operator.Addition,
5558 (Expression) args[x], new IntLiteral (1), Location.Null);
5562 if (RedimTarget.Type.GetArrayRank() != args.Count)
5563 Report.Error (415, "'ReDim' cannot change the number of dimensions of an array.");
5565 BaseType = RedimTarget.Type.GetElementType();
5566 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5567 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
5570 // TODO: Generate call to copying code, which has to make lots of verifications
5571 //PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5572 //ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5573 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5576 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5577 ReDimExpr.Resolve(ec);
5582 protected override bool DoEmit (EmitContext ec)
5590 public class Erase : Statement {
5591 Expression EraseTarget;
5593 private StatementExpression EraseExpr;
5595 public Erase (Expression expr, Location l)
5601 public override bool Resolve (EmitContext ec)
5603 EraseTarget = EraseTarget.Resolve (ec);
5604 if (!EraseTarget.Type.IsArray)
5605 Report.Error (49, "'Erase' statement requires an array");
5607 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5608 EraseExpr.Resolve(ec);
5613 protected override bool DoEmit (EmitContext ec)