2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
7 // Anirban Bhattacharjee (banirban@novell.com)
8 // Manjula GHM (mmanjula@novell.com)
10 // (C) 2001, 2002 Ximian, Inc.
15 using System.Reflection;
16 using System.Reflection.Emit;
17 using System.Diagnostics;
19 namespace Mono.MonoBASIC {
21 using System.Collections;
23 public abstract class Statement {
27 /// Resolves the statement, true means that all sub-statements
30 public virtual bool Resolve (EmitContext ec)
36 /// Return value indicates whether all code paths emitted return.
38 protected abstract bool DoEmit (EmitContext ec);
41 /// Return value indicates whether all code paths emitted return.
43 public virtual bool Emit (EmitContext ec)
46 Report.Debug (8, "MARK", this, loc);
50 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
56 if (e.Type != TypeManager.bool_type){
57 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type, Location.Null);
62 30311, loc, "Can not convert the expression to a boolean");
71 /// Encapsulates the emission of a boolean test and jumping to a
74 /// This will emit the bool expression in `bool_expr' and if
75 /// `target_is_for_true' is true, then the code will generate a
76 /// brtrue to the target. Otherwise a brfalse.
78 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
79 Label target, bool target_is_for_true)
81 ILGenerator ig = ec.ig;
84 if (bool_expr is Unary){
85 Unary u = (Unary) bool_expr;
87 if (u.Oper == Unary.Operator.LogicalNot){
90 u.EmitLogicalNot (ec);
92 } else if (bool_expr is Binary){
93 Binary b = (Binary) bool_expr;
95 if (b.EmitBranchable (ec, target, target_is_for_true))
102 if (target_is_for_true){
104 ig.Emit (OpCodes.Brfalse, target);
106 ig.Emit (OpCodes.Brtrue, target);
109 ig.Emit (OpCodes.Brtrue, target);
111 ig.Emit (OpCodes.Brfalse, target);
115 public static void Warning_DeadCodeFound (Location loc)
117 Report.Warning (162, loc, "Unreachable code detected");
121 public class EmptyStatement : Statement {
122 public override bool Resolve (EmitContext ec)
127 protected override bool DoEmit (EmitContext ec)
133 public class If : Statement {
135 public Statement TrueStatement;
136 public Statement FalseStatement;
138 public If (Expression expr, Statement trueStatement, Location l)
141 TrueStatement = trueStatement;
145 public If (Expression expr,
146 Statement trueStatement,
147 Statement falseStatement,
151 TrueStatement = trueStatement;
152 FalseStatement = falseStatement;
156 public override bool Resolve (EmitContext ec)
158 Report.Debug (1, "START IF BLOCK", loc);
160 expr = ResolveBoolean (ec, expr, loc);
165 ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
167 if (!TrueStatement.Resolve (ec)) {
168 ec.KillFlowBranching ();
172 ec.CurrentBranching.CreateSibling ();
174 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
175 ec.KillFlowBranching ();
179 ec.EndFlowBranching ();
181 Report.Debug (1, "END IF BLOCK", loc);
186 protected override bool DoEmit (EmitContext ec)
188 ILGenerator ig = ec.ig;
189 Label false_target = ig.DefineLabel ();
191 bool is_true_ret, is_false_ret;
194 // Dead code elimination
196 if (expr is BoolConstant){
197 bool take = ((BoolConstant) expr).Value;
200 if (FalseStatement != null){
201 Warning_DeadCodeFound (FalseStatement.loc);
203 return TrueStatement.Emit (ec);
205 Warning_DeadCodeFound (TrueStatement.loc);
206 if (FalseStatement != null)
207 return FalseStatement.Emit (ec);
211 EmitBoolExpression (ec, expr, false_target, false);
213 is_true_ret = TrueStatement.Emit (ec);
214 is_false_ret = is_true_ret;
216 if (FalseStatement != null){
217 bool branch_emitted = false;
219 end = ig.DefineLabel ();
221 ig.Emit (OpCodes.Br, end);
222 branch_emitted = true;
225 ig.MarkLabel (false_target);
226 is_false_ret = FalseStatement.Emit (ec);
231 ig.MarkLabel (false_target);
232 is_false_ret = false;
235 return is_true_ret && is_false_ret;
239 public enum DoOptions {
246 public class Do : Statement {
247 public Expression expr;
248 public readonly Statement EmbeddedStatement;
249 //public DoOptions type;
250 public DoOptions test;
251 bool infinite, may_return;
254 public Do (Statement statement, Expression boolExpr, DoOptions do_test, Location l)
257 EmbeddedStatement = statement;
263 public override bool Resolve (EmitContext ec)
267 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
269 if (!EmbeddedStatement.Resolve (ec))
272 expr = ResolveBoolean (ec, expr, loc);
275 else if (expr is BoolConstant){
276 bool res = ((BoolConstant) expr).Value;
282 ec.CurrentBranching.Infinite = infinite;
283 FlowReturns returns = ec.EndFlowBranching ();
284 may_return = returns != FlowReturns.NEVER;
289 protected override bool DoEmit (EmitContext ec)
291 ILGenerator ig = ec.ig;
292 Label loop = ig.DefineLabel ();
293 Label old_begin = ec.LoopBegin;
294 Label old_end = ec.LoopEnd;
295 bool old_inloop = ec.InLoop;
296 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
298 ec.LoopBegin = ig.DefineLabel ();
299 ec.LoopEnd = ig.DefineLabel ();
301 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
303 if (test == DoOptions.TEST_AFTER) {
305 EmbeddedStatement.Emit (ec);
306 ig.MarkLabel (ec.LoopBegin);
309 // Dead code elimination
311 if (expr is BoolConstant){
312 bool res = ((BoolConstant) expr).Value;
315 ec.ig.Emit (OpCodes.Br, loop);
317 EmitBoolExpression (ec, expr, loop, true);
319 ig.MarkLabel (ec.LoopEnd);
324 ig.MarkLabel (ec.LoopBegin);
327 // Dead code elimination
329 if (expr is BoolConstant){
330 bool res = ((BoolConstant) expr).Value;
333 ec.ig.Emit (OpCodes.Br, ec.LoopEnd);
335 EmitBoolExpression (ec, expr, ec.LoopEnd, true);
337 EmbeddedStatement.Emit (ec);
338 ec.ig.Emit (OpCodes.Br, loop);
339 ig.MarkLabel (ec.LoopEnd);
341 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
342 ec.LoopBegin = old_begin;
343 ec.LoopEnd = old_end;
344 ec.InLoop = old_inloop;
347 return may_return == false;
353 public class While : Statement {
354 public Expression expr;
355 public readonly Statement Statement;
356 bool may_return, empty, infinite;
358 public While (Expression boolExpr, Statement statement, Location l)
360 this.expr = boolExpr;
361 Statement = statement;
365 public override bool Resolve (EmitContext ec)
369 expr = ResolveBoolean (ec, expr, loc);
373 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
376 // Inform whether we are infinite or not
378 if (expr is BoolConstant){
379 BoolConstant bc = (BoolConstant) expr;
381 if (bc.Value == false){
382 Warning_DeadCodeFound (Statement.loc);
388 // We are not infinite, so the loop may or may not be executed.
390 ec.CurrentBranching.CreateSibling ();
393 if (!Statement.Resolve (ec))
397 ec.KillFlowBranching ();
399 ec.CurrentBranching.Infinite = infinite;
400 FlowReturns returns = ec.EndFlowBranching ();
401 may_return = returns != FlowReturns.NEVER;
407 protected override bool DoEmit (EmitContext ec)
412 ILGenerator ig = ec.ig;
413 Label old_begin = ec.LoopBegin;
414 Label old_end = ec.LoopEnd;
415 bool old_inloop = ec.InLoop;
416 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
419 ec.LoopBegin = ig.DefineLabel ();
420 ec.LoopEnd = ig.DefineLabel ();
422 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
425 // Inform whether we are infinite or not
427 if (expr is BoolConstant){
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 (30132, 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 (30132, 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 (30665, 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 // Support 'End' Statement which terminates execution immediately
975 public class End : Statement {
977 public End (Location l)
982 public override bool Resolve (EmitContext ec)
987 protected override bool DoEmit (EmitContext ec)
990 Expression tmp = Mono.MonoBASIC.Parser.DecomposeQI (
991 "Microsoft.VisualBasic.CompilerServices.ProjectData.EndApp",
994 e = new Invocation (tmp, null, loc);
1006 public class Break : Statement {
1008 public Break (Location l)
1013 public override bool Resolve (EmitContext ec)
1015 ec.CurrentBranching.MayLeaveLoop = true;
1016 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1020 protected override bool DoEmit (EmitContext ec)
1022 ILGenerator ig = ec.ig;
1024 if (ec.InLoop == false && ec.Switch == null){
1025 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1029 if (ec.InTry || ec.InCatch)
1030 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1032 ig.Emit (OpCodes.Br, ec.LoopEnd);
1038 public enum ExitType {
1049 public class Exit : Statement {
1050 public readonly ExitType type;
1051 public Exit (ExitType t, Location l)
1057 public override bool Resolve (EmitContext ec)
1059 ec.CurrentBranching.MayLeaveLoop = true;
1060 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1064 protected override bool DoEmit (EmitContext ec)
1066 ILGenerator ig = ec.ig;
1068 if (type != ExitType.SUB && type != ExitType.FUNCTION &&
1069 type != ExitType.PROPERTY && type != ExitType.TRY) {
1070 if (ec.InLoop == false && ec.Switch == null){
1071 if (type == ExitType.FOR)
1072 Report.Error (30096, loc, "No enclosing FOR loop to exit from");
1073 if (type == ExitType.WHILE)
\r
1074 Report.Error (30097, loc, "No enclosing WHILE loop to exit from");
1075 if (type == ExitType.DO)
1076 Report.Error (30089, loc, "No enclosing DO loop to exit from");
1077 if (type == ExitType.SELECT)
1078 Report.Error (30099, loc, "No enclosing SELECT to exit from");
1083 if (ec.InTry || ec.InCatch)
1084 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1086 ig.Emit (OpCodes.Br, ec.LoopEnd);
1089 Report.Error (30393, loc,
1090 "Control can not leave the body of the finally block");
1094 if (ec.InTry || ec.InCatch) {
1095 if (!ec.HasReturnLabel) {
1096 ec.ReturnLabel = ec.ig.DefineLabel ();
1097 ec.HasReturnLabel = true;
1099 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
1101 ec.ig.Emit (OpCodes.Ret);
1110 public class Continue : Statement {
1112 public Continue (Location l)
1117 public override bool Resolve (EmitContext ec)
1119 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1123 protected override bool DoEmit (EmitContext ec)
1125 Label begin = ec.LoopBegin;
1128 Report.Error (139, loc, "No enclosing loop to continue to");
1133 // UGH: Non trivial. This Br might cross a try/catch boundary
1137 // try { ... } catch { continue; }
1141 // try {} catch { while () { continue; }}
1143 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1144 ec.ig.Emit (OpCodes.Leave, begin);
1145 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1146 throw new Exception ("Should never happen");
1148 ec.ig.Emit (OpCodes.Br, begin);
1154 // This is used in the control flow analysis code to specify whether the
1155 // current code block may return to its enclosing block before reaching
1158 public enum FlowReturns {
1159 // It can never return.
1162 // This means that the block contains a conditional return statement
1166 // The code always returns, ie. there's an unconditional return / break
1170 // The code always throws an exception.
1173 // The current code block is unreachable. This happens if it's immediately
1174 // following a FlowReturns.ALWAYS block.
1179 // This is a special bit vector which can inherit from another bit vector doing a
1180 // copy-on-write strategy. The inherited vector may have a smaller size than the
1183 public class MyBitVector {
1184 public readonly int Count;
1185 public readonly MyBitVector InheritsFrom;
1190 public MyBitVector (int Count)
1191 : this (null, Count)
1194 public MyBitVector (MyBitVector InheritsFrom, int Count)
1196 this.InheritsFrom = InheritsFrom;
1201 // Checks whether this bit vector has been modified. After setting this to true,
1202 // we won't use the inherited vector anymore, but our own copy of it.
1204 public bool IsDirty {
1211 initialize_vector ();
1216 // Get/set bit `index' in the bit vector.
1218 public bool this [int index]
1222 throw new ArgumentOutOfRangeException ();
1224 // We're doing a "copy-on-write" strategy here; as long
1225 // as nobody writes to the array, we can use our parent's
1226 // copy instead of duplicating the vector.
1229 return vector [index];
1230 else if (InheritsFrom != null) {
1231 BitArray inherited = InheritsFrom.Vector;
1233 if (index < inherited.Count)
1234 return inherited [index];
1243 throw new ArgumentOutOfRangeException ();
1245 // Only copy the vector if we're actually modifying it.
1247 if (this [index] != value) {
1248 initialize_vector ();
1250 vector [index] = value;
1256 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1257 // copy of the bit vector.
1259 public static explicit operator BitArray (MyBitVector vector)
1261 vector.initialize_vector ();
1262 return vector.Vector;
1266 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1267 // different size than the current one.
1269 public void Or (MyBitVector new_vector)
1271 BitArray new_array = new_vector.Vector;
1273 initialize_vector ();
1276 if (vector.Count < new_array.Count)
1277 upper = vector.Count;
1279 upper = new_array.Count;
1281 for (int i = 0; i < upper; i++)
1282 vector [i] = vector [i] | new_array [i];
1286 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1287 // a different size than the current one.
1289 public void And (MyBitVector new_vector)
1291 BitArray new_array = new_vector.Vector;
1293 initialize_vector ();
1296 if (vector.Count < new_array.Count)
1297 lower = upper = vector.Count;
1299 lower = new_array.Count;
1300 upper = vector.Count;
1303 for (int i = 0; i < lower; i++)
1304 vector [i] = vector [i] & new_array [i];
1306 for (int i = lower; i < upper; i++)
1311 // This does a deep copy of the bit vector.
1313 public MyBitVector Clone ()
1315 MyBitVector retval = new MyBitVector (Count);
1317 retval.Vector = Vector;
1326 else if (!is_dirty && (InheritsFrom != null))
1327 return InheritsFrom.Vector;
1329 initialize_vector ();
1335 initialize_vector ();
1337 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1338 vector [i] = value [i];
1342 void initialize_vector ()
1347 vector = new BitArray (Count, false);
1348 if (InheritsFrom != null)
1349 Vector = InheritsFrom.Vector;
1354 public override string ToString ()
1356 StringBuilder sb = new StringBuilder ("MyBitVector (");
1358 BitArray vector = Vector;
1362 sb.Append ("INHERITED - ");
1363 for (int i = 0; i < vector.Count; i++) {
1366 sb.Append (vector [i]);
1370 return sb.ToString ();
1375 // The type of a FlowBranching.
1377 public enum FlowBranchingType {
1378 // Normal (conditional or toplevel) block.
1395 // A new instance of this class is created every time a new block is resolved
1396 // and if there's branching in the block's control flow.
1398 public class FlowBranching {
1400 // The type of this flow branching.
1402 public readonly FlowBranchingType Type;
1405 // The block this branching is contained in. This may be null if it's not
1406 // a top-level block and it doesn't declare any local variables.
1408 public readonly Block Block;
1411 // The parent of this branching or null if this is the top-block.
1413 public readonly FlowBranching Parent;
1416 // Start-Location of this flow branching.
1418 public readonly Location Location;
1421 // A list of UsageVectors. A new vector is added each time control flow may
1422 // take a different path.
1424 public ArrayList Siblings;
1427 // If this is an infinite loop.
1429 public bool Infinite;
1432 // If we may leave the current loop.
1434 public bool MayLeaveLoop;
1439 InternalParameters param_info;
1441 MyStructInfo[] struct_params;
1443 ArrayList finally_vectors;
1445 static int next_id = 0;
1449 // Performs an `And' operation on the FlowReturns status
1450 // (for instance, a block only returns ALWAYS if all its siblings
1453 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1455 if (b == FlowReturns.UNREACHABLE)
1459 case FlowReturns.NEVER:
1460 if (b == FlowReturns.NEVER)
1461 return FlowReturns.NEVER;
1463 return FlowReturns.SOMETIMES;
1465 case FlowReturns.SOMETIMES:
1466 return FlowReturns.SOMETIMES;
1468 case FlowReturns.ALWAYS:
1469 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1470 return FlowReturns.ALWAYS;
1472 return FlowReturns.SOMETIMES;
1474 case FlowReturns.EXCEPTION:
1475 if (b == FlowReturns.EXCEPTION)
1476 return FlowReturns.EXCEPTION;
1477 else if (b == FlowReturns.ALWAYS)
1478 return FlowReturns.ALWAYS;
1480 return FlowReturns.SOMETIMES;
1487 // The vector contains a BitArray with information about which local variables
1488 // and parameters are already initialized at the current code position.
1490 public class UsageVector {
1492 // If this is true, then the usage vector has been modified and must be
1493 // merged when we're done with this branching.
1495 public bool IsDirty;
1498 // The number of parameters in this block.
1500 public readonly int CountParameters;
1503 // The number of locals in this block.
1505 public readonly int CountLocals;
1508 // If not null, then we inherit our state from this vector and do a
1509 // copy-on-write. If null, then we're the first sibling in a top-level
1510 // block and inherit from the empty vector.
1512 public readonly UsageVector InheritsFrom;
1517 MyBitVector locals, parameters;
1518 FlowReturns real_returns, real_breaks;
1521 static int next_id = 0;
1525 // Normally, you should not use any of these constructors.
1527 public UsageVector (UsageVector parent, int num_params, int num_locals)
1529 this.InheritsFrom = parent;
1530 this.CountParameters = num_params;
1531 this.CountLocals = num_locals;
1532 this.real_returns = FlowReturns.NEVER;
1533 this.real_breaks = FlowReturns.NEVER;
1535 if (parent != null) {
1536 locals = new MyBitVector (parent.locals, CountLocals);
1538 parameters = new MyBitVector (parent.parameters, num_params);
1539 real_returns = parent.Returns;
1540 real_breaks = parent.Breaks;
1542 locals = new MyBitVector (null, CountLocals);
1544 parameters = new MyBitVector (null, num_params);
1550 public UsageVector (UsageVector parent)
1551 : this (parent, parent.CountParameters, parent.CountLocals)
1555 // This does a deep copy of the usage vector.
1557 public UsageVector Clone ()
1559 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1561 retval.locals = locals.Clone ();
1562 if (parameters != null)
1563 retval.parameters = parameters.Clone ();
1564 retval.real_returns = real_returns;
1565 retval.real_breaks = real_breaks;
1571 // State of parameter `number'.
1573 public bool this [int number]
1578 else if (number == 0)
1579 throw new ArgumentException ();
1581 return parameters [number - 1];
1587 else if (number == 0)
1588 throw new ArgumentException ();
1590 parameters [number - 1] = value;
1595 // State of the local variable `vi'.
1596 // If the local variable is a struct, use a non-zero `field_idx'
1597 // to check an individual field in it.
1599 public bool this [VariableInfo vi, int field_idx]
1602 if (vi.Number == -1)
1604 else if (vi.Number == 0)
1605 throw new ArgumentException ();
1607 return locals [vi.Number + field_idx - 1];
1611 if (vi.Number == -1)
1613 else if (vi.Number == 0)
1614 throw new ArgumentException ();
1616 locals [vi.Number + field_idx - 1] = value;
1621 // Specifies when the current block returns.
1622 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1623 // end of the method (so that we don't need to emit a return statement).
1624 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1625 // value will never be used.
1627 public FlowReturns Returns {
1629 return real_returns;
1633 real_returns = value;
1638 // Specifies whether control may return to our containing block
1639 // before reaching the end of this block. This happens if there
1640 // is a break/continue/goto/return in it.
1641 // This can also be used to find out whether the statement immediately
1642 // following the current block may be reached or not.
1644 public FlowReturns Breaks {
1650 real_breaks = value;
1654 public bool AlwaysBreaks {
1656 return (Breaks == FlowReturns.ALWAYS) ||
1657 (Breaks == FlowReturns.EXCEPTION) ||
1658 (Breaks == FlowReturns.UNREACHABLE);
1662 public bool MayBreak {
1664 return Breaks != FlowReturns.NEVER;
1668 public bool AlwaysReturns {
1670 return (Returns == FlowReturns.ALWAYS) ||
1671 (Returns == FlowReturns.EXCEPTION);
1675 public bool MayReturn {
1677 return (Returns == FlowReturns.SOMETIMES) ||
1678 (Returns == FlowReturns.ALWAYS);
1683 // Merge a child branching.
1685 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1687 MyBitVector new_locals = null;
1688 MyBitVector new_params = null;
1690 FlowReturns new_returns = FlowReturns.NEVER;
1691 FlowReturns new_breaks = FlowReturns.NEVER;
1692 bool new_returns_set = false, new_breaks_set = false;
1694 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1695 this, children.Count);
1697 foreach (UsageVector child in children) {
1698 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1700 if (!child.is_finally) {
1701 if (child.Breaks != FlowReturns.UNREACHABLE) {
1702 // If Returns is already set, perform an
1703 // `And' operation on it, otherwise just set just.
1704 if (!new_returns_set) {
1705 new_returns = child.Returns;
1706 new_returns_set = true;
1708 new_returns = AndFlowReturns (
1709 new_returns, child.Returns);
1712 // If Breaks is already set, perform an
1713 // `And' operation on it, otherwise just set just.
1714 if (!new_breaks_set) {
1715 new_breaks = child.Breaks;
1716 new_breaks_set = true;
1718 new_breaks = AndFlowReturns (
1719 new_breaks, child.Breaks);
1722 // Ignore unreachable children.
1723 if (child.Returns == FlowReturns.UNREACHABLE)
1726 // A local variable is initialized after a flow branching if it
1727 // has been initialized in all its branches which do neither
1728 // always return or always throw an exception.
1730 // If a branch may return, but does not always return, then we
1731 // can treat it like a never-returning branch here: control will
1732 // only reach the code position after the branching if we did not
1735 // It's important to distinguish between always and sometimes
1736 // returning branches here:
1739 // 2 if (something) {
1743 // 6 Console.WriteLine (a);
1745 // The if block in lines 3-4 always returns, so we must not look
1746 // at the initialization of `a' in line 4 - thus it'll still be
1747 // uninitialized in line 6.
1749 // On the other hand, the following is allowed:
1756 // 6 Console.WriteLine (a);
1758 // Here, `a' is initialized in line 3 and we must not look at
1759 // line 5 since it always returns.
1761 if (child.is_finally) {
1762 if (new_locals == null)
1763 new_locals = locals.Clone ();
1764 new_locals.Or (child.locals);
1766 if (parameters != null) {
1767 if (new_params == null)
1768 new_params = parameters.Clone ();
1769 new_params.Or (child.parameters);
1773 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1774 if (new_locals != null)
1775 new_locals.And (child.locals);
1777 new_locals = locals.Clone ();
1778 new_locals.Or (child.locals);
1780 } else if (children.Count == 1) {
1781 new_locals = locals.Clone ();
1782 new_locals.Or (child.locals);
1785 // An `out' parameter must be assigned in all branches which do
1786 // not always throw an exception.
1787 if (parameters != null) {
1788 if (child.Breaks != FlowReturns.EXCEPTION) {
1789 if (new_params != null)
1790 new_params.And (child.parameters);
1792 new_params = parameters.Clone ();
1793 new_params.Or (child.parameters);
1795 } else if (children.Count == 1) {
1796 new_params = parameters.Clone ();
1797 new_params.Or (child.parameters);
1803 Returns = new_returns;
1804 if ((branching.Type == FlowBranchingType.BLOCK) ||
1805 (branching.Type == FlowBranchingType.EXCEPTION) ||
1806 (new_breaks == FlowReturns.UNREACHABLE) ||
1807 (new_breaks == FlowReturns.EXCEPTION))
1808 Breaks = new_breaks;
1809 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1810 Breaks = new_returns;
1811 else if (branching.Type == FlowBranchingType.SWITCH){
1812 if (new_breaks == FlowReturns.ALWAYS)
1813 Breaks = FlowReturns.ALWAYS;
1817 // We've now either reached the point after the branching or we will
1818 // never get there since we always return or always throw an exception.
1820 // If we can reach the point after the branching, mark all locals and
1821 // parameters as initialized which have been initialized in all branches
1822 // we need to look at (see above).
1825 if (((new_breaks != FlowReturns.ALWAYS) &&
1826 (new_breaks != FlowReturns.EXCEPTION) &&
1827 (new_breaks != FlowReturns.UNREACHABLE)) ||
1828 (children.Count == 1)) {
1829 if (new_locals != null)
1830 locals.Or (new_locals);
1832 if (new_params != null)
1833 parameters.Or (new_params);
1836 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1837 new_params, new_locals, new_returns, new_breaks,
1838 branching.Infinite, branching.MayLeaveLoop, this);
1840 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1841 if ((new_breaks != FlowReturns.ALWAYS) &&
1842 (new_breaks != FlowReturns.EXCEPTION) &&
1843 (new_breaks != FlowReturns.UNREACHABLE))
1844 Report.Error (163, branching.Location,
1845 "Control cannot fall through from one " +
1846 "case label to another");
1849 if (branching.Infinite && !branching.MayLeaveLoop) {
1850 Report.Debug (1, "INFINITE", new_returns, new_breaks,
1851 Returns, Breaks, this);
1853 // We're actually infinite.
1854 if (new_returns == FlowReturns.NEVER) {
1855 Breaks = FlowReturns.UNREACHABLE;
1856 return FlowReturns.UNREACHABLE;
1859 // If we're an infinite loop and do not break, the code after
1860 // the loop can never be reached. However, if we may return
1861 // from the loop, then we do always return (or stay in the loop
1863 if ((new_returns == FlowReturns.SOMETIMES) ||
1864 (new_returns == FlowReturns.ALWAYS)) {
1865 Returns = FlowReturns.ALWAYS;
1866 return FlowReturns.ALWAYS;
1874 // Tells control flow analysis that the current code position may be reached with
1875 // a forward jump from any of the origins listed in `origin_vectors' which is a
1876 // list of UsageVectors.
1878 // This is used when resolving forward gotos - in the following example, the
1879 // variable `a' is uninitialized in line 8 becase this line may be reached via
1880 // the goto in line 4:
1890 // 8 Console.WriteLine (a);
1893 public void MergeJumpOrigins (ICollection origin_vectors)
1895 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1897 real_breaks = FlowReturns.NEVER;
1898 real_returns = FlowReturns.NEVER;
1900 foreach (UsageVector vector in origin_vectors) {
1901 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1903 locals.And (vector.locals);
1904 if (parameters != null)
1905 parameters.And (vector.parameters);
1906 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1907 Returns = AndFlowReturns (Returns, vector.Returns);
1910 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1914 // This is used at the beginning of a finally block if there were
1915 // any return statements in the try block or one of the catch blocks.
1917 public void MergeFinallyOrigins (ICollection finally_vectors)
1919 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1921 real_breaks = FlowReturns.NEVER;
1923 foreach (UsageVector vector in finally_vectors) {
1924 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1926 if (parameters != null)
1927 parameters.And (vector.parameters);
1928 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1933 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1936 public void CheckOutParameters (FlowBranching branching)
1938 if (parameters != null)
1939 branching.CheckOutParameters (parameters, branching.Location);
1943 // Performs an `or' operation on the locals and the parameters.
1945 public void Or (UsageVector new_vector)
1947 locals.Or (new_vector.locals);
1948 if (parameters != null)
1949 parameters.Or (new_vector.parameters);
1953 // Performs an `and' operation on the locals.
1955 public void AndLocals (UsageVector new_vector)
1957 locals.And (new_vector.locals);
1961 // Returns a deep copy of the parameters.
1963 public MyBitVector Parameters {
1965 if (parameters != null)
1966 return parameters.Clone ();
1973 // Returns a deep copy of the locals.
1975 public MyBitVector Locals {
1977 return locals.Clone ();
1985 public override string ToString ()
1987 StringBuilder sb = new StringBuilder ();
1989 sb.Append ("Vector (");
1992 sb.Append (Returns);
1995 if (parameters != null) {
1997 sb.Append (parameters);
2003 return sb.ToString ();
2007 FlowBranching (FlowBranchingType type, Location loc)
2009 this.Siblings = new ArrayList ();
2011 this.Location = loc;
2017 // Creates a new flow branching for `block'.
2018 // This is used from Block.Resolve to create the top-level branching of
2021 public FlowBranching (Block block, InternalParameters ip, Location loc)
2022 : this (FlowBranchingType.BLOCK, loc)
2027 int count = (ip != null) ? ip.Count : 0;
2030 param_map = new int [count];
2031 struct_params = new MyStructInfo [count];
2034 for (int i = 0; i < count; i++) {
2035 Parameter.Modifier mod = param_info.ParameterModifier (i);
2037 if ((mod & Parameter.Modifier.OUT) == 0)
2040 param_map [i] = ++num_params;
2042 Type param_type = param_info.ParameterType (i);
2044 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2045 if (struct_params [i] != null)
2046 num_params += struct_params [i].Count;
2049 Siblings = new ArrayList ();
2050 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2054 // Creates a new flow branching which is contained in `parent'.
2055 // You should only pass non-null for the `block' argument if this block
2056 // introduces any new variables - in this case, we need to create a new
2057 // usage vector with a different size than our parent's one.
2059 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2060 Block block, Location loc)
2066 if (parent != null) {
2067 param_info = parent.param_info;
2068 param_map = parent.param_map;
2069 struct_params = parent.struct_params;
2070 num_params = parent.num_params;
2075 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2076 Block.CountVariables);
2078 vector = new UsageVector (Parent.CurrentUsageVector);
2080 Siblings.Add (vector);
2083 case FlowBranchingType.EXCEPTION:
2084 finally_vectors = new ArrayList ();
2093 // Returns the branching's current usage vector.
2095 public UsageVector CurrentUsageVector
2098 return (UsageVector) Siblings [Siblings.Count - 1];
2103 // Creates a sibling of the current usage vector.
2105 public void CreateSibling ()
2107 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2109 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2113 // Creates a sibling for a `finally' block.
2115 public void CreateSiblingForFinally ()
2117 if (Type != FlowBranchingType.EXCEPTION)
2118 throw new NotSupportedException ();
2122 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2126 // Check whether all `out' parameters have been assigned.
2128 public void CheckOutParameters (MyBitVector parameters, Location loc)
2133 for (int i = 0; i < param_map.Length; i++) {
2134 int index = param_map [i];
2139 if (parameters [index - 1])
2142 // If it's a struct, we must ensure that all its fields have
2143 // been assigned. If the struct has any non-public fields, this
2144 // can only be done by assigning the whole struct.
2146 MyStructInfo struct_info = struct_params [index - 1];
2147 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2149 177, loc, "The out parameter `" +
2150 param_info.ParameterName (i) + "' must be " +
2151 "assigned before control leave the current method.");
2157 for (int j = 0; j < struct_info.Count; j++) {
2158 if (!parameters [index + j]) {
2160 177, loc, "The out parameter `" +
2161 param_info.ParameterName (i) + "' must be " +
2162 "assigned before control leave the current method.");
2171 // Merge a child branching.
2173 public FlowReturns MergeChild (FlowBranching child)
2175 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2177 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2178 MayLeaveLoop |= child.MayLeaveLoop;
2180 MayLeaveLoop = false;
2186 // Does the toplevel merging.
2188 public FlowReturns MergeTopBlock ()
2190 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2191 throw new NotSupportedException ();
2193 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2195 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2197 vector.MergeChildren (this, Siblings);
2200 Siblings.Add (vector);
2202 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2204 if (vector.Breaks != FlowReturns.EXCEPTION) {
2205 if (!vector.AlwaysBreaks)
2206 CheckOutParameters (CurrentUsageVector.Parameters, Location);
2207 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2209 return FlowReturns.EXCEPTION;
2212 public bool InTryBlock ()
2214 if (finally_vectors != null)
2216 else if (Parent != null)
2217 return Parent.InTryBlock ();
2222 public void AddFinallyVector (UsageVector vector)
2224 if (finally_vectors != null) {
2225 finally_vectors.Add (vector.Clone ());
2230 Parent.AddFinallyVector (vector);
2232 throw new NotSupportedException ();
2235 public bool IsVariableAssigned (VariableInfo vi)
2237 if (CurrentUsageVector.AlwaysBreaks)
2240 return CurrentUsageVector [vi, 0];
2243 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2245 if (CurrentUsageVector.AlwaysBreaks)
2248 return CurrentUsageVector [vi, field_idx];
2251 public void SetVariableAssigned (VariableInfo vi)
2253 if (CurrentUsageVector.AlwaysBreaks)
2256 CurrentUsageVector [vi, 0] = true;
2259 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2261 if (CurrentUsageVector.AlwaysBreaks)
2264 CurrentUsageVector [vi, field_idx] = true;
2267 public bool IsParameterAssigned (int number)
2269 int index = param_map [number];
2274 if (CurrentUsageVector [index])
2277 // Parameter is not assigned, so check whether it's a struct.
2278 // If it's either not a struct or a struct which non-public
2279 // fields, return false.
2280 MyStructInfo struct_info = struct_params [number];
2281 if ((struct_info == null) || struct_info.HasNonPublicFields)
2284 // Ok, so each field must be assigned.
2285 for (int i = 0; i < struct_info.Count; i++)
2286 if (!CurrentUsageVector [index + i])
2292 public bool IsParameterAssigned (int number, string field_name)
2294 int index = param_map [number];
2299 MyStructInfo info = (MyStructInfo) struct_params [number];
2303 int field_idx = info [field_name];
2305 return CurrentUsageVector [index + field_idx];
2308 public void SetParameterAssigned (int number)
2310 if (param_map [number] == 0)
2313 if (!CurrentUsageVector.AlwaysBreaks)
2314 CurrentUsageVector [param_map [number]] = true;
2317 public void SetParameterAssigned (int number, string field_name)
2319 int index = param_map [number];
2324 MyStructInfo info = (MyStructInfo) struct_params [number];
2328 int field_idx = info [field_name];
2330 if (!CurrentUsageVector.AlwaysBreaks)
2331 CurrentUsageVector [index + field_idx] = true;
2334 public bool IsReachable ()
2339 case FlowBranchingType.SWITCH_SECTION:
2340 // The code following a switch block is reachable unless the switch
2341 // block always returns.
2342 reachable = !CurrentUsageVector.AlwaysReturns;
2345 case FlowBranchingType.LOOP_BLOCK:
2346 // The code following a loop is reachable unless the loop always
2347 // returns or it's an infinite loop without any `break's in it.
2348 reachable = !CurrentUsageVector.AlwaysReturns &&
2349 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2353 // The code following a block or exception is reachable unless the
2354 // block either always returns or always breaks.
2355 reachable = !CurrentUsageVector.AlwaysBreaks &&
2356 !CurrentUsageVector.AlwaysReturns;
2360 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2361 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2366 public override string ToString ()
2368 StringBuilder sb = new StringBuilder ("FlowBranching (");
2373 if (Block != null) {
2375 sb.Append (Block.ID);
2377 sb.Append (Block.StartLocation);
2380 sb.Append (Siblings.Count);
2382 sb.Append (CurrentUsageVector);
2384 return sb.ToString ();
2388 public class MyStructInfo {
2389 public readonly Type Type;
2390 public readonly FieldInfo[] Fields;
2391 public readonly FieldInfo[] NonPublicFields;
2392 public readonly int Count;
2393 public readonly int CountNonPublic;
2394 public readonly bool HasNonPublicFields;
2396 private static Hashtable field_type_hash = new Hashtable ();
2397 private Hashtable field_hash;
2399 // Private constructor. To save memory usage, we only need to create one instance
2400 // of this class per struct type.
2401 private MyStructInfo (Type type)
2405 if (type is TypeBuilder) {
2406 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2408 ArrayList fields = tc.Fields;
2409 if (fields != null) {
2410 foreach (Field field in fields) {
2411 if ((field.ModFlags & Modifiers.STATIC) != 0)
2413 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2420 Fields = new FieldInfo [Count];
2421 NonPublicFields = new FieldInfo [CountNonPublic];
2423 Count = CountNonPublic = 0;
2424 if (fields != null) {
2425 foreach (Field field in fields) {
2426 if ((field.ModFlags & Modifiers.STATIC) != 0)
2428 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2429 Fields [Count++] = field.FieldBuilder;
2431 NonPublicFields [CountNonPublic++] =
2437 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2438 Count = Fields.Length;
2440 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2441 CountNonPublic = NonPublicFields.Length;
2444 Count += NonPublicFields.Length;
2447 field_hash = new Hashtable ();
2448 foreach (FieldInfo field in Fields)
2449 field_hash.Add (field.Name, ++number);
2451 if (NonPublicFields.Length != 0)
2452 HasNonPublicFields = true;
2454 foreach (FieldInfo field in NonPublicFields)
2455 field_hash.Add (field.Name, ++number);
2458 public int this [string name] {
2460 if (field_hash.Contains (name))
2461 return (int) field_hash [name];
2467 public FieldInfo this [int index] {
2469 if (index >= Fields.Length)
2470 return NonPublicFields [index - Fields.Length];
2472 return Fields [index];
2476 public static MyStructInfo GetStructInfo (Type type)
2478 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2481 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2484 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2488 info = new MyStructInfo (type);
2489 field_type_hash.Add (type, info);
2493 public static MyStructInfo GetStructInfo (TypeContainer tc)
2495 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2499 info = new MyStructInfo (tc.TypeBuilder);
2500 field_type_hash.Add (tc.TypeBuilder, info);
2505 public class VariableInfo : IVariable {
2506 public Expression Type;
2507 public LocalBuilder LocalBuilder;
2508 public Type VariableType;
2509 public readonly string Name;
2510 public readonly Location Location;
2511 public readonly int Block;
2516 public bool Assigned;
2517 public bool ReadOnly;
2519 public VariableInfo (Expression type, string name, int block, Location l)
2524 LocalBuilder = null;
2528 public VariableInfo (TypeContainer tc, int block, Location l)
2530 VariableType = tc.TypeBuilder;
2531 struct_info = MyStructInfo.GetStructInfo (tc);
2533 LocalBuilder = null;
2537 MyStructInfo struct_info;
2538 public MyStructInfo StructInfo {
2544 public bool IsAssigned (EmitContext ec, Location loc)
2545 {/* FIXME: we shouldn't just skip this!!!
2546 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2549 MyStructInfo struct_info = StructInfo;
2550 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2551 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2552 ec.CurrentBranching.SetVariableAssigned (this);
2556 int count = struct_info.Count;
2558 for (int i = 0; i < count; i++) {
2559 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2561 Report.Error (165, loc,
2562 "Use of unassigned local variable `" +
2564 ec.CurrentBranching.SetVariableAssigned (this);
2568 FieldInfo field = struct_info [i];
2569 Report.Error (171, loc,
2570 "Field `" + TypeManager.MonoBASIC_Name (VariableType) +
2571 "." + field.Name + "' must be fully initialized " +
2572 "before control leaves the constructor");
2580 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2582 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2583 (struct_info == null))
2586 int field_idx = StructInfo [name];
2590 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2591 Report.Error (170, loc,
2592 "Use of possibly unassigned field `" + name + "'");
2593 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2600 public void SetAssigned (EmitContext ec)
2602 if (ec.DoFlowAnalysis)
2603 ec.CurrentBranching.SetVariableAssigned (this);
2606 public void SetFieldAssigned (EmitContext ec, string name)
2608 if (ec.DoFlowAnalysis && (struct_info != null))
2609 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2612 public bool Resolve (DeclSpace decl)
2614 if (struct_info != null)
2617 if (VariableType == null)
2618 VariableType = decl.ResolveType (Type, false, Location);
2620 if (VariableType == null)
2623 struct_info = MyStructInfo.GetStructInfo (VariableType);
2628 public void MakePinned ()
2630 TypeManager.MakePinned (LocalBuilder);
2633 public override string ToString ()
2635 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2640 /// Block represents a C# block.
2644 /// This class is used in a number of places: either to represent
2645 /// explicit blocks that the programmer places or implicit blocks.
2647 /// Implicit blocks are used as labels or to introduce variable
2650 public class Block : Statement {
2651 public readonly Block Parent;
2652 public readonly bool Implicit;
2653 public readonly Location StartLocation;
2654 public Location EndLocation;
2657 // The statements in this block
2659 public ArrayList statements;
2662 // An array of Blocks. We keep track of children just
2663 // to generate the local variable declarations.
2665 // Statements and child statements are handled through the
2671 // Labels. (label, block) pairs.
2673 CaseInsensitiveHashtable labels;
2676 // Keeps track of (name, type) pairs
2678 CaseInsensitiveHashtable variables;
2681 // Keeps track of constants
2682 CaseInsensitiveHashtable constants;
2685 // Maps variable names to ILGenerator.LocalBuilders
2687 CaseInsensitiveHashtable local_builders;
2695 public Block (Block parent)
2696 : this (parent, false, Location.Null, Location.Null)
2699 public Block (Block parent, bool implicit_block)
2700 : this (parent, implicit_block, Location.Null, Location.Null)
2703 public Block (Block parent, bool implicit_block, Parameters parameters)
2704 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2707 public Block (Block parent, Location start, Location end)
2708 : this (parent, false, start, end)
2711 public Block (Block parent, Parameters parameters, Location start, Location end)
2712 : this (parent, false, parameters, start, end)
2715 public Block (Block parent, bool implicit_block, Location start, Location end)
2716 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2720 public Block (Block parent, bool implicit_block, Parameters parameters,
2721 Location start, Location end)
2724 parent.AddChild (this);
2726 this.Parent = parent;
2727 this.Implicit = implicit_block;
2728 this.parameters = parameters;
2729 this.StartLocation = start;
2730 this.EndLocation = end;
2733 statements = new ArrayList ();
2742 void AddChild (Block b)
2744 if (children == null)
2745 children = new ArrayList ();
2750 public void SetEndLocation (Location loc)
2756 /// Adds a label to the current block.
2760 /// false if the name already exists in this block. true
2764 public bool AddLabel (string name, LabeledStatement target)
2767 labels = new CaseInsensitiveHashtable ();
2768 if (labels.Contains (name))
2771 labels.Add (name, target);
2775 public LabeledStatement LookupLabel (string name)
2777 if (labels != null){
2778 if (labels.Contains (name))
2779 return ((LabeledStatement) labels [name]);
2783 return Parent.LookupLabel (name);
2788 VariableInfo this_variable = null;
2791 // Returns the "this" instance variable of this block.
2792 // See AddThisVariable() for more information.
2794 public VariableInfo ThisVariable {
2796 if (this_variable != null)
2797 return this_variable;
2798 else if (Parent != null)
2799 return Parent.ThisVariable;
2805 Hashtable child_variable_names;
2808 // Marks a variable with name @name as being used in a child block.
2809 // If a variable name has been used in a child block, it's illegal to
2810 // declare a variable with the same name in the current block.
2812 public void AddChildVariableName (string name)
2814 if (child_variable_names == null)
2815 child_variable_names = new CaseInsensitiveHashtable ();
2817 if (!child_variable_names.Contains (name))
2818 child_variable_names.Add (name, true);
2822 // Marks all variables from block @block and all its children as being
2823 // used in a child block.
2825 public void AddChildVariableNames (Block block)
2827 if (block.Variables != null) {
2828 foreach (string name in block.Variables.Keys)
2829 AddChildVariableName (name);
2832 foreach (Block child in block.children) {
2833 if (child.Variables != null) {
2834 foreach (string name in child.Variables.Keys)
2835 AddChildVariableName (name);
2841 // Checks whether a variable name has already been used in a child block.
2843 public bool IsVariableNameUsedInChildBlock (string name)
2845 if (child_variable_names == null)
2848 return child_variable_names.Contains (name);
2852 // This is used by non-static `struct' constructors which do not have an
2853 // initializer - in this case, the constructor must initialize all of the
2854 // struct's fields. To do this, we add a "this" variable and use the flow
2855 // analysis code to ensure that it's been fully initialized before control
2856 // leaves the constructor.
2858 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2860 if (this_variable != null)
2861 return this_variable;
2863 this_variable = new VariableInfo (tc, ID, l);
2865 if (variables == null)
2866 variables = new CaseInsensitiveHashtable ();
2867 variables.Add ("this", this_variable);
2869 return this_variable;
2872 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2874 if (variables == null)
2875 variables = new CaseInsensitiveHashtable ();
2877 VariableInfo vi = GetVariableInfo (name);
2880 Report.Error (30616, l, "A local variable named `" + name + "' " +
2881 "cannot be declared in this scope since it would " +
2882 "give a different meaning to `" + name + "', which " +
2883 "is already used in a `parent or current' scope to " +
2884 "denote something else");
2886 Report.Error (30290, l, "A local variable `" + name + "' is already " +
2887 "defined in this scope");
2891 if (IsVariableNameUsedInChildBlock (name)) {
2892 Report.Error (136, l, "A local variable named `" + name + "' " +
2893 "cannot be declared in this scope since it would " +
2894 "give a different meaning to `" + name + "', which " +
2895 "is already used in a `child' scope to denote something " +
2902 Parameter p = pars.GetParameterByName (name, out idx);
2904 Report.Error (30616, l, "A local variable named `" + name + "' " +
2905 "cannot be declared in this scope since it would " +
2906 "give a different meaning to `" + name + "', which " +
2907 "is already used in a `parent or current' scope to " +
2908 "denote something else");
2913 vi = new VariableInfo (type, name, ID, l);
2915 variables.Add (name, vi);
2917 if (variables_initialized)
2918 throw new Exception ();
2920 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2924 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2926 if (AddVariable (type, name, pars, l) == null)
2929 if (constants == null)
2930 constants = new CaseInsensitiveHashtable ();
2932 constants.Add (name, value);
2936 public Hashtable Variables {
2942 public VariableInfo GetVariableInfo (string name)
2944 if (variables != null) {
2946 temp = variables [name];
2949 return (VariableInfo) temp;
2954 return Parent.GetVariableInfo (name);
2959 public Expression GetVariableType (string name)
2961 VariableInfo vi = GetVariableInfo (name);
2969 public Expression GetConstantExpression (string name)
2971 if (constants != null) {
2973 temp = constants [name];
2976 return (Expression) temp;
2980 return Parent.GetConstantExpression (name);
2986 /// True if the variable named @name has been defined
2989 public bool IsVariableDefined (string name)
2991 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2992 if (variables != null) {
2993 if (variables.Contains (name))
2998 return Parent.IsVariableDefined (name);
3004 /// True if the variable named @name is a constant
3006 public bool IsConstant (string name)
3008 Expression e = null;
3010 e = GetConstantExpression (name);
3016 /// Use to fetch the statement associated with this label
3018 public Statement this [string name] {
3020 return (Statement) labels [name];
3024 Parameters parameters = null;
3025 public Parameters Parameters {
3028 return Parent.Parameters;
3035 /// A list of labels that were not used within this block
3037 public string [] GetUnreferenced ()
3039 // FIXME: Implement me
3043 public void AddStatement (Statement s)
3060 bool variables_initialized = false;
3061 int count_variables = 0, first_variable = 0;
3063 void UpdateVariableInfo (EmitContext ec)
3065 DeclSpace ds = ec.DeclSpace;
3070 first_variable += Parent.CountVariables;
3072 count_variables = first_variable;
3073 if (variables != null) {
3074 foreach (VariableInfo vi in variables.Values) {
3075 if (!vi.Resolve (ds)) {
3080 vi.Number = ++count_variables;
3082 if (vi.StructInfo != null)
3083 count_variables += vi.StructInfo.Count;
3087 variables_initialized = true;
3092 // The number of local variables in this block
3094 public int CountVariables
3097 if (!variables_initialized)
3098 throw new Exception ();
3100 return count_variables;
3105 /// Emits the variable declarations and labels.
3108 /// tc: is our typecontainer (to resolve type references)
3109 /// ig: is the code generator:
3110 /// toplevel: the toplevel block. This is used for checking
3111 /// that no two labels with the same name are used.
3113 public void EmitMeta (EmitContext ec, Block toplevel)
3115 //DeclSpace ds = ec.DeclSpace;
3116 ILGenerator ig = ec.ig;
3118 if (!variables_initialized)
3119 UpdateVariableInfo (ec);
3122 // Process this block variables
3124 if (variables != null){
3125 local_builders = new CaseInsensitiveHashtable ();
3127 foreach (DictionaryEntry de in variables){
3128 string name = (string) de.Key;
3129 VariableInfo vi = (VariableInfo) de.Value;
3131 if (vi.VariableType == null)
3134 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3136 if (CodeGen.SymbolWriter != null)
3137 vi.LocalBuilder.SetLocalSymInfo (name);
3139 if (constants == null)
3142 Expression cv = (Expression) constants [name];
3146 Expression e = cv.Resolve (ec);
3150 if (!(e is Constant)){
3151 Report.Error (133, vi.Location,
3152 "The expression being assigned to `" +
3153 name + "' must be constant (" + e + ")");
3157 constants.Remove (name);
3158 constants.Add (name, e);
3163 // Now, handle the children
3165 if (children != null){
3166 foreach (Block b in children)
3167 b.EmitMeta (ec, toplevel);
3171 public void UsageWarning ()
3175 if (variables != null){
3176 foreach (DictionaryEntry de in variables){
3177 VariableInfo vi = (VariableInfo) de.Value;
3182 name = (string) de.Key;
3186 219, vi.Location, "The variable `" + name +
3187 "' is assigned but its value is never used");
3190 168, vi.Location, "The variable `" +
3192 "' is declared but never used");
3197 if (children != null)
3198 foreach (Block b in children)
3202 bool has_ret = false;
3204 public override bool Resolve (EmitContext ec)
3206 Block prev_block = ec.CurrentBlock;
3209 ec.CurrentBlock = this;
3210 ec.StartFlowBranching (this);
3212 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3214 if (!variables_initialized)
3215 UpdateVariableInfo (ec);
3217 ArrayList new_statements = new ArrayList ();
3218 bool unreachable = false, warning_shown = false;
3220 foreach (Statement s in statements){
3221 if (unreachable && !(s is LabeledStatement)) {
3222 if (!warning_shown && !(s is EmptyStatement)) {
3223 warning_shown = true;
3224 Warning_DeadCodeFound (s.loc);
3230 if (s.Resolve (ec) == false) {
3235 if (s is LabeledStatement)
3236 unreachable = false;
3238 unreachable = ! ec.CurrentBranching.IsReachable ();
3240 new_statements.Add (s);
3243 statements = new_statements;
3245 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3247 FlowReturns returns = ec.EndFlowBranching ();
3248 ec.CurrentBlock = prev_block;
3250 // If we're a non-static `struct' constructor which doesn't have an
3251 // initializer, then we must initialize all of the struct's fields.
3252 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3253 !this_variable.IsAssigned (ec, loc))
3256 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3257 foreach (LabeledStatement label in labels.Values)
3258 if (!label.HasBeenReferenced)
3259 Report.Warning (164, label.Location,
3260 "This label has not been referenced");
3263 if ((returns == FlowReturns.ALWAYS) ||
3264 (returns == FlowReturns.EXCEPTION) ||
3265 (returns == FlowReturns.UNREACHABLE))
3271 protected override bool DoEmit (EmitContext ec)
3273 Block prev_block = ec.CurrentBlock;
3275 ec.CurrentBlock = this;
3277 ec.Mark (StartLocation);
3278 foreach (Statement s in statements)
3281 ec.Mark (EndLocation);
3283 ec.CurrentBlock = prev_block;
3288 public class SwitchLabel {
3291 public Location loc;
3292 public Label ILLabel;
3293 public Label ILLabelCode;
3296 // if expr == null, then it is the default case.
3298 public SwitchLabel (Expression expr, Location l)
3304 public Expression Label {
3310 public object Converted {
3317 // Resolves the expression, reduces it to a literal if possible
3318 // and then converts it to the requested type.
3320 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3322 ILLabel = ec.ig.DefineLabel ();
3323 ILLabelCode = ec.ig.DefineLabel ();
3328 Expression e = label.Resolve (ec);
3333 if (!(e is Constant)){
3334 Console.WriteLine ("Value is: " + label);
3335 Report.Error (150, loc, "A constant value is expected");
3339 if (e is StringConstant || e is NullLiteral){
3340 if (required_type == TypeManager.string_type){
3342 ILLabel = ec.ig.DefineLabel ();
3347 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3348 if (converted == null)
3355 public class SwitchSection {
3356 // An array of SwitchLabels.
3357 public readonly ArrayList Labels;
3358 public readonly Block Block;
3360 public SwitchSection (ArrayList labels, Block block)
3367 public class Switch : Statement {
3368 public readonly ArrayList Sections;
3369 public Expression Expr;
3372 /// Maps constants whose type type SwitchType to their SwitchLabels.
3374 public Hashtable Elements;
3377 /// The governing switch type
3379 public Type SwitchType;
3385 Label default_target;
3386 Expression new_expr;
3389 // The types allowed to be implicitly cast from
3390 // on the governing type
3392 static Type [] allowed_types;
3394 public Switch (Expression e, ArrayList sects, Location l)
3401 public bool GotDefault {
3407 public Label DefaultTarget {
3409 return default_target;
3414 // Determines the governing type for a switch. The returned
3415 // expression might be the expression from the switch, or an
3416 // expression that includes any potential conversions to the
3417 // integral types or to string.
3419 Expression SwitchGoverningType (EmitContext ec, Type t)
3421 if (t == TypeManager.int32_type ||
3422 t == TypeManager.uint32_type ||
3423 t == TypeManager.char_type ||
3424 t == TypeManager.byte_type ||
3425 t == TypeManager.sbyte_type ||
3426 t == TypeManager.ushort_type ||
3427 t == TypeManager.short_type ||
3428 t == TypeManager.uint64_type ||
3429 t == TypeManager.int64_type ||
3430 t == TypeManager.string_type ||
3431 t == TypeManager.bool_type ||
3432 t.IsSubclassOf (TypeManager.enum_type))
3435 if (allowed_types == null){
3436 allowed_types = new Type [] {
3437 TypeManager.sbyte_type,
3438 TypeManager.byte_type,
3439 TypeManager.short_type,
3440 TypeManager.ushort_type,
3441 TypeManager.int32_type,
3442 TypeManager.uint32_type,
3443 TypeManager.int64_type,
3444 TypeManager.uint64_type,
3445 TypeManager.char_type,
3446 TypeManager.bool_type,
3447 TypeManager.string_type
3452 // Try to find a *user* defined implicit conversion.
3454 // If there is no implicit conversion, or if there are multiple
3455 // conversions, we have to report an error
3457 Expression converted = null;
3458 foreach (Type tt in allowed_types){
3461 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3465 if (converted != null){
3466 Report.Error (-12, loc, "More than one conversion to an integral " +
3467 " type exists for type `" +
3468 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3476 void error152 (string n)
3479 152, "The label `" + n + ":' " +
3480 "is already present on this switch statement");
3484 // Performs the basic sanity checks on the switch statement
3485 // (looks for duplicate keys and non-constant expressions).
3487 // It also returns a hashtable with the keys that we will later
3488 // use to compute the switch tables
3490 bool CheckSwitch (EmitContext ec)
3494 Elements = new CaseInsensitiveHashtable ();
3496 got_default = false;
3498 if (TypeManager.IsEnumType (SwitchType)){
3499 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3501 compare_type = SwitchType;
3503 foreach (SwitchSection ss in Sections){
3504 foreach (SwitchLabel sl in ss.Labels){
3505 if (!sl.ResolveAndReduce (ec, SwitchType)){
3510 if (sl.Label == null){
3512 error152 ("default");
3519 object key = sl.Converted;
3521 if (key is Constant)
3522 key = ((Constant) key).GetValue ();
3525 key = NullLiteral.Null;
3527 string lname = null;
3528 if (compare_type == TypeManager.uint64_type){
3529 ulong v = (ulong) key;
3531 if (Elements.Contains (v))
3532 lname = v.ToString ();
3534 Elements.Add (v, sl);
3535 } else if (compare_type == TypeManager.int64_type){
3536 long v = (long) key;
3538 if (Elements.Contains (v))
3539 lname = v.ToString ();
3541 Elements.Add (v, sl);
3542 } else if (compare_type == TypeManager.uint32_type){
3543 uint v = (uint) key;
3545 if (Elements.Contains (v))
3546 lname = v.ToString ();
3548 Elements.Add (v, sl);
3549 } else if (compare_type == TypeManager.char_type){
3550 char v = (char) key;
3552 if (Elements.Contains (v))
3553 lname = v.ToString ();
3555 Elements.Add (v, sl);
3556 } else if (compare_type == TypeManager.byte_type){
3557 byte v = (byte) key;
3559 if (Elements.Contains (v))
3560 lname = v.ToString ();
3562 Elements.Add (v, sl);
3563 } else if (compare_type == TypeManager.sbyte_type){
3564 sbyte v = (sbyte) key;
3566 if (Elements.Contains (v))
3567 lname = v.ToString ();
3569 Elements.Add (v, sl);
3570 } else if (compare_type == TypeManager.short_type){
3571 short v = (short) key;
3573 if (Elements.Contains (v))
3574 lname = v.ToString ();
3576 Elements.Add (v, sl);
3577 } else if (compare_type == TypeManager.ushort_type){
3578 ushort v = (ushort) key;
3580 if (Elements.Contains (v))
3581 lname = v.ToString ();
3583 Elements.Add (v, sl);
3584 } else if (compare_type == TypeManager.string_type){
3585 if (key is NullLiteral){
3586 if (Elements.Contains (NullLiteral.Null))
3589 Elements.Add (NullLiteral.Null, null);
3591 string s = (string) key;
3593 if (Elements.Contains (s))
3596 Elements.Add (s, sl);
3598 } else if (compare_type == TypeManager.int32_type) {
3601 if (Elements.Contains (v))
3602 lname = v.ToString ();
3604 Elements.Add (v, sl);
3605 } else if (compare_type == TypeManager.bool_type) {
3606 bool v = (bool) key;
3608 if (Elements.Contains (v))
3609 lname = v.ToString ();
3611 Elements.Add (v, sl);
3615 throw new Exception ("Unknown switch type!" +
3616 SwitchType + " " + compare_type);
3620 error152 ("case + " + lname);
3631 void EmitObjectInteger (ILGenerator ig, object k)
3634 IntConstant.EmitInt (ig, (int) k);
3635 else if (k is Constant) {
3636 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3639 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3642 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3644 IntConstant.EmitInt (ig, (int) (long) k);
3645 ig.Emit (OpCodes.Conv_I8);
3648 LongConstant.EmitLong (ig, (long) k);
3650 else if (k is ulong)
3652 if ((ulong) k < (1L<<32))
3654 IntConstant.EmitInt (ig, (int) (long) k);
3655 ig.Emit (OpCodes.Conv_U8);
3659 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3663 IntConstant.EmitInt (ig, (int) ((char) k));
3664 else if (k is sbyte)
3665 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3667 IntConstant.EmitInt (ig, (int) ((byte) k));
3668 else if (k is short)
3669 IntConstant.EmitInt (ig, (int) ((short) k));
3670 else if (k is ushort)
3671 IntConstant.EmitInt (ig, (int) ((ushort) k));
3673 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3675 throw new Exception ("Unhandled case");
3678 // structure used to hold blocks of keys while calculating table switch
3679 class KeyBlock : IComparable
3681 public KeyBlock (long _nFirst)
3683 nFirst = nLast = _nFirst;
3687 public ArrayList rgKeys = null;
3690 get { return (int) (nLast - nFirst + 1); }
3692 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3694 return kbLast.nLast - kbFirst.nFirst + 1;
3696 public int CompareTo (object obj)
3698 KeyBlock kb = (KeyBlock) obj;
3699 int nLength = Length;
3700 int nLengthOther = kb.Length;
3701 if (nLengthOther == nLength)
3702 return (int) (kb.nFirst - nFirst);
3703 return nLength - nLengthOther;
3708 /// This method emits code for a lookup-based switch statement (non-string)
3709 /// Basically it groups the cases into blocks that are at least half full,
3710 /// and then spits out individual lookup opcodes for each block.
3711 /// It emits the longest blocks first, and short blocks are just
3712 /// handled with direct compares.
3714 /// <param name="ec"></param>
3715 /// <param name="val"></param>
3716 /// <returns></returns>
3717 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3719 int cElements = Elements.Count;
3720 object [] rgKeys = new object [cElements];
3721 Elements.Keys.CopyTo (rgKeys, 0);
3722 Array.Sort (rgKeys);
3724 // initialize the block list with one element per key
3725 ArrayList rgKeyBlocks = new ArrayList ();
3726 foreach (object key in rgKeys)
3727 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3730 // iteratively merge the blocks while they are at least half full
3731 // there's probably a really cool way to do this with a tree...
3732 while (rgKeyBlocks.Count > 1)
3734 ArrayList rgKeyBlocksNew = new ArrayList ();
3735 kbCurr = (KeyBlock) rgKeyBlocks [0];
3736 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3738 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3739 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3742 kbCurr.nLast = kb.nLast;
3746 // start a new block
3747 rgKeyBlocksNew.Add (kbCurr);
3751 rgKeyBlocksNew.Add (kbCurr);
3752 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3754 rgKeyBlocks = rgKeyBlocksNew;
3757 // initialize the key lists
3758 foreach (KeyBlock kb in rgKeyBlocks)
3759 kb.rgKeys = new ArrayList ();
3761 // fill the key lists
3763 if (rgKeyBlocks.Count > 0) {
3764 kbCurr = (KeyBlock) rgKeyBlocks [0];
3765 foreach (object key in rgKeys)
3767 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3769 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3770 kbCurr.rgKeys.Add (key);
3774 // sort the blocks so we can tackle the largest ones first
3775 rgKeyBlocks.Sort ();
3777 // okay now we can start...
3778 ILGenerator ig = ec.ig;
3779 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3780 Label lblDefault = ig.DefineLabel ();
3782 Type typeKeys = null;
3783 if (rgKeys.Length > 0)
3784 typeKeys = rgKeys [0].GetType (); // used for conversions
3786 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3788 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3789 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3792 foreach (object key in kb.rgKeys)
3794 ig.Emit (OpCodes.Ldloc, val);
3795 EmitObjectInteger (ig, key);
3796 SwitchLabel sl = (SwitchLabel) Elements [key];
3797 ig.Emit (OpCodes.Beq, sl.ILLabel);
3802 // TODO: if all the keys in the block are the same and there are
3803 // no gaps/defaults then just use a range-check.
3804 if (SwitchType == TypeManager.int64_type ||
3805 SwitchType == TypeManager.uint64_type)
3807 // TODO: optimize constant/I4 cases
3809 // check block range (could be > 2^31)
3810 ig.Emit (OpCodes.Ldloc, val);
3811 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3812 ig.Emit (OpCodes.Blt, lblDefault);
3813 ig.Emit (OpCodes.Ldloc, val);
3814 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3815 ig.Emit (OpCodes.Bgt, lblDefault);
3818 ig.Emit (OpCodes.Ldloc, val);
3821 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3822 ig.Emit (OpCodes.Sub);
3824 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3829 ig.Emit (OpCodes.Ldloc, val);
3830 int nFirst = (int) kb.nFirst;
3833 IntConstant.EmitInt (ig, nFirst);
3834 ig.Emit (OpCodes.Sub);
3836 else if (nFirst < 0)
3838 IntConstant.EmitInt (ig, -nFirst);
3839 ig.Emit (OpCodes.Add);
3843 // first, build the list of labels for the switch
3845 int cJumps = kb.Length;
3846 Label [] rgLabels = new Label [cJumps];
3847 for (int iJump = 0; iJump < cJumps; iJump++)
3849 object key = kb.rgKeys [iKey];
3850 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3852 SwitchLabel sl = (SwitchLabel) Elements [key];
3853 rgLabels [iJump] = sl.ILLabel;
3857 rgLabels [iJump] = lblDefault;
3859 // emit the switch opcode
3860 ig.Emit (OpCodes.Switch, rgLabels);
3863 // mark the default for this block
3865 ig.MarkLabel (lblDefault);
3868 // TODO: find the default case and emit it here,
3869 // to prevent having to do the following jump.
3870 // make sure to mark other labels in the default section
3872 // the last default just goes to the end
3873 ig.Emit (OpCodes.Br, lblDefault);
3875 // now emit the code for the sections
3876 bool fFoundDefault = false;
3877 bool fAllReturn = true;
3878 foreach (SwitchSection ss in Sections)
3880 foreach (SwitchLabel sl in ss.Labels)
3882 ig.MarkLabel (sl.ILLabel);
3883 ig.MarkLabel (sl.ILLabelCode);
3884 if (sl.Label == null)
3886 ig.MarkLabel (lblDefault);
3887 fFoundDefault = true;
3890 bool returns = ss.Block.Emit (ec);
3891 fAllReturn &= returns;
3892 //ig.Emit (OpCodes.Br, lblEnd);
3895 if (!fFoundDefault) {
3896 ig.MarkLabel (lblDefault);
3899 ig.MarkLabel (lblEnd);
3904 // This simple emit switch works, but does not take advantage of the
3906 // TODO: remove non-string logic from here
3907 // TODO: binary search strings?
3909 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3911 ILGenerator ig = ec.ig;
3912 Label end_of_switch = ig.DefineLabel ();
3913 Label next_test = ig.DefineLabel ();
3914 Label null_target = ig.DefineLabel ();
3915 bool default_found = false;
3916 bool first_test = true;
3917 bool pending_goto_end = false;
3918 bool all_return = true;
3919 bool is_string = false;
3923 // Special processing for strings: we cant compare
3926 if (SwitchType == TypeManager.string_type){
3927 ig.Emit (OpCodes.Ldloc, val);
3930 if (Elements.Contains (NullLiteral.Null)){
3931 ig.Emit (OpCodes.Brfalse, null_target);
3933 ig.Emit (OpCodes.Brfalse, default_target);
3935 ig.Emit (OpCodes.Ldloc, val);
3936 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3937 ig.Emit (OpCodes.Stloc, val);
3940 foreach (SwitchSection ss in Sections){
3941 Label sec_begin = ig.DefineLabel ();
3943 if (pending_goto_end)
3944 ig.Emit (OpCodes.Br, end_of_switch);
3946 int label_count = ss.Labels.Count;
3948 foreach (SwitchLabel sl in ss.Labels){
3949 ig.MarkLabel (sl.ILLabel);
3952 ig.MarkLabel (next_test);
3953 next_test = ig.DefineLabel ();
3956 // If we are the default target
3958 if (sl.Label == null){
3959 ig.MarkLabel (default_target);
3960 default_found = true;
3962 object lit = sl.Converted;
3964 if (lit is NullLiteral){
3966 if (label_count == 1)
3967 ig.Emit (OpCodes.Br, next_test);
3972 StringConstant str = (StringConstant) lit;
3974 ig.Emit (OpCodes.Ldloc, val);
3975 ig.Emit (OpCodes.Ldstr, str.Value);
3976 if (label_count == 1)
3977 ig.Emit (OpCodes.Bne_Un, next_test);
3979 ig.Emit (OpCodes.Beq, sec_begin);
3981 ig.Emit (OpCodes.Ldloc, val);
3982 EmitObjectInteger (ig, lit);
3983 ig.Emit (OpCodes.Ceq);
3984 if (label_count == 1)
3985 ig.Emit (OpCodes.Brfalse, next_test);
3987 ig.Emit (OpCodes.Brtrue, sec_begin);
3991 if (label_count != 1)
3992 ig.Emit (OpCodes.Br, next_test);
3995 ig.MarkLabel (null_target);
3996 ig.MarkLabel (sec_begin);
3997 foreach (SwitchLabel sl in ss.Labels)
3998 ig.MarkLabel (sl.ILLabelCode);
4000 bool returns = ss.Block.Emit (ec);
4002 pending_goto_end = false;
4005 pending_goto_end = true;
4009 if (!default_found){
4010 ig.MarkLabel (default_target);
4013 ig.MarkLabel (next_test);
4014 ig.MarkLabel (end_of_switch);
4019 public override bool Resolve (EmitContext ec)
4021 Expr = Expr.Resolve (ec);
4025 new_expr = SwitchGoverningType (ec, Expr.Type);
4026 if (new_expr == null){
4027 Report.Error (151, loc, "An integer type or string was expected for switch");
4032 SwitchType = new_expr.Type;
4034 if (!CheckSwitch (ec))
4037 Switch old_switch = ec.Switch;
4039 ec.Switch.SwitchType = SwitchType;
4041 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
4044 foreach (SwitchSection ss in Sections){
4046 ec.CurrentBranching.CreateSibling ();
4050 if (ss.Block.Resolve (ec) != true)
4056 ec.CurrentBranching.CreateSibling ();
4058 ec.EndFlowBranching ();
4059 ec.Switch = old_switch;
4064 protected override bool DoEmit (EmitContext ec)
4066 // Store variable for comparission purposes
4067 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
4069 ec.ig.Emit (OpCodes.Stloc, value);
4071 ILGenerator ig = ec.ig;
4073 default_target = ig.DefineLabel ();
4076 // Setup the codegen context
4078 Label old_end = ec.LoopEnd;
4079 Switch old_switch = ec.Switch;
4081 ec.LoopEnd = ig.DefineLabel ();
4086 if (SwitchType == TypeManager.string_type)
4087 all_return = SimpleSwitchEmit (ec, value);
4089 all_return = TableSwitchEmit (ec, value);
4091 // Restore context state.
4092 ig.MarkLabel (ec.LoopEnd);
4095 // Restore the previous context
4097 ec.LoopEnd = old_end;
4098 ec.Switch = old_switch;
4104 public class Lock : Statement {
4106 Statement Statement;
4108 public Lock (Expression expr, Statement stmt, Location l)
4115 public override bool Resolve (EmitContext ec)
4117 expr = expr.Resolve (ec);
4118 return Statement.Resolve (ec) && expr != null;
4121 protected override bool DoEmit (EmitContext ec)
4123 Type type = expr.Type;
4126 if (type.IsValueType){
4127 Report.Error (30582, loc, "lock statement requires the expression to be " +
4128 " a reference type (type is: `" +
4129 TypeManager.MonoBASIC_Name (type) + "'");
4133 ILGenerator ig = ec.ig;
4134 LocalBuilder temp = ig.DeclareLocal (type);
4137 ig.Emit (OpCodes.Dup);
4138 ig.Emit (OpCodes.Stloc, temp);
4139 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4142 ig.BeginExceptionBlock ();
4143 bool old_in_try = ec.InTry;
4145 Label finish = ig.DefineLabel ();
4146 val = Statement.Emit (ec);
4147 ec.InTry = old_in_try;
4148 // ig.Emit (OpCodes.Leave, finish);
4150 ig.MarkLabel (finish);
4153 ig.BeginFinallyBlock ();
4154 ig.Emit (OpCodes.Ldloc, temp);
4155 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4156 ig.EndExceptionBlock ();
4162 public class Unchecked : Statement {
4163 public readonly Block Block;
4165 public Unchecked (Block b)
4170 public override bool Resolve (EmitContext ec)
4172 return Block.Resolve (ec);
4175 protected override bool DoEmit (EmitContext ec)
4177 bool previous_state = ec.CheckState;
4178 bool previous_state_const = ec.ConstantCheckState;
4181 ec.CheckState = false;
4182 ec.ConstantCheckState = false;
4183 val = Block.Emit (ec);
4184 ec.CheckState = previous_state;
4185 ec.ConstantCheckState = previous_state_const;
4191 public class Checked : Statement {
4192 public readonly Block Block;
4194 public Checked (Block b)
4199 public override bool Resolve (EmitContext ec)
4201 bool previous_state = ec.CheckState;
4202 bool previous_state_const = ec.ConstantCheckState;
4204 ec.CheckState = true;
4205 ec.ConstantCheckState = true;
4206 bool ret = Block.Resolve (ec);
4207 ec.CheckState = previous_state;
4208 ec.ConstantCheckState = previous_state_const;
4213 protected override bool DoEmit (EmitContext ec)
4215 bool previous_state = ec.CheckState;
4216 bool previous_state_const = ec.ConstantCheckState;
4219 ec.CheckState = true;
4220 ec.ConstantCheckState = true;
4221 val = Block.Emit (ec);
4222 ec.CheckState = previous_state;
4223 ec.ConstantCheckState = previous_state_const;
4229 public class Unsafe : Statement {
4230 public readonly Block Block;
4232 public Unsafe (Block b)
4237 public override bool Resolve (EmitContext ec)
4239 bool previous_state = ec.InUnsafe;
4243 val = Block.Resolve (ec);
4244 ec.InUnsafe = previous_state;
4249 protected override bool DoEmit (EmitContext ec)
4251 bool previous_state = ec.InUnsafe;
4255 val = Block.Emit (ec);
4256 ec.InUnsafe = previous_state;
4265 public class Fixed : Statement {
4267 ArrayList declarators;
4268 Statement statement;
4273 public bool is_object;
4274 public VariableInfo vi;
4275 public Expression expr;
4276 public Expression converted;
4279 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4282 declarators = decls;
4287 public override bool Resolve (EmitContext ec)
4289 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4290 if (expr_type == null)
4293 data = new FixedData [declarators.Count];
4296 foreach (Pair p in declarators){
4297 VariableInfo vi = (VariableInfo) p.First;
4298 Expression e = (Expression) p.Second;
4303 // The rules for the possible declarators are pretty wise,
4304 // but the production on the grammar is more concise.
4306 // So we have to enforce these rules here.
4308 // We do not resolve before doing the case 1 test,
4309 // because the grammar is explicit in that the token &
4310 // is present, so we need to test for this particular case.
4314 // Case 1: & object.
4316 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4317 Expression child = ((Unary) e).Expr;
4320 if (child is ParameterReference || child is LocalVariableReference){
4323 "No need to use fixed statement for parameters or " +
4324 "local variable declarations (address is already " +
4333 child = ((Unary) e).Expr;
4335 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4338 data [i].is_object = true;
4340 data [i].converted = null;
4354 if (e.Type.IsArray){
4355 Type array_type = e.Type.GetElementType ();
4359 // Provided that array_type is unmanaged,
4361 if (!TypeManager.VerifyUnManaged (array_type, loc))
4365 // and T* is implicitly convertible to the
4366 // pointer type given in the fixed statement.
4368 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4370 Expression converted = Expression.ConvertImplicitRequired (
4371 ec, array_ptr, vi.VariableType, loc);
4372 if (converted == null)
4375 data [i].is_object = false;
4377 data [i].converted = converted;
4387 if (e.Type == TypeManager.string_type){
4388 data [i].is_object = false;
4390 data [i].converted = null;
4396 return statement.Resolve (ec);
4399 protected override bool DoEmit (EmitContext ec)
4401 ILGenerator ig = ec.ig;
4403 bool is_ret = false;
4405 for (int i = 0; i < data.Length; i++) {
4406 VariableInfo vi = data [i].vi;
4409 // Case 1: & object.
4411 if (data [i].is_object) {
4413 // Store pointer in pinned location
4415 data [i].expr.Emit (ec);
4416 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4418 is_ret = statement.Emit (ec);
4420 // Clear the pinned variable.
4421 ig.Emit (OpCodes.Ldc_I4_0);
4422 ig.Emit (OpCodes.Conv_U);
4423 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4431 if (data [i].expr.Type.IsArray){
4433 // Store pointer in pinned location
4435 data [i].converted.Emit (ec);
4437 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4439 is_ret = statement.Emit (ec);
4441 // Clear the pinned variable.
4442 ig.Emit (OpCodes.Ldc_I4_0);
4443 ig.Emit (OpCodes.Conv_U);
4444 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4452 if (data [i].expr.Type == TypeManager.string_type){
4453 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4454 TypeManager.MakePinned (pinned_string);
4456 data [i].expr.Emit (ec);
4457 ig.Emit (OpCodes.Stloc, pinned_string);
4459 Expression sptr = new StringPtr (pinned_string, loc);
4460 Expression converted = Expression.ConvertImplicitRequired (
4461 ec, sptr, vi.VariableType, loc);
4463 if (converted == null)
4466 converted.Emit (ec);
4467 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4469 is_ret = statement.Emit (ec);
4471 // Clear the pinned variable
4472 ig.Emit (OpCodes.Ldnull);
4473 ig.Emit (OpCodes.Stloc, pinned_string);
4481 public class Catch {
4482 public readonly string Name;
4483 public readonly Block Block;
4484 public Expression Clause;
4485 public readonly Location Location;
4487 Expression type_expr;
4488 //Expression clus_expr;
4491 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4500 public Type CatchType {
4506 public bool IsGeneral {
4508 return type_expr == null;
4512 public bool Resolve (EmitContext ec)
4514 if (type_expr != null) {
4515 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4519 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4520 Report.Error (30665, Location,
4521 "The type caught or thrown must be derived " +
4522 "from System.Exception");
4528 if (Clause != null) {
4529 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4530 if (Clause == null) {
4535 if (!Block.Resolve (ec))
4542 public class Try : Statement {
4543 public readonly Block Fini, Block;
4544 public readonly ArrayList Specific;
4545 public readonly Catch General;
4548 // specific, general and fini might all be null.
4550 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4552 if (specific == null && general == null){
4553 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4557 this.Specific = specific;
4558 this.General = general;
4563 public override bool Resolve (EmitContext ec)
4567 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4569 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4571 bool old_in_try = ec.InTry;
4574 if (!Block.Resolve (ec))
4577 ec.InTry = old_in_try;
4579 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4581 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4583 foreach (Catch c in Specific){
4584 ec.CurrentBranching.CreateSibling ();
4585 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4587 if (c.Name != null) {
4588 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4590 throw new Exception ();
4595 bool old_in_catch = ec.InCatch;
4598 if (!c.Resolve (ec))
4601 ec.InCatch = old_in_catch;
4603 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4605 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4606 vector.AndLocals (current);
4609 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4611 if (General != null){
4612 ec.CurrentBranching.CreateSibling ();
4613 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4615 bool old_in_catch = ec.InCatch;
4618 if (!General.Resolve (ec))
4621 ec.InCatch = old_in_catch;
4623 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4625 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4626 vector.AndLocals (current);
4629 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4632 ec.CurrentBranching.CreateSiblingForFinally ();
4633 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4635 bool old_in_finally = ec.InFinally;
4636 ec.InFinally = true;
4638 if (!Fini.Resolve (ec))
4641 ec.InFinally = old_in_finally;
4644 FlowReturns returns = ec.EndFlowBranching ();
4646 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4648 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4650 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4651 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4654 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4656 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4661 protected override bool DoEmit (EmitContext ec)
4663 ILGenerator ig = ec.ig;
4664 Label finish = ig.DefineLabel ();;
4668 ig.BeginExceptionBlock ();
4669 bool old_in_try = ec.InTry;
4671 returns = Block.Emit (ec);
4672 ec.InTry = old_in_try;
4675 // System.Reflection.Emit provides this automatically:
4676 // ig.Emit (OpCodes.Leave, finish);
4678 bool old_in_catch = ec.InCatch;
4680 //DeclSpace ds = ec.DeclSpace;
4682 foreach (Catch c in Specific){
4685 ig.BeginCatchBlock (c.CatchType);
4687 if (c.Name != null){
4688 vi = c.Block.GetVariableInfo (c.Name);
4690 throw new Exception ("Variable does not exist in this block");
4692 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4694 ig.Emit (OpCodes.Pop);
4697 // if when clause is there
4699 if (c.Clause != null) {
4700 if (c.Clause is BoolConstant) {
4701 bool take = ((BoolConstant) c.Clause).Value;
4704 if (!c.Block.Emit (ec))
4707 EmitBoolExpression (ec, c.Clause, finish, false);
4708 if (!c.Block.Emit (ec))
4712 if (!c.Block.Emit (ec))
4716 if (General != null){
4717 ig.BeginCatchBlock (TypeManager.object_type);
4718 ig.Emit (OpCodes.Pop);
4720 if (General.Clause != null) {
4721 if (General.Clause is BoolConstant) {
4722 bool take = ((BoolConstant) General.Clause).Value;
4724 if (!General.Block.Emit (ec))
4727 EmitBoolExpression (ec, General.Clause, finish, false);
4728 if (!General.Block.Emit (ec))
4732 if (!General.Block.Emit (ec))
4736 ec.InCatch = old_in_catch;
4738 ig.MarkLabel (finish);
4740 ig.BeginFinallyBlock ();
4741 bool old_in_finally = ec.InFinally;
4742 ec.InFinally = true;
4744 ec.InFinally = old_in_finally;
4747 ig.EndExceptionBlock ();
4750 if (!returns || ec.InTry || ec.InCatch)
4753 // Unfortunately, System.Reflection.Emit automatically emits a leave
4754 // to the end of the finally block. This is a problem if `returns'
4755 // is true since we may jump to a point after the end of the method.
4756 // As a workaround, emit an explicit ret here.
4758 if (ec.ReturnType != null)
4759 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4760 ec.ig.Emit (OpCodes.Ret);
4766 public class Using : Statement {
4767 object expression_or_block;
4768 Statement Statement;
4773 Expression [] converted_vars;
4774 ExpressionStatement [] assign;
4776 public Using (object expression_or_block, Statement stmt, Location l)
4778 this.expression_or_block = expression_or_block;
4784 // Resolves for the case of using using a local variable declaration.
4786 bool ResolveLocalVariableDecls (EmitContext ec)
4788 bool need_conv = false;
4789 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4792 if (expr_type == null)
4796 // The type must be an IDisposable or an implicit conversion
4799 converted_vars = new Expression [var_list.Count];
4800 assign = new ExpressionStatement [var_list.Count];
4801 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4802 foreach (DictionaryEntry e in var_list){
4803 Expression var = (Expression) e.Key;
4805 var = var.ResolveLValue (ec, new EmptyExpression ());
4809 converted_vars [i] = Expression.ConvertImplicitRequired (
4810 ec, var, TypeManager.idisposable_type, loc);
4812 if (converted_vars [i] == null)
4820 foreach (DictionaryEntry e in var_list){
4821 LocalVariableReference var = (LocalVariableReference) e.Key;
4822 Expression new_expr = (Expression) e.Value;
4825 a = new Assign (var, new_expr, loc);
4831 converted_vars [i] = var;
4832 assign [i] = (ExpressionStatement) a;
4839 bool ResolveExpression (EmitContext ec)
4841 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4842 conv = Expression.ConvertImplicitRequired (
4843 ec, expr, TypeManager.idisposable_type, loc);
4853 // Emits the code for the case of using using a local variable declaration.
4855 bool EmitLocalVariableDecls (EmitContext ec)
4857 ILGenerator ig = ec.ig;
4860 bool old_in_try = ec.InTry;
4862 for (i = 0; i < assign.Length; i++) {
4863 assign [i].EmitStatement (ec);
4865 ig.BeginExceptionBlock ();
4867 Statement.Emit (ec);
4868 ec.InTry = old_in_try;
4870 bool old_in_finally = ec.InFinally;
4871 ec.InFinally = true;
4872 var_list.Reverse ();
4873 foreach (DictionaryEntry e in var_list){
4874 LocalVariableReference var = (LocalVariableReference) e.Key;
4875 Label skip = ig.DefineLabel ();
4878 ig.BeginFinallyBlock ();
4881 ig.Emit (OpCodes.Brfalse, skip);
4882 converted_vars [i].Emit (ec);
4883 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4884 ig.MarkLabel (skip);
4885 ig.EndExceptionBlock ();
4887 ec.InFinally = old_in_finally;
4892 bool EmitExpression (EmitContext ec)
4895 // Make a copy of the expression and operate on that.
4897 ILGenerator ig = ec.ig;
4898 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4903 ig.Emit (OpCodes.Stloc, local_copy);
4905 bool old_in_try = ec.InTry;
4907 ig.BeginExceptionBlock ();
4908 Statement.Emit (ec);
4909 ec.InTry = old_in_try;
4911 Label skip = ig.DefineLabel ();
4912 bool old_in_finally = ec.InFinally;
4913 ig.BeginFinallyBlock ();
4914 ig.Emit (OpCodes.Ldloc, local_copy);
4915 ig.Emit (OpCodes.Brfalse, skip);
4916 ig.Emit (OpCodes.Ldloc, local_copy);
4917 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4918 ig.MarkLabel (skip);
4919 ec.InFinally = old_in_finally;
4920 ig.EndExceptionBlock ();
4925 public override bool Resolve (EmitContext ec)
4927 if (expression_or_block is DictionaryEntry){
4928 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4929 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4931 if (!ResolveLocalVariableDecls (ec))
4934 } else if (expression_or_block is Expression){
4935 expr = (Expression) expression_or_block;
4937 expr = expr.Resolve (ec);
4941 expr_type = expr.Type;
4943 if (!ResolveExpression (ec))
4947 return Statement.Resolve (ec);
4950 protected override bool DoEmit (EmitContext ec)
4952 if (expression_or_block is DictionaryEntry)
4953 return EmitLocalVariableDecls (ec);
4954 else if (expression_or_block is Expression)
4955 return EmitExpression (ec);
4962 /// Implementation of the foreach C# statement
4964 public class Foreach : Statement {
4966 LocalVariableReference variable;
4968 Statement statement;
4969 ForeachHelperMethods hm;
4970 Expression empty, conv;
4971 Type array_type, element_type;
4974 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4975 Statement stmt, Location l)
4982 VariableInfo vi = var.VariableInfo;
4983 this.type = vi.Type;
4985 this.variable = var;
4991 public override bool Resolve (EmitContext ec)
4993 expr = expr.Resolve (ec);
4997 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4998 if (var_type == null)
5002 // We need an instance variable. Not sure this is the best
5003 // way of doing this.
5005 // FIXME: When we implement propertyaccess, will those turn
5006 // out to return values in ExprClass? I think they should.
5008 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
5009 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
5010 error1579 (expr.Type);
5014 if (expr.Type.IsArray) {
5015 array_type = expr.Type;
5016 element_type = array_type.GetElementType ();
5018 empty = new EmptyExpression (element_type);
5020 hm = ProbeCollectionType (ec, expr.Type);
5022 error1579 (expr.Type);
5026 array_type = expr.Type;
5027 element_type = hm.element_type;
5029 empty = new EmptyExpression (hm.element_type);
5032 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
5033 ec.CurrentBranching.CreateSibling ();
5037 // FIXME: maybe we can apply the same trick we do in the
5038 // array handling to avoid creating empty and conv in some cases.
5040 // Although it is not as important in this case, as the type
5041 // will not likely be object (what the enumerator will return).
5043 conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
5047 if (variable.ResolveLValue (ec, empty) == null)
5050 if (!statement.Resolve (ec))
5053 //FlowReturns returns = ec.EndFlowBranching ();
5059 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5061 static MethodInfo FetchMethodMoveNext (Type t)
5063 MemberList move_next_list;
5065 move_next_list = TypeContainer.FindMembers (
5066 t, MemberTypes.Method,
5067 BindingFlags.Public | BindingFlags.Instance,
5068 Type.FilterName, "MoveNext");
5069 if (move_next_list.Count == 0)
5072 foreach (MemberInfo m in move_next_list){
5073 MethodInfo mi = (MethodInfo) m;
5076 args = TypeManager.GetArgumentTypes (mi);
5077 if (args != null && args.Length == 0){
5078 if (mi.ReturnType == TypeManager.bool_type)
5086 // Retrieves a `public T get_Current ()' method from the Type `t'
5088 static MethodInfo FetchMethodGetCurrent (Type t)
5090 MemberList move_next_list;
5092 move_next_list = TypeContainer.FindMembers (
5093 t, MemberTypes.Method,
5094 BindingFlags.Public | BindingFlags.Instance,
5095 Type.FilterName, "get_Current");
5096 if (move_next_list.Count == 0)
5099 foreach (MemberInfo m in move_next_list){
5100 MethodInfo mi = (MethodInfo) m;
5103 args = TypeManager.GetArgumentTypes (mi);
5104 if (args != null && args.Length == 0)
5111 // This struct records the helper methods used by the Foreach construct
5113 class ForeachHelperMethods {
5114 public EmitContext ec;
5115 public MethodInfo get_enumerator;
5116 public MethodInfo move_next;
5117 public MethodInfo get_current;
5118 public Type element_type;
5119 public Type enumerator_type;
5120 public bool is_disposable;
5122 public ForeachHelperMethods (EmitContext ec)
5125 this.element_type = TypeManager.object_type;
5126 this.enumerator_type = TypeManager.ienumerator_type;
5127 this.is_disposable = true;
5131 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5136 if (!(m is MethodInfo))
5139 if (m.Name != "GetEnumerator")
5142 MethodInfo mi = (MethodInfo) m;
5143 Type [] args = TypeManager.GetArgumentTypes (mi);
5145 if (args.Length != 0)
5148 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5149 EmitContext ec = hm.ec;
5152 // Check whether GetEnumerator is accessible to us
5154 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5156 Type declaring = mi.DeclaringType;
5157 if (prot == MethodAttributes.Private){
5158 if (declaring != ec.ContainerType)
5160 } else if (prot == MethodAttributes.FamANDAssem){
5161 // If from a different assembly, false
5162 if (!(mi is MethodBuilder))
5165 // Are we being invoked from the same class, or from a derived method?
5167 if (ec.ContainerType != declaring){
5168 if (!ec.ContainerType.IsSubclassOf (declaring))
5171 } else if (prot == MethodAttributes.FamORAssem){
5172 if (!(mi is MethodBuilder ||
5173 ec.ContainerType == declaring ||
5174 ec.ContainerType.IsSubclassOf (declaring)))
5176 } if (prot == MethodAttributes.Family){
5177 if (!(ec.ContainerType == declaring ||
5178 ec.ContainerType.IsSubclassOf (declaring)))
5183 // Ok, we can access it, now make sure that we can do something
5184 // with this `GetEnumerator'
5187 if (mi.ReturnType == TypeManager.ienumerator_type ||
5188 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5189 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5190 hm.move_next = TypeManager.bool_movenext_void;
5191 hm.get_current = TypeManager.object_getcurrent_void;
5196 // Ok, so they dont return an IEnumerable, we will have to
5197 // find if they support the GetEnumerator pattern.
5199 Type return_type = mi.ReturnType;
5201 hm.move_next = FetchMethodMoveNext (return_type);
5202 if (hm.move_next == null)
5204 hm.get_current = FetchMethodGetCurrent (return_type);
5205 if (hm.get_current == null)
5208 hm.element_type = hm.get_current.ReturnType;
5209 hm.enumerator_type = return_type;
5210 hm.is_disposable = TypeManager.ImplementsInterface (
5211 hm.enumerator_type, TypeManager.idisposable_type);
5217 /// This filter is used to find the GetEnumerator method
5218 /// on which IEnumerator operates
5220 static MemberFilter FilterEnumerator;
5224 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5227 void error1579 (Type t)
5229 Report.Error (1579, loc,
5230 "foreach statement cannot operate on variables of type `" +
5231 t.FullName + "' because that class does not provide a " +
5232 " GetEnumerator method or it is inaccessible");
5235 static bool TryType (Type t, ForeachHelperMethods hm)
5239 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5240 BindingFlags.Public | BindingFlags.NonPublic |
5241 BindingFlags.Instance,
5242 FilterEnumerator, hm);
5247 hm.get_enumerator = (MethodInfo) mi [0];
5252 // Looks for a usable GetEnumerator in the Type, and if found returns
5253 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5255 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5257 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5259 if (TryType (t, hm))
5263 // Now try to find the method in the interfaces
5266 Type [] ifaces = t.GetInterfaces ();
5268 foreach (Type i in ifaces){
5269 if (TryType (i, hm))
5274 // Since TypeBuilder.GetInterfaces only returns the interface
5275 // types for this type, we have to keep looping, but once
5276 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5277 // done, because it returns all the types
5279 if ((t is TypeBuilder))
5289 // FIXME: possible optimization.
5290 // We might be able to avoid creating `empty' if the type is the sam
5292 bool EmitCollectionForeach (EmitContext ec)
5294 ILGenerator ig = ec.ig;
5295 LocalBuilder enumerator, disposable;
5297 enumerator = ig.DeclareLocal (hm.enumerator_type);
5298 if (hm.is_disposable)
5299 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5304 // Instantiate the enumerator
5306 if (expr.Type.IsValueType){
5307 if (expr is IMemoryLocation){
5308 IMemoryLocation ml = (IMemoryLocation) expr;
5310 ml.AddressOf (ec, AddressOp.Load);
5312 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5313 " does not implement IMemoryLocation");
5314 ig.Emit (OpCodes.Call, hm.get_enumerator);
5317 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5319 ig.Emit (OpCodes.Stloc, enumerator);
5322 // Protect the code in a try/finalize block, so that
5323 // if the beast implement IDisposable, we get rid of it
5325 bool old_in_try = ec.InTry;
5327 if (hm.is_disposable)
5330 Label end_try = ig.DefineLabel ();
5332 ig.MarkLabel (ec.LoopBegin);
5333 ig.Emit (OpCodes.Ldloc, enumerator);
5334 ig.Emit (OpCodes.Callvirt, hm.move_next);
5335 ig.Emit (OpCodes.Brfalse, end_try);
5336 ig.Emit (OpCodes.Ldloc, enumerator);
5337 ig.Emit (OpCodes.Callvirt, hm.get_current);
5338 variable.EmitAssign (ec, conv);
5339 statement.Emit (ec);
5340 ig.Emit (OpCodes.Br, ec.LoopBegin);
5341 ig.MarkLabel (end_try);
5342 ec.InTry = old_in_try;
5344 // The runtime provides this for us.
5345 // ig.Emit (OpCodes.Leave, end);
5348 // Now the finally block
5350 if (hm.is_disposable) {
5351 Label end_finally = ig.DefineLabel ();
5352 bool old_in_finally = ec.InFinally;
5353 ec.InFinally = true;
5354 ig.BeginFinallyBlock ();
5356 ig.Emit (OpCodes.Ldloc, enumerator);
5357 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5358 ig.Emit (OpCodes.Stloc, disposable);
5359 ig.Emit (OpCodes.Ldloc, disposable);
5360 ig.Emit (OpCodes.Brfalse, end_finally);
5361 ig.Emit (OpCodes.Ldloc, disposable);
5362 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5363 ig.MarkLabel (end_finally);
5364 ec.InFinally = old_in_finally;
5366 // The runtime generates this anyways.
5367 // ig.Emit (OpCodes.Endfinally);
5369 ig.EndExceptionBlock ();
5372 ig.MarkLabel (ec.LoopEnd);
5377 // FIXME: possible optimization.
5378 // We might be able to avoid creating `empty' if the type is the sam
5380 bool EmitArrayForeach (EmitContext ec)
5382 int rank = array_type.GetArrayRank ();
5383 ILGenerator ig = ec.ig;
5385 LocalBuilder copy = ig.DeclareLocal (array_type);
5388 // Make our copy of the array
5391 ig.Emit (OpCodes.Stloc, copy);
5394 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5398 ig.Emit (OpCodes.Ldc_I4_0);
5399 ig.Emit (OpCodes.Stloc, counter);
5400 test = ig.DefineLabel ();
5401 ig.Emit (OpCodes.Br, test);
5403 loop = ig.DefineLabel ();
5404 ig.MarkLabel (loop);
5406 ig.Emit (OpCodes.Ldloc, copy);
5407 ig.Emit (OpCodes.Ldloc, counter);
5408 ArrayAccess.EmitLoadOpcode (ig, var_type);
5410 variable.EmitAssign (ec, conv);
5412 statement.Emit (ec);
5414 ig.MarkLabel (ec.LoopBegin);
5415 ig.Emit (OpCodes.Ldloc, counter);
5416 ig.Emit (OpCodes.Ldc_I4_1);
5417 ig.Emit (OpCodes.Add);
5418 ig.Emit (OpCodes.Stloc, counter);
5420 ig.MarkLabel (test);
5421 ig.Emit (OpCodes.Ldloc, counter);
5422 ig.Emit (OpCodes.Ldloc, copy);
5423 ig.Emit (OpCodes.Ldlen);
5424 ig.Emit (OpCodes.Conv_I4);
5425 ig.Emit (OpCodes.Blt, loop);
5427 LocalBuilder [] dim_len = new LocalBuilder [rank];
5428 LocalBuilder [] dim_count = new LocalBuilder [rank];
5429 Label [] loop = new Label [rank];
5430 Label [] test = new Label [rank];
5433 for (dim = 0; dim < rank; dim++){
5434 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5435 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5436 test [dim] = ig.DefineLabel ();
5437 loop [dim] = ig.DefineLabel ();
5440 for (dim = 0; dim < rank; dim++){
5441 ig.Emit (OpCodes.Ldloc, copy);
5442 IntLiteral.EmitInt (ig, dim);
5443 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5444 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5447 for (dim = 0; dim < rank; dim++){
5448 ig.Emit (OpCodes.Ldc_I4_0);
5449 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5450 ig.Emit (OpCodes.Br, test [dim]);
5451 ig.MarkLabel (loop [dim]);
5454 ig.Emit (OpCodes.Ldloc, copy);
5455 for (dim = 0; dim < rank; dim++)
5456 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5459 // FIXME: Maybe we can cache the computation of `get'?
5461 Type [] args = new Type [rank];
5464 for (int i = 0; i < rank; i++)
5465 args [i] = TypeManager.int32_type;
5467 ModuleBuilder mb = CodeGen.ModuleBuilder;
5468 get = mb.GetArrayMethod (
5470 CallingConventions.HasThis| CallingConventions.Standard,
5472 ig.Emit (OpCodes.Call, get);
5473 variable.EmitAssign (ec, conv);
5474 statement.Emit (ec);
5475 ig.MarkLabel (ec.LoopBegin);
5476 for (dim = rank - 1; dim >= 0; dim--){
5477 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5478 ig.Emit (OpCodes.Ldc_I4_1);
5479 ig.Emit (OpCodes.Add);
5480 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5482 ig.MarkLabel (test [dim]);
5483 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5484 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5485 ig.Emit (OpCodes.Blt, loop [dim]);
5488 ig.MarkLabel (ec.LoopEnd);
5493 protected override bool DoEmit (EmitContext ec)
5497 ILGenerator ig = ec.ig;
5499 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5500 bool old_inloop = ec.InLoop;
5501 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5502 ec.LoopBegin = ig.DefineLabel ();
5503 ec.LoopEnd = ig.DefineLabel ();
5505 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5508 ret_val = EmitCollectionForeach (ec);
5510 ret_val = EmitArrayForeach (ec);
5512 ec.LoopBegin = old_begin;
5513 ec.LoopEnd = old_end;
5514 ec.InLoop = old_inloop;
5515 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5522 /// AddHandler statement
5524 public class AddHandler : Statement {
5526 Expression EvtHandler;
5529 // keeps track whether EvtId is already resolved
5533 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5536 EvtHandler = evt_handler;
5539 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5542 public override bool Resolve (EmitContext ec)
5545 // if EvetId is of EventExpr type that means
5546 // this is already resolved
5548 if (EvtId is EventExpr) {
5553 EvtId = EvtId.Resolve(ec);
5554 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5555 if (EvtId == null || (!(EvtId is EventExpr))) {
5556 Report.Error (30676, "Need an event designator.");
5560 if (EvtHandler == null)
5562 Report.Error (999, "'AddHandler' statement needs an event handler.");
5569 protected override bool DoEmit (EmitContext ec)
5572 // Already resolved and emitted don't do anything
5578 ArrayList args = new ArrayList();
5579 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5584 // The even type was already resolved to a delegate, so
5585 // we must un-resolve its name to generate a type expression
5586 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5587 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5589 // which we can use to declare a new event handler
5591 d = new New (dtype, args, Location.Null);
5593 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5595 // we resolve it all and emit the code
5608 /// RemoveHandler statement
5610 public class RemoveHandler : Statement
\r
5613 Expression EvtHandler;
5615 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
5618 EvtHandler = evt_handler;
5622 public override bool Resolve (EmitContext ec)
5624 EvtId = EvtId.Resolve(ec);
5625 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5626 if (EvtId == null || (!(EvtId is EventExpr)))
\r
5628 Report.Error (30676, "Need an event designator.");
5632 if (EvtHandler == null)
5634 Report.Error (999, "'AddHandler' statement needs an event handler.");
5640 protected override bool DoEmit (EmitContext ec)
5643 ArrayList args = new ArrayList();
5644 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5647 // The even type was already resolved to a delegate, so
5648 // we must un-resolve its name to generate a type expression
5649 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5650 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5652 // which we can use to declare a new event handler
5654 d = new New (dtype, args, Location.Null);
5657 e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
5659 // we resolve it all and emit the code
5671 public class RedimClause {
5672 public Expression Expr;
5673 public ArrayList NewIndexes;
5675 public RedimClause (Expression e, ArrayList args)
5682 public class ReDim : Statement {
5683 ArrayList RedimTargets;
5687 private StatementExpression ReDimExpr;
5689 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5692 RedimTargets = targets;
5693 Preserve = opt_preserve;
5696 public override bool Resolve (EmitContext ec)
5698 Expression RedimTarget;
5699 ArrayList NewIndexes;
5701 foreach (RedimClause rc in RedimTargets) {
5702 RedimTarget = rc.Expr;
5703 NewIndexes = rc.NewIndexes;
5705 RedimTarget = RedimTarget.Resolve (ec);
5706 if (!RedimTarget.Type.IsArray)
5707 Report.Error (49, "'ReDim' statement requires an array");
5709 ArrayList args = new ArrayList();
5710 foreach (Argument a in NewIndexes) {
5711 if (a.Resolve(ec, loc))
5715 for (int x = 0; x < args.Count; x++) {
5716 args[x] = new Binary (Binary.Operator.Addition,
5717 (Expression) args[x], new IntLiteral (1), Location.Null);
5721 if (RedimTarget.Type.GetArrayRank() != args.Count)
5722 Report.Error (30415, "'ReDim' cannot change the number of dimensions of an array.");
5724 BaseType = RedimTarget.Type.GetElementType();
5725 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5726 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
5727 // TODO: we are in a foreach we probably can't reuse ReDimExpr, must turn it into an array(list)
5730 ExpressionStatement PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5731 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5734 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5735 ReDimExpr.Resolve(ec);
5740 protected override bool DoEmit (EmitContext ec)
5748 public class Erase : Statement {
5749 Expression EraseTarget;
5751 private StatementExpression EraseExpr;
5753 public Erase (Expression expr, Location l)
5759 public override bool Resolve (EmitContext ec)
5761 EraseTarget = EraseTarget.Resolve (ec);
5762 if (!EraseTarget.Type.IsArray)
5763 Report.Error (49, "'Erase' statement requires an array");
5765 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5766 EraseExpr.Resolve(ec);
5771 protected override bool DoEmit (EmitContext ec)