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)
9 // (C) 2001, 2002 Ximian, Inc.
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
18 namespace Mono.MonoBASIC {
20 using System.Collections;
22 public abstract class Statement {
26 /// Resolves the statement, true means that all sub-statements
29 public virtual bool Resolve (EmitContext ec)
35 /// Return value indicates whether all code paths emitted return.
37 protected abstract bool DoEmit (EmitContext ec);
40 /// Return value indicates whether all code paths emitted return.
42 public virtual bool Emit (EmitContext ec)
45 Report.Debug (8, "MARK", this, loc);
49 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
55 if (e.Type != TypeManager.bool_type){
56 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type, Location.Null);
61 31, loc, "Can not convert the expression to a boolean");
70 /// Encapsulates the emission of a boolean test and jumping to a
73 /// This will emit the bool expression in `bool_expr' and if
74 /// `target_is_for_true' is true, then the code will generate a
75 /// brtrue to the target. Otherwise a brfalse.
77 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
78 Label target, bool target_is_for_true)
80 ILGenerator ig = ec.ig;
83 if (bool_expr is Unary){
84 Unary u = (Unary) bool_expr;
86 if (u.Oper == Unary.Operator.LogicalNot){
89 u.EmitLogicalNot (ec);
91 } else if (bool_expr is Binary){
92 Binary b = (Binary) bool_expr;
94 if (b.EmitBranchable (ec, target, target_is_for_true))
101 if (target_is_for_true){
103 ig.Emit (OpCodes.Brfalse, target);
105 ig.Emit (OpCodes.Brtrue, target);
108 ig.Emit (OpCodes.Brtrue, target);
110 ig.Emit (OpCodes.Brfalse, target);
114 public static void Warning_DeadCodeFound (Location loc)
116 Report.Warning (162, loc, "Unreachable code detected");
120 public class EmptyStatement : Statement {
121 public override bool Resolve (EmitContext ec)
126 protected override bool DoEmit (EmitContext ec)
132 public class If : Statement {
134 public Statement TrueStatement;
135 public Statement FalseStatement;
137 public If (Expression expr, Statement trueStatement, Location l)
140 TrueStatement = trueStatement;
144 public If (Expression expr,
145 Statement trueStatement,
146 Statement falseStatement,
150 TrueStatement = trueStatement;
151 FalseStatement = falseStatement;
155 public override bool Resolve (EmitContext ec)
157 Report.Debug (1, "START IF BLOCK", loc);
159 expr = ResolveBoolean (ec, expr, loc);
164 ec.StartFlowBranching (FlowBranchingType.BLOCK, loc);
166 if (!TrueStatement.Resolve (ec)) {
167 ec.KillFlowBranching ();
171 ec.CurrentBranching.CreateSibling ();
173 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
174 ec.KillFlowBranching ();
178 ec.EndFlowBranching ();
180 Report.Debug (1, "END IF BLOCK", loc);
185 protected override bool DoEmit (EmitContext ec)
187 ILGenerator ig = ec.ig;
188 Label false_target = ig.DefineLabel ();
190 bool is_true_ret, is_false_ret;
193 // Dead code elimination
195 if (expr is BoolConstant){
196 bool take = ((BoolConstant) expr).Value;
199 if (FalseStatement != null){
200 Warning_DeadCodeFound (FalseStatement.loc);
202 return TrueStatement.Emit (ec);
204 Warning_DeadCodeFound (TrueStatement.loc);
205 if (FalseStatement != null)
206 return FalseStatement.Emit (ec);
210 EmitBoolExpression (ec, expr, false_target, false);
212 is_true_ret = TrueStatement.Emit (ec);
213 is_false_ret = is_true_ret;
215 if (FalseStatement != null){
216 bool branch_emitted = false;
218 end = ig.DefineLabel ();
220 ig.Emit (OpCodes.Br, end);
221 branch_emitted = true;
224 ig.MarkLabel (false_target);
225 is_false_ret = FalseStatement.Emit (ec);
230 ig.MarkLabel (false_target);
231 is_false_ret = false;
234 return is_true_ret && is_false_ret;
238 public enum DoOptions {
245 public class Do : Statement {
246 public Expression expr;
247 public readonly Statement EmbeddedStatement;
248 //public DoOptions type;
249 public DoOptions test;
250 bool infinite, may_return;
253 public Do (Statement statement, Expression boolExpr, DoOptions do_test, Location l)
256 EmbeddedStatement = statement;
262 public override bool Resolve (EmitContext ec)
266 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
268 if (!EmbeddedStatement.Resolve (ec))
271 expr = ResolveBoolean (ec, expr, loc);
274 else if (expr is BoolConstant){
275 bool res = ((BoolConstant) expr).Value;
281 ec.CurrentBranching.Infinite = infinite;
282 FlowReturns returns = ec.EndFlowBranching ();
283 may_return = returns != FlowReturns.NEVER;
288 protected override bool DoEmit (EmitContext ec)
290 ILGenerator ig = ec.ig;
291 Label loop = ig.DefineLabel ();
292 Label old_begin = ec.LoopBegin;
293 Label old_end = ec.LoopEnd;
294 bool old_inloop = ec.InLoop;
295 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
297 ec.LoopBegin = ig.DefineLabel ();
298 ec.LoopEnd = ig.DefineLabel ();
300 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
302 if (test == DoOptions.TEST_AFTER) {
304 EmbeddedStatement.Emit (ec);
305 ig.MarkLabel (ec.LoopBegin);
308 // Dead code elimination
310 if (expr is BoolConstant){
311 bool res = ((BoolConstant) expr).Value;
314 ec.ig.Emit (OpCodes.Br, loop);
316 EmitBoolExpression (ec, expr, loop, true);
318 ig.MarkLabel (ec.LoopEnd);
323 ig.MarkLabel (ec.LoopBegin);
326 // Dead code elimination
328 if (expr is BoolConstant){
329 bool res = ((BoolConstant) expr).Value;
332 ec.ig.Emit (OpCodes.Br, ec.LoopEnd);
334 EmitBoolExpression (ec, expr, ec.LoopEnd, true);
336 EmbeddedStatement.Emit (ec);
337 ec.ig.Emit (OpCodes.Br, loop);
338 ig.MarkLabel (ec.LoopEnd);
340 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
341 ec.LoopBegin = old_begin;
342 ec.LoopEnd = old_end;
343 ec.InLoop = old_inloop;
346 return may_return == false;
352 public class While : Statement {
353 public Expression expr;
354 public readonly Statement Statement;
355 bool may_return, empty, infinite;
357 public While (Expression boolExpr, Statement statement, Location l)
359 this.expr = boolExpr;
360 Statement = statement;
364 public override bool Resolve (EmitContext ec)
368 expr = ResolveBoolean (ec, expr, loc);
372 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
375 // Inform whether we are infinite or not
377 if (expr is BoolConstant){
378 BoolConstant bc = (BoolConstant) expr;
380 if (bc.Value == false){
381 Warning_DeadCodeFound (Statement.loc);
387 // We are not infinite, so the loop may or may not be executed.
389 ec.CurrentBranching.CreateSibling ();
392 if (!Statement.Resolve (ec))
396 ec.KillFlowBranching ();
398 ec.CurrentBranching.Infinite = infinite;
399 FlowReturns returns = ec.EndFlowBranching ();
400 may_return = returns != FlowReturns.NEVER;
406 protected override bool DoEmit (EmitContext ec)
411 ILGenerator ig = ec.ig;
412 Label old_begin = ec.LoopBegin;
413 Label old_end = ec.LoopEnd;
414 bool old_inloop = ec.InLoop;
415 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
418 ec.LoopBegin = ig.DefineLabel ();
419 ec.LoopEnd = ig.DefineLabel ();
421 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
424 // Inform whether we are infinite or not
426 if (expr is BoolConstant){
427 ig.MarkLabel (ec.LoopBegin);
429 ig.Emit (OpCodes.Br, ec.LoopBegin);
432 // Inform that we are infinite (ie, `we return'), only
433 // if we do not `break' inside the code.
435 ret = may_return == false;
436 ig.MarkLabel (ec.LoopEnd);
438 Label while_loop = ig.DefineLabel ();
440 ig.Emit (OpCodes.Br, ec.LoopBegin);
441 ig.MarkLabel (while_loop);
445 ig.MarkLabel (ec.LoopBegin);
447 EmitBoolExpression (ec, expr, while_loop, true);
448 ig.MarkLabel (ec.LoopEnd);
453 ec.LoopBegin = old_begin;
454 ec.LoopEnd = old_end;
455 ec.InLoop = old_inloop;
456 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
462 public class For : Statement {
464 readonly Statement InitStatement;
465 readonly Statement Increment;
466 readonly Statement Statement;
467 bool may_return, infinite, empty;
469 public For (Statement initStatement,
475 InitStatement = initStatement;
477 Increment = increment;
478 Statement = statement;
483 public override bool Resolve (EmitContext ec)
487 if (InitStatement != null){
488 if (!InitStatement.Resolve (ec))
493 Test = ResolveBoolean (ec, Test, loc);
496 else if (Test is BoolConstant){
497 BoolConstant bc = (BoolConstant) Test;
499 if (bc.Value == false){
500 Warning_DeadCodeFound (Statement.loc);
508 if (Increment != null){
509 if (!Increment.Resolve (ec))
513 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
515 ec.CurrentBranching.CreateSibling ();
517 if (!Statement.Resolve (ec))
521 ec.KillFlowBranching ();
523 ec.CurrentBranching.Infinite = infinite;
524 FlowReturns returns = ec.EndFlowBranching ();
525 may_return = returns != FlowReturns.NEVER;
531 protected override bool DoEmit (EmitContext ec)
536 ILGenerator ig = ec.ig;
537 Label old_begin = ec.LoopBegin;
538 Label old_end = ec.LoopEnd;
539 bool old_inloop = ec.InLoop;
540 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
541 Label loop = ig.DefineLabel ();
542 Label test = ig.DefineLabel ();
544 if (InitStatement != null)
545 if (! (InitStatement is EmptyStatement))
546 InitStatement.Emit (ec);
548 ec.LoopBegin = ig.DefineLabel ();
549 ec.LoopEnd = ig.DefineLabel ();
551 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
553 ig.Emit (OpCodes.Br, test);
557 ig.MarkLabel (ec.LoopBegin);
558 if (!(Increment is EmptyStatement))
563 // If test is null, there is no test, and we are just
567 EmitBoolExpression (ec, Test, loop, true);
569 ig.Emit (OpCodes.Br, loop);
570 ig.MarkLabel (ec.LoopEnd);
572 ec.LoopBegin = old_begin;
573 ec.LoopEnd = old_end;
574 ec.InLoop = old_inloop;
575 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
578 // Inform whether we are infinite or not
581 if (Test is BoolConstant){
582 BoolConstant bc = (BoolConstant) Test;
585 return may_return == false;
589 return may_return == false;
593 public class StatementExpression : Statement {
594 public Expression expr;
596 public StatementExpression (ExpressionStatement expr, Location l)
602 public override bool Resolve (EmitContext ec)
604 expr = (Expression) expr.Resolve (ec);
608 protected override bool DoEmit (EmitContext ec)
610 ILGenerator ig = ec.ig;
612 if (expr is ExpressionStatement)
613 ((ExpressionStatement) expr).EmitStatement (ec);
616 ig.Emit (OpCodes.Pop);
622 public override string ToString ()
624 return "StatementExpression (" + expr + ")";
629 /// Implements the return statement
631 public class Return : Statement {
632 public Expression Expr;
634 public Return (Expression expr, Location l)
640 public override bool Resolve (EmitContext ec)
643 Expr = Expr.Resolve (ec);
648 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
650 if (ec.CurrentBranching.InTryBlock ())
651 ec.CurrentBranching.AddFinallyVector (vector);
653 vector.CheckOutParameters (ec.CurrentBranching);
655 vector.Returns = FlowReturns.ALWAYS;
656 vector.Breaks = FlowReturns.ALWAYS;
660 protected override bool DoEmit (EmitContext ec)
663 Report.Error (157,loc,"Control can not leave the body of the finally block");
667 if (ec.ReturnType == null){
669 Report.Error (127, loc, "Return with a value not allowed here");
674 Report.Error (126, loc, "An object of type `" +
675 TypeManager.MonoBASIC_Name (ec.ReturnType) + "' is " +
676 "expected for the return statement");
680 if (Expr.Type != ec.ReturnType)
681 Expr = Expression.ConvertImplicitRequired (
682 ec, Expr, ec.ReturnType, loc);
689 if (ec.InTry || ec.InCatch)
690 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
693 if (ec.InTry || ec.InCatch) {
694 if (!ec.HasReturnLabel) {
695 ec.ReturnLabel = ec.ig.DefineLabel ();
696 ec.HasReturnLabel = true;
698 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
700 ec.ig.Emit (OpCodes.Ret);
706 public class Goto : Statement {
709 LabeledStatement label;
711 public override bool Resolve (EmitContext ec)
713 label = block.LookupLabel (target);
717 "No such label `" + target + "' in this scope");
721 // If this is a forward goto.
722 if (!label.IsDefined)
723 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
725 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
730 public Goto (Block parent_block, string label, Location l)
732 block = parent_block;
737 public string Target {
743 protected override bool DoEmit (EmitContext ec)
745 Label l = label.LabelTarget (ec);
746 ec.ig.Emit (OpCodes.Br, l);
752 public class LabeledStatement : Statement {
753 public readonly Location Location;
761 public LabeledStatement (string label_name, Location l)
763 this.label_name = label_name;
767 public Label LabelTarget (EmitContext ec)
771 label = ec.ig.DefineLabel ();
777 public bool IsDefined {
783 public bool HasBeenReferenced {
789 public void AddUsageVector (FlowBranching.UsageVector vector)
792 vectors = new ArrayList ();
794 vectors.Add (vector.Clone ());
797 public override bool Resolve (EmitContext ec)
800 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
802 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
803 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
811 protected override bool DoEmit (EmitContext ec)
814 ec.ig.MarkLabel (label);
822 /// `goto default' statement
824 public class GotoDefault : Statement {
826 public GotoDefault (Location l)
831 public override bool Resolve (EmitContext ec)
833 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
837 protected override bool DoEmit (EmitContext ec)
839 if (ec.Switch == null){
840 Report.Error (153, loc, "goto default is only valid in a switch statement");
844 if (!ec.Switch.GotDefault){
845 Report.Error (159, loc, "No default target on switch statement");
848 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
854 /// `goto case' statement
856 public class GotoCase : Statement {
860 public GotoCase (Expression e, Location l)
866 public override bool Resolve (EmitContext ec)
868 if (ec.Switch == null){
869 Report.Error (153, loc, "goto case is only valid in a switch statement");
873 expr = expr.Resolve (ec);
877 if (!(expr is Constant)){
878 Report.Error (159, loc, "Target expression for goto case is not constant");
882 object val = Expression.ConvertIntLiteral (
883 (Constant) expr, ec.Switch.SwitchType, loc);
888 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
893 "No such label 'case " + val + "': for the goto case");
896 label = sl.ILLabelCode;
898 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
902 protected override bool DoEmit (EmitContext ec)
904 ec.ig.Emit (OpCodes.Br, label);
909 public class Throw : Statement {
912 public Throw (Expression expr, Location l)
918 public override bool Resolve (EmitContext ec)
921 expr = expr.Resolve (ec);
925 ExprClass eclass = expr.eclass;
927 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
928 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
929 expr.Error118 ("value, variable, property or indexer access ");
935 if ((t != TypeManager.exception_type) &&
936 !t.IsSubclassOf (TypeManager.exception_type) &&
937 !(expr is NullLiteral)) {
938 Report.Error (30665, loc,
939 "The type caught or thrown must be derived " +
940 "from System.Exception");
945 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
946 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
950 protected override bool DoEmit (EmitContext ec)
954 ec.ig.Emit (OpCodes.Rethrow);
958 "A throw statement with no argument is only " +
959 "allowed in a catch clause");
966 ec.ig.Emit (OpCodes.Throw);
972 public class Break : Statement {
974 public Break (Location l)
979 public override bool Resolve (EmitContext ec)
981 ec.CurrentBranching.MayLeaveLoop = true;
982 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
986 protected override bool DoEmit (EmitContext ec)
988 ILGenerator ig = ec.ig;
990 if (ec.InLoop == false && ec.Switch == null){
991 Report.Error (139, loc, "No enclosing loop or switch to continue to");
995 if (ec.InTry || ec.InCatch)
996 ig.Emit (OpCodes.Leave, ec.LoopEnd);
998 ig.Emit (OpCodes.Br, ec.LoopEnd);
1004 public enum ExitType {
1015 public class Exit : Statement {
1016 public readonly ExitType type;
1017 public Exit (ExitType t, Location l)
1023 public override bool Resolve (EmitContext ec)
1025 ec.CurrentBranching.MayLeaveLoop = true;
1026 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1030 protected override bool DoEmit (EmitContext ec)
1032 ILGenerator ig = ec.ig;
1034 if (type != ExitType.SUB && type != ExitType.FUNCTION &&
1035 type != ExitType.PROPERTY && type != ExitType.TRY) {
1036 if (ec.InLoop == false && ec.Switch == null){
1037 if (type == ExitType.FOR)
1038 Report.Error (30096, loc, "No enclosing FOR loop to exit from");
1039 if (type == ExitType.WHILE)
\r
1040 Report.Error (30097, loc, "No enclosing WHILE loop to exit from");
1041 if (type == ExitType.DO)
1042 Report.Error (30089, loc, "No enclosing DO loop to exit from");
1043 if (type == ExitType.SELECT)
1044 Report.Error (30099, loc, "No enclosing SELECT to exit from");
1049 if (ec.InTry || ec.InCatch)
1050 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1052 ig.Emit (OpCodes.Br, ec.LoopEnd);
1055 Report.Error (30393, loc,
1056 "Control can not leave the body of the finally block");
1060 if (ec.InTry || ec.InCatch) {
1061 if (!ec.HasReturnLabel) {
1062 ec.ReturnLabel = ec.ig.DefineLabel ();
1063 ec.HasReturnLabel = true;
1065 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
1067 ec.ig.Emit (OpCodes.Ret);
1076 public class Continue : Statement {
1078 public Continue (Location l)
1083 public override bool Resolve (EmitContext ec)
1085 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1089 protected override bool DoEmit (EmitContext ec)
1091 Label begin = ec.LoopBegin;
1094 Report.Error (139, loc, "No enclosing loop to continue to");
1099 // UGH: Non trivial. This Br might cross a try/catch boundary
1103 // try { ... } catch { continue; }
1107 // try {} catch { while () { continue; }}
1109 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1110 ec.ig.Emit (OpCodes.Leave, begin);
1111 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1112 throw new Exception ("Should never happen");
1114 ec.ig.Emit (OpCodes.Br, begin);
1120 // This is used in the control flow analysis code to specify whether the
1121 // current code block may return to its enclosing block before reaching
1124 public enum FlowReturns {
1125 // It can never return.
1128 // This means that the block contains a conditional return statement
1132 // The code always returns, ie. there's an unconditional return / break
1136 // The code always throws an exception.
1139 // The current code block is unreachable. This happens if it's immediately
1140 // following a FlowReturns.ALWAYS block.
1145 // This is a special bit vector which can inherit from another bit vector doing a
1146 // copy-on-write strategy. The inherited vector may have a smaller size than the
1149 public class MyBitVector {
1150 public readonly int Count;
1151 public readonly MyBitVector InheritsFrom;
1156 public MyBitVector (int Count)
1157 : this (null, Count)
1160 public MyBitVector (MyBitVector InheritsFrom, int Count)
1162 this.InheritsFrom = InheritsFrom;
1167 // Checks whether this bit vector has been modified. After setting this to true,
1168 // we won't use the inherited vector anymore, but our own copy of it.
1170 public bool IsDirty {
1177 initialize_vector ();
1182 // Get/set bit `index' in the bit vector.
1184 public bool this [int index]
1188 throw new ArgumentOutOfRangeException ();
1190 // We're doing a "copy-on-write" strategy here; as long
1191 // as nobody writes to the array, we can use our parent's
1192 // copy instead of duplicating the vector.
1195 return vector [index];
1196 else if (InheritsFrom != null) {
1197 BitArray inherited = InheritsFrom.Vector;
1199 if (index < inherited.Count)
1200 return inherited [index];
1209 throw new ArgumentOutOfRangeException ();
1211 // Only copy the vector if we're actually modifying it.
1213 if (this [index] != value) {
1214 initialize_vector ();
1216 vector [index] = value;
1222 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1223 // copy of the bit vector.
1225 public static explicit operator BitArray (MyBitVector vector)
1227 vector.initialize_vector ();
1228 return vector.Vector;
1232 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1233 // different size than the current one.
1235 public void Or (MyBitVector new_vector)
1237 BitArray new_array = new_vector.Vector;
1239 initialize_vector ();
1242 if (vector.Count < new_array.Count)
1243 upper = vector.Count;
1245 upper = new_array.Count;
1247 for (int i = 0; i < upper; i++)
1248 vector [i] = vector [i] | new_array [i];
1252 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1253 // a different size than the current one.
1255 public void And (MyBitVector new_vector)
1257 BitArray new_array = new_vector.Vector;
1259 initialize_vector ();
1262 if (vector.Count < new_array.Count)
1263 lower = upper = vector.Count;
1265 lower = new_array.Count;
1266 upper = vector.Count;
1269 for (int i = 0; i < lower; i++)
1270 vector [i] = vector [i] & new_array [i];
1272 for (int i = lower; i < upper; i++)
1277 // This does a deep copy of the bit vector.
1279 public MyBitVector Clone ()
1281 MyBitVector retval = new MyBitVector (Count);
1283 retval.Vector = Vector;
1292 else if (!is_dirty && (InheritsFrom != null))
1293 return InheritsFrom.Vector;
1295 initialize_vector ();
1301 initialize_vector ();
1303 for (int i = 0; i < System.Math.Min (vector.Count, value.Count); i++)
1304 vector [i] = value [i];
1308 void initialize_vector ()
1313 vector = new BitArray (Count, false);
1314 if (InheritsFrom != null)
1315 Vector = InheritsFrom.Vector;
1320 public override string ToString ()
1322 StringBuilder sb = new StringBuilder ("MyBitVector (");
1324 BitArray vector = Vector;
1328 sb.Append ("INHERITED - ");
1329 for (int i = 0; i < vector.Count; i++) {
1332 sb.Append (vector [i]);
1336 return sb.ToString ();
1341 // The type of a FlowBranching.
1343 public enum FlowBranchingType {
1344 // Normal (conditional or toplevel) block.
1361 // A new instance of this class is created every time a new block is resolved
1362 // and if there's branching in the block's control flow.
1364 public class FlowBranching {
1366 // The type of this flow branching.
1368 public readonly FlowBranchingType Type;
1371 // The block this branching is contained in. This may be null if it's not
1372 // a top-level block and it doesn't declare any local variables.
1374 public readonly Block Block;
1377 // The parent of this branching or null if this is the top-block.
1379 public readonly FlowBranching Parent;
1382 // Start-Location of this flow branching.
1384 public readonly Location Location;
1387 // A list of UsageVectors. A new vector is added each time control flow may
1388 // take a different path.
1390 public ArrayList Siblings;
1393 // If this is an infinite loop.
1395 public bool Infinite;
1398 // If we may leave the current loop.
1400 public bool MayLeaveLoop;
1405 InternalParameters param_info;
1407 MyStructInfo[] struct_params;
1409 ArrayList finally_vectors;
1411 static int next_id = 0;
1415 // Performs an `And' operation on the FlowReturns status
1416 // (for instance, a block only returns ALWAYS if all its siblings
1419 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1421 if (b == FlowReturns.UNREACHABLE)
1425 case FlowReturns.NEVER:
1426 if (b == FlowReturns.NEVER)
1427 return FlowReturns.NEVER;
1429 return FlowReturns.SOMETIMES;
1431 case FlowReturns.SOMETIMES:
1432 return FlowReturns.SOMETIMES;
1434 case FlowReturns.ALWAYS:
1435 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1436 return FlowReturns.ALWAYS;
1438 return FlowReturns.SOMETIMES;
1440 case FlowReturns.EXCEPTION:
1441 if (b == FlowReturns.EXCEPTION)
1442 return FlowReturns.EXCEPTION;
1443 else if (b == FlowReturns.ALWAYS)
1444 return FlowReturns.ALWAYS;
1446 return FlowReturns.SOMETIMES;
1453 // The vector contains a BitArray with information about which local variables
1454 // and parameters are already initialized at the current code position.
1456 public class UsageVector {
1458 // If this is true, then the usage vector has been modified and must be
1459 // merged when we're done with this branching.
1461 public bool IsDirty;
1464 // The number of parameters in this block.
1466 public readonly int CountParameters;
1469 // The number of locals in this block.
1471 public readonly int CountLocals;
1474 // If not null, then we inherit our state from this vector and do a
1475 // copy-on-write. If null, then we're the first sibling in a top-level
1476 // block and inherit from the empty vector.
1478 public readonly UsageVector InheritsFrom;
1483 MyBitVector locals, parameters;
1484 FlowReturns real_returns, real_breaks;
1487 static int next_id = 0;
1491 // Normally, you should not use any of these constructors.
1493 public UsageVector (UsageVector parent, int num_params, int num_locals)
1495 this.InheritsFrom = parent;
1496 this.CountParameters = num_params;
1497 this.CountLocals = num_locals;
1498 this.real_returns = FlowReturns.NEVER;
1499 this.real_breaks = FlowReturns.NEVER;
1501 if (parent != null) {
1502 locals = new MyBitVector (parent.locals, CountLocals);
1504 parameters = new MyBitVector (parent.parameters, num_params);
1505 real_returns = parent.Returns;
1506 real_breaks = parent.Breaks;
1508 locals = new MyBitVector (null, CountLocals);
1510 parameters = new MyBitVector (null, num_params);
1516 public UsageVector (UsageVector parent)
1517 : this (parent, parent.CountParameters, parent.CountLocals)
1521 // This does a deep copy of the usage vector.
1523 public UsageVector Clone ()
1525 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1527 retval.locals = locals.Clone ();
1528 if (parameters != null)
1529 retval.parameters = parameters.Clone ();
1530 retval.real_returns = real_returns;
1531 retval.real_breaks = real_breaks;
1537 // State of parameter `number'.
1539 public bool this [int number]
1544 else if (number == 0)
1545 throw new ArgumentException ();
1547 return parameters [number - 1];
1553 else if (number == 0)
1554 throw new ArgumentException ();
1556 parameters [number - 1] = value;
1561 // State of the local variable `vi'.
1562 // If the local variable is a struct, use a non-zero `field_idx'
1563 // to check an individual field in it.
1565 public bool this [VariableInfo vi, int field_idx]
1568 if (vi.Number == -1)
1570 else if (vi.Number == 0)
1571 throw new ArgumentException ();
1573 return locals [vi.Number + field_idx - 1];
1577 if (vi.Number == -1)
1579 else if (vi.Number == 0)
1580 throw new ArgumentException ();
1582 locals [vi.Number + field_idx - 1] = value;
1587 // Specifies when the current block returns.
1588 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1589 // end of the method (so that we don't need to emit a return statement).
1590 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1591 // value will never be used.
1593 public FlowReturns Returns {
1595 return real_returns;
1599 real_returns = value;
1604 // Specifies whether control may return to our containing block
1605 // before reaching the end of this block. This happens if there
1606 // is a break/continue/goto/return in it.
1607 // This can also be used to find out whether the statement immediately
1608 // following the current block may be reached or not.
1610 public FlowReturns Breaks {
1616 real_breaks = value;
1620 public bool AlwaysBreaks {
1622 return (Breaks == FlowReturns.ALWAYS) ||
1623 (Breaks == FlowReturns.EXCEPTION) ||
1624 (Breaks == FlowReturns.UNREACHABLE);
1628 public bool MayBreak {
1630 return Breaks != FlowReturns.NEVER;
1634 public bool AlwaysReturns {
1636 return (Returns == FlowReturns.ALWAYS) ||
1637 (Returns == FlowReturns.EXCEPTION);
1641 public bool MayReturn {
1643 return (Returns == FlowReturns.SOMETIMES) ||
1644 (Returns == FlowReturns.ALWAYS);
1649 // Merge a child branching.
1651 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1653 MyBitVector new_locals = null;
1654 MyBitVector new_params = null;
1656 FlowReturns new_returns = FlowReturns.NEVER;
1657 FlowReturns new_breaks = FlowReturns.NEVER;
1658 bool new_returns_set = false, new_breaks_set = false;
1660 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1661 this, children.Count);
1663 foreach (UsageVector child in children) {
1664 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1666 if (!child.is_finally) {
1667 if (child.Breaks != FlowReturns.UNREACHABLE) {
1668 // If Returns is already set, perform an
1669 // `And' operation on it, otherwise just set just.
1670 if (!new_returns_set) {
1671 new_returns = child.Returns;
1672 new_returns_set = true;
1674 new_returns = AndFlowReturns (
1675 new_returns, child.Returns);
1678 // If Breaks is already set, perform an
1679 // `And' operation on it, otherwise just set just.
1680 if (!new_breaks_set) {
1681 new_breaks = child.Breaks;
1682 new_breaks_set = true;
1684 new_breaks = AndFlowReturns (
1685 new_breaks, child.Breaks);
1688 // Ignore unreachable children.
1689 if (child.Returns == FlowReturns.UNREACHABLE)
1692 // A local variable is initialized after a flow branching if it
1693 // has been initialized in all its branches which do neither
1694 // always return or always throw an exception.
1696 // If a branch may return, but does not always return, then we
1697 // can treat it like a never-returning branch here: control will
1698 // only reach the code position after the branching if we did not
1701 // It's important to distinguish between always and sometimes
1702 // returning branches here:
1705 // 2 if (something) {
1709 // 6 Console.WriteLine (a);
1711 // The if block in lines 3-4 always returns, so we must not look
1712 // at the initialization of `a' in line 4 - thus it'll still be
1713 // uninitialized in line 6.
1715 // On the other hand, the following is allowed:
1722 // 6 Console.WriteLine (a);
1724 // Here, `a' is initialized in line 3 and we must not look at
1725 // line 5 since it always returns.
1727 if (child.is_finally) {
1728 if (new_locals == null)
1729 new_locals = locals.Clone ();
1730 new_locals.Or (child.locals);
1732 if (parameters != null) {
1733 if (new_params == null)
1734 new_params = parameters.Clone ();
1735 new_params.Or (child.parameters);
1739 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1740 if (new_locals != null)
1741 new_locals.And (child.locals);
1743 new_locals = locals.Clone ();
1744 new_locals.Or (child.locals);
1746 } else if (children.Count == 1) {
1747 new_locals = locals.Clone ();
1748 new_locals.Or (child.locals);
1751 // An `out' parameter must be assigned in all branches which do
1752 // not always throw an exception.
1753 if (parameters != null) {
1754 if (child.Breaks != FlowReturns.EXCEPTION) {
1755 if (new_params != null)
1756 new_params.And (child.parameters);
1758 new_params = parameters.Clone ();
1759 new_params.Or (child.parameters);
1761 } else if (children.Count == 1) {
1762 new_params = parameters.Clone ();
1763 new_params.Or (child.parameters);
1769 Returns = new_returns;
1770 if ((branching.Type == FlowBranchingType.BLOCK) ||
1771 (branching.Type == FlowBranchingType.EXCEPTION) ||
1772 (new_breaks == FlowReturns.UNREACHABLE) ||
1773 (new_breaks == FlowReturns.EXCEPTION))
1774 Breaks = new_breaks;
1775 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1776 Breaks = new_returns;
1777 else if (branching.Type == FlowBranchingType.SWITCH){
1778 if (new_breaks == FlowReturns.ALWAYS)
1779 Breaks = FlowReturns.ALWAYS;
1783 // We've now either reached the point after the branching or we will
1784 // never get there since we always return or always throw an exception.
1786 // If we can reach the point after the branching, mark all locals and
1787 // parameters as initialized which have been initialized in all branches
1788 // we need to look at (see above).
1791 if (((new_breaks != FlowReturns.ALWAYS) &&
1792 (new_breaks != FlowReturns.EXCEPTION) &&
1793 (new_breaks != FlowReturns.UNREACHABLE)) ||
1794 (children.Count == 1)) {
1795 if (new_locals != null)
1796 locals.Or (new_locals);
1798 if (new_params != null)
1799 parameters.Or (new_params);
1802 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1803 new_params, new_locals, new_returns, new_breaks,
1804 branching.Infinite, branching.MayLeaveLoop, this);
1806 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1807 if ((new_breaks != FlowReturns.ALWAYS) &&
1808 (new_breaks != FlowReturns.EXCEPTION) &&
1809 (new_breaks != FlowReturns.UNREACHABLE))
1810 Report.Error (163, branching.Location,
1811 "Control cannot fall through from one " +
1812 "case label to another");
1815 if (branching.Infinite && !branching.MayLeaveLoop) {
1816 Report.Debug (1, "INFINITE", new_returns, new_breaks,
1817 Returns, Breaks, this);
1819 // We're actually infinite.
1820 if (new_returns == FlowReturns.NEVER) {
1821 Breaks = FlowReturns.UNREACHABLE;
1822 return FlowReturns.UNREACHABLE;
1825 // If we're an infinite loop and do not break, the code after
1826 // the loop can never be reached. However, if we may return
1827 // from the loop, then we do always return (or stay in the loop
1829 if ((new_returns == FlowReturns.SOMETIMES) ||
1830 (new_returns == FlowReturns.ALWAYS)) {
1831 Returns = FlowReturns.ALWAYS;
1832 return FlowReturns.ALWAYS;
1840 // Tells control flow analysis that the current code position may be reached with
1841 // a forward jump from any of the origins listed in `origin_vectors' which is a
1842 // list of UsageVectors.
1844 // This is used when resolving forward gotos - in the following example, the
1845 // variable `a' is uninitialized in line 8 becase this line may be reached via
1846 // the goto in line 4:
1856 // 8 Console.WriteLine (a);
1859 public void MergeJumpOrigins (ICollection origin_vectors)
1861 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1863 real_breaks = FlowReturns.NEVER;
1864 real_returns = FlowReturns.NEVER;
1866 foreach (UsageVector vector in origin_vectors) {
1867 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1869 locals.And (vector.locals);
1870 if (parameters != null)
1871 parameters.And (vector.parameters);
1872 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1873 Returns = AndFlowReturns (Returns, vector.Returns);
1876 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1880 // This is used at the beginning of a finally block if there were
1881 // any return statements in the try block or one of the catch blocks.
1883 public void MergeFinallyOrigins (ICollection finally_vectors)
1885 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1887 real_breaks = FlowReturns.NEVER;
1889 foreach (UsageVector vector in finally_vectors) {
1890 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1892 if (parameters != null)
1893 parameters.And (vector.parameters);
1894 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1899 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1902 public void CheckOutParameters (FlowBranching branching)
1904 if (parameters != null)
1905 branching.CheckOutParameters (parameters, branching.Location);
1909 // Performs an `or' operation on the locals and the parameters.
1911 public void Or (UsageVector new_vector)
1913 locals.Or (new_vector.locals);
1914 if (parameters != null)
1915 parameters.Or (new_vector.parameters);
1919 // Performs an `and' operation on the locals.
1921 public void AndLocals (UsageVector new_vector)
1923 locals.And (new_vector.locals);
1927 // Returns a deep copy of the parameters.
1929 public MyBitVector Parameters {
1931 if (parameters != null)
1932 return parameters.Clone ();
1939 // Returns a deep copy of the locals.
1941 public MyBitVector Locals {
1943 return locals.Clone ();
1951 public override string ToString ()
1953 StringBuilder sb = new StringBuilder ();
1955 sb.Append ("Vector (");
1958 sb.Append (Returns);
1961 if (parameters != null) {
1963 sb.Append (parameters);
1969 return sb.ToString ();
1973 FlowBranching (FlowBranchingType type, Location loc)
1975 this.Siblings = new ArrayList ();
1977 this.Location = loc;
1983 // Creates a new flow branching for `block'.
1984 // This is used from Block.Resolve to create the top-level branching of
1987 public FlowBranching (Block block, InternalParameters ip, Location loc)
1988 : this (FlowBranchingType.BLOCK, loc)
1993 int count = (ip != null) ? ip.Count : 0;
1996 param_map = new int [count];
1997 struct_params = new MyStructInfo [count];
2000 for (int i = 0; i < count; i++) {
2001 Parameter.Modifier mod = param_info.ParameterModifier (i);
2003 if ((mod & Parameter.Modifier.OUT) == 0)
2006 param_map [i] = ++num_params;
2008 Type param_type = param_info.ParameterType (i);
2010 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
2011 if (struct_params [i] != null)
2012 num_params += struct_params [i].Count;
2015 Siblings = new ArrayList ();
2016 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
2020 // Creates a new flow branching which is contained in `parent'.
2021 // You should only pass non-null for the `block' argument if this block
2022 // introduces any new variables - in this case, we need to create a new
2023 // usage vector with a different size than our parent's one.
2025 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2026 Block block, Location loc)
2032 if (parent != null) {
2033 param_info = parent.param_info;
2034 param_map = parent.param_map;
2035 struct_params = parent.struct_params;
2036 num_params = parent.num_params;
2041 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2042 Block.CountVariables);
2044 vector = new UsageVector (Parent.CurrentUsageVector);
2046 Siblings.Add (vector);
2049 case FlowBranchingType.EXCEPTION:
2050 finally_vectors = new ArrayList ();
2059 // Returns the branching's current usage vector.
2061 public UsageVector CurrentUsageVector
2064 return (UsageVector) Siblings [Siblings.Count - 1];
2069 // Creates a sibling of the current usage vector.
2071 public void CreateSibling ()
2073 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2075 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2079 // Creates a sibling for a `finally' block.
2081 public void CreateSiblingForFinally ()
2083 if (Type != FlowBranchingType.EXCEPTION)
2084 throw new NotSupportedException ();
2088 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2092 // Check whether all `out' parameters have been assigned.
2094 public void CheckOutParameters (MyBitVector parameters, Location loc)
2099 for (int i = 0; i < param_map.Length; i++) {
2100 int index = param_map [i];
2105 if (parameters [index - 1])
2108 // If it's a struct, we must ensure that all its fields have
2109 // been assigned. If the struct has any non-public fields, this
2110 // can only be done by assigning the whole struct.
2112 MyStructInfo struct_info = struct_params [index - 1];
2113 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2115 177, loc, "The out parameter `" +
2116 param_info.ParameterName (i) + "' must be " +
2117 "assigned before control leave the current method.");
2123 for (int j = 0; j < struct_info.Count; j++) {
2124 if (!parameters [index + j]) {
2126 177, loc, "The out parameter `" +
2127 param_info.ParameterName (i) + "' must be " +
2128 "assigned before control leave the current method.");
2137 // Merge a child branching.
2139 public FlowReturns MergeChild (FlowBranching child)
2141 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2143 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2144 MayLeaveLoop |= child.MayLeaveLoop;
2146 MayLeaveLoop = false;
2152 // Does the toplevel merging.
2154 public FlowReturns MergeTopBlock ()
2156 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2157 throw new NotSupportedException ();
2159 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2161 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2163 vector.MergeChildren (this, Siblings);
2166 Siblings.Add (vector);
2168 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2170 if (vector.Breaks != FlowReturns.EXCEPTION) {
2171 if (!vector.AlwaysBreaks)
2172 CheckOutParameters (CurrentUsageVector.Parameters, Location);
2173 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2175 return FlowReturns.EXCEPTION;
2178 public bool InTryBlock ()
2180 if (finally_vectors != null)
2182 else if (Parent != null)
2183 return Parent.InTryBlock ();
2188 public void AddFinallyVector (UsageVector vector)
2190 if (finally_vectors != null) {
2191 finally_vectors.Add (vector.Clone ());
2196 Parent.AddFinallyVector (vector);
2198 throw new NotSupportedException ();
2201 public bool IsVariableAssigned (VariableInfo vi)
2203 if (CurrentUsageVector.AlwaysBreaks)
2206 return CurrentUsageVector [vi, 0];
2209 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2211 if (CurrentUsageVector.AlwaysBreaks)
2214 return CurrentUsageVector [vi, field_idx];
2217 public void SetVariableAssigned (VariableInfo vi)
2219 if (CurrentUsageVector.AlwaysBreaks)
2222 CurrentUsageVector [vi, 0] = true;
2225 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2227 if (CurrentUsageVector.AlwaysBreaks)
2230 CurrentUsageVector [vi, field_idx] = true;
2233 public bool IsParameterAssigned (int number)
2235 int index = param_map [number];
2240 if (CurrentUsageVector [index])
2243 // Parameter is not assigned, so check whether it's a struct.
2244 // If it's either not a struct or a struct which non-public
2245 // fields, return false.
2246 MyStructInfo struct_info = struct_params [number];
2247 if ((struct_info == null) || struct_info.HasNonPublicFields)
2250 // Ok, so each field must be assigned.
2251 for (int i = 0; i < struct_info.Count; i++)
2252 if (!CurrentUsageVector [index + i])
2258 public bool IsParameterAssigned (int number, string field_name)
2260 int index = param_map [number];
2265 MyStructInfo info = (MyStructInfo) struct_params [number];
2269 int field_idx = info [field_name];
2271 return CurrentUsageVector [index + field_idx];
2274 public void SetParameterAssigned (int number)
2276 if (param_map [number] == 0)
2279 if (!CurrentUsageVector.AlwaysBreaks)
2280 CurrentUsageVector [param_map [number]] = true;
2283 public void SetParameterAssigned (int number, string field_name)
2285 int index = param_map [number];
2290 MyStructInfo info = (MyStructInfo) struct_params [number];
2294 int field_idx = info [field_name];
2296 if (!CurrentUsageVector.AlwaysBreaks)
2297 CurrentUsageVector [index + field_idx] = true;
2300 public bool IsReachable ()
2305 case FlowBranchingType.SWITCH_SECTION:
2306 // The code following a switch block is reachable unless the switch
2307 // block always returns.
2308 reachable = !CurrentUsageVector.AlwaysReturns;
2311 case FlowBranchingType.LOOP_BLOCK:
2312 // The code following a loop is reachable unless the loop always
2313 // returns or it's an infinite loop without any `break's in it.
2314 reachable = !CurrentUsageVector.AlwaysReturns &&
2315 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2319 // The code following a block or exception is reachable unless the
2320 // block either always returns or always breaks.
2321 reachable = !CurrentUsageVector.AlwaysBreaks &&
2322 !CurrentUsageVector.AlwaysReturns;
2326 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2327 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2332 public override string ToString ()
2334 StringBuilder sb = new StringBuilder ("FlowBranching (");
2339 if (Block != null) {
2341 sb.Append (Block.ID);
2343 sb.Append (Block.StartLocation);
2346 sb.Append (Siblings.Count);
2348 sb.Append (CurrentUsageVector);
2350 return sb.ToString ();
2354 public class MyStructInfo {
2355 public readonly Type Type;
2356 public readonly FieldInfo[] Fields;
2357 public readonly FieldInfo[] NonPublicFields;
2358 public readonly int Count;
2359 public readonly int CountNonPublic;
2360 public readonly bool HasNonPublicFields;
2362 private static Hashtable field_type_hash = new Hashtable ();
2363 private Hashtable field_hash;
2365 // Private constructor. To save memory usage, we only need to create one instance
2366 // of this class per struct type.
2367 private MyStructInfo (Type type)
2371 if (type is TypeBuilder) {
2372 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2374 ArrayList fields = tc.Fields;
2375 if (fields != null) {
2376 foreach (Field field in fields) {
2377 if ((field.ModFlags & Modifiers.STATIC) != 0)
2379 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2386 Fields = new FieldInfo [Count];
2387 NonPublicFields = new FieldInfo [CountNonPublic];
2389 Count = CountNonPublic = 0;
2390 if (fields != null) {
2391 foreach (Field field in fields) {
2392 if ((field.ModFlags & Modifiers.STATIC) != 0)
2394 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2395 Fields [Count++] = field.FieldBuilder;
2397 NonPublicFields [CountNonPublic++] =
2403 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2404 Count = Fields.Length;
2406 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2407 CountNonPublic = NonPublicFields.Length;
2410 Count += NonPublicFields.Length;
2413 field_hash = new Hashtable ();
2414 foreach (FieldInfo field in Fields)
2415 field_hash.Add (field.Name, ++number);
2417 if (NonPublicFields.Length != 0)
2418 HasNonPublicFields = true;
2420 foreach (FieldInfo field in NonPublicFields)
2421 field_hash.Add (field.Name, ++number);
2424 public int this [string name] {
2426 if (field_hash.Contains (name))
2427 return (int) field_hash [name];
2433 public FieldInfo this [int index] {
2435 if (index >= Fields.Length)
2436 return NonPublicFields [index - Fields.Length];
2438 return Fields [index];
2442 public static MyStructInfo GetStructInfo (Type type)
2444 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2447 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2450 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2454 info = new MyStructInfo (type);
2455 field_type_hash.Add (type, info);
2459 public static MyStructInfo GetStructInfo (TypeContainer tc)
2461 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2465 info = new MyStructInfo (tc.TypeBuilder);
2466 field_type_hash.Add (tc.TypeBuilder, info);
2471 public class VariableInfo : IVariable {
2472 public Expression Type;
2473 public LocalBuilder LocalBuilder;
2474 public Type VariableType;
2475 public readonly string Name;
2476 public readonly Location Location;
2477 public readonly int Block;
2482 public bool Assigned;
2483 public bool ReadOnly;
2485 public VariableInfo (Expression type, string name, int block, Location l)
2490 LocalBuilder = null;
2494 public VariableInfo (TypeContainer tc, int block, Location l)
2496 VariableType = tc.TypeBuilder;
2497 struct_info = MyStructInfo.GetStructInfo (tc);
2499 LocalBuilder = null;
2503 MyStructInfo struct_info;
2504 public MyStructInfo StructInfo {
2510 public bool IsAssigned (EmitContext ec, Location loc)
2511 {/* FIXME: we shouldn't just skip this!!!
2512 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2515 MyStructInfo struct_info = StructInfo;
2516 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2517 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2518 ec.CurrentBranching.SetVariableAssigned (this);
2522 int count = struct_info.Count;
2524 for (int i = 0; i < count; i++) {
2525 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2527 Report.Error (165, loc,
2528 "Use of unassigned local variable `" +
2530 ec.CurrentBranching.SetVariableAssigned (this);
2534 FieldInfo field = struct_info [i];
2535 Report.Error (171, loc,
2536 "Field `" + TypeManager.MonoBASIC_Name (VariableType) +
2537 "." + field.Name + "' must be fully initialized " +
2538 "before control leaves the constructor");
2546 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2548 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2549 (struct_info == null))
2552 int field_idx = StructInfo [name];
2556 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2557 Report.Error (170, loc,
2558 "Use of possibly unassigned field `" + name + "'");
2559 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2566 public void SetAssigned (EmitContext ec)
2568 if (ec.DoFlowAnalysis)
2569 ec.CurrentBranching.SetVariableAssigned (this);
2572 public void SetFieldAssigned (EmitContext ec, string name)
2574 if (ec.DoFlowAnalysis && (struct_info != null))
2575 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2578 public bool Resolve (DeclSpace decl)
2580 if (struct_info != null)
2583 if (VariableType == null)
2584 VariableType = decl.ResolveType (Type, false, Location);
2586 if (VariableType == null)
2589 struct_info = MyStructInfo.GetStructInfo (VariableType);
2594 public void MakePinned ()
2596 TypeManager.MakePinned (LocalBuilder);
2599 public override string ToString ()
2601 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2606 /// Block represents a C# block.
2610 /// This class is used in a number of places: either to represent
2611 /// explicit blocks that the programmer places or implicit blocks.
2613 /// Implicit blocks are used as labels or to introduce variable
2616 public class Block : Statement {
2617 public readonly Block Parent;
2618 public readonly bool Implicit;
2619 public readonly Location StartLocation;
2620 public Location EndLocation;
2623 // The statements in this block
2625 public ArrayList statements;
2628 // An array of Blocks. We keep track of children just
2629 // to generate the local variable declarations.
2631 // Statements and child statements are handled through the
2637 // Labels. (label, block) pairs.
2639 CaseInsensitiveHashtable labels;
2642 // Keeps track of (name, type) pairs
2644 CaseInsensitiveHashtable variables;
2647 // Keeps track of constants
2648 CaseInsensitiveHashtable constants;
2651 // Maps variable names to ILGenerator.LocalBuilders
2653 CaseInsensitiveHashtable local_builders;
2661 public Block (Block parent)
2662 : this (parent, false, Location.Null, Location.Null)
2665 public Block (Block parent, bool implicit_block)
2666 : this (parent, implicit_block, Location.Null, Location.Null)
2669 public Block (Block parent, bool implicit_block, Parameters parameters)
2670 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2673 public Block (Block parent, Location start, Location end)
2674 : this (parent, false, start, end)
2677 public Block (Block parent, Parameters parameters, Location start, Location end)
2678 : this (parent, false, parameters, start, end)
2681 public Block (Block parent, bool implicit_block, Location start, Location end)
2682 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2686 public Block (Block parent, bool implicit_block, Parameters parameters,
2687 Location start, Location end)
2690 parent.AddChild (this);
2692 this.Parent = parent;
2693 this.Implicit = implicit_block;
2694 this.parameters = parameters;
2695 this.StartLocation = start;
2696 this.EndLocation = end;
2699 statements = new ArrayList ();
2708 void AddChild (Block b)
2710 if (children == null)
2711 children = new ArrayList ();
2716 public void SetEndLocation (Location loc)
2722 /// Adds a label to the current block.
2726 /// false if the name already exists in this block. true
2730 public bool AddLabel (string name, LabeledStatement target)
2733 labels = new CaseInsensitiveHashtable ();
2734 if (labels.Contains (name))
2737 labels.Add (name, target);
2741 public LabeledStatement LookupLabel (string name)
2743 if (labels != null){
2744 if (labels.Contains (name))
2745 return ((LabeledStatement) labels [name]);
2749 return Parent.LookupLabel (name);
2754 VariableInfo this_variable = null;
2757 // Returns the "this" instance variable of this block.
2758 // See AddThisVariable() for more information.
2760 public VariableInfo ThisVariable {
2762 if (this_variable != null)
2763 return this_variable;
2764 else if (Parent != null)
2765 return Parent.ThisVariable;
2771 Hashtable child_variable_names;
2774 // Marks a variable with name @name as being used in a child block.
2775 // If a variable name has been used in a child block, it's illegal to
2776 // declare a variable with the same name in the current block.
2778 public void AddChildVariableName (string name)
2780 if (child_variable_names == null)
2781 child_variable_names = new CaseInsensitiveHashtable ();
2783 if (!child_variable_names.Contains (name))
2784 child_variable_names.Add (name, true);
2788 // Marks all variables from block @block and all its children as being
2789 // used in a child block.
2791 public void AddChildVariableNames (Block block)
2793 if (block.Variables != null) {
2794 foreach (string name in block.Variables.Keys)
2795 AddChildVariableName (name);
2798 foreach (Block child in block.children) {
2799 if (child.Variables != null) {
2800 foreach (string name in child.Variables.Keys)
2801 AddChildVariableName (name);
2807 // Checks whether a variable name has already been used in a child block.
2809 public bool IsVariableNameUsedInChildBlock (string name)
2811 if (child_variable_names == null)
2814 return child_variable_names.Contains (name);
2818 // This is used by non-static `struct' constructors which do not have an
2819 // initializer - in this case, the constructor must initialize all of the
2820 // struct's fields. To do this, we add a "this" variable and use the flow
2821 // analysis code to ensure that it's been fully initialized before control
2822 // leaves the constructor.
2824 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2826 if (this_variable != null)
2827 return this_variable;
2829 this_variable = new VariableInfo (tc, ID, l);
2831 if (variables == null)
2832 variables = new CaseInsensitiveHashtable ();
2833 variables.Add ("this", this_variable);
2835 return this_variable;
2838 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2840 if (variables == null)
2841 variables = new CaseInsensitiveHashtable ();
2843 VariableInfo vi = GetVariableInfo (name);
2846 Report.Error (136, l, "A local variable named `" + name + "' " +
2847 "cannot be declared in this scope since it would " +
2848 "give a different meaning to `" + name + "', which " +
2849 "is already used in a `parent or current' scope to " +
2850 "denote something else");
2852 Report.Error (128, l, "A local variable `" + name + "' is already " +
2853 "defined in this scope");
2857 if (IsVariableNameUsedInChildBlock (name)) {
2858 Report.Error (136, l, "A local variable named `" + name + "' " +
2859 "cannot be declared in this scope since it would " +
2860 "give a different meaning to `" + name + "', which " +
2861 "is already used in a `child' scope to denote something " +
2868 Parameter p = pars.GetParameterByName (name, out idx);
2870 Report.Error (136, l, "A local variable named `" + name + "' " +
2871 "cannot be declared in this scope since it would " +
2872 "give a different meaning to `" + name + "', which " +
2873 "is already used in a `parent or current' scope to " +
2874 "denote something else");
2879 vi = new VariableInfo (type, name, ID, l);
2881 variables.Add (name, vi);
2883 if (variables_initialized)
2884 throw new Exception ();
2886 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2890 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2892 if (AddVariable (type, name, pars, l) == null)
2895 if (constants == null)
2896 constants = new CaseInsensitiveHashtable ();
2898 constants.Add (name, value);
2902 public Hashtable Variables {
2908 public VariableInfo GetVariableInfo (string name)
2910 if (variables != null) {
2912 temp = variables [name];
2915 return (VariableInfo) temp;
2920 return Parent.GetVariableInfo (name);
2925 public Expression GetVariableType (string name)
2927 VariableInfo vi = GetVariableInfo (name);
2935 public Expression GetConstantExpression (string name)
2937 if (constants != null) {
2939 temp = constants [name];
2942 return (Expression) temp;
2946 return Parent.GetConstantExpression (name);
2952 /// True if the variable named @name has been defined
2955 public bool IsVariableDefined (string name)
2957 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2958 if (variables != null) {
2959 if (variables.Contains (name))
2964 return Parent.IsVariableDefined (name);
2970 /// True if the variable named @name is a constant
2972 public bool IsConstant (string name)
2974 Expression e = null;
2976 e = GetConstantExpression (name);
2982 /// Use to fetch the statement associated with this label
2984 public Statement this [string name] {
2986 return (Statement) labels [name];
2990 Parameters parameters = null;
2991 public Parameters Parameters {
2994 return Parent.Parameters;
3001 /// A list of labels that were not used within this block
3003 public string [] GetUnreferenced ()
3005 // FIXME: Implement me
3009 public void AddStatement (Statement s)
3026 bool variables_initialized = false;
3027 int count_variables = 0, first_variable = 0;
3029 void UpdateVariableInfo (EmitContext ec)
3031 DeclSpace ds = ec.DeclSpace;
3036 first_variable += Parent.CountVariables;
3038 count_variables = first_variable;
3039 if (variables != null) {
3040 foreach (VariableInfo vi in variables.Values) {
3041 if (!vi.Resolve (ds)) {
3046 vi.Number = ++count_variables;
3048 if (vi.StructInfo != null)
3049 count_variables += vi.StructInfo.Count;
3053 variables_initialized = true;
3058 // The number of local variables in this block
3060 public int CountVariables
3063 if (!variables_initialized)
3064 throw new Exception ();
3066 return count_variables;
3071 /// Emits the variable declarations and labels.
3074 /// tc: is our typecontainer (to resolve type references)
3075 /// ig: is the code generator:
3076 /// toplevel: the toplevel block. This is used for checking
3077 /// that no two labels with the same name are used.
3079 public void EmitMeta (EmitContext ec, Block toplevel)
3081 //DeclSpace ds = ec.DeclSpace;
3082 ILGenerator ig = ec.ig;
3084 if (!variables_initialized)
3085 UpdateVariableInfo (ec);
3088 // Process this block variables
3090 if (variables != null){
3091 local_builders = new CaseInsensitiveHashtable ();
3093 foreach (DictionaryEntry de in variables){
3094 string name = (string) de.Key;
3095 VariableInfo vi = (VariableInfo) de.Value;
3097 if (vi.VariableType == null)
3100 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3102 if (CodeGen.SymbolWriter != null)
3103 vi.LocalBuilder.SetLocalSymInfo (name);
3105 if (constants == null)
3108 Expression cv = (Expression) constants [name];
3112 Expression e = cv.Resolve (ec);
3116 if (!(e is Constant)){
3117 Report.Error (133, vi.Location,
3118 "The expression being assigned to `" +
3119 name + "' must be constant (" + e + ")");
3123 constants.Remove (name);
3124 constants.Add (name, e);
3129 // Now, handle the children
3131 if (children != null){
3132 foreach (Block b in children)
3133 b.EmitMeta (ec, toplevel);
3137 public void UsageWarning ()
3141 if (variables != null){
3142 foreach (DictionaryEntry de in variables){
3143 VariableInfo vi = (VariableInfo) de.Value;
3148 name = (string) de.Key;
3152 219, vi.Location, "The variable `" + name +
3153 "' is assigned but its value is never used");
3156 168, vi.Location, "The variable `" +
3158 "' is declared but never used");
3163 if (children != null)
3164 foreach (Block b in children)
3168 bool has_ret = false;
3170 public override bool Resolve (EmitContext ec)
3172 Block prev_block = ec.CurrentBlock;
3175 ec.CurrentBlock = this;
3176 ec.StartFlowBranching (this);
3178 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3180 if (!variables_initialized)
3181 UpdateVariableInfo (ec);
3183 ArrayList new_statements = new ArrayList ();
3184 bool unreachable = false, warning_shown = false;
3186 foreach (Statement s in statements){
3187 if (unreachable && !(s is LabeledStatement)) {
3188 if (!warning_shown && !(s is EmptyStatement)) {
3189 warning_shown = true;
3190 Warning_DeadCodeFound (s.loc);
3196 if (s.Resolve (ec) == false) {
3201 if (s is LabeledStatement)
3202 unreachable = false;
3204 unreachable = ! ec.CurrentBranching.IsReachable ();
3206 new_statements.Add (s);
3209 statements = new_statements;
3211 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3213 FlowReturns returns = ec.EndFlowBranching ();
3214 ec.CurrentBlock = prev_block;
3216 // If we're a non-static `struct' constructor which doesn't have an
3217 // initializer, then we must initialize all of the struct's fields.
3218 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3219 !this_variable.IsAssigned (ec, loc))
3222 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3223 foreach (LabeledStatement label in labels.Values)
3224 if (!label.HasBeenReferenced)
3225 Report.Warning (164, label.Location,
3226 "This label has not been referenced");
3229 if ((returns == FlowReturns.ALWAYS) ||
3230 (returns == FlowReturns.EXCEPTION) ||
3231 (returns == FlowReturns.UNREACHABLE))
3237 protected override bool DoEmit (EmitContext ec)
3239 Block prev_block = ec.CurrentBlock;
3241 ec.CurrentBlock = this;
3243 ec.Mark (StartLocation);
3244 foreach (Statement s in statements)
3247 ec.Mark (EndLocation);
3249 ec.CurrentBlock = prev_block;
3254 public class SwitchLabel {
3257 public Location loc;
3258 public Label ILLabel;
3259 public Label ILLabelCode;
3262 // if expr == null, then it is the default case.
3264 public SwitchLabel (Expression expr, Location l)
3270 public Expression Label {
3276 public object Converted {
3283 // Resolves the expression, reduces it to a literal if possible
3284 // and then converts it to the requested type.
3286 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3288 ILLabel = ec.ig.DefineLabel ();
3289 ILLabelCode = ec.ig.DefineLabel ();
3294 Expression e = label.Resolve (ec);
3299 if (!(e is Constant)){
3300 Console.WriteLine ("Value is: " + label);
3301 Report.Error (150, loc, "A constant value is expected");
3305 if (e is StringConstant || e is NullLiteral){
3306 if (required_type == TypeManager.string_type){
3308 ILLabel = ec.ig.DefineLabel ();
3313 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3314 if (converted == null)
3321 public class SwitchSection {
3322 // An array of SwitchLabels.
3323 public readonly ArrayList Labels;
3324 public readonly Block Block;
3326 public SwitchSection (ArrayList labels, Block block)
3333 public class Switch : Statement {
3334 public readonly ArrayList Sections;
3335 public Expression Expr;
3338 /// Maps constants whose type type SwitchType to their SwitchLabels.
3340 public Hashtable Elements;
3343 /// The governing switch type
3345 public Type SwitchType;
3351 Label default_target;
3352 Expression new_expr;
3355 // The types allowed to be implicitly cast from
3356 // on the governing type
3358 static Type [] allowed_types;
3360 public Switch (Expression e, ArrayList sects, Location l)
3367 public bool GotDefault {
3373 public Label DefaultTarget {
3375 return default_target;
3380 // Determines the governing type for a switch. The returned
3381 // expression might be the expression from the switch, or an
3382 // expression that includes any potential conversions to the
3383 // integral types or to string.
3385 Expression SwitchGoverningType (EmitContext ec, Type t)
3387 if (t == TypeManager.int32_type ||
3388 t == TypeManager.uint32_type ||
3389 t == TypeManager.char_type ||
3390 t == TypeManager.byte_type ||
3391 t == TypeManager.sbyte_type ||
3392 t == TypeManager.ushort_type ||
3393 t == TypeManager.short_type ||
3394 t == TypeManager.uint64_type ||
3395 t == TypeManager.int64_type ||
3396 t == TypeManager.string_type ||
3397 t == TypeManager.bool_type ||
3398 t.IsSubclassOf (TypeManager.enum_type))
3401 if (allowed_types == null){
3402 allowed_types = new Type [] {
3403 TypeManager.sbyte_type,
3404 TypeManager.byte_type,
3405 TypeManager.short_type,
3406 TypeManager.ushort_type,
3407 TypeManager.int32_type,
3408 TypeManager.uint32_type,
3409 TypeManager.int64_type,
3410 TypeManager.uint64_type,
3411 TypeManager.char_type,
3412 TypeManager.bool_type,
3413 TypeManager.string_type
3418 // Try to find a *user* defined implicit conversion.
3420 // If there is no implicit conversion, or if there are multiple
3421 // conversions, we have to report an error
3423 Expression converted = null;
3424 foreach (Type tt in allowed_types){
3427 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3431 if (converted != null){
3432 Report.Error (-12, loc, "More than one conversion to an integral " +
3433 " type exists for type `" +
3434 TypeManager.MonoBASIC_Name (Expr.Type)+"'");
3442 void error152 (string n)
3445 152, "The label `" + n + ":' " +
3446 "is already present on this switch statement");
3450 // Performs the basic sanity checks on the switch statement
3451 // (looks for duplicate keys and non-constant expressions).
3453 // It also returns a hashtable with the keys that we will later
3454 // use to compute the switch tables
3456 bool CheckSwitch (EmitContext ec)
3460 Elements = new CaseInsensitiveHashtable ();
3462 got_default = false;
3464 if (TypeManager.IsEnumType (SwitchType)){
3465 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3467 compare_type = SwitchType;
3469 foreach (SwitchSection ss in Sections){
3470 foreach (SwitchLabel sl in ss.Labels){
3471 if (!sl.ResolveAndReduce (ec, SwitchType)){
3476 if (sl.Label == null){
3478 error152 ("default");
3485 object key = sl.Converted;
3487 if (key is Constant)
3488 key = ((Constant) key).GetValue ();
3491 key = NullLiteral.Null;
3493 string lname = null;
3494 if (compare_type == TypeManager.uint64_type){
3495 ulong v = (ulong) key;
3497 if (Elements.Contains (v))
3498 lname = v.ToString ();
3500 Elements.Add (v, sl);
3501 } else if (compare_type == TypeManager.int64_type){
3502 long v = (long) key;
3504 if (Elements.Contains (v))
3505 lname = v.ToString ();
3507 Elements.Add (v, sl);
3508 } else if (compare_type == TypeManager.uint32_type){
3509 uint v = (uint) key;
3511 if (Elements.Contains (v))
3512 lname = v.ToString ();
3514 Elements.Add (v, sl);
3515 } else if (compare_type == TypeManager.char_type){
3516 char v = (char) key;
3518 if (Elements.Contains (v))
3519 lname = v.ToString ();
3521 Elements.Add (v, sl);
3522 } else if (compare_type == TypeManager.byte_type){
3523 byte v = (byte) key;
3525 if (Elements.Contains (v))
3526 lname = v.ToString ();
3528 Elements.Add (v, sl);
3529 } else if (compare_type == TypeManager.sbyte_type){
3530 sbyte v = (sbyte) key;
3532 if (Elements.Contains (v))
3533 lname = v.ToString ();
3535 Elements.Add (v, sl);
3536 } else if (compare_type == TypeManager.short_type){
3537 short v = (short) key;
3539 if (Elements.Contains (v))
3540 lname = v.ToString ();
3542 Elements.Add (v, sl);
3543 } else if (compare_type == TypeManager.ushort_type){
3544 ushort v = (ushort) key;
3546 if (Elements.Contains (v))
3547 lname = v.ToString ();
3549 Elements.Add (v, sl);
3550 } else if (compare_type == TypeManager.string_type){
3551 if (key is NullLiteral){
3552 if (Elements.Contains (NullLiteral.Null))
3555 Elements.Add (NullLiteral.Null, null);
3557 string s = (string) key;
3559 if (Elements.Contains (s))
3562 Elements.Add (s, sl);
3564 } else if (compare_type == TypeManager.int32_type) {
3567 if (Elements.Contains (v))
3568 lname = v.ToString ();
3570 Elements.Add (v, sl);
3571 } else if (compare_type == TypeManager.bool_type) {
3572 bool v = (bool) key;
3574 if (Elements.Contains (v))
3575 lname = v.ToString ();
3577 Elements.Add (v, sl);
3581 throw new Exception ("Unknown switch type!" +
3582 SwitchType + " " + compare_type);
3586 error152 ("case + " + lname);
3597 void EmitObjectInteger (ILGenerator ig, object k)
3600 IntConstant.EmitInt (ig, (int) k);
3601 else if (k is Constant) {
3602 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3605 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3608 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3610 IntConstant.EmitInt (ig, (int) (long) k);
3611 ig.Emit (OpCodes.Conv_I8);
3614 LongConstant.EmitLong (ig, (long) k);
3616 else if (k is ulong)
3618 if ((ulong) k < (1L<<32))
3620 IntConstant.EmitInt (ig, (int) (long) k);
3621 ig.Emit (OpCodes.Conv_U8);
3625 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3629 IntConstant.EmitInt (ig, (int) ((char) k));
3630 else if (k is sbyte)
3631 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3633 IntConstant.EmitInt (ig, (int) ((byte) k));
3634 else if (k is short)
3635 IntConstant.EmitInt (ig, (int) ((short) k));
3636 else if (k is ushort)
3637 IntConstant.EmitInt (ig, (int) ((ushort) k));
3639 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3641 throw new Exception ("Unhandled case");
3644 // structure used to hold blocks of keys while calculating table switch
3645 class KeyBlock : IComparable
3647 public KeyBlock (long _nFirst)
3649 nFirst = nLast = _nFirst;
3653 public ArrayList rgKeys = null;
3656 get { return (int) (nLast - nFirst + 1); }
3658 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3660 return kbLast.nLast - kbFirst.nFirst + 1;
3662 public int CompareTo (object obj)
3664 KeyBlock kb = (KeyBlock) obj;
3665 int nLength = Length;
3666 int nLengthOther = kb.Length;
3667 if (nLengthOther == nLength)
3668 return (int) (kb.nFirst - nFirst);
3669 return nLength - nLengthOther;
3674 /// This method emits code for a lookup-based switch statement (non-string)
3675 /// Basically it groups the cases into blocks that are at least half full,
3676 /// and then spits out individual lookup opcodes for each block.
3677 /// It emits the longest blocks first, and short blocks are just
3678 /// handled with direct compares.
3680 /// <param name="ec"></param>
3681 /// <param name="val"></param>
3682 /// <returns></returns>
3683 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3685 int cElements = Elements.Count;
3686 object [] rgKeys = new object [cElements];
3687 Elements.Keys.CopyTo (rgKeys, 0);
3688 Array.Sort (rgKeys);
3690 // initialize the block list with one element per key
3691 ArrayList rgKeyBlocks = new ArrayList ();
3692 foreach (object key in rgKeys)
3693 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3696 // iteratively merge the blocks while they are at least half full
3697 // there's probably a really cool way to do this with a tree...
3698 while (rgKeyBlocks.Count > 1)
3700 ArrayList rgKeyBlocksNew = new ArrayList ();
3701 kbCurr = (KeyBlock) rgKeyBlocks [0];
3702 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3704 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3705 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3708 kbCurr.nLast = kb.nLast;
3712 // start a new block
3713 rgKeyBlocksNew.Add (kbCurr);
3717 rgKeyBlocksNew.Add (kbCurr);
3718 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3720 rgKeyBlocks = rgKeyBlocksNew;
3723 // initialize the key lists
3724 foreach (KeyBlock kb in rgKeyBlocks)
3725 kb.rgKeys = new ArrayList ();
3727 // fill the key lists
3729 if (rgKeyBlocks.Count > 0) {
3730 kbCurr = (KeyBlock) rgKeyBlocks [0];
3731 foreach (object key in rgKeys)
3733 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3735 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3736 kbCurr.rgKeys.Add (key);
3740 // sort the blocks so we can tackle the largest ones first
3741 rgKeyBlocks.Sort ();
3743 // okay now we can start...
3744 ILGenerator ig = ec.ig;
3745 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3746 Label lblDefault = ig.DefineLabel ();
3748 Type typeKeys = null;
3749 if (rgKeys.Length > 0)
3750 typeKeys = rgKeys [0].GetType (); // used for conversions
3752 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3754 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3755 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3758 foreach (object key in kb.rgKeys)
3760 ig.Emit (OpCodes.Ldloc, val);
3761 EmitObjectInteger (ig, key);
3762 SwitchLabel sl = (SwitchLabel) Elements [key];
3763 ig.Emit (OpCodes.Beq, sl.ILLabel);
3768 // TODO: if all the keys in the block are the same and there are
3769 // no gaps/defaults then just use a range-check.
3770 if (SwitchType == TypeManager.int64_type ||
3771 SwitchType == TypeManager.uint64_type)
3773 // TODO: optimize constant/I4 cases
3775 // check block range (could be > 2^31)
3776 ig.Emit (OpCodes.Ldloc, val);
3777 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3778 ig.Emit (OpCodes.Blt, lblDefault);
3779 ig.Emit (OpCodes.Ldloc, val);
3780 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3781 ig.Emit (OpCodes.Bgt, lblDefault);
3784 ig.Emit (OpCodes.Ldloc, val);
3787 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3788 ig.Emit (OpCodes.Sub);
3790 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3795 ig.Emit (OpCodes.Ldloc, val);
3796 int nFirst = (int) kb.nFirst;
3799 IntConstant.EmitInt (ig, nFirst);
3800 ig.Emit (OpCodes.Sub);
3802 else if (nFirst < 0)
3804 IntConstant.EmitInt (ig, -nFirst);
3805 ig.Emit (OpCodes.Add);
3809 // first, build the list of labels for the switch
3811 int cJumps = kb.Length;
3812 Label [] rgLabels = new Label [cJumps];
3813 for (int iJump = 0; iJump < cJumps; iJump++)
3815 object key = kb.rgKeys [iKey];
3816 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3818 SwitchLabel sl = (SwitchLabel) Elements [key];
3819 rgLabels [iJump] = sl.ILLabel;
3823 rgLabels [iJump] = lblDefault;
3825 // emit the switch opcode
3826 ig.Emit (OpCodes.Switch, rgLabels);
3829 // mark the default for this block
3831 ig.MarkLabel (lblDefault);
3834 // TODO: find the default case and emit it here,
3835 // to prevent having to do the following jump.
3836 // make sure to mark other labels in the default section
3838 // the last default just goes to the end
3839 ig.Emit (OpCodes.Br, lblDefault);
3841 // now emit the code for the sections
3842 bool fFoundDefault = false;
3843 bool fAllReturn = true;
3844 foreach (SwitchSection ss in Sections)
3846 foreach (SwitchLabel sl in ss.Labels)
3848 ig.MarkLabel (sl.ILLabel);
3849 ig.MarkLabel (sl.ILLabelCode);
3850 if (sl.Label == null)
3852 ig.MarkLabel (lblDefault);
3853 fFoundDefault = true;
3856 bool returns = ss.Block.Emit (ec);
3857 fAllReturn &= returns;
3858 //ig.Emit (OpCodes.Br, lblEnd);
3861 if (!fFoundDefault) {
3862 ig.MarkLabel (lblDefault);
3865 ig.MarkLabel (lblEnd);
3870 // This simple emit switch works, but does not take advantage of the
3872 // TODO: remove non-string logic from here
3873 // TODO: binary search strings?
3875 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3877 ILGenerator ig = ec.ig;
3878 Label end_of_switch = ig.DefineLabel ();
3879 Label next_test = ig.DefineLabel ();
3880 Label null_target = ig.DefineLabel ();
3881 bool default_found = false;
3882 bool first_test = true;
3883 bool pending_goto_end = false;
3884 bool all_return = true;
3885 bool is_string = false;
3889 // Special processing for strings: we cant compare
3892 if (SwitchType == TypeManager.string_type){
3893 ig.Emit (OpCodes.Ldloc, val);
3896 if (Elements.Contains (NullLiteral.Null)){
3897 ig.Emit (OpCodes.Brfalse, null_target);
3899 ig.Emit (OpCodes.Brfalse, default_target);
3901 ig.Emit (OpCodes.Ldloc, val);
3902 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3903 ig.Emit (OpCodes.Stloc, val);
3906 foreach (SwitchSection ss in Sections){
3907 Label sec_begin = ig.DefineLabel ();
3909 if (pending_goto_end)
3910 ig.Emit (OpCodes.Br, end_of_switch);
3912 int label_count = ss.Labels.Count;
3914 foreach (SwitchLabel sl in ss.Labels){
3915 ig.MarkLabel (sl.ILLabel);
3918 ig.MarkLabel (next_test);
3919 next_test = ig.DefineLabel ();
3922 // If we are the default target
3924 if (sl.Label == null){
3925 ig.MarkLabel (default_target);
3926 default_found = true;
3928 object lit = sl.Converted;
3930 if (lit is NullLiteral){
3932 if (label_count == 1)
3933 ig.Emit (OpCodes.Br, next_test);
3938 StringConstant str = (StringConstant) lit;
3940 ig.Emit (OpCodes.Ldloc, val);
3941 ig.Emit (OpCodes.Ldstr, str.Value);
3942 if (label_count == 1)
3943 ig.Emit (OpCodes.Bne_Un, next_test);
3945 ig.Emit (OpCodes.Beq, sec_begin);
3947 ig.Emit (OpCodes.Ldloc, val);
3948 EmitObjectInteger (ig, lit);
3949 ig.Emit (OpCodes.Ceq);
3950 if (label_count == 1)
3951 ig.Emit (OpCodes.Brfalse, next_test);
3953 ig.Emit (OpCodes.Brtrue, sec_begin);
3957 if (label_count != 1)
3958 ig.Emit (OpCodes.Br, next_test);
3961 ig.MarkLabel (null_target);
3962 ig.MarkLabel (sec_begin);
3963 foreach (SwitchLabel sl in ss.Labels)
3964 ig.MarkLabel (sl.ILLabelCode);
3966 bool returns = ss.Block.Emit (ec);
3968 pending_goto_end = false;
3971 pending_goto_end = true;
3975 if (!default_found){
3976 ig.MarkLabel (default_target);
3979 ig.MarkLabel (next_test);
3980 ig.MarkLabel (end_of_switch);
3985 public override bool Resolve (EmitContext ec)
3987 Expr = Expr.Resolve (ec);
3991 new_expr = SwitchGoverningType (ec, Expr.Type);
3992 if (new_expr == null){
3993 Report.Error (151, loc, "An integer type or string was expected for switch");
3998 SwitchType = new_expr.Type;
4000 if (!CheckSwitch (ec))
4003 Switch old_switch = ec.Switch;
4005 ec.Switch.SwitchType = SwitchType;
4007 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
4010 foreach (SwitchSection ss in Sections){
4012 ec.CurrentBranching.CreateSibling ();
4016 if (ss.Block.Resolve (ec) != true)
4022 ec.CurrentBranching.CreateSibling ();
4024 ec.EndFlowBranching ();
4025 ec.Switch = old_switch;
4030 protected override bool DoEmit (EmitContext ec)
4032 // Store variable for comparission purposes
4033 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
4035 ec.ig.Emit (OpCodes.Stloc, value);
4037 ILGenerator ig = ec.ig;
4039 default_target = ig.DefineLabel ();
4042 // Setup the codegen context
4044 Label old_end = ec.LoopEnd;
4045 Switch old_switch = ec.Switch;
4047 ec.LoopEnd = ig.DefineLabel ();
4052 if (SwitchType == TypeManager.string_type)
4053 all_return = SimpleSwitchEmit (ec, value);
4055 all_return = TableSwitchEmit (ec, value);
4057 // Restore context state.
4058 ig.MarkLabel (ec.LoopEnd);
4061 // Restore the previous context
4063 ec.LoopEnd = old_end;
4064 ec.Switch = old_switch;
4070 public class Lock : Statement {
4072 Statement Statement;
4074 public Lock (Expression expr, Statement stmt, Location l)
4081 public override bool Resolve (EmitContext ec)
4083 expr = expr.Resolve (ec);
4084 return Statement.Resolve (ec) && expr != null;
4087 protected override bool DoEmit (EmitContext ec)
4089 Type type = expr.Type;
4092 if (type.IsValueType){
4093 Report.Error (185, loc, "lock statement requires the expression to be " +
4094 " a reference type (type is: `" +
4095 TypeManager.MonoBASIC_Name (type) + "'");
4099 ILGenerator ig = ec.ig;
4100 LocalBuilder temp = ig.DeclareLocal (type);
4103 ig.Emit (OpCodes.Dup);
4104 ig.Emit (OpCodes.Stloc, temp);
4105 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4108 ig.BeginExceptionBlock ();
4109 bool old_in_try = ec.InTry;
4111 Label finish = ig.DefineLabel ();
4112 val = Statement.Emit (ec);
4113 ec.InTry = old_in_try;
4114 // ig.Emit (OpCodes.Leave, finish);
4116 ig.MarkLabel (finish);
4119 ig.BeginFinallyBlock ();
4120 ig.Emit (OpCodes.Ldloc, temp);
4121 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4122 ig.EndExceptionBlock ();
4128 public class Unchecked : Statement {
4129 public readonly Block Block;
4131 public Unchecked (Block b)
4136 public override bool Resolve (EmitContext ec)
4138 return Block.Resolve (ec);
4141 protected override bool DoEmit (EmitContext ec)
4143 bool previous_state = ec.CheckState;
4144 bool previous_state_const = ec.ConstantCheckState;
4147 ec.CheckState = false;
4148 ec.ConstantCheckState = false;
4149 val = Block.Emit (ec);
4150 ec.CheckState = previous_state;
4151 ec.ConstantCheckState = previous_state_const;
4157 public class Checked : Statement {
4158 public readonly Block Block;
4160 public Checked (Block b)
4165 public override bool Resolve (EmitContext ec)
4167 bool previous_state = ec.CheckState;
4168 bool previous_state_const = ec.ConstantCheckState;
4170 ec.CheckState = true;
4171 ec.ConstantCheckState = true;
4172 bool ret = Block.Resolve (ec);
4173 ec.CheckState = previous_state;
4174 ec.ConstantCheckState = previous_state_const;
4179 protected override bool DoEmit (EmitContext ec)
4181 bool previous_state = ec.CheckState;
4182 bool previous_state_const = ec.ConstantCheckState;
4185 ec.CheckState = true;
4186 ec.ConstantCheckState = true;
4187 val = Block.Emit (ec);
4188 ec.CheckState = previous_state;
4189 ec.ConstantCheckState = previous_state_const;
4195 public class Unsafe : Statement {
4196 public readonly Block Block;
4198 public Unsafe (Block b)
4203 public override bool Resolve (EmitContext ec)
4205 bool previous_state = ec.InUnsafe;
4209 val = Block.Resolve (ec);
4210 ec.InUnsafe = previous_state;
4215 protected override bool DoEmit (EmitContext ec)
4217 bool previous_state = ec.InUnsafe;
4221 val = Block.Emit (ec);
4222 ec.InUnsafe = previous_state;
4231 public class Fixed : Statement {
4233 ArrayList declarators;
4234 Statement statement;
4239 public bool is_object;
4240 public VariableInfo vi;
4241 public Expression expr;
4242 public Expression converted;
4245 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4248 declarators = decls;
4253 public override bool Resolve (EmitContext ec)
4255 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4256 if (expr_type == null)
4259 data = new FixedData [declarators.Count];
4262 foreach (Pair p in declarators){
4263 VariableInfo vi = (VariableInfo) p.First;
4264 Expression e = (Expression) p.Second;
4269 // The rules for the possible declarators are pretty wise,
4270 // but the production on the grammar is more concise.
4272 // So we have to enforce these rules here.
4274 // We do not resolve before doing the case 1 test,
4275 // because the grammar is explicit in that the token &
4276 // is present, so we need to test for this particular case.
4280 // Case 1: & object.
4282 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4283 Expression child = ((Unary) e).Expr;
4286 if (child is ParameterReference || child is LocalVariableReference){
4289 "No need to use fixed statement for parameters or " +
4290 "local variable declarations (address is already " +
4299 child = ((Unary) e).Expr;
4301 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4304 data [i].is_object = true;
4306 data [i].converted = null;
4320 if (e.Type.IsArray){
4321 Type array_type = e.Type.GetElementType ();
4325 // Provided that array_type is unmanaged,
4327 if (!TypeManager.VerifyUnManaged (array_type, loc))
4331 // and T* is implicitly convertible to the
4332 // pointer type given in the fixed statement.
4334 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4336 Expression converted = Expression.ConvertImplicitRequired (
4337 ec, array_ptr, vi.VariableType, loc);
4338 if (converted == null)
4341 data [i].is_object = false;
4343 data [i].converted = converted;
4353 if (e.Type == TypeManager.string_type){
4354 data [i].is_object = false;
4356 data [i].converted = null;
4362 return statement.Resolve (ec);
4365 protected override bool DoEmit (EmitContext ec)
4367 ILGenerator ig = ec.ig;
4369 bool is_ret = false;
4371 for (int i = 0; i < data.Length; i++) {
4372 VariableInfo vi = data [i].vi;
4375 // Case 1: & object.
4377 if (data [i].is_object) {
4379 // Store pointer in pinned location
4381 data [i].expr.Emit (ec);
4382 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4384 is_ret = statement.Emit (ec);
4386 // Clear the pinned variable.
4387 ig.Emit (OpCodes.Ldc_I4_0);
4388 ig.Emit (OpCodes.Conv_U);
4389 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4397 if (data [i].expr.Type.IsArray){
4399 // Store pointer in pinned location
4401 data [i].converted.Emit (ec);
4403 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4405 is_ret = statement.Emit (ec);
4407 // Clear the pinned variable.
4408 ig.Emit (OpCodes.Ldc_I4_0);
4409 ig.Emit (OpCodes.Conv_U);
4410 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4418 if (data [i].expr.Type == TypeManager.string_type){
4419 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4420 TypeManager.MakePinned (pinned_string);
4422 data [i].expr.Emit (ec);
4423 ig.Emit (OpCodes.Stloc, pinned_string);
4425 Expression sptr = new StringPtr (pinned_string, loc);
4426 Expression converted = Expression.ConvertImplicitRequired (
4427 ec, sptr, vi.VariableType, loc);
4429 if (converted == null)
4432 converted.Emit (ec);
4433 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4435 is_ret = statement.Emit (ec);
4437 // Clear the pinned variable
4438 ig.Emit (OpCodes.Ldnull);
4439 ig.Emit (OpCodes.Stloc, pinned_string);
4447 public class Catch {
4448 public readonly string Name;
4449 public readonly Block Block;
4450 public Expression Clause;
4451 public readonly Location Location;
4453 Expression type_expr;
4454 //Expression clus_expr;
4457 public Catch (Expression type, string name, Block block, Expression clause, Location l)
4466 public Type CatchType {
4472 public bool IsGeneral {
4474 return type_expr == null;
4478 public bool Resolve (EmitContext ec)
4480 if (type_expr != null) {
4481 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4485 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4486 Report.Error (30665, Location,
4487 "The type caught or thrown must be derived " +
4488 "from System.Exception");
4494 if (Clause != null) {
4495 Clause = Statement.ResolveBoolean (ec, Clause, Location);
4496 if (Clause == null) {
4501 if (!Block.Resolve (ec))
4508 public class Try : Statement {
4509 public readonly Block Fini, Block;
4510 public readonly ArrayList Specific;
4511 public readonly Catch General;
4514 // specific, general and fini might all be null.
4516 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4518 if (specific == null && general == null){
4519 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4523 this.Specific = specific;
4524 this.General = general;
4529 public override bool Resolve (EmitContext ec)
4533 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4535 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4537 bool old_in_try = ec.InTry;
4540 if (!Block.Resolve (ec))
4543 ec.InTry = old_in_try;
4545 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4547 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4549 foreach (Catch c in Specific){
4550 ec.CurrentBranching.CreateSibling ();
4551 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4553 if (c.Name != null) {
4554 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4556 throw new Exception ();
4561 bool old_in_catch = ec.InCatch;
4564 if (!c.Resolve (ec))
4567 ec.InCatch = old_in_catch;
4569 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4571 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4572 vector.AndLocals (current);
4575 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4577 if (General != null){
4578 ec.CurrentBranching.CreateSibling ();
4579 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4581 bool old_in_catch = ec.InCatch;
4584 if (!General.Resolve (ec))
4587 ec.InCatch = old_in_catch;
4589 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4591 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4592 vector.AndLocals (current);
4595 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4598 ec.CurrentBranching.CreateSiblingForFinally ();
4599 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4601 bool old_in_finally = ec.InFinally;
4602 ec.InFinally = true;
4604 if (!Fini.Resolve (ec))
4607 ec.InFinally = old_in_finally;
4610 FlowReturns returns = ec.EndFlowBranching ();
4612 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4614 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4616 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4617 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4620 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4622 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4627 protected override bool DoEmit (EmitContext ec)
4629 ILGenerator ig = ec.ig;
4630 Label finish = ig.DefineLabel ();;
4634 ig.BeginExceptionBlock ();
4635 bool old_in_try = ec.InTry;
4637 returns = Block.Emit (ec);
4638 ec.InTry = old_in_try;
4641 // System.Reflection.Emit provides this automatically:
4642 // ig.Emit (OpCodes.Leave, finish);
4644 bool old_in_catch = ec.InCatch;
4646 //DeclSpace ds = ec.DeclSpace;
4648 foreach (Catch c in Specific){
4651 ig.BeginCatchBlock (c.CatchType);
4653 if (c.Name != null){
4654 vi = c.Block.GetVariableInfo (c.Name);
4656 throw new Exception ("Variable does not exist in this block");
4658 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4660 ig.Emit (OpCodes.Pop);
4663 // if when clause is there
4665 if (c.Clause != null) {
4666 if (c.Clause is BoolConstant) {
4667 bool take = ((BoolConstant) c.Clause).Value;
4670 if (!c.Block.Emit (ec))
4673 EmitBoolExpression (ec, c.Clause, finish, false);
4674 if (!c.Block.Emit (ec))
4678 if (!c.Block.Emit (ec))
4682 if (General != null){
4683 ig.BeginCatchBlock (TypeManager.object_type);
4684 ig.Emit (OpCodes.Pop);
4686 if (General.Clause != null) {
4687 if (General.Clause is BoolConstant) {
4688 bool take = ((BoolConstant) General.Clause).Value;
4690 if (!General.Block.Emit (ec))
4693 EmitBoolExpression (ec, General.Clause, finish, false);
4694 if (!General.Block.Emit (ec))
4698 if (!General.Block.Emit (ec))
4702 ec.InCatch = old_in_catch;
4704 ig.MarkLabel (finish);
4706 ig.BeginFinallyBlock ();
4707 bool old_in_finally = ec.InFinally;
4708 ec.InFinally = true;
4710 ec.InFinally = old_in_finally;
4713 ig.EndExceptionBlock ();
4716 if (!returns || ec.InTry || ec.InCatch)
4719 // Unfortunately, System.Reflection.Emit automatically emits a leave
4720 // to the end of the finally block. This is a problem if `returns'
4721 // is true since we may jump to a point after the end of the method.
4722 // As a workaround, emit an explicit ret here.
4724 if (ec.ReturnType != null)
4725 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4726 ec.ig.Emit (OpCodes.Ret);
4732 public class Using : Statement {
4733 object expression_or_block;
4734 Statement Statement;
4739 Expression [] converted_vars;
4740 ExpressionStatement [] assign;
4742 public Using (object expression_or_block, Statement stmt, Location l)
4744 this.expression_or_block = expression_or_block;
4750 // Resolves for the case of using using a local variable declaration.
4752 bool ResolveLocalVariableDecls (EmitContext ec)
4754 bool need_conv = false;
4755 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4758 if (expr_type == null)
4762 // The type must be an IDisposable or an implicit conversion
4765 converted_vars = new Expression [var_list.Count];
4766 assign = new ExpressionStatement [var_list.Count];
4767 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4768 foreach (DictionaryEntry e in var_list){
4769 Expression var = (Expression) e.Key;
4771 var = var.ResolveLValue (ec, new EmptyExpression ());
4775 converted_vars [i] = Expression.ConvertImplicitRequired (
4776 ec, var, TypeManager.idisposable_type, loc);
4778 if (converted_vars [i] == null)
4786 foreach (DictionaryEntry e in var_list){
4787 LocalVariableReference var = (LocalVariableReference) e.Key;
4788 Expression new_expr = (Expression) e.Value;
4791 a = new Assign (var, new_expr, loc);
4797 converted_vars [i] = var;
4798 assign [i] = (ExpressionStatement) a;
4805 bool ResolveExpression (EmitContext ec)
4807 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4808 conv = Expression.ConvertImplicitRequired (
4809 ec, expr, TypeManager.idisposable_type, loc);
4819 // Emits the code for the case of using using a local variable declaration.
4821 bool EmitLocalVariableDecls (EmitContext ec)
4823 ILGenerator ig = ec.ig;
4826 bool old_in_try = ec.InTry;
4828 for (i = 0; i < assign.Length; i++) {
4829 assign [i].EmitStatement (ec);
4831 ig.BeginExceptionBlock ();
4833 Statement.Emit (ec);
4834 ec.InTry = old_in_try;
4836 bool old_in_finally = ec.InFinally;
4837 ec.InFinally = true;
4838 var_list.Reverse ();
4839 foreach (DictionaryEntry e in var_list){
4840 LocalVariableReference var = (LocalVariableReference) e.Key;
4841 Label skip = ig.DefineLabel ();
4844 ig.BeginFinallyBlock ();
4847 ig.Emit (OpCodes.Brfalse, skip);
4848 converted_vars [i].Emit (ec);
4849 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4850 ig.MarkLabel (skip);
4851 ig.EndExceptionBlock ();
4853 ec.InFinally = old_in_finally;
4858 bool EmitExpression (EmitContext ec)
4861 // Make a copy of the expression and operate on that.
4863 ILGenerator ig = ec.ig;
4864 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4869 ig.Emit (OpCodes.Stloc, local_copy);
4871 bool old_in_try = ec.InTry;
4873 ig.BeginExceptionBlock ();
4874 Statement.Emit (ec);
4875 ec.InTry = old_in_try;
4877 Label skip = ig.DefineLabel ();
4878 bool old_in_finally = ec.InFinally;
4879 ig.BeginFinallyBlock ();
4880 ig.Emit (OpCodes.Ldloc, local_copy);
4881 ig.Emit (OpCodes.Brfalse, skip);
4882 ig.Emit (OpCodes.Ldloc, local_copy);
4883 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4884 ig.MarkLabel (skip);
4885 ec.InFinally = old_in_finally;
4886 ig.EndExceptionBlock ();
4891 public override bool Resolve (EmitContext ec)
4893 if (expression_or_block is DictionaryEntry){
4894 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4895 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4897 if (!ResolveLocalVariableDecls (ec))
4900 } else if (expression_or_block is Expression){
4901 expr = (Expression) expression_or_block;
4903 expr = expr.Resolve (ec);
4907 expr_type = expr.Type;
4909 if (!ResolveExpression (ec))
4913 return Statement.Resolve (ec);
4916 protected override bool DoEmit (EmitContext ec)
4918 if (expression_or_block is DictionaryEntry)
4919 return EmitLocalVariableDecls (ec);
4920 else if (expression_or_block is Expression)
4921 return EmitExpression (ec);
4928 /// Implementation of the foreach C# statement
4930 public class Foreach : Statement {
4932 LocalVariableReference variable;
4934 Statement statement;
4935 ForeachHelperMethods hm;
4936 Expression empty, conv;
4937 Type array_type, element_type;
4940 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4941 Statement stmt, Location l)
4948 VariableInfo vi = var.VariableInfo;
4949 this.type = vi.Type;
4951 this.variable = var;
4957 public override bool Resolve (EmitContext ec)
4959 expr = expr.Resolve (ec);
4963 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4964 if (var_type == null)
4968 // We need an instance variable. Not sure this is the best
4969 // way of doing this.
4971 // FIXME: When we implement propertyaccess, will those turn
4972 // out to return values in ExprClass? I think they should.
4974 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4975 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4976 error1579 (expr.Type);
4980 if (expr.Type.IsArray) {
4981 array_type = expr.Type;
4982 element_type = array_type.GetElementType ();
4984 empty = new EmptyExpression (element_type);
4986 hm = ProbeCollectionType (ec, expr.Type);
4988 error1579 (expr.Type);
4992 array_type = expr.Type;
4993 element_type = hm.element_type;
4995 empty = new EmptyExpression (hm.element_type);
4998 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4999 ec.CurrentBranching.CreateSibling ();
5003 // FIXME: maybe we can apply the same trick we do in the
5004 // array handling to avoid creating empty and conv in some cases.
5006 // Although it is not as important in this case, as the type
5007 // will not likely be object (what the enumerator will return).
5009 conv = Expression.ConvertExplicit (ec, empty, var_type, false, loc);
5013 if (variable.ResolveLValue (ec, empty) == null)
5016 if (!statement.Resolve (ec))
5019 //FlowReturns returns = ec.EndFlowBranching ();
5025 // Retrieves a `public bool MoveNext ()' method from the Type `t'
5027 static MethodInfo FetchMethodMoveNext (Type t)
5029 MemberList move_next_list;
5031 move_next_list = TypeContainer.FindMembers (
5032 t, MemberTypes.Method,
5033 BindingFlags.Public | BindingFlags.Instance,
5034 Type.FilterName, "MoveNext");
5035 if (move_next_list.Count == 0)
5038 foreach (MemberInfo m in move_next_list){
5039 MethodInfo mi = (MethodInfo) m;
5042 args = TypeManager.GetArgumentTypes (mi);
5043 if (args != null && args.Length == 0){
5044 if (mi.ReturnType == TypeManager.bool_type)
5052 // Retrieves a `public T get_Current ()' method from the Type `t'
5054 static MethodInfo FetchMethodGetCurrent (Type t)
5056 MemberList move_next_list;
5058 move_next_list = TypeContainer.FindMembers (
5059 t, MemberTypes.Method,
5060 BindingFlags.Public | BindingFlags.Instance,
5061 Type.FilterName, "get_Current");
5062 if (move_next_list.Count == 0)
5065 foreach (MemberInfo m in move_next_list){
5066 MethodInfo mi = (MethodInfo) m;
5069 args = TypeManager.GetArgumentTypes (mi);
5070 if (args != null && args.Length == 0)
5077 // This struct records the helper methods used by the Foreach construct
5079 class ForeachHelperMethods {
5080 public EmitContext ec;
5081 public MethodInfo get_enumerator;
5082 public MethodInfo move_next;
5083 public MethodInfo get_current;
5084 public Type element_type;
5085 public Type enumerator_type;
5086 public bool is_disposable;
5088 public ForeachHelperMethods (EmitContext ec)
5091 this.element_type = TypeManager.object_type;
5092 this.enumerator_type = TypeManager.ienumerator_type;
5093 this.is_disposable = true;
5097 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5102 if (!(m is MethodInfo))
5105 if (m.Name != "GetEnumerator")
5108 MethodInfo mi = (MethodInfo) m;
5109 Type [] args = TypeManager.GetArgumentTypes (mi);
5111 if (args.Length != 0)
5114 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5115 EmitContext ec = hm.ec;
5118 // Check whether GetEnumerator is accessible to us
5120 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5122 Type declaring = mi.DeclaringType;
5123 if (prot == MethodAttributes.Private){
5124 if (declaring != ec.ContainerType)
5126 } else if (prot == MethodAttributes.FamANDAssem){
5127 // If from a different assembly, false
5128 if (!(mi is MethodBuilder))
5131 // Are we being invoked from the same class, or from a derived method?
5133 if (ec.ContainerType != declaring){
5134 if (!ec.ContainerType.IsSubclassOf (declaring))
5137 } else if (prot == MethodAttributes.FamORAssem){
5138 if (!(mi is MethodBuilder ||
5139 ec.ContainerType == declaring ||
5140 ec.ContainerType.IsSubclassOf (declaring)))
5142 } if (prot == MethodAttributes.Family){
5143 if (!(ec.ContainerType == declaring ||
5144 ec.ContainerType.IsSubclassOf (declaring)))
5149 // Ok, we can access it, now make sure that we can do something
5150 // with this `GetEnumerator'
5153 if (mi.ReturnType == TypeManager.ienumerator_type ||
5154 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5155 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5156 hm.move_next = TypeManager.bool_movenext_void;
5157 hm.get_current = TypeManager.object_getcurrent_void;
5162 // Ok, so they dont return an IEnumerable, we will have to
5163 // find if they support the GetEnumerator pattern.
5165 Type return_type = mi.ReturnType;
5167 hm.move_next = FetchMethodMoveNext (return_type);
5168 if (hm.move_next == null)
5170 hm.get_current = FetchMethodGetCurrent (return_type);
5171 if (hm.get_current == null)
5174 hm.element_type = hm.get_current.ReturnType;
5175 hm.enumerator_type = return_type;
5176 hm.is_disposable = TypeManager.ImplementsInterface (
5177 hm.enumerator_type, TypeManager.idisposable_type);
5183 /// This filter is used to find the GetEnumerator method
5184 /// on which IEnumerator operates
5186 static MemberFilter FilterEnumerator;
5190 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5193 void error1579 (Type t)
5195 Report.Error (1579, loc,
5196 "foreach statement cannot operate on variables of type `" +
5197 t.FullName + "' because that class does not provide a " +
5198 " GetEnumerator method or it is inaccessible");
5201 static bool TryType (Type t, ForeachHelperMethods hm)
5205 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5206 BindingFlags.Public | BindingFlags.NonPublic |
5207 BindingFlags.Instance,
5208 FilterEnumerator, hm);
5213 hm.get_enumerator = (MethodInfo) mi [0];
5218 // Looks for a usable GetEnumerator in the Type, and if found returns
5219 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5221 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5223 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5225 if (TryType (t, hm))
5229 // Now try to find the method in the interfaces
5232 Type [] ifaces = t.GetInterfaces ();
5234 foreach (Type i in ifaces){
5235 if (TryType (i, hm))
5240 // Since TypeBuilder.GetInterfaces only returns the interface
5241 // types for this type, we have to keep looping, but once
5242 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5243 // done, because it returns all the types
5245 if ((t is TypeBuilder))
5255 // FIXME: possible optimization.
5256 // We might be able to avoid creating `empty' if the type is the sam
5258 bool EmitCollectionForeach (EmitContext ec)
5260 ILGenerator ig = ec.ig;
5261 LocalBuilder enumerator, disposable;
5263 enumerator = ig.DeclareLocal (hm.enumerator_type);
5264 if (hm.is_disposable)
5265 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5270 // Instantiate the enumerator
5272 if (expr.Type.IsValueType){
5273 if (expr is IMemoryLocation){
5274 IMemoryLocation ml = (IMemoryLocation) expr;
5276 ml.AddressOf (ec, AddressOp.Load);
5278 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5279 " does not implement IMemoryLocation");
5280 ig.Emit (OpCodes.Call, hm.get_enumerator);
5283 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5285 ig.Emit (OpCodes.Stloc, enumerator);
5288 // Protect the code in a try/finalize block, so that
5289 // if the beast implement IDisposable, we get rid of it
5291 bool old_in_try = ec.InTry;
5293 if (hm.is_disposable)
5296 Label end_try = ig.DefineLabel ();
5298 ig.MarkLabel (ec.LoopBegin);
5299 ig.Emit (OpCodes.Ldloc, enumerator);
5300 ig.Emit (OpCodes.Callvirt, hm.move_next);
5301 ig.Emit (OpCodes.Brfalse, end_try);
5302 ig.Emit (OpCodes.Ldloc, enumerator);
5303 ig.Emit (OpCodes.Callvirt, hm.get_current);
5304 variable.EmitAssign (ec, conv);
5305 statement.Emit (ec);
5306 ig.Emit (OpCodes.Br, ec.LoopBegin);
5307 ig.MarkLabel (end_try);
5308 ec.InTry = old_in_try;
5310 // The runtime provides this for us.
5311 // ig.Emit (OpCodes.Leave, end);
5314 // Now the finally block
5316 if (hm.is_disposable) {
5317 Label end_finally = ig.DefineLabel ();
5318 bool old_in_finally = ec.InFinally;
5319 ec.InFinally = true;
5320 ig.BeginFinallyBlock ();
5322 ig.Emit (OpCodes.Ldloc, enumerator);
5323 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5324 ig.Emit (OpCodes.Stloc, disposable);
5325 ig.Emit (OpCodes.Ldloc, disposable);
5326 ig.Emit (OpCodes.Brfalse, end_finally);
5327 ig.Emit (OpCodes.Ldloc, disposable);
5328 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5329 ig.MarkLabel (end_finally);
5330 ec.InFinally = old_in_finally;
5332 // The runtime generates this anyways.
5333 // ig.Emit (OpCodes.Endfinally);
5335 ig.EndExceptionBlock ();
5338 ig.MarkLabel (ec.LoopEnd);
5343 // FIXME: possible optimization.
5344 // We might be able to avoid creating `empty' if the type is the sam
5346 bool EmitArrayForeach (EmitContext ec)
5348 int rank = array_type.GetArrayRank ();
5349 ILGenerator ig = ec.ig;
5351 LocalBuilder copy = ig.DeclareLocal (array_type);
5354 // Make our copy of the array
5357 ig.Emit (OpCodes.Stloc, copy);
5360 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5364 ig.Emit (OpCodes.Ldc_I4_0);
5365 ig.Emit (OpCodes.Stloc, counter);
5366 test = ig.DefineLabel ();
5367 ig.Emit (OpCodes.Br, test);
5369 loop = ig.DefineLabel ();
5370 ig.MarkLabel (loop);
5372 ig.Emit (OpCodes.Ldloc, copy);
5373 ig.Emit (OpCodes.Ldloc, counter);
5374 ArrayAccess.EmitLoadOpcode (ig, var_type);
5376 variable.EmitAssign (ec, conv);
5378 statement.Emit (ec);
5380 ig.MarkLabel (ec.LoopBegin);
5381 ig.Emit (OpCodes.Ldloc, counter);
5382 ig.Emit (OpCodes.Ldc_I4_1);
5383 ig.Emit (OpCodes.Add);
5384 ig.Emit (OpCodes.Stloc, counter);
5386 ig.MarkLabel (test);
5387 ig.Emit (OpCodes.Ldloc, counter);
5388 ig.Emit (OpCodes.Ldloc, copy);
5389 ig.Emit (OpCodes.Ldlen);
5390 ig.Emit (OpCodes.Conv_I4);
5391 ig.Emit (OpCodes.Blt, loop);
5393 LocalBuilder [] dim_len = new LocalBuilder [rank];
5394 LocalBuilder [] dim_count = new LocalBuilder [rank];
5395 Label [] loop = new Label [rank];
5396 Label [] test = new Label [rank];
5399 for (dim = 0; dim < rank; dim++){
5400 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5401 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5402 test [dim] = ig.DefineLabel ();
5403 loop [dim] = ig.DefineLabel ();
5406 for (dim = 0; dim < rank; dim++){
5407 ig.Emit (OpCodes.Ldloc, copy);
5408 IntLiteral.EmitInt (ig, dim);
5409 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5410 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5413 for (dim = 0; dim < rank; dim++){
5414 ig.Emit (OpCodes.Ldc_I4_0);
5415 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5416 ig.Emit (OpCodes.Br, test [dim]);
5417 ig.MarkLabel (loop [dim]);
5420 ig.Emit (OpCodes.Ldloc, copy);
5421 for (dim = 0; dim < rank; dim++)
5422 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5425 // FIXME: Maybe we can cache the computation of `get'?
5427 Type [] args = new Type [rank];
5430 for (int i = 0; i < rank; i++)
5431 args [i] = TypeManager.int32_type;
5433 ModuleBuilder mb = CodeGen.ModuleBuilder;
5434 get = mb.GetArrayMethod (
5436 CallingConventions.HasThis| CallingConventions.Standard,
5438 ig.Emit (OpCodes.Call, get);
5439 variable.EmitAssign (ec, conv);
5440 statement.Emit (ec);
5441 ig.MarkLabel (ec.LoopBegin);
5442 for (dim = rank - 1; dim >= 0; dim--){
5443 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5444 ig.Emit (OpCodes.Ldc_I4_1);
5445 ig.Emit (OpCodes.Add);
5446 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5448 ig.MarkLabel (test [dim]);
5449 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5450 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5451 ig.Emit (OpCodes.Blt, loop [dim]);
5454 ig.MarkLabel (ec.LoopEnd);
5459 protected override bool DoEmit (EmitContext ec)
5463 ILGenerator ig = ec.ig;
5465 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5466 bool old_inloop = ec.InLoop;
5467 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5468 ec.LoopBegin = ig.DefineLabel ();
5469 ec.LoopEnd = ig.DefineLabel ();
5471 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5474 ret_val = EmitCollectionForeach (ec);
5476 ret_val = EmitArrayForeach (ec);
5478 ec.LoopBegin = old_begin;
5479 ec.LoopEnd = old_end;
5480 ec.InLoop = old_inloop;
5481 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5488 /// AddHandler statement
5490 public class AddHandler : Statement {
5492 Expression EvtHandler;
5495 // keeps track whether EvtId is already resolved
5499 public AddHandler (Expression evt_id, Expression evt_handler, Location l)
5502 EvtHandler = evt_handler;
5505 //Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5508 public override bool Resolve (EmitContext ec)
5511 // if EvetId is of EventExpr type that means
5512 // this is already resolved
5514 if (EvtId is EventExpr) {
5519 EvtId = EvtId.Resolve(ec);
5520 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5521 if (EvtId == null || (!(EvtId is EventExpr))) {
5522 Report.Error (30676, "Need an event designator.");
5526 if (EvtHandler == null)
5528 Report.Error (999, "'AddHandler' statement needs an event handler.");
5535 protected override bool DoEmit (EmitContext ec)
5538 // Already resolved and emitted don't do anything
5544 ArrayList args = new ArrayList();
5545 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5550 // The even type was already resolved to a delegate, so
5551 // we must un-resolve its name to generate a type expression
5552 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5553 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5555 // which we can use to declare a new event handler
5557 d = new New (dtype, args, Location.Null);
5559 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5561 // we resolve it all and emit the code
5574 /// RemoveHandler statement
5576 public class RemoveHandler : Statement
\r
5579 Expression EvtHandler;
5581 public RemoveHandler (Expression evt_id, Expression evt_handler, Location l)
5584 EvtHandler = evt_handler;
5588 public override bool Resolve (EmitContext ec)
5590 EvtId = EvtId.Resolve(ec);
5591 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5592 if (EvtId == null || (!(EvtId is EventExpr)))
\r
5594 Report.Error (30676, "Need an event designator.");
5598 if (EvtHandler == null)
5600 Report.Error (999, "'AddHandler' statement needs an event handler.");
5606 protected override bool DoEmit (EmitContext ec)
5609 ArrayList args = new ArrayList();
5610 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5613 // The even type was already resolved to a delegate, so
5614 // we must un-resolve its name to generate a type expression
5615 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5616 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5618 // which we can use to declare a new event handler
5620 d = new New (dtype, args, Location.Null);
5623 e = new CompoundAssign(Binary.Operator.Subtraction, EvtId, d, Location.Null);
5625 // we resolve it all and emit the code
5637 public class RedimClause {
5638 public Expression Expr;
5639 public ArrayList NewIndexes;
5641 public RedimClause (Expression e, ArrayList args)
5648 public class ReDim : Statement {
5649 ArrayList RedimTargets;
5653 private StatementExpression ReDimExpr;
5655 public ReDim (ArrayList targets, bool opt_preserve, Location l)
5658 RedimTargets = targets;
5659 Preserve = opt_preserve;
5662 public override bool Resolve (EmitContext ec)
5664 Expression RedimTarget;
5665 ArrayList NewIndexes;
5667 foreach (RedimClause rc in RedimTargets) {
5668 RedimTarget = rc.Expr;
5669 NewIndexes = rc.NewIndexes;
5671 RedimTarget = RedimTarget.Resolve (ec);
5672 if (!RedimTarget.Type.IsArray)
5673 Report.Error (49, "'ReDim' statement requires an array");
5675 ArrayList args = new ArrayList();
5676 foreach (Argument a in NewIndexes) {
5677 if (a.Resolve(ec, loc))
5681 for (int x = 0; x < args.Count; x++) {
5682 args[x] = new Binary (Binary.Operator.Addition,
5683 (Expression) args[x], new IntLiteral (1), Location.Null);
5687 if (RedimTarget.Type.GetArrayRank() != args.Count)
5688 Report.Error (3415, "'ReDim' cannot change the number of dimensions of an array.");
5690 BaseType = RedimTarget.Type.GetElementType();
5691 Expression BaseTypeExpr = MonoBASIC.Parser.DecomposeQI(BaseType.FullName.ToString(), Location.Null);
5692 ArrayCreation acExpr = new ArrayCreation (BaseTypeExpr, NewIndexes, "", null, Location.Null);
5693 // TODO: we are in a foreach we probably can't reuse ReDimExpr, must turn it into an array(list)
5696 ExpressionStatement PreserveExpr = (ExpressionStatement) new Preserve(RedimTarget, acExpr, loc);
5697 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, PreserveExpr, loc), loc);
5700 ReDimExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (RedimTarget, acExpr, loc), loc);
5701 ReDimExpr.Resolve(ec);
5706 protected override bool DoEmit (EmitContext ec)
5714 public class Erase : Statement {
5715 Expression EraseTarget;
5717 private StatementExpression EraseExpr;
5719 public Erase (Expression expr, Location l)
5725 public override bool Resolve (EmitContext ec)
5727 EraseTarget = EraseTarget.Resolve (ec);
5728 if (!EraseTarget.Type.IsArray)
5729 Report.Error (49, "'Erase' statement requires an array");
5731 EraseExpr = (StatementExpression) new StatementExpression ((ExpressionStatement) new Assign (EraseTarget, NullLiteral.Null, loc), loc);
5732 EraseExpr.Resolve(ec);
5737 protected override bool DoEmit (EmitContext ec)