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)
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.Ldloc_0);
1102 ec.ig.Emit (OpCodes.Ret);
1113 public class Continue : Statement {
1115 public Continue (Location l)
1120 public override bool Resolve (EmitContext ec)
1122 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1126 protected override bool DoEmit (EmitContext ec)
1128 Label begin = ec.LoopBegin;
1131 Report.Error (139, loc, "No enclosing loop to continue to");
1136 // UGH: Non trivial. This Br might cross a try/catch boundary
1140 // try { ... } catch { continue; }
1144 // try {} catch { while () { continue; }}
1146 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1147 ec.ig.Emit (OpCodes.Leave, begin);
1148 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1149 throw new Exception ("Should never happen");
1151 ec.ig.Emit (OpCodes.Br, begin);
1157 // This is used in the control flow analysis code to specify whether the
1158 // current code block may return to its enclosing block before reaching
1161 public enum FlowReturns {
1162 // It can never return.
1165 // This means that the block contains a conditional return statement
1169 // The code always returns, ie. there's an unconditional return / break
1173 // The code always throws an exception.
1176 // The current code block is unreachable. This happens if it's immediately
1177 // following a FlowReturns.ALWAYS block.
1182 // This is a special bit vector which can inherit from another bit vector doing a
1183 // copy-on-write strategy. The inherited vector may have a smaller size than the
1186 public class MyBitVector {
1187 public readonly int Count;
1188 public readonly MyBitVector InheritsFrom;
1193 public MyBitVector (int Count)
1194 : this (null, Count)
1197 public MyBitVector (MyBitVector InheritsFrom, int Count)
1199 this.InheritsFrom = InheritsFrom;
1204 // Checks whether this bit vector has been modified. After setting this to true,
1205 // we won't use the inherited vector anymore, but our own copy of it.
1207 public bool IsDirty {
1214 initialize_vector ();
1219 // Get/set bit `index' in the bit vector.
1221 public bool this [int index]
1225 throw new ArgumentOutOfRangeException ();
1227 // We're doing a "copy-on-write" strategy here; as long
1228 // as nobody writes to the array, we can use our parent's
1229 // copy instead of duplicating the vector.
1232 return vector [index];
1233 else if (InheritsFrom != null) {
1234 BitArray inherited = InheritsFrom.Vector;
1236 if (index < inherited.Count)
1237 return inherited [index];
1246 throw new ArgumentOutOfRangeException ();
1248 // Only copy the vector if we're actually modifying it.
1250 if (this [index] != value) {
1251 initialize_vector ();
1253 vector [index] = value;
1259 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1260 // copy of the bit vector.
1262 public static explicit operator BitArray (MyBitVector vector)
1264 vector.initialize_vector ();
1265 return vector.Vector;
1269 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1270 // different size than the current one.
1272 public void Or (MyBitVector new_vector)
1274 BitArray new_array = new_vector.Vector;
1276 initialize_vector ();
1279 if (vector.Count < new_array.Count)
1280 upper = vector.Count;
1282 upper = new_array.Count;
1284 for (int i = 0; i < upper; i++)
1285 vector [i] = vector [i] | new_array [i];
1289 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1290 // a different size than the current one.
1292 public void And (MyBitVector new_vector)
1294 BitArray new_array = new_vector.Vector;
1296 initialize_vector ();
1299 if (vector.Count < new_array.Count)
1300 lower = upper = vector.Count;
1302 lower = new_array.Count;
1303 upper = vector.Count;
1306 for (int i = 0; i < lower; i++)
1307 vector [i] = vector [i] & new_array [i];
1309 for (int i = lower; i < upper; i++)
1314 // This does a deep copy of the bit vector.
1316 public MyBitVector Clone ()
1318 MyBitVector retval = new MyBitVector (Count);
1320 retval.Vector = Vector;
1329 else if (!is_dirty && (InheritsFrom != null))
1330 return InheritsFrom.Vector;
1332 initialize_vector ();
1338 initialize_vector ();
1340 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1341 vector [i] = value [i];
1345 void initialize_vector ()
1350 vector = new BitArray (Count, false);
1351 if (InheritsFrom != null)
1352 Vector = InheritsFrom.Vector;
1357 public override string ToString ()
1359 StringBuilder sb = new StringBuilder ("MyBitVector (");
1361 BitArray vector = Vector;
1365 sb.Append ("INHERITED - ");
1366 for (int i = 0; i < vector.Count; i++) {
1369 sb.Append (vector [i]);
1373 return sb.ToString ();
1378 // The type of a FlowBranching.
1380 public enum FlowBranchingType {
1381 // Normal (conditional or toplevel) block.
1398 // A new instance of this class is created every time a new block is resolved
1399 // and if there's branching in the block's control flow.
1401 public class FlowBranching {
1403 // The type of this flow branching.
1405 public readonly FlowBranchingType Type;
1408 // The block this branching is contained in. This may be null if it's not
1409 // a top-level block and it doesn't declare any local variables.
1411 public readonly Block Block;
1414 // The parent of this branching or null if this is the top-block.
1416 public readonly FlowBranching Parent;
1419 // Start-Location of this flow branching.
1421 public readonly Location Location;
1424 // A list of UsageVectors. A new vector is added each time control flow may
1425 // take a different path.
1427 public ArrayList Siblings;
1430 // If this is an infinite loop.
1432 public bool Infinite;
1435 // If we may leave the current loop.
1437 public bool MayLeaveLoop;
1442 InternalParameters param_info;
1444 MyStructInfo[] struct_params;
1446 ArrayList finally_vectors;
1448 static int next_id = 0;
1452 // Performs an `And' operation on the FlowReturns status
1453 // (for instance, a block only returns ALWAYS if all its siblings
1456 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1458 if (b == FlowReturns.UNREACHABLE)
1462 case FlowReturns.NEVER:
1463 if (b == FlowReturns.NEVER)
1464 return FlowReturns.NEVER;
1466 return FlowReturns.SOMETIMES;
1468 case FlowReturns.SOMETIMES:
1469 return FlowReturns.SOMETIMES;
1471 case FlowReturns.ALWAYS:
1472 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1473 return FlowReturns.ALWAYS;
1475 return FlowReturns.SOMETIMES;
1477 case FlowReturns.EXCEPTION:
1478 if (b == FlowReturns.EXCEPTION)
1479 return FlowReturns.EXCEPTION;
1480 else if (b == FlowReturns.ALWAYS)
1481 return FlowReturns.ALWAYS;
1483 return FlowReturns.SOMETIMES;
1490 // The vector contains a BitArray with information about which local variables
1491 // and parameters are already initialized at the current code position.
1493 public class UsageVector {
1495 // If this is true, then the usage vector has been modified and must be
1496 // merged when we're done with this branching.
1498 public bool IsDirty;
1501 // The number of parameters in this block.
1503 public readonly int CountParameters;
1506 // The number of locals in this block.
1508 public readonly int CountLocals;
1511 // If not null, then we inherit our state from this vector and do a
1512 // copy-on-write. If null, then we're the first sibling in a top-level
1513 // block and inherit from the empty vector.
1515 public readonly UsageVector InheritsFrom;
1520 MyBitVector locals, parameters;
1521 FlowReturns real_returns, real_breaks;
1524 static int next_id = 0;
1528 // Normally, you should not use any of these constructors.
1530 public UsageVector (UsageVector parent, int num_params, int num_locals)
1532 this.InheritsFrom = parent;
1533 this.CountParameters = num_params;
1534 this.CountLocals = num_locals;
1535 this.real_returns = FlowReturns.NEVER;
1536 this.real_breaks = FlowReturns.NEVER;
1538 if (parent != null) {
1539 locals = new MyBitVector (parent.locals, CountLocals);
1541 parameters = new MyBitVector (parent.parameters, num_params);
1542 real_returns = parent.Returns;
1543 real_breaks = parent.Breaks;
1545 locals = new MyBitVector (null, CountLocals);
1547 parameters = new MyBitVector (null, num_params);
1553 public UsageVector (UsageVector parent)
1554 : this (parent, parent.CountParameters, parent.CountLocals)
1558 // This does a deep copy of the usage vector.
1560 public UsageVector Clone ()
1562 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1564 retval.locals = locals.Clone ();
1565 if (parameters != null)
1566 retval.parameters = parameters.Clone ();
1567 retval.real_returns = real_returns;
1568 retval.real_breaks = real_breaks;
1574 // State of parameter `number'.
1576 public bool this [int number]
1581 else if (number == 0)
1582 throw new ArgumentException ();
1584 return parameters [number - 1];
1590 else if (number == 0)
1591 throw new ArgumentException ();
1593 parameters [number - 1] = value;
1598 // State of the local variable `vi'.
1599 // If the local variable is a struct, use a non-zero `field_idx'
1600 // to check an individual field in it.
1602 public bool this [VariableInfo vi, int field_idx]
1605 if (vi.Number == -1)
1607 else if (vi.Number == 0)
1608 throw new ArgumentException ();
1610 return locals [vi.Number + field_idx - 1];
1614 if (vi.Number == -1)
1616 else if (vi.Number == 0)
1617 throw new ArgumentException ();
1619 locals [vi.Number + field_idx - 1] = value;
1624 // Specifies when the current block returns.
1625 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1626 // end of the method (so that we don't need to emit a return statement).
1627 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1628 // value will never be used.
1630 public FlowReturns Returns {
1632 return real_returns;
1636 real_returns = value;
1641 // Specifies whether control may return to our containing block
1642 // before reaching the end of this block. This happens if there
1643 // is a break/continue/goto/return in it.
1644 // This can also be used to find out whether the statement immediately
1645 // following the current block may be reached or not.
1647 public FlowReturns Breaks {
1653 real_breaks = value;
1657 public bool AlwaysBreaks {
1659 return (Breaks == FlowReturns.ALWAYS) ||
1660 (Breaks == FlowReturns.EXCEPTION) ||
1661 (Breaks == FlowReturns.UNREACHABLE);
1665 public bool MayBreak {
1667 return Breaks != FlowReturns.NEVER;
1671 public bool AlwaysReturns {
1673 return (Returns == FlowReturns.ALWAYS) ||
1674 (Returns == FlowReturns.EXCEPTION);
1678 public bool MayReturn {
1680 return (Returns == FlowReturns.SOMETIMES) ||
1681 (Returns == FlowReturns.ALWAYS);
1686 // Merge a child branching.
1688 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1690 MyBitVector new_locals = null;
1691 MyBitVector new_params = null;
1693 FlowReturns new_returns = FlowReturns.NEVER;
1694 FlowReturns new_breaks = FlowReturns.NEVER;
1695 bool new_returns_set = false, new_breaks_set = false;
1697 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1698 this, children.Count);
1700 foreach (UsageVector child in children) {
1701 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1703 if (!child.is_finally) {
1704 if (child.Breaks != FlowReturns.UNREACHABLE) {
1705 // If Returns is already set, perform an
1706 // `And' operation on it, otherwise just set just.
1707 if (!new_returns_set) {
1708 new_returns = child.Returns;
1709 new_returns_set = true;
1711 new_returns = AndFlowReturns (
1712 new_returns, child.Returns);
1715 // If Breaks is already set, perform an
1716 // `And' operation on it, otherwise just set just.
1717 if (!new_breaks_set) {
1718 new_breaks = child.Breaks;
1719 new_breaks_set = true;
1721 new_breaks = AndFlowReturns (
1722 new_breaks, child.Breaks);
1725 // Ignore unreachable children.
1726 if (child.Returns == FlowReturns.UNREACHABLE)
1729 // A local variable is initialized after a flow branching if it
1730 // has been initialized in all its branches which do neither
1731 // always return or always throw an exception.
1733 // If a branch may return, but does not always return, then we
1734 // can treat it like a never-returning branch here: control will
1735 // only reach the code position after the branching if we did not
1738 // It's important to distinguish between always and sometimes
1739 // returning branches here:
1742 // 2 if (something) {
1746 // 6 Console.WriteLine (a);
1748 // The if block in lines 3-4 always returns, so we must not look
1749 // at the initialization of `a' in line 4 - thus it'll still be
1750 // uninitialized in line 6.
1752 // On the other hand, the following is allowed:
1759 // 6 Console.WriteLine (a);
1761 // Here, `a' is initialized in line 3 and we must not look at
1762 // line 5 since it always returns.
1764 if (child.is_finally) {
1765 if (new_locals == null)
1766 new_locals = locals.Clone ();
1767 new_locals.Or (child.locals);
1769 if (parameters != null) {
1770 if (new_params == null)
1771 new_params = parameters.Clone ();
1772 new_params.Or (child.parameters);
1776 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1777 if (new_locals != null)
1778 new_locals.And (child.locals);
1780 new_locals = locals.Clone ();
1781 new_locals.Or (child.locals);
1783 } else if (children.Count == 1) {
1784 new_locals = locals.Clone ();
1785 new_locals.Or (child.locals);
1788 // An `out' parameter must be assigned in all branches which do
1789 // not always throw an exception.
1790 if (parameters != null) {
1791 if (child.Breaks != FlowReturns.EXCEPTION) {
1792 if (new_params != null)
1793 new_params.And (child.parameters);
1795 new_params = parameters.Clone ();
1796 new_params.Or (child.parameters);
1798 } else if (children.Count == 1) {
1799 new_params = parameters.Clone ();
1800 new_params.Or (child.parameters);
1806 Returns = new_returns;
1807 if ((branching.Type == FlowBranchingType.BLOCK) ||
1808 (branching.Type == FlowBranchingType.EXCEPTION) ||
1809 (new_breaks == FlowReturns.UNREACHABLE) ||
1810 (new_breaks == FlowReturns.EXCEPTION))
1811 Breaks = new_breaks;
1812 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1813 Breaks = new_returns;
1814 else if (branching.Type == FlowBranchingType.SWITCH){
1815 if (new_breaks == FlowReturns.ALWAYS)
1816 Breaks = FlowReturns.ALWAYS;
1820 // We've now either reached the point after the branching or we will
1821 // never get there since we always return or always throw an exception.
1823 // If we can reach the point after the branching, mark all locals and
1824 // parameters as initialized which have been initialized in all branches
1825 // we need to look at (see above).
1828 if (((new_breaks != FlowReturns.ALWAYS) &&
1829 (new_breaks != FlowReturns.EXCEPTION) &&
1830 (new_breaks != FlowReturns.UNREACHABLE)) ||
1831 (children.Count == 1)) {
1832 if (new_locals != null)
1833 locals.Or (new_locals);
1835 if (new_params != null)
1836 parameters.Or (new_params);
1839 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1840 new_params, new_locals, new_returns, new_breaks,
1841 branching.Infinite, branching.MayLeaveLoop, this);
1843 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1844 if ((new_breaks != FlowReturns.ALWAYS) &&
1845 (new_breaks != FlowReturns.EXCEPTION) &&
1846 (new_breaks != FlowReturns.UNREACHABLE))
1847 Report.Error (163, branching.Location,
1848 "Control cannot fall through from one " +
1849 "case label to another");
1852 if (branching.Infinite && !branching.MayLeaveLoop) {
1853 Report.Debug (1, "INFINITE", new_returns, new_breaks,
1854 Returns, Breaks, this);
1856 // We're actually infinite.
1857 if (new_returns == FlowReturns.NEVER) {
1858 Breaks = FlowReturns.UNREACHABLE;
1859 return FlowReturns.UNREACHABLE;
1862 // If we're an infinite loop and do not break, the code after
1863 // the loop can never be reached. However, if we may return
1864 // from the loop, then we do always return (or stay in the loop
1866 if ((new_returns == FlowReturns.SOMETIMES) ||
1867 (new_returns == FlowReturns.ALWAYS)) {
1868 Returns = FlowReturns.ALWAYS;
1869 return FlowReturns.ALWAYS;
1877 // Tells control flow analysis that the current code position may be reached with
1878 // a forward jump from any of the origins listed in `origin_vectors' which is a
1879 // list of UsageVectors.
1881 // This is used when resolving forward gotos - in the following example, the
1882 // variable `a' is uninitialized in line 8 becase this line may be reached via
1883 // the goto in line 4:
1893 // 8 Console.WriteLine (a);
1896 public void MergeJumpOrigins (ICollection origin_vectors)
1898 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1900 real_breaks = FlowReturns.NEVER;
1901 real_returns = FlowReturns.NEVER;
1903 foreach (UsageVector vector in origin_vectors) {
1904 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1906 locals.And (vector.locals);
1907 if (parameters != null)
1908 parameters.And (vector.parameters);
1909 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1910 Returns = AndFlowReturns (Returns, vector.Returns);
1913 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1917 // This is used at the beginning of a finally block if there were
1918 // any return statements in the try block or one of the catch blocks.
1920 public void MergeFinallyOrigins (ICollection finally_vectors)
1922 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1924 real_breaks = FlowReturns.NEVER;
1926 foreach (UsageVector vector in finally_vectors) {
1927 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1929 if (parameters != null)
1930 parameters.And (vector.parameters);
1931 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1936 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1939 public void CheckOutParameters (FlowBranching branching)
1941 if (parameters != null)
1942 branching.CheckOutParameters (parameters, branching.Location);
1946 // Performs an `or' operation on the locals and the parameters.
1948 public void Or (UsageVector new_vector)
1950 locals.Or (new_vector.locals);
1951 if (parameters != null)
1952 parameters.Or (new_vector.parameters);
1956 // Performs an `and' operation on the locals.
1958 public void AndLocals (UsageVector new_vector)
1960 locals.And (new_vector.locals);
1964 // Returns a deep copy of the parameters.
1966 public MyBitVector Parameters {
1968 if (parameters != null)
1969 return parameters.Clone ();
1976 // Returns a deep copy of the locals.
1978 public MyBitVector Locals {
1980 return locals.Clone ();
1988 public override string ToString ()
1990 StringBuilder sb = new StringBuilder ();
1992 sb.Append ("Vector (");
1995 sb.Append (Returns);
1998 if (parameters != null) {
2000 sb.Append (parameters);
2006 return sb.ToString ();
2010 FlowBranching (FlowBranchingType type, Location loc)
2012 this.Siblings = new ArrayList ();
2014 this.Location = loc;
2020 // Creates a new flow branching for `block'.
2021 // This is used from Block.Resolve to create the top-level branching of
2024 public FlowBranching (Block block, InternalParameters ip, Location loc)
2025 : this (FlowBranchingType.BLOCK, loc)
2030 int count = (ip != null) ? ip.Count : 0;
2033 param_map = new int [count];
2034 struct_params = new MyStructInfo [count];
2037 for (int i = 0; i < count; i++) {
2038 Parameter.Modifier mod = param_info.ParameterModifier (i);
2040 if ((mod & Parameter.Modifier.OUT) == 0)
2043 param_map [i] = ++num_params;
2045 Type param_type = param_info.ParameterType (i);
2047 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2048 if (struct_params [i] != null)
2049 num_params += struct_params [i].Count;
2052 Siblings = new ArrayList ();
2053 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2057 // Creates a new flow branching which is contained in `parent'.
2058 // You should only pass non-null for the `block' argument if this block
2059 // introduces any new variables - in this case, we need to create a new
2060 // usage vector with a different size than our parent's one.
2062 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2063 Block block, Location loc)
2069 if (parent != null) {
2070 param_info = parent.param_info;
2071 param_map = parent.param_map;
2072 struct_params = parent.struct_params;
2073 num_params = parent.num_params;
2078 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2079 Block.CountVariables);
2081 vector = new UsageVector (Parent.CurrentUsageVector);
2083 Siblings.Add (vector);
2086 case FlowBranchingType.EXCEPTION:
2087 finally_vectors = new ArrayList ();
2096 // Returns the branching's current usage vector.
2098 public UsageVector CurrentUsageVector
2101 return (UsageVector) Siblings [Siblings.Count - 1];
2106 // Creates a sibling of the current usage vector.
2108 public void CreateSibling ()
2110 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2112 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2116 // Creates a sibling for a `finally' block.
2118 public void CreateSiblingForFinally ()
2120 if (Type != FlowBranchingType.EXCEPTION)
2121 throw new NotSupportedException ();
2125 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2129 // Check whether all `out' parameters have been assigned.
2131 public void CheckOutParameters (MyBitVector parameters, Location loc)
2136 for (int i = 0; i < param_map.Length; i++) {
2137 int index = param_map [i];
2142 if (parameters [index - 1])
2145 // If it's a struct, we must ensure that all its fields have
2146 // been assigned. If the struct has any non-public fields, this
2147 // can only be done by assigning the whole struct.
2149 MyStructInfo struct_info = struct_params [index - 1];
2150 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2152 177, loc, "The out parameter `" +
2153 param_info.ParameterName (i) + "' must be " +
2154 "assigned before control leave the current method.");
2160 for (int j = 0; j < struct_info.Count; j++) {
2161 if (!parameters [index + j]) {
2163 177, loc, "The out parameter `" +
2164 param_info.ParameterName (i) + "' must be " +
2165 "assigned before control leave the current method.");
2174 // Merge a child branching.
2176 public FlowReturns MergeChild (FlowBranching child)
2178 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2180 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2181 MayLeaveLoop |= child.MayLeaveLoop;
2183 MayLeaveLoop = false;
2189 // Does the toplevel merging.
2191 public FlowReturns MergeTopBlock ()
2193 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2194 throw new NotSupportedException ();
2196 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2198 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2200 vector.MergeChildren (this, Siblings);
2203 Siblings.Add (vector);
2205 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2207 if (vector.Breaks != FlowReturns.EXCEPTION) {
2208 if (!vector.AlwaysBreaks)
2209 CheckOutParameters (CurrentUsageVector.Parameters, Location);
2210 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2212 return FlowReturns.EXCEPTION;
2215 public bool InTryBlock ()
2217 if (finally_vectors != null)
2219 else if (Parent != null)
2220 return Parent.InTryBlock ();
2225 public void AddFinallyVector (UsageVector vector)
2227 if (finally_vectors != null) {
2228 finally_vectors.Add (vector.Clone ());
2233 Parent.AddFinallyVector (vector);
2235 throw new NotSupportedException ();
2238 public bool IsVariableAssigned (VariableInfo vi)
2240 if (CurrentUsageVector.AlwaysBreaks)
2243 return CurrentUsageVector [vi, 0];
2246 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2248 if (CurrentUsageVector.AlwaysBreaks)
2251 return CurrentUsageVector [vi, field_idx];
2254 public void SetVariableAssigned (VariableInfo vi)
2256 if (CurrentUsageVector.AlwaysBreaks)
2259 CurrentUsageVector [vi, 0] = true;
2262 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2264 if (CurrentUsageVector.AlwaysBreaks)
2267 CurrentUsageVector [vi, field_idx] = true;
2270 public bool IsParameterAssigned (int number)
2272 int index = param_map [number];
2277 if (CurrentUsageVector [index])
2280 // Parameter is not assigned, so check whether it's a struct.
2281 // If it's either not a struct or a struct which non-public
2282 // fields, return false.
2283 MyStructInfo struct_info = struct_params [number];
2284 if ((struct_info == null) || struct_info.HasNonPublicFields)
2287 // Ok, so each field must be assigned.
2288 for (int i = 0; i < struct_info.Count; i++)
2289 if (!CurrentUsageVector [index + i])
2295 public bool IsParameterAssigned (int number, string field_name)
2297 int index = param_map [number];
2302 MyStructInfo info = (MyStructInfo) struct_params [number];
2306 int field_idx = info [field_name];
2308 return CurrentUsageVector [index + field_idx];
2311 public void SetParameterAssigned (int number)
2313 if (param_map [number] == 0)
2316 if (!CurrentUsageVector.AlwaysBreaks)
2317 CurrentUsageVector [param_map [number]] = true;
2320 public void SetParameterAssigned (int number, string field_name)
2322 int index = param_map [number];
2327 MyStructInfo info = (MyStructInfo) struct_params [number];
2331 int field_idx = info [field_name];
2333 if (!CurrentUsageVector.AlwaysBreaks)
2334 CurrentUsageVector [index + field_idx] = true;
2337 public bool IsReachable ()
2342 case FlowBranchingType.SWITCH_SECTION:
2343 // The code following a switch block is reachable unless the switch
2344 // block always returns.
2345 reachable = !CurrentUsageVector.AlwaysReturns;
2348 case FlowBranchingType.LOOP_BLOCK:
2349 // The code following a loop is reachable unless the loop always
2350 // returns or it's an infinite loop without any `break's in it.
2351 reachable = !CurrentUsageVector.AlwaysReturns &&
2352 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2356 // The code following a block or exception is reachable unless the
2357 // block either always returns or always breaks.
2358 reachable = !CurrentUsageVector.AlwaysBreaks &&
2359 !CurrentUsageVector.AlwaysReturns;
2363 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2364 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2369 public override string ToString ()
2371 StringBuilder sb = new StringBuilder ("FlowBranching (");
2376 if (Block != null) {
2378 sb.Append (Block.ID);
2380 sb.Append (Block.StartLocation);
2383 sb.Append (Siblings.Count);
2385 sb.Append (CurrentUsageVector);
2387 return sb.ToString ();
2391 public class MyStructInfo {
2392 public readonly Type Type;
2393 public readonly FieldInfo[] Fields;
2394 public readonly FieldInfo[] NonPublicFields;
2395 public readonly int Count;
2396 public readonly int CountNonPublic;
2397 public readonly bool HasNonPublicFields;
2399 private static Hashtable field_type_hash = new Hashtable ();
2400 private Hashtable field_hash;
2402 // Private constructor. To save memory usage, we only need to create one instance
2403 // of this class per struct type.
2404 private MyStructInfo (Type type)
2408 if (type is TypeBuilder) {
2409 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2411 ArrayList fields = tc.Fields;
2412 if (fields != null) {
2413 foreach (Field field in fields) {
2414 if ((field.ModFlags & Modifiers.STATIC) != 0)
2416 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2423 Fields = new FieldInfo [Count];
2424 NonPublicFields = new FieldInfo [CountNonPublic];
2426 Count = CountNonPublic = 0;
2427 if (fields != null) {
2428 foreach (Field field in fields) {
2429 if ((field.ModFlags & Modifiers.STATIC) != 0)
2431 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2432 Fields [Count++] = field.FieldBuilder;
2434 NonPublicFields [CountNonPublic++] =
2440 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2441 Count = Fields.Length;
2443 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2444 CountNonPublic = NonPublicFields.Length;
2447 Count += NonPublicFields.Length;
2450 field_hash = new Hashtable ();
2451 foreach (FieldInfo field in Fields)
2452 field_hash.Add (field.Name, ++number);
2454 if (NonPublicFields.Length != 0)
2455 HasNonPublicFields = true;
2457 foreach (FieldInfo field in NonPublicFields)
2458 field_hash.Add (field.Name, ++number);
2461 public int this [string name] {
2463 if (field_hash.Contains (name))
2464 return (int) field_hash [name];
2470 public FieldInfo this [int index] {
2472 if (index >= Fields.Length)
2473 return NonPublicFields [index - Fields.Length];
2475 return Fields [index];
2479 public static MyStructInfo GetStructInfo (Type type)
2481 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2484 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2487 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2491 info = new MyStructInfo (type);
2492 field_type_hash.Add (type, info);
2496 public static MyStructInfo GetStructInfo (TypeContainer tc)
2498 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2502 info = new MyStructInfo (tc.TypeBuilder);
2503 field_type_hash.Add (tc.TypeBuilder, info);
2508 public class VariableInfo : IVariable {
2509 public Expression Type;
2510 public LocalBuilder LocalBuilder;
2511 public Type VariableType;
2512 public readonly string Name;
2513 public readonly Location Location;
2514 public readonly int Block;
2519 public bool Assigned;
2520 public bool ReadOnly;
2522 public VariableInfo (Expression type, string name, int block, Location l)
2527 LocalBuilder = null;
2531 public VariableInfo (TypeContainer tc, int block, Location l)
2533 VariableType = tc.TypeBuilder;
2534 struct_info = MyStructInfo.GetStructInfo (tc);
2536 LocalBuilder = null;
2540 MyStructInfo struct_info;
2541 public MyStructInfo StructInfo {
2547 public bool IsAssigned (EmitContext ec, Location loc)
2548 {/* FIXME: we shouldn't just skip this!!!
2549 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2552 MyStructInfo struct_info = StructInfo;
2553 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2554 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2555 ec.CurrentBranching.SetVariableAssigned (this);
2559 int count = struct_info.Count;
2561 for (int i = 0; i < count; i++) {
2562 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2564 Report.Error (165, loc,
2565 "Use of unassigned local variable `" +
2567 ec.CurrentBranching.SetVariableAssigned (this);
2571 FieldInfo field = struct_info [i];
2572 Report.Error (171, loc,
2573 "Field `" + TypeManager.MonoBASIC_Name (VariableType) +
2574 "." + field.Name + "' must be fully initialized " +
2575 "before control leaves the constructor");
2583 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2585 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2586 (struct_info == null))
2589 int field_idx = StructInfo [name];
2593 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2594 Report.Error (170, loc,
2595 "Use of possibly unassigned field `" + name + "'");
2596 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2603 public void SetAssigned (EmitContext ec)
2605 if (ec.DoFlowAnalysis)
2606 ec.CurrentBranching.SetVariableAssigned (this);
2609 public void SetFieldAssigned (EmitContext ec, string name)
2611 if (ec.DoFlowAnalysis && (struct_info != null))
2612 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2615 public bool Resolve (DeclSpace decl)
2617 if (struct_info != null)
2620 if (VariableType == null)
2621 VariableType = decl.ResolveType (Type, false, Location);
2623 if (VariableType == null)
2626 struct_info = MyStructInfo.GetStructInfo (VariableType);
2631 public void MakePinned ()
2633 TypeManager.MakePinned (LocalBuilder);
2636 public override string ToString ()
2638 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2643 /// Block represents a C# block.
2647 /// This class is used in a number of places: either to represent
2648 /// explicit blocks that the programmer places or implicit blocks.
2650 /// Implicit blocks are used as labels or to introduce variable
2653 public class Block : Statement {
2654 public readonly Block Parent;
2655 public readonly bool Implicit;
2656 public readonly Location StartLocation;
2657 public Location EndLocation;
2660 // The statements in this block
2662 public ArrayList statements;
2665 // An array of Blocks. We keep track of children just
2666 // to generate the local variable declarations.
2668 // Statements and child statements are handled through the
2674 // Labels. (label, block) pairs.
2676 CaseInsensitiveHashtable labels;
2679 // Keeps track of (name, type) pairs
2681 CaseInsensitiveHashtable variables;
2684 // Keeps track of constants
2685 CaseInsensitiveHashtable constants;
2688 // Maps variable names to ILGenerator.LocalBuilders
2690 CaseInsensitiveHashtable local_builders;
2698 public Block (Block parent)
2699 : this (parent, false, Location.Null, Location.Null)
2702 public Block (Block parent, bool implicit_block)
2703 : this (parent, implicit_block, Location.Null, Location.Null)
2706 public Block (Block parent, bool implicit_block, Parameters parameters)
2707 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2710 public Block (Block parent, Location start, Location end)
2711 : this (parent, false, start, end)
2714 public Block (Block parent, Parameters parameters, Location start, Location end)
2715 : this (parent, false, parameters, start, end)
2718 public Block (Block parent, bool implicit_block, Location start, Location end)
2719 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2723 public Block (Block parent, bool implicit_block, Parameters parameters,
2724 Location start, Location end)
2727 parent.AddChild (this);
2729 this.Parent = parent;
2730 this.Implicit = implicit_block;
2731 this.parameters = parameters;
2732 this.StartLocation = start;
2733 this.EndLocation = end;
2736 statements = new ArrayList ();
2745 void AddChild (Block b)
2747 if (children == null)
2748 children = new ArrayList ();
2753 public void SetEndLocation (Location loc)
2759 /// Adds a label to the current block.
2763 /// false if the name already exists in this block. true
2767 public bool AddLabel (string name, LabeledStatement target)
2770 labels = new CaseInsensitiveHashtable ();
2771 if (labels.Contains (name))
2774 labels.Add (name, target);
2778 public LabeledStatement LookupLabel (string name)
2780 if (labels != null){
2781 if (labels.Contains (name))
2782 return ((LabeledStatement) labels [name]);
2786 return Parent.LookupLabel (name);
2791 VariableInfo this_variable = null;
2794 // Returns the "this" instance variable of this block.
2795 // See AddThisVariable() for more information.
2797 public VariableInfo ThisVariable {
2799 if (this_variable != null)
2800 return this_variable;
2801 else if (Parent != null)
2802 return Parent.ThisVariable;
2808 Hashtable child_variable_names;
2811 // Marks a variable with name @name as being used in a child block.
2812 // If a variable name has been used in a child block, it's illegal to
2813 // declare a variable with the same name in the current block.
2815 public void AddChildVariableName (string name)
2817 if (child_variable_names == null)
2818 child_variable_names = new CaseInsensitiveHashtable ();
2820 if (!child_variable_names.Contains (name))
2821 child_variable_names.Add (name, true);
2825 // Marks all variables from block @block and all its children as being
2826 // used in a child block.
2828 public void AddChildVariableNames (Block block)
2830 if (block.Variables != null) {
2831 foreach (string name in block.Variables.Keys)
2832 AddChildVariableName (name);
2835 foreach (Block child in block.children) {
2836 if (child.Variables != null) {
2837 foreach (string name in child.Variables.Keys)
2838 AddChildVariableName (name);
2844 // Checks whether a variable name has already been used in a child block.
2846 public bool IsVariableNameUsedInChildBlock (string name)
2848 if (child_variable_names == null)
2851 return child_variable_names.Contains (name);
2855 // This is used by non-static `struct' constructors which do not have an
2856 // initializer - in this case, the constructor must initialize all of the
2857 // struct's fields. To do this, we add a "this" variable and use the flow
2858 // analysis code to ensure that it's been fully initialized before control
2859 // leaves the constructor.
2861 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2863 if (this_variable != null)
2864 return this_variable;
2866 this_variable = new VariableInfo (tc, ID, l);
2868 if (variables == null)
2869 variables = new CaseInsensitiveHashtable ();
2870 variables.Add ("this", this_variable);
2872 return this_variable;
2875 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2877 if (variables == null)
2878 variables = new CaseInsensitiveHashtable ();
2880 VariableInfo vi = GetVariableInfo (name);
2883 Report.Error (30616, l, "A local variable named `" + name + "' " +
2884 "cannot be declared in this scope since it would " +
2885 "give a different meaning to `" + name + "', which " +
2886 "is already used in a `parent or current' scope to " +
2887 "denote something else");
2889 Report.Error (30290, l, "A local variable `" + name + "' is already " +
2890 "defined in this scope");
2894 if (IsVariableNameUsedInChildBlock (name)) {
2895 Report.Error (136, l, "A local variable named `" + name + "' " +
2896 "cannot be declared in this scope since it would " +
2897 "give a different meaning to `" + name + "', which " +
2898 "is already used in a `child' scope to denote something " +
2905 Parameter p = pars.GetParameterByName (name, out idx);
2907 Report.Error (30616, l, "A local variable named `" + name + "' " +
2908 "cannot be declared in this scope since it would " +
2909 "give a different meaning to `" + name + "', which " +
2910 "is already used in a `parent or current' scope to " +
2911 "denote something else");
2916 vi = new VariableInfo (type, name, ID, l);
2918 variables.Add (name, vi);
2920 if (variables_initialized)
2921 throw new Exception ();
2923 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2927 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2929 if (AddVariable (type, name, pars, l) == null)
2932 if (constants == null)
2933 constants = new CaseInsensitiveHashtable ();
2935 constants.Add (name, value);
2939 public Hashtable Variables {
2945 public VariableInfo GetVariableInfo (string name)
2947 if (variables != null) {
2949 temp = variables [name];
2952 return (VariableInfo) temp;
2957 return Parent.GetVariableInfo (name);
2962 public Expression GetVariableType (string name)
2964 VariableInfo vi = GetVariableInfo (name);
2972 public Expression GetConstantExpression (string name)
2974 if (constants != null) {
2976 temp = constants [name];
2979 return (Expression) temp;
2983 return Parent.GetConstantExpression (name);
2989 /// True if the variable named @name has been defined
2992 public bool IsVariableDefined (string name)
2994 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2995 if (variables != null) {
2996 if (variables.Contains (name))
3001 return Parent.IsVariableDefined (name);
3007 /// True if the variable named @name is a constant
3009 public bool IsConstant (string name)
3011 Expression e = null;
3013 e = GetConstantExpression (name);
3019 /// Use to fetch the statement associated with this label
3021 public Statement this [string name] {
3023 return (Statement) labels [name];
3027 Parameters parameters = null;
3028 public Parameters Parameters {
3031 return Parent.Parameters;
3038 /// A list of labels that were not used within this block
3040 public string [] GetUnreferenced ()
3042 // FIXME: Implement me
3046 public void AddStatement (Statement s)
3063 bool variables_initialized = false;
3064 int count_variables = 0, first_variable = 0;
3066 void UpdateVariableInfo (EmitContext ec)
3068 DeclSpace ds = ec.DeclSpace;
3073 first_variable += Parent.CountVariables;
3075 count_variables = first_variable;
3076 if (variables != null) {
3077 foreach (VariableInfo vi in variables.Values) {
3078 if (!vi.Resolve (ds)) {
3083 vi.Number = ++count_variables;
3085 if (vi.StructInfo != null)
3086 count_variables += vi.StructInfo.Count;
3090 variables_initialized = true;
3095 // The number of local variables in this block
3097 public int CountVariables
3100 if (!variables_initialized)
3101 throw new Exception ();
3103 return count_variables;
3108 /// Emits the variable declarations and labels.
3111 /// tc: is our typecontainer (to resolve type references)
3112 /// ig: is the code generator:
3113 /// toplevel: the toplevel block. This is used for checking
3114 /// that no two labels with the same name are used.
3116 public void EmitMeta (EmitContext ec, Block toplevel)
3118 //DeclSpace ds = ec.DeclSpace;
3119 ILGenerator ig = ec.ig;
3121 if (!variables_initialized)
3122 UpdateVariableInfo (ec);
3125 // Process this block variables
3127 if (variables != null){
3128 local_builders = new CaseInsensitiveHashtable ();
3130 foreach (DictionaryEntry de in variables){
3131 string name = (string) de.Key;
3132 VariableInfo vi = (VariableInfo) de.Value;
3134 if (vi.VariableType == null)
3137 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3139 if (CodeGen.SymbolWriter != null)
3140 vi.LocalBuilder.SetLocalSymInfo (name);
3142 if (constants == null)
3145 Expression cv = (Expression) constants [name];
3149 Expression e = cv.Resolve (ec);
3153 if (!(e is Constant)){
3154 Report.Error (133, vi.Location,
3155 "The expression being assigned to `" +
3156 name + "' must be constant (" + e + ")");
3160 constants.Remove (name);
3161 constants.Add (name, e);
3166 // Now, handle the children
3168 if (children != null){
3169 foreach (Block b in children)
3170 b.EmitMeta (ec, toplevel);
3174 public void UsageWarning ()
3178 if (variables != null){
3179 foreach (DictionaryEntry de in variables){
3180 VariableInfo vi = (VariableInfo) de.Value;
3185 name = (string) de.Key;
3189 219, vi.Location, "The variable `" + name +
3190 "' is assigned but its value is never used");
3193 168, vi.Location, "The variable `" +
3195 "' is declared but never used");
3200 if (children != null)
3201 foreach (Block b in children)
3205 bool has_ret = false;
3207 public override bool Resolve (EmitContext ec)
3209 Block prev_block = ec.CurrentBlock;
3212 ec.CurrentBlock = this;
3213 ec.StartFlowBranching (this);
3215 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3217 if (!variables_initialized)
3218 UpdateVariableInfo (ec);
3220 ArrayList new_statements = new ArrayList ();
3221 bool unreachable = false, warning_shown = false;
3223 foreach (Statement s in statements){
3224 if (unreachable && !(s is LabeledStatement)) {
3225 if (!warning_shown && !(s is EmptyStatement)) {
3226 warning_shown = true;
3227 Warning_DeadCodeFound (s.loc);
3233 if (s.Resolve (ec) == false) {
3238 if (s is LabeledStatement)
3239 unreachable = false;
3241 unreachable = ! ec.CurrentBranching.IsReachable ();
3243 new_statements.Add (s);
3246 statements = new_statements;
3248 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3250 FlowReturns returns = ec.EndFlowBranching ();
3251 ec.CurrentBlock = prev_block;
3253 // If we're a non-static `struct' constructor which doesn't have an
3254 // initializer, then we must initialize all of the struct's fields.
3255 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3256 !this_variable.IsAssigned (ec, loc))
3259 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3260 foreach (LabeledStatement label in labels.Values)
3261 if (!label.HasBeenReferenced)
3262 Report.Warning (164, label.Location,
3263 "This label has not been referenced");
3266 if ((returns == FlowReturns.ALWAYS) ||
3267 (returns == FlowReturns.EXCEPTION) ||
3268 (returns == FlowReturns.UNREACHABLE))
3274 protected override bool DoEmit (EmitContext ec)
3276 Block prev_block = ec.CurrentBlock;
3278 ec.CurrentBlock = this;
3280 ec.Mark (StartLocation);
3281 foreach (Statement s in statements)
3284 ec.Mark (EndLocation);
3286 ec.CurrentBlock = prev_block;
3291 public class SwitchLabel {
3294 public Location loc;
3295 public Label ILLabel;
3296 public Label ILLabelCode;
3299 // if expr == null, then it is the default case.
3301 public SwitchLabel (Expression expr, Location l)
3307 public Expression Label {
3313 public object Converted {
3320 // Resolves the expression, reduces it to a literal if possible
3321 // and then converts it to the requested type.
3323 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3325 ILLabel = ec.ig.DefineLabel ();
3326 ILLabelCode = ec.ig.DefineLabel ();
3331 Expression e = label.Resolve (ec);
3336 if (!(e is Constant)){
3337 Console.WriteLine ("Value is: " + label);
3338 Report.Error (150, loc, "A constant value is expected");
3342 if (e is StringConstant || e is NullLiteral){
3343 if (required_type == TypeManager.string_type){
3345 ILLabel = ec.ig.DefineLabel ();
3350 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3351 if (converted == null)
3358 public class SwitchSection {
3359 // An array of SwitchLabels.
3360 public readonly ArrayList Labels;
3361 public readonly Block Block;
3363 public SwitchSection (ArrayList labels, Block block)
3370 public class Switch : Statement {
3371 public readonly ArrayList Sections;
3372 public Expression Expr;
3375 /// Maps constants whose type type SwitchType to their SwitchLabels.
3377 public Hashtable Elements;
3380 /// The governing switch type
3382 public Type SwitchType;
3388 Label default_target;
3389 Expression new_expr;
3392 // The types allowed to be implicitly cast from
3393 // on the governing type
3395 static Type [] allowed_types;
3397 public Switch (Expression e, ArrayList sects, Location l)
3404 public bool GotDefault {
3410 public Label DefaultTarget {
3412 return default_target;
3417 // Determines the governing type for a switch. The returned
3418 // expression might be the expression from the switch, or an
3419 // expression that includes any potential conversions to the
3420 // integral types or to string.
3422 Expression SwitchGoverningType (EmitContext ec, Type t)
3424 if (t == TypeManager.int32_type ||
3425 t == TypeManager.uint32_type ||
3426 t == TypeManager.char_type ||
3427 t == TypeManager.byte_type ||
3428 t == TypeManager.sbyte_type ||
3429 t == TypeManager.ushort_type ||
3430 t == TypeManager.short_type ||
3431 t == TypeManager.uint64_type ||
3432 t == TypeManager.int64_type ||
3433 t == TypeManager.string_type ||
3434 t == TypeManager.bool_type ||
3435 t.IsSubclassOf (TypeManager.enum_type))
3438 if (allowed_types == null){
3439 allowed_types = new Type [] {
3440 TypeManager.sbyte_type,
3441 TypeManager.byte_type,
3442 TypeManager.short_type,
3443 TypeManager.ushort_type,
3444 TypeManager.int32_type,
3445 TypeManager.uint32_type,
3446 TypeManager.int64_type,
3447 TypeManager.uint64_type,
3448 TypeManager.char_type,
3449 TypeManager.bool_type,
3450 TypeManager.string_type
3455 // Try to find a *user* defined implicit conversion.
3457 // If there is no implicit conversion, or if there are multiple
3458 // conversions, we have to report an error
3460 Expression converted = null;
3461 foreach (Type tt in allowed_types){
3464 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3468 if (converted != null){
3469 Report.Error (-12, loc, "More than one conversion to an integral " +
3470 " type exists for type `" +
3471 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3479 void error152 (string n)
3482 152, "The label `" + n + ":' " +
3483 "is already present on this switch statement");
3487 // Performs the basic sanity checks on the switch statement
3488 // (looks for duplicate keys and non-constant expressions).
3490 // It also returns a hashtable with the keys that we will later
3491 // use to compute the switch tables
3493 bool CheckSwitch (EmitContext ec)
3497 Elements = new CaseInsensitiveHashtable ();
3499 got_default = false;
3501 if (TypeManager.IsEnumType (SwitchType)){
3502 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3504 compare_type = SwitchType;
3506 foreach (SwitchSection ss in Sections){
3507 foreach (SwitchLabel sl in ss.Labels){
3508 if (!sl.ResolveAndReduce (ec, SwitchType)){
3513 if (sl.Label == null){
3515 error152 ("default");
3522 object key = sl.Converted;
3524 if (key is Constant)
3525 key = ((Constant) key).GetValue ();
3528 key = NullLiteral.Null;
3530 string lname = null;
3531 if (compare_type == TypeManager.uint64_type){
3532 ulong v = (ulong) key;
3534 if (Elements.Contains (v))
3535 lname = v.ToString ();
3537 Elements.Add (v, sl);
3538 } else if (compare_type == TypeManager.int64_type){
3539 long v = (long) key;
3541 if (Elements.Contains (v))
3542 lname = v.ToString ();
3544 Elements.Add (v, sl);
3545 } else if (compare_type == TypeManager.uint32_type){
3546 uint v = (uint) key;
3548 if (Elements.Contains (v))
3549 lname = v.ToString ();
3551 Elements.Add (v, sl);
3552 } else if (compare_type == TypeManager.char_type){
3553 char v = (char) key;
3555 if (Elements.Contains (v))
3556 lname = v.ToString ();
3558 Elements.Add (v, sl);
3559 } else if (compare_type == TypeManager.byte_type){
3560 byte v = (byte) key;
3562 if (Elements.Contains (v))
3563 lname = v.ToString ();
3565 Elements.Add (v, sl);
3566 } else if (compare_type == TypeManager.sbyte_type){
3567 sbyte v = (sbyte) key;
3569 if (Elements.Contains (v))
3570 lname = v.ToString ();
3572 Elements.Add (v, sl);
3573 } else if (compare_type == TypeManager.short_type){
3574 short v = (short) key;
3576 if (Elements.Contains (v))
3577 lname = v.ToString ();
3579 Elements.Add (v, sl);
3580 } else if (compare_type == TypeManager.ushort_type){
3581 ushort v = (ushort) key;
3583 if (Elements.Contains (v))
3584 lname = v.ToString ();
3586 Elements.Add (v, sl);
3587 } else if (compare_type == TypeManager.string_type){
3588 if (key is NullLiteral){
3589 if (Elements.Contains (NullLiteral.Null))
3592 Elements.Add (NullLiteral.Null, null);
3594 string s = (string) key;
3596 if (Elements.Contains (s))
3599 Elements.Add (s, sl);
3601 } else if (compare_type == TypeManager.int32_type) {
3604 if (Elements.Contains (v))
3605 lname = v.ToString ();
3607 Elements.Add (v, sl);
3608 } else if (compare_type == TypeManager.bool_type) {
3609 bool v = (bool) key;
3611 if (Elements.Contains (v))
3612 lname = v.ToString ();
3614 Elements.Add (v, sl);
3618 throw new Exception ("Unknown switch type!" +
3619 SwitchType + " " + compare_type);
3623 error152 ("case + " + lname);
3634 void EmitObjectInteger (ILGenerator ig, object k)
3637 IntConstant.EmitInt (ig, (int) k);
3638 else if (k is Constant) {
3639 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3642 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3645 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3647 IntConstant.EmitInt (ig, (int) (long) k);
3648 ig.Emit (OpCodes.Conv_I8);
3651 LongConstant.EmitLong (ig, (long) k);
3653 else if (k is ulong)
3655 if ((ulong) k < (1L<<32))
3657 IntConstant.EmitInt (ig, (int) (long) k);
3658 ig.Emit (OpCodes.Conv_U8);
3662 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3666 IntConstant.EmitInt (ig, (int) ((char) k));
3667 else if (k is sbyte)
3668 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3670 IntConstant.EmitInt (ig, (int) ((byte) k));
3671 else if (k is short)
3672 IntConstant.EmitInt (ig, (int) ((short) k));
3673 else if (k is ushort)
3674 IntConstant.EmitInt (ig, (int) ((ushort) k));
3676 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3678 throw new Exception ("Unhandled case");
3681 // structure used to hold blocks of keys while calculating table switch
3682 class KeyBlock : IComparable
3684 public KeyBlock (long _nFirst)
3686 nFirst = nLast = _nFirst;
3690 public ArrayList rgKeys = null;
3693 get { return (int) (nLast - nFirst + 1); }
3695 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3697 return kbLast.nLast - kbFirst.nFirst + 1;
3699 public int CompareTo (object obj)
3701 KeyBlock kb = (KeyBlock) obj;
3702 int nLength = Length;
3703 int nLengthOther = kb.Length;
3704 if (nLengthOther == nLength)
3705 return (int) (kb.nFirst - nFirst);
3706 return nLength - nLengthOther;
3711 /// This method emits code for a lookup-based switch statement (non-string)
3712 /// Basically it groups the cases into blocks that are at least half full,
3713 /// and then spits out individual lookup opcodes for each block.
3714 /// It emits the longest blocks first, and short blocks are just
3715 /// handled with direct compares.
3717 /// <param name="ec"></param>
3718 /// <param name="val"></param>
3719 /// <returns></returns>
3720 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3722 int cElements = Elements.Count;
3723 object [] rgKeys = new object [cElements];
3724 Elements.Keys.CopyTo (rgKeys, 0);
3725 Array.Sort (rgKeys);
3727 // initialize the block list with one element per key
3728 ArrayList rgKeyBlocks = new ArrayList ();
3729 foreach (object key in rgKeys)
3730 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3733 // iteratively merge the blocks while they are at least half full
3734 // there's probably a really cool way to do this with a tree...
3735 while (rgKeyBlocks.Count > 1)
3737 ArrayList rgKeyBlocksNew = new ArrayList ();
3738 kbCurr = (KeyBlock) rgKeyBlocks [0];
3739 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3741 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3742 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3745 kbCurr.nLast = kb.nLast;
3749 // start a new block
3750 rgKeyBlocksNew.Add (kbCurr);
3754 rgKeyBlocksNew.Add (kbCurr);
3755 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3757 rgKeyBlocks = rgKeyBlocksNew;
3760 // initialize the key lists
3761 foreach (KeyBlock kb in rgKeyBlocks)
3762 kb.rgKeys = new ArrayList ();
3764 // fill the key lists
3766 if (rgKeyBlocks.Count > 0) {
3767 kbCurr = (KeyBlock) rgKeyBlocks [0];
3768 foreach (object key in rgKeys)
3770 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3772 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3773 kbCurr.rgKeys.Add (key);
3777 // sort the blocks so we can tackle the largest ones first
3778 rgKeyBlocks.Sort ();
3780 // okay now we can start...
3781 ILGenerator ig = ec.ig;
3782 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3783 Label lblDefault = ig.DefineLabel ();
3785 Type typeKeys = null;
3786 if (rgKeys.Length > 0)
3787 typeKeys = rgKeys [0].GetType (); // used for conversions
3789 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3791 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3792 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3795 foreach (object key in kb.rgKeys)
3797 ig.Emit (OpCodes.Ldloc, val);
3798 EmitObjectInteger (ig, key);
3799 SwitchLabel sl = (SwitchLabel) Elements [key];
3800 ig.Emit (OpCodes.Beq, sl.ILLabel);
3805 // TODO: if all the keys in the block are the same and there are
3806 // no gaps/defaults then just use a range-check.
3807 if (SwitchType == TypeManager.int64_type ||
3808 SwitchType == TypeManager.uint64_type)
3810 // TODO: optimize constant/I4 cases
3812 // check block range (could be > 2^31)
3813 ig.Emit (OpCodes.Ldloc, val);
3814 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3815 ig.Emit (OpCodes.Blt, lblDefault);
3816 ig.Emit (OpCodes.Ldloc, val);
3817 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3818 ig.Emit (OpCodes.Bgt, lblDefault);
3821 ig.Emit (OpCodes.Ldloc, val);
3824 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3825 ig.Emit (OpCodes.Sub);
3827 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3832 ig.Emit (OpCodes.Ldloc, val);
3833 int nFirst = (int) kb.nFirst;
3836 IntConstant.EmitInt (ig, nFirst);
3837 ig.Emit (OpCodes.Sub);
3839 else if (nFirst < 0)
3841 IntConstant.EmitInt (ig, -nFirst);
3842 ig.Emit (OpCodes.Add);
3846 // first, build the list of labels for the switch
3848 int cJumps = kb.Length;
3849 Label [] rgLabels = new Label [cJumps];
3850 for (int iJump = 0; iJump < cJumps; iJump++)
3852 object key = kb.rgKeys [iKey];
3853 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3855 SwitchLabel sl = (SwitchLabel) Elements [key];
3856 rgLabels [iJump] = sl.ILLabel;
3860 rgLabels [iJump] = lblDefault;
3862 // emit the switch opcode
3863 ig.Emit (OpCodes.Switch, rgLabels);
3866 // mark the default for this block
3868 ig.MarkLabel (lblDefault);
3871 // TODO: find the default case and emit it here,
3872 // to prevent having to do the following jump.
3873 // make sure to mark other labels in the default section
3875 // the last default just goes to the end
3876 ig.Emit (OpCodes.Br, lblDefault);
3878 // now emit the code for the sections
3879 bool fFoundDefault = false;
3880 bool fAllReturn = true;
3881 foreach (SwitchSection ss in Sections)
3883 foreach (SwitchLabel sl in ss.Labels)
3885 ig.MarkLabel (sl.ILLabel);
3886 ig.MarkLabel (sl.ILLabelCode);
3887 if (sl.Label == null)
3889 ig.MarkLabel (lblDefault);
3890 fFoundDefault = true;
3893 bool returns = ss.Block.Emit (ec);
3894 fAllReturn &= returns;
3895 //ig.Emit (OpCodes.Br, lblEnd);
3898 if (!fFoundDefault) {
3899 ig.MarkLabel (lblDefault);
3902 ig.MarkLabel (lblEnd);
3907 // This simple emit switch works, but does not take advantage of the
3909 // TODO: remove non-string logic from here
3910 // TODO: binary search strings?
3912 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3914 ILGenerator ig = ec.ig;
3915 Label end_of_switch = ig.DefineLabel ();
3916 Label next_test = ig.DefineLabel ();
3917 Label null_target = ig.DefineLabel ();
3918 bool default_found = false;
3919 bool first_test = true;
3920 bool pending_goto_end = false;
3921 bool all_return = true;
3922 bool is_string = false;
3926 // Special processing for strings: we cant compare
3929 if (SwitchType == TypeManager.string_type){
3930 ig.Emit (OpCodes.Ldloc, val);
3933 if (Elements.Contains (NullLiteral.Null)){
3934 ig.Emit (OpCodes.Brfalse, null_target);
3936 ig.Emit (OpCodes.Brfalse, default_target);
3938 ig.Emit (OpCodes.Ldloc, val);
3939 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3940 ig.Emit (OpCodes.Stloc, val);
3943 foreach (SwitchSection ss in Sections){
3944 Label sec_begin = ig.DefineLabel ();
3946 if (pending_goto_end)
3947 ig.Emit (OpCodes.Br, end_of_switch);
3949 int label_count = ss.Labels.Count;
3951 foreach (SwitchLabel sl in ss.Labels){
3952 ig.MarkLabel (sl.ILLabel);
3955 ig.MarkLabel (next_test);
3956 next_test = ig.DefineLabel ();
3959 // If we are the default target
3961 if (sl.Label == null){
3962 ig.MarkLabel (default_target);
3963 default_found = true;
3965 object lit = sl.Converted;
3967 if (lit is NullLiteral){
3969 if (label_count == 1)
3970 ig.Emit (OpCodes.Br, next_test);
3975 StringConstant str = (StringConstant) lit;
3977 ig.Emit (OpCodes.Ldloc, val);
3978 ig.Emit (OpCodes.Ldstr, str.Value);
3979 if (label_count == 1)
3980 ig.Emit (OpCodes.Bne_Un, next_test);
3982 ig.Emit (OpCodes.Beq, sec_begin);
3984 ig.Emit (OpCodes.Ldloc, val);
3985 EmitObjectInteger (ig, lit);
3986 ig.Emit (OpCodes.Ceq);
3987 if (label_count == 1)
3988 ig.Emit (OpCodes.Brfalse, next_test);
3990 ig.Emit (OpCodes.Brtrue, sec_begin);
3994 if (label_count != 1)
3995 ig.Emit (OpCodes.Br, next_test);
3998 ig.MarkLabel (null_target);
3999 ig.MarkLabel (sec_begin);
4000 foreach (SwitchLabel sl in ss.Labels)
4001 ig.MarkLabel (sl.ILLabelCode);
4003 bool returns = ss.Block.Emit (ec);
4005 pending_goto_end = false;
4008 pending_goto_end = true;
4012 if (!default_found){
4013 ig.MarkLabel (default_target);
4016 ig.MarkLabel (next_test);
4017 ig.MarkLabel (end_of_switch);
4022 public override bool Resolve (EmitContext ec)
4024 Expr = Expr.Resolve (ec);
4028 new_expr = SwitchGoverningType (ec, Expr.Type);
4029 if (new_expr == null){
4030 Report.Error (151, loc, "An integer type or string was expected for switch");
4035 SwitchType = new_expr.Type;
4037 if (!CheckSwitch (ec))
4040 Switch old_switch = ec.Switch;
4042 ec.Switch.SwitchType = SwitchType;
4044 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
4047 foreach (SwitchSection ss in Sections){
4049 ec.CurrentBranching.CreateSibling ();
4053 if (ss.Block.Resolve (ec) != true)
4059 ec.CurrentBranching.CreateSibling ();
4061 ec.EndFlowBranching ();
4062 ec.Switch = old_switch;
4067 protected override bool DoEmit (EmitContext ec)
4069 // Store variable for comparission purposes
4070 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
4072 ec.ig.Emit (OpCodes.Stloc, value);
4074 ILGenerator ig = ec.ig;
4076 default_target = ig.DefineLabel ();
4079 // Setup the codegen context
4081 Label old_end = ec.LoopEnd;
4082 Switch old_switch = ec.Switch;
4084 ec.LoopEnd = ig.DefineLabel ();
4089 if (SwitchType == TypeManager.string_type)
4090 all_return = SimpleSwitchEmit (ec, value);
4092 all_return = TableSwitchEmit (ec, value);
4094 // Restore context state.
4095 ig.MarkLabel (ec.LoopEnd);
4098 // Restore the previous context
4100 ec.LoopEnd = old_end;
4101 ec.Switch = old_switch;
4107 public class Lock : Statement {
4109 Statement Statement;
4111 public Lock (Expression expr, Statement stmt, Location l)
4118 public override bool Resolve (EmitContext ec)
4120 expr = expr.Resolve (ec);
4121 return Statement.Resolve (ec) && expr != null;
4124 protected override bool DoEmit (EmitContext ec)
4126 Type type = expr.Type;
4129 if (type.IsValueType){
4130 Report.Error (30582, loc, "lock statement requires the expression to be " +
4131 " a reference type (type is: `" +
4132 TypeManager.MonoBASIC_Name (type) + "'");
4136 ILGenerator ig = ec.ig;
4137 LocalBuilder temp = ig.DeclareLocal (type);
4140 ig.Emit (OpCodes.Dup);
4141 ig.Emit (OpCodes.Stloc, temp);
4142 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4145 ig.BeginExceptionBlock ();
4146 bool old_in_try = ec.InTry;
4148 Label finish = ig.DefineLabel ();
4149 val = Statement.Emit (ec);
4150 ec.InTry = old_in_try;
4151 // ig.Emit (OpCodes.Leave, finish);
4153 ig.MarkLabel (finish);
4156 ig.BeginFinallyBlock ();
4157 ig.Emit (OpCodes.Ldloc, temp);
4158 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4159 ig.EndExceptionBlock ();
4165 public class Unchecked : Statement {
4166 public readonly Block Block;
4168 public Unchecked (Block b)
4173 public override bool Resolve (EmitContext ec)
4175 return Block.Resolve (ec);
4178 protected override bool DoEmit (EmitContext ec)
4180 bool previous_state = ec.CheckState;
4181 bool previous_state_const = ec.ConstantCheckState;
4184 ec.CheckState = false;
4185 ec.ConstantCheckState = false;
4186 val = Block.Emit (ec);
4187 ec.CheckState = previous_state;
4188 ec.ConstantCheckState = previous_state_const;
4194 public class Checked : Statement {
4195 public readonly Block Block;
4197 public Checked (Block b)
4202 public override bool Resolve (EmitContext ec)
4204 bool previous_state = ec.CheckState;
4205 bool previous_state_const = ec.ConstantCheckState;
4207 ec.CheckState = true;
4208 ec.ConstantCheckState = true;
4209 bool ret = Block.Resolve (ec);
4210 ec.CheckState = previous_state;
4211 ec.ConstantCheckState = previous_state_const;
4216 protected override bool DoEmit (EmitContext ec)
4218 bool previous_state = ec.CheckState;
4219 bool previous_state_const = ec.ConstantCheckState;
4222 ec.CheckState = true;
4223 ec.ConstantCheckState = true;
4224 val = Block.Emit (ec);
4225 ec.CheckState = previous_state;
4226 ec.ConstantCheckState = previous_state_const;
4232 public class Unsafe : Statement {
4233 public readonly Block Block;
4235 public Unsafe (Block b)
4240 public override bool Resolve (EmitContext ec)
4242 bool previous_state = ec.InUnsafe;
4246 val = Block.Resolve (ec);
4247 ec.InUnsafe = previous_state;
4252 protected override bool DoEmit (EmitContext ec)
4254 bool previous_state = ec.InUnsafe;
4258 val = Block.Emit (ec);
4259 ec.InUnsafe = previous_state;
4268 public class Fixed : Statement {
4270 ArrayList declarators;
4271 Statement statement;
4276 public bool is_object;
4277 public VariableInfo vi;
4278 public Expression expr;
4279 public Expression converted;
4282 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4285 declarators = decls;
4290 public override bool Resolve (EmitContext ec)
4292 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4293 if (expr_type == null)
4296 data = new FixedData [declarators.Count];
4299 foreach (Pair p in declarators){
4300 VariableInfo vi = (VariableInfo) p.First;
4301 Expression e = (Expression) p.Second;
4306 // The rules for the possible declarators are pretty wise,
4307 // but the production on the grammar is more concise.
4309 // So we have to enforce these rules here.
4311 // We do not resolve before doing the case 1 test,
4312 // because the grammar is explicit in that the token &
4313 // is present, so we need to test for this particular case.
4317 // Case 1: & object.
4319 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4320 Expression child = ((Unary) e).Expr;
4323 if (child is ParameterReference || child is LocalVariableReference){
4326 "No need to use fixed statement for parameters or " +
4327 "local variable declarations (address is already " +
4336 child = ((Unary) e).Expr;
4338 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4341 data [i].is_object = true;
4343 data [i].converted = null;
4357 if (e.Type.IsArray){
4358 Type array_type = e.Type.GetElementType ();
4362 // Provided that array_type is unmanaged,
4364 if (!TypeManager.VerifyUnManaged (array_type, loc))
4368 // and T* is implicitly convertible to the
4369 // pointer type given in the fixed statement.
4371 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4373 Expression converted = Expression.ConvertImplicitRequired (
4374 ec, array_ptr, vi.VariableType, loc);
4375 if (converted == null)
4378 data [i].is_object = false;
4380 data [i].converted = converted;
4390 if (e.Type == TypeManager.string_type){
4391 data [i].is_object = false;
4393 data [i].converted = null;
4399 return statement.Resolve (ec);
4402 protected override bool DoEmit (EmitContext ec)
4404 ILGenerator ig = ec.ig;
4406 bool is_ret = false;
4408 for (int i = 0; i < data.Length; i++) {
4409 VariableInfo vi = data [i].vi;
4412 // Case 1: & object.
4414 if (data [i].is_object) {
4416 // Store pointer in pinned location
4418 data [i].expr.Emit (ec);
4419 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4421 is_ret = statement.Emit (ec);
4423 // Clear the pinned variable.
4424 ig.Emit (OpCodes.Ldc_I4_0);
4425 ig.Emit (OpCodes.Conv_U);
4426 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4434 if (data [i].expr.Type.IsArray){
4436 // Store pointer in pinned location
4438 data [i].converted.Emit (ec);
4440 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4442 is_ret = statement.Emit (ec);
4444 // Clear the pinned variable.
4445 ig.Emit (OpCodes.Ldc_I4_0);
4446 ig.Emit (OpCodes.Conv_U);
4447 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4455 if (data [i].expr.Type == TypeManager.string_type){
4456 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4457 TypeManager.MakePinned (pinned_string);
4459 data [i].expr.Emit (ec);
4460 ig.Emit (OpCodes.Stloc, pinned_string);
4462 Expression sptr = new StringPtr (pinned_string, loc);
4463 Expression converted = Expression.ConvertImplicitRequired (
4464 ec, sptr, vi.VariableType, loc);
4466 if (converted == null)
4469 converted.Emit (ec);
4470 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4472 is_ret = statement.Emit (ec);
4474 // Clear the pinned variable
4475 ig.Emit (OpCodes.Ldnull);
4476 ig.Emit (OpCodes.Stloc, pinned_string);
4484 public class Catch {
4485 public readonly string Name;
4486 public readonly Block Block;
4487 public Expression Clause;
4488 public readonly Location Location;
4490 Expression type_expr;
4491 //Expression clus_expr;
4494 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4503 public Type CatchType {
4509 public bool IsGeneral {
4511 return type_expr == null;
4515 public bool Resolve (EmitContext ec)
4517 if (type_expr != null) {
4518 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4522 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4523 Report.Error (30665, Location,
4524 "The type caught or thrown must be derived " +
4525 "from System.Exception");
4531 if (Clause != null) {
4532 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4533 if (Clause == null) {
4538 if (!Block.Resolve (ec))
4545 public class Try : Statement {
4546 public readonly Block Fini, Block;
4547 public readonly ArrayList Specific;
4548 public readonly Catch General;
4551 // specific, general and fini might all be null.
4553 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4555 if (specific == null && general == null){
4556 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4560 this.Specific = specific;
4561 this.General = general;
4566 public override bool Resolve (EmitContext ec)
4570 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4572 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4574 bool old_in_try = ec.InTry;
4577 if (!Block.Resolve (ec))
4580 ec.InTry = old_in_try;
4582 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4584 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4586 foreach (Catch c in Specific){
4587 ec.CurrentBranching.CreateSibling ();
4588 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4590 if (c.Name != null) {
4591 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4593 throw new Exception ();
4598 bool old_in_catch = ec.InCatch;
4601 if (!c.Resolve (ec))
4604 ec.InCatch = old_in_catch;
4606 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4608 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4609 vector.AndLocals (current);
4612 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4614 if (General != null){
4615 ec.CurrentBranching.CreateSibling ();
4616 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4618 bool old_in_catch = ec.InCatch;
4621 if (!General.Resolve (ec))
4624 ec.InCatch = old_in_catch;
4626 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4628 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4629 vector.AndLocals (current);
4632 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4635 ec.CurrentBranching.CreateSiblingForFinally ();
4636 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4638 bool old_in_finally = ec.InFinally;
4639 ec.InFinally = true;
4641 if (!Fini.Resolve (ec))
4644 ec.InFinally = old_in_finally;
4647 FlowReturns returns = ec.EndFlowBranching ();
4649 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4651 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4653 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4654 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4657 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4659 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4664 protected override bool DoEmit (EmitContext ec)
4666 ILGenerator ig = ec.ig;
4667 Label finish = ig.DefineLabel ();;
4671 ig.BeginExceptionBlock ();
4672 bool old_in_try = ec.InTry;
4674 returns = Block.Emit (ec);
4675 ec.InTry = old_in_try;
4678 // System.Reflection.Emit provides this automatically:
4679 // ig.Emit (OpCodes.Leave, finish);
4681 bool old_in_catch = ec.InCatch;
4683 //DeclSpace ds = ec.DeclSpace;
4685 foreach (Catch c in Specific){
4688 ig.BeginCatchBlock (c.CatchType);
4690 if (c.Name != null){
4691 vi = c.Block.GetVariableInfo (c.Name);
4693 throw new Exception ("Variable does not exist in this block");
4695 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4697 ig.Emit (OpCodes.Pop);
4700 // if when clause is there
4702 if (c.Clause != null) {
4703 if (c.Clause is BoolConstant) {
4704 bool take = ((BoolConstant) c.Clause).Value;
4707 if (!c.Block.Emit (ec))
4710 EmitBoolExpression (ec, c.Clause, finish, false);
4711 if (!c.Block.Emit (ec))
4715 if (!c.Block.Emit (ec))
4719 if (General != null){
4720 ig.BeginCatchBlock (TypeManager.object_type);
4721 ig.Emit (OpCodes.Pop);
4723 if (General.Clause != null) {
4724 if (General.Clause is BoolConstant) {
4725 bool take = ((BoolConstant) General.Clause).Value;
4727 if (!General.Block.Emit (ec))
4730 EmitBoolExpression (ec, General.Clause, finish, false);
4731 if (!General.Block.Emit (ec))
4735 if (!General.Block.Emit (ec))
4739 ec.InCatch = old_in_catch;
4741 ig.MarkLabel (finish);
4743 ig.BeginFinallyBlock ();
4744 bool old_in_finally = ec.InFinally;
4745 ec.InFinally = true;
4747 ec.InFinally = old_in_finally;
4750 ig.EndExceptionBlock ();
4753 if (!returns || ec.InTry || ec.InCatch)
4756 // Unfortunately, System.Reflection.Emit automatically emits a leave
4757 // to the end of the finally block. This is a problem if `returns'
4758 // is true since we may jump to a point after the end of the method.
4759 // As a workaround, emit an explicit ret here.
4761 if (ec.ReturnType != null)
4762 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4763 ec.ig.Emit (OpCodes.Ret);
4769 public class Using : Statement {
4770 object expression_or_block;
4771 Statement Statement;
4776 Expression [] converted_vars;
4777 ExpressionStatement [] assign;
4779 public Using (object expression_or_block, Statement stmt, Location l)
4781 this.expression_or_block = expression_or_block;
4787 // Resolves for the case of using using a local variable declaration.
4789 bool ResolveLocalVariableDecls (EmitContext ec)
4791 bool need_conv = false;
4792 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4795 if (expr_type == null)
4799 // The type must be an IDisposable or an implicit conversion
4802 converted_vars = new Expression [var_list.Count];
4803 assign = new ExpressionStatement [var_list.Count];
4804 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4805 foreach (DictionaryEntry e in var_list){
4806 Expression var = (Expression) e.Key;
4808 var = var.ResolveLValue (ec, new EmptyExpression ());
4812 converted_vars [i] = Expression.ConvertImplicitRequired (
4813 ec, var, TypeManager.idisposable_type, loc);
4815 if (converted_vars [i] == null)
4823 foreach (DictionaryEntry e in var_list){
4824 LocalVariableReference var = (LocalVariableReference) e.Key;
4825 Expression new_expr = (Expression) e.Value;
4828 a = new Assign (var, new_expr, loc);
4834 converted_vars [i] = var;
4835 assign [i] = (ExpressionStatement) a;
4842 bool ResolveExpression (EmitContext ec)
4844 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4845 conv = Expression.ConvertImplicitRequired (
4846 ec, expr, TypeManager.idisposable_type, loc);
4856 // Emits the code for the case of using using a local variable declaration.
4858 bool EmitLocalVariableDecls (EmitContext ec)
4860 ILGenerator ig = ec.ig;
4863 bool old_in_try = ec.InTry;
4865 for (i = 0; i < assign.Length; i++) {
4866 assign [i].EmitStatement (ec);
4868 ig.BeginExceptionBlock ();
4870 Statement.Emit (ec);
4871 ec.InTry = old_in_try;
4873 bool old_in_finally = ec.InFinally;
4874 ec.InFinally = true;
4875 var_list.Reverse ();
4876 foreach (DictionaryEntry e in var_list){
4877 LocalVariableReference var = (LocalVariableReference) e.Key;
4878 Label skip = ig.DefineLabel ();
4881 ig.BeginFinallyBlock ();
4884 ig.Emit (OpCodes.Brfalse, skip);
4885 converted_vars [i].Emit (ec);
4886 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4887 ig.MarkLabel (skip);
4888 ig.EndExceptionBlock ();
4890 ec.InFinally = old_in_finally;
4895 bool EmitExpression (EmitContext ec)
4898 // Make a copy of the expression and operate on that.
4900 ILGenerator ig = ec.ig;
4901 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4906 ig.Emit (OpCodes.Stloc, local_copy);
4908 bool old_in_try = ec.InTry;
4910 ig.BeginExceptionBlock ();
4911 Statement.Emit (ec);
4912 ec.InTry = old_in_try;
4914 Label skip = ig.DefineLabel ();
4915 bool old_in_finally = ec.InFinally;
4916 ig.BeginFinallyBlock ();
4917 ig.Emit (OpCodes.Ldloc, local_copy);
4918 ig.Emit (OpCodes.Brfalse, skip);
4919 ig.Emit (OpCodes.Ldloc, local_copy);
4920 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4921 ig.MarkLabel (skip);
4922 ec.InFinally = old_in_finally;
4923 ig.EndExceptionBlock ();
4928 public override bool Resolve (EmitContext ec)
4930 if (expression_or_block is DictionaryEntry){
4931 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4932 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4934 if (!ResolveLocalVariableDecls (ec))
4937 } else if (expression_or_block is Expression){
4938 expr = (Expression) expression_or_block;
4940 expr = expr.Resolve (ec);
4944 expr_type = expr.Type;
4946 if (!ResolveExpression (ec))
4950 return Statement.Resolve (ec);
4953 protected override bool DoEmit (EmitContext ec)
4955 if (expression_or_block is DictionaryEntry)
4956 return EmitLocalVariableDecls (ec);
4957 else if (expression_or_block is Expression)
4958 return EmitExpression (ec);
4965 /// Implementation of the foreach C# statement
4967 public class Foreach : Statement {
4969 LocalVariableReference variable;
4971 Statement statement;
4972 ForeachHelperMethods hm;
4973 Expression empty, conv;
4974 Type array_type, element_type;
4977 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4978 Statement stmt, Location l)
4985 VariableInfo vi = var.VariableInfo;
4986 this.type = vi.Type;
4988 this.variable = var;
4994 public override bool Resolve (EmitContext ec)
4996 expr = expr.Resolve (ec);
5000 var_type = ec.DeclSpace.ResolveType (type, false, loc);
5001 if (var_type == null)
5005 // We need an instance variable. Not sure this is the best
5006 // way of doing this.
5008 // FIXME: When we implement propertyaccess, will those turn
5009 // out to return values in ExprClass? I think they should.
5011 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
5012 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
5013 error1579 (expr.Type);
5017 if (expr.Type.IsArray) {
5018 array_type = expr.Type;
5019 element_type = array_type.GetElementType ();
5021 empty = new EmptyExpression (element_type);
5023 hm = ProbeCollectionType (ec, expr.Type);
5025 error1579 (expr.Type);
5029 array_type = expr.Type;
5030 element_type = hm.element_type;
5032 empty = new EmptyExpression (hm.element_type);
5035 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
5036 ec.CurrentBranching.CreateSibling ();
5040 // FIXME: maybe we can apply the same trick we do in the
5041 // array handling to avoid creating empty and conv in some cases.
5043 // Although it is not as important in this case, as the type
5044 // will not likely be object (what the enumerator will return).
5046 conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
5050 if (variable.ResolveLValue (ec, empty) == null)
5053 if (!statement.Resolve (ec))
5056 //FlowReturns returns = ec.EndFlowBranching ();
5062 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5064 static MethodInfo FetchMethodMoveNext (Type t)
5066 MemberList move_next_list;
5068 move_next_list = TypeContainer.FindMembers (
5069 t, MemberTypes.Method,
5070 BindingFlags.Public | BindingFlags.Instance,
5071 Type.FilterName, "MoveNext");
5072 if (move_next_list.Count == 0)
5075 foreach (MemberInfo m in move_next_list){
5076 MethodInfo mi = (MethodInfo) m;
5079 args = TypeManager.GetArgumentTypes (mi);
5080 if (args != null && args.Length == 0){
5081 if (mi.ReturnType == TypeManager.bool_type)
5089 // Retrieves a `public T get_Current ()' method from the Type `t'
5091 static MethodInfo FetchMethodGetCurrent (Type t)
5093 MemberList move_next_list;
5095 move_next_list = TypeContainer.FindMembers (
5096 t, MemberTypes.Method,
5097 BindingFlags.Public | BindingFlags.Instance,
5098 Type.FilterName, "get_Current");
5099 if (move_next_list.Count == 0)
5102 foreach (MemberInfo m in move_next_list){
5103 MethodInfo mi = (MethodInfo) m;
5106 args = TypeManager.GetArgumentTypes (mi);
5107 if (args != null && args.Length == 0)
5114 // This struct records the helper methods used by the Foreach construct
5116 class ForeachHelperMethods {
5117 public EmitContext ec;
5118 public MethodInfo get_enumerator;
5119 public MethodInfo move_next;
5120 public MethodInfo get_current;
5121 public Type element_type;
5122 public Type enumerator_type;
5123 public bool is_disposable;
5125 public ForeachHelperMethods (EmitContext ec)
5128 this.element_type = TypeManager.object_type;
5129 this.enumerator_type = TypeManager.ienumerator_type;
5130 this.is_disposable = true;
5134 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5139 if (!(m is MethodInfo))
5142 if (m.Name != "GetEnumerator")
5145 MethodInfo mi = (MethodInfo) m;
5146 Type [] args = TypeManager.GetArgumentTypes (mi);
5148 if (args.Length != 0)
5151 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5152 EmitContext ec = hm.ec;
5155 // Check whether GetEnumerator is accessible to us
5157 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5159 Type declaring = mi.DeclaringType;
5160 if (prot == MethodAttributes.Private){
5161 if (declaring != ec.ContainerType)
5163 } else if (prot == MethodAttributes.FamANDAssem){
5164 // If from a different assembly, false
5165 if (!(mi is MethodBuilder))
5168 // Are we being invoked from the same class, or from a derived method?
5170 if (ec.ContainerType != declaring){
5171 if (!ec.ContainerType.IsSubclassOf (declaring))
5174 } else if (prot == MethodAttributes.FamORAssem){
5175 if (!(mi is MethodBuilder ||
5176 ec.ContainerType == declaring ||
5177 ec.ContainerType.IsSubclassOf (declaring)))
5179 } if (prot == MethodAttributes.Family){
5180 if (!(ec.ContainerType == declaring ||
5181 ec.ContainerType.IsSubclassOf (declaring)))
5186 // Ok, we can access it, now make sure that we can do something
5187 // with this `GetEnumerator'
5190 if (mi.ReturnType == TypeManager.ienumerator_type ||
5191 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5192 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5193 hm.move_next = TypeManager.bool_movenext_void;
5194 hm.get_current = TypeManager.object_getcurrent_void;
5199 // Ok, so they dont return an IEnumerable, we will have to
5200 // find if they support the GetEnumerator pattern.
5202 Type return_type = mi.ReturnType;
5204 hm.move_next = FetchMethodMoveNext (return_type);
5205 if (hm.move_next == null)
5207 hm.get_current = FetchMethodGetCurrent (return_type);
5208 if (hm.get_current == null)
5211 hm.element_type = hm.get_current.ReturnType;
5212 hm.enumerator_type = return_type;
5213 hm.is_disposable = TypeManager.ImplementsInterface (
5214 hm.enumerator_type, TypeManager.idisposable_type);
5220 /// This filter is used to find the GetEnumerator method
5221 /// on which IEnumerator operates
5223 static MemberFilter FilterEnumerator;
5227 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5230 void error1579 (Type t)
5232 Report.Error (1579, loc,
5233 "foreach statement cannot operate on variables of type `" +
5234 t.FullName + "' because that class does not provide a " +
5235 " GetEnumerator method or it is inaccessible");
5238 static bool TryType (Type t, ForeachHelperMethods hm)
5242 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5243 BindingFlags.Public | BindingFlags.NonPublic |
5244 BindingFlags.Instance,
5245 FilterEnumerator, hm);
5250 hm.get_enumerator = (MethodInfo) mi [0];
5255 // Looks for a usable GetEnumerator in the Type, and if found returns
5256 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5258 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5260 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5262 if (TryType (t, hm))
5266 // Now try to find the method in the interfaces
5269 Type [] ifaces = t.GetInterfaces ();
5271 foreach (Type i in ifaces){
5272 if (TryType (i, hm))
5277 // Since TypeBuilder.GetInterfaces only returns the interface
5278 // types for this type, we have to keep looping, but once
5279 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5280 // done, because it returns all the types
5282 if ((t is TypeBuilder))
5292 // FIXME: possible optimization.
5293 // We might be able to avoid creating `empty' if the type is the sam
5295 bool EmitCollectionForeach (EmitContext ec)
5297 ILGenerator ig = ec.ig;
5298 LocalBuilder enumerator, disposable;
5300 enumerator = ig.DeclareLocal (hm.enumerator_type);
5301 if (hm.is_disposable)
5302 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5307 // Instantiate the enumerator
5309 if (expr.Type.IsValueType){
5310 if (expr is IMemoryLocation){
5311 IMemoryLocation ml = (IMemoryLocation) expr;
5313 ml.AddressOf (ec, AddressOp.Load);
5315 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5316 " does not implement IMemoryLocation");
5317 ig.Emit (OpCodes.Call, hm.get_enumerator);
5320 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5322 ig.Emit (OpCodes.Stloc, enumerator);
5325 // Protect the code in a try/finalize block, so that
5326 // if the beast implement IDisposable, we get rid of it
5328 bool old_in_try = ec.InTry;
5330 if (hm.is_disposable)
5333 Label end_try = ig.DefineLabel ();
5335 ig.MarkLabel (ec.LoopBegin);
5336 ig.Emit (OpCodes.Ldloc, enumerator);
5337 ig.Emit (OpCodes.Callvirt, hm.move_next);
5338 ig.Emit (OpCodes.Brfalse, end_try);
5339 ig.Emit (OpCodes.Ldloc, enumerator);
5340 ig.Emit (OpCodes.Callvirt, hm.get_current);
5341 variable.EmitAssign (ec, conv);
5342 statement.Emit (ec);
5343 ig.Emit (OpCodes.Br, ec.LoopBegin);
5344 ig.MarkLabel (end_try);
5345 ec.InTry = old_in_try;
5347 // The runtime provides this for us.
5348 // ig.Emit (OpCodes.Leave, end);
5351 // Now the finally block
5353 if (hm.is_disposable) {
5354 Label end_finally = ig.DefineLabel ();
5355 bool old_in_finally = ec.InFinally;
5356 ec.InFinally = true;
5357 ig.BeginFinallyBlock ();
5359 ig.Emit (OpCodes.Ldloc, enumerator);
5360 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5361 ig.Emit (OpCodes.Stloc, disposable);
5362 ig.Emit (OpCodes.Ldloc, disposable);
5363 ig.Emit (OpCodes.Brfalse, end_finally);
5364 ig.Emit (OpCodes.Ldloc, disposable);
5365 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5366 ig.MarkLabel (end_finally);
5367 ec.InFinally = old_in_finally;
5369 // The runtime generates this anyways.
5370 // ig.Emit (OpCodes.Endfinally);
5372 ig.EndExceptionBlock ();
5375 ig.MarkLabel (ec.LoopEnd);
5380 // FIXME: possible optimization.
5381 // We might be able to avoid creating `empty' if the type is the sam
5383 bool EmitArrayForeach (EmitContext ec)
5385 int rank = array_type.GetArrayRank ();
5386 ILGenerator ig = ec.ig;
5388 LocalBuilder copy = ig.DeclareLocal (array_type);
5391 // Make our copy of the array
5394 ig.Emit (OpCodes.Stloc, copy);
5397 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5401 ig.Emit (OpCodes.Ldc_I4_0);
5402 ig.Emit (OpCodes.Stloc, counter);
5403 test = ig.DefineLabel ();
5404 ig.Emit (OpCodes.Br, test);
5406 loop = ig.DefineLabel ();
5407 ig.MarkLabel (loop);
5409 ig.Emit (OpCodes.Ldloc, copy);
5410 ig.Emit (OpCodes.Ldloc, counter);
5411 ArrayAccess.EmitLoadOpcode (ig, var_type);
5413 variable.EmitAssign (ec, conv);
5415 statement.Emit (ec);
5417 ig.MarkLabel (ec.LoopBegin);
5418 ig.Emit (OpCodes.Ldloc, counter);
5419 ig.Emit (OpCodes.Ldc_I4_1);
5420 ig.Emit (OpCodes.Add);
5421 ig.Emit (OpCodes.Stloc, counter);
5423 ig.MarkLabel (test);
5424 ig.Emit (OpCodes.Ldloc, counter);
5425 ig.Emit (OpCodes.Ldloc, copy);
5426 ig.Emit (OpCodes.Ldlen);
5427 ig.Emit (OpCodes.Conv_I4);
5428 ig.Emit (OpCodes.Blt, loop);
5430 LocalBuilder [] dim_len = new LocalBuilder [rank];
5431 LocalBuilder [] dim_count = new LocalBuilder [rank];
5432 Label [] loop = new Label [rank];
5433 Label [] test = new Label [rank];
5436 for (dim = 0; dim < rank; dim++){
5437 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5438 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5439 test [dim] = ig.DefineLabel ();
5440 loop [dim] = ig.DefineLabel ();
5443 for (dim = 0; dim < rank; dim++){
5444 ig.Emit (OpCodes.Ldloc, copy);
5445 IntLiteral.EmitInt (ig, dim);
5446 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5447 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5450 for (dim = 0; dim < rank; dim++){
5451 ig.Emit (OpCodes.Ldc_I4_0);
5452 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5453 ig.Emit (OpCodes.Br, test [dim]);
5454 ig.MarkLabel (loop [dim]);
5457 ig.Emit (OpCodes.Ldloc, copy);
5458 for (dim = 0; dim < rank; dim++)
5459 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5462 // FIXME: Maybe we can cache the computation of `get'?
5464 Type [] args = new Type [rank];
5467 for (int i = 0; i < rank; i++)
5468 args [i] = TypeManager.int32_type;
5470 ModuleBuilder mb = CodeGen.ModuleBuilder;
5471 get = mb.GetArrayMethod (
5473 CallingConventions.HasThis| CallingConventions.Standard,
5475 ig.Emit (OpCodes.Call, get);
5476 variable.EmitAssign (ec, conv);
5477 statement.Emit (ec);
5478 ig.MarkLabel (ec.LoopBegin);
5479 for (dim = rank - 1; dim >= 0; dim--){
5480 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5481 ig.Emit (OpCodes.Ldc_I4_1);
5482 ig.Emit (OpCodes.Add);
5483 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5485 ig.MarkLabel (test [dim]);
5486 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5487 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5488 ig.Emit (OpCodes.Blt, loop [dim]);
5491 ig.MarkLabel (ec.LoopEnd);
5496 protected override bool DoEmit (EmitContext ec)
5500 ILGenerator ig = ec.ig;
5502 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5503 bool old_inloop = ec.InLoop;
5504 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5505 ec.LoopBegin = ig.DefineLabel ();
5506 ec.LoopEnd = ig.DefineLabel ();
5508 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5511 ret_val = EmitCollectionForeach (ec);
5513 ret_val = EmitArrayForeach (ec);
5515 ec.LoopBegin = old_begin;
5516 ec.LoopEnd = old_end;
5517 ec.InLoop = old_inloop;
5518 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5525 /// AddHandler statement
5527 public class AddHandler : Statement {
5529 Expression EvtHandler;
5532 // keeps track whether EvtId is already resolved
5536 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5539 EvtHandler = evt_handler;
5542 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5545 public override bool Resolve (EmitContext ec)
5548 // if EvetId is of EventExpr type that means
5549 // this is already resolved
5551 if (EvtId is EventExpr) {
5556 EvtId = EvtId.Resolve(ec);
5557 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5558 if (EvtId == null || (!(EvtId is EventExpr))) {
5559 Report.Error (30676, "Need an event designator.");
5563 if (EvtHandler == null)
5565 Report.Error (999, "'AddHandler' statement needs an event handler.");
5572 protected override bool DoEmit (EmitContext ec)
5575 // Already resolved and emitted don't do anything
5581 ArrayList args = new ArrayList();
5582 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5587 // The even type was already resolved to a delegate, so
5588 // we must un-resolve its name to generate a type expression
5589 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5590 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5592 // which we can use to declare a new event handler
5594 d = new New (dtype, args, Location.Null);
5596 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5598 // we resolve it all and emit the code
5611 /// RemoveHandler statement
5613 public class RemoveHandler : Statement
\r
5616 Expression EvtHandler;
5618 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
5621 EvtHandler = evt_handler;
5625 public override bool Resolve (EmitContext ec)
5627 EvtId = EvtId.Resolve(ec);
5628 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5629 if (EvtId == null || (!(EvtId is EventExpr)))
\r
5631 Report.Error (30676, "Need an event designator.");
5635 if (EvtHandler == null)
5637 Report.Error (999, "'AddHandler' statement needs an event handler.");
5643 protected override bool DoEmit (EmitContext ec)
5646 ArrayList args = new ArrayList();
5647 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5650 // The even type was already resolved to a delegate, so
5651 // we must un-resolve its name to generate a type expression
5652 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5653 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5655 // which we can use to declare a new event handler
5657 d = new New (dtype, args, Location.Null);
5660 e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
5662 // we resolve it all and emit the code
5674 public class RedimClause {
5675 public Expression Expr;
5676 public ArrayList NewIndexes;
5678 public RedimClause (Expression e, ArrayList args)
5685 public class ReDim : Statement {
5686 ArrayList RedimTargets;
5690 private StatementExpression ReDimExpr;
5692 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5695 RedimTargets = targets;
5696 Preserve = opt_preserve;
5699 public override bool Resolve (EmitContext ec)
5701 Expression RedimTarget;
5702 ArrayList NewIndexes;
5704 foreach (RedimClause rc in RedimTargets) {
5705 RedimTarget = rc.Expr;
5706 NewIndexes = rc.NewIndexes;
5708 RedimTarget = RedimTarget.Resolve (ec);
5709 if (!RedimTarget.Type.IsArray)
5710 Report.Error (49, "'ReDim' statement requires an array");
5712 ArrayList args = new ArrayList();
5713 foreach (Argument a in NewIndexes) {
5714 if (a.Resolve(ec, loc))
5718 for (int x = 0; x < args.Count; x++) {
5719 args[x] = new Binary (Binary.Operator.Addition,
5720 (Expression) args[x], new IntLiteral (1), Location.Null);
5724 if (RedimTarget.Type.GetArrayRank() != args.Count)
5725 Report.Error (30415, "'ReDim' cannot change the number of dimensions of an array.");
5727 BaseType = RedimTarget.Type.GetElementType();
5728 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5729 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
5730 // TODO: we are in a foreach we probably can't reuse ReDimExpr, must turn it into an array(list)
5733 ExpressionStatement PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5734 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5737 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5738 ReDimExpr.Resolve(ec);
5743 protected override bool DoEmit (EmitContext ec)
5751 public class Erase : Statement {
5752 Expression EraseTarget;
5754 private StatementExpression EraseExpr;
5756 public Erase (Expression expr, Location l)
5762 public override bool Resolve (EmitContext ec)
5764 EraseTarget = EraseTarget.Resolve (ec);
5765 if (!EraseTarget.Type.IsArray)
5766 Report.Error (49, "'Erase' statement requires an array");
5768 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5769 EraseExpr.Resolve(ec);
5774 protected override bool DoEmit (EmitContext ec)