2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
8 // (C) 2001, 2002 Ximian, Inc.
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 using System.Collections;
21 public abstract class Statement {
25 /// Resolves the statement, true means that all sub-statements
28 public virtual bool Resolve (EmitContext ec)
34 /// Return value indicates whether all code paths emitted return.
36 protected abstract bool DoEmit (EmitContext ec);
39 /// Return value indicates whether all code paths emitted return.
41 public virtual bool Emit (EmitContext ec)
44 Report.Debug (8, "MARK", this, loc);
48 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
54 if (e.Type != TypeManager.bool_type){
55 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
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 BoolConstant bc = (BoolConstant) expr;
429 ig.MarkLabel (ec.LoopBegin);
431 ig.Emit (OpCodes.Br, ec.LoopBegin);
434 // Inform that we are infinite (ie, `we return'), only
435 // if we do not `break' inside the code.
437 ret = may_return == false;
438 ig.MarkLabel (ec.LoopEnd);
440 Label while_loop = ig.DefineLabel ();
442 ig.Emit (OpCodes.Br, ec.LoopBegin);
443 ig.MarkLabel (while_loop);
447 ig.MarkLabel (ec.LoopBegin);
449 EmitBoolExpression (ec, expr, while_loop, true);
450 ig.MarkLabel (ec.LoopEnd);
455 ec.LoopBegin = old_begin;
456 ec.LoopEnd = old_end;
457 ec.InLoop = old_inloop;
458 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
464 public class For : Statement {
466 readonly Statement InitStatement;
467 readonly Statement Increment;
468 readonly Statement Statement;
469 bool may_return, infinite, empty;
471 public For (Statement initStatement,
477 InitStatement = initStatement;
479 Increment = increment;
480 Statement = statement;
485 public override bool Resolve (EmitContext ec)
489 if (InitStatement != null){
490 if (!InitStatement.Resolve (ec))
495 Test = ResolveBoolean (ec, Test, loc);
498 else if (Test is BoolConstant){
499 BoolConstant bc = (BoolConstant) Test;
501 if (bc.Value == false){
502 Warning_DeadCodeFound (Statement.loc);
510 if (Increment != null){
511 if (!Increment.Resolve (ec))
515 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
517 ec.CurrentBranching.CreateSibling ();
519 if (!Statement.Resolve (ec))
523 ec.KillFlowBranching ();
525 ec.CurrentBranching.Infinite = infinite;
526 FlowReturns returns = ec.EndFlowBranching ();
527 may_return = returns != FlowReturns.NEVER;
533 protected override bool DoEmit (EmitContext ec)
538 ILGenerator ig = ec.ig;
539 Label old_begin = ec.LoopBegin;
540 Label old_end = ec.LoopEnd;
541 bool old_inloop = ec.InLoop;
542 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
543 Label loop = ig.DefineLabel ();
544 Label test = ig.DefineLabel ();
546 if (InitStatement != null)
547 if (! (InitStatement is EmptyStatement))
548 InitStatement.Emit (ec);
550 ec.LoopBegin = ig.DefineLabel ();
551 ec.LoopEnd = ig.DefineLabel ();
553 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
555 ig.Emit (OpCodes.Br, test);
559 ig.MarkLabel (ec.LoopBegin);
560 if (!(Increment is EmptyStatement))
565 // If test is null, there is no test, and we are just
569 EmitBoolExpression (ec, Test, loop, true);
571 ig.Emit (OpCodes.Br, loop);
572 ig.MarkLabel (ec.LoopEnd);
574 ec.LoopBegin = old_begin;
575 ec.LoopEnd = old_end;
576 ec.InLoop = old_inloop;
577 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
580 // Inform whether we are infinite or not
583 if (Test is BoolConstant){
584 BoolConstant bc = (BoolConstant) Test;
587 return may_return == false;
591 return may_return == false;
595 public class StatementExpression : Statement {
598 public StatementExpression (ExpressionStatement expr, Location l)
604 public override bool Resolve (EmitContext ec)
606 expr = (Expression) expr.Resolve (ec);
610 protected override bool DoEmit (EmitContext ec)
612 ILGenerator ig = ec.ig;
614 if (expr is ExpressionStatement)
615 ((ExpressionStatement) expr).EmitStatement (ec);
618 ig.Emit (OpCodes.Pop);
624 public override string ToString ()
626 return "StatementExpression (" + expr + ")";
631 /// Implements the return statement
633 public class Return : Statement {
634 public Expression Expr;
636 public Return (Expression expr, Location l)
642 public override bool Resolve (EmitContext ec)
645 Expr = Expr.Resolve (ec);
650 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
652 if (ec.CurrentBranching.InTryBlock ())
653 ec.CurrentBranching.AddFinallyVector (vector);
655 vector.CheckOutParameters (ec.CurrentBranching);
657 vector.Returns = FlowReturns.ALWAYS;
658 vector.Breaks = FlowReturns.ALWAYS;
662 protected override bool DoEmit (EmitContext ec)
665 Report.Error (157,loc,"Control can not leave the body of the finally block");
669 if (ec.ReturnType == null){
671 Report.Error (127, loc, "Return with a value not allowed here");
676 Report.Error (126, loc, "An object of type `" +
677 TypeManager.CSharpName (ec.ReturnType) + "' is " +
678 "expected for the return statement");
682 if (Expr.Type != ec.ReturnType)
683 Expr = Expression.ConvertImplicitRequired (
684 ec, Expr, ec.ReturnType, loc);
691 if (ec.InTry || ec.InCatch)
692 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
695 if (ec.InTry || ec.InCatch) {
696 if (!ec.HasReturnLabel) {
697 ec.ReturnLabel = ec.ig.DefineLabel ();
698 ec.HasReturnLabel = true;
700 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
702 ec.ig.Emit (OpCodes.Ret);
708 public class Goto : Statement {
711 LabeledStatement label;
713 public override bool Resolve (EmitContext ec)
715 label = block.LookupLabel (target);
719 "No such label `" + target + "' in this scope");
723 // If this is a forward goto.
724 if (!label.IsDefined)
725 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
727 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
732 public Goto (Block parent_block, string label, Location l)
734 block = parent_block;
739 public string Target {
745 protected override bool DoEmit (EmitContext ec)
747 Label l = label.LabelTarget (ec);
748 ec.ig.Emit (OpCodes.Br, l);
754 public class LabeledStatement : Statement {
755 public readonly Location Location;
763 public LabeledStatement (string label_name, Location l)
765 this.label_name = label_name;
769 public Label LabelTarget (EmitContext ec)
773 label = ec.ig.DefineLabel ();
779 public bool IsDefined {
785 public bool HasBeenReferenced {
791 public void AddUsageVector (FlowBranching.UsageVector vector)
794 vectors = new ArrayList ();
796 vectors.Add (vector.Clone ());
799 public override bool Resolve (EmitContext ec)
802 ec.CurrentBranching.CurrentUsageVector.MergeJumpOrigins (vectors);
804 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.NEVER;
805 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.NEVER;
813 protected override bool DoEmit (EmitContext ec)
816 ec.ig.MarkLabel (label);
824 /// `goto default' statement
826 public class GotoDefault : Statement {
828 public GotoDefault (Location l)
833 public override bool Resolve (EmitContext ec)
835 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
839 protected override bool DoEmit (EmitContext ec)
841 if (ec.Switch == null){
842 Report.Error (153, loc, "goto default is only valid in a switch statement");
846 if (!ec.Switch.GotDefault){
847 Report.Error (159, loc, "No default target on switch statement");
850 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
856 /// `goto case' statement
858 public class GotoCase : Statement {
862 public GotoCase (Expression e, Location l)
868 public override bool Resolve (EmitContext ec)
870 if (ec.Switch == null){
871 Report.Error (153, loc, "goto case is only valid in a switch statement");
875 expr = expr.Resolve (ec);
879 if (!(expr is Constant)){
880 Report.Error (159, loc, "Target expression for goto case is not constant");
884 object val = Expression.ConvertIntLiteral (
885 (Constant) expr, ec.Switch.SwitchType, loc);
890 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
895 "No such label 'case " + val + "': for the goto case");
898 label = sl.ILLabelCode;
900 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.UNREACHABLE;
904 protected override bool DoEmit (EmitContext ec)
906 ec.ig.Emit (OpCodes.Br, label);
911 public class Throw : Statement {
914 public Throw (Expression expr, Location l)
920 public override bool Resolve (EmitContext ec)
923 expr = expr.Resolve (ec);
927 ExprClass eclass = expr.eclass;
929 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
930 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
931 expr.Error118 ("value, variable, property or indexer access ");
937 if ((t != TypeManager.exception_type) &&
938 !t.IsSubclassOf (TypeManager.exception_type) &&
939 !(expr is NullLiteral)) {
940 Report.Error (155, loc,
941 "The type caught or thrown must be derived " +
942 "from System.Exception");
947 ec.CurrentBranching.CurrentUsageVector.Returns = FlowReturns.EXCEPTION;
948 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.EXCEPTION;
952 protected override bool DoEmit (EmitContext ec)
956 ec.ig.Emit (OpCodes.Rethrow);
960 "A throw statement with no argument is only " +
961 "allowed in a catch clause");
968 ec.ig.Emit (OpCodes.Throw);
974 public class Break : Statement {
976 public Break (Location l)
981 public override bool Resolve (EmitContext ec)
983 ec.CurrentBranching.MayLeaveLoop = true;
984 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
988 protected override bool DoEmit (EmitContext ec)
990 ILGenerator ig = ec.ig;
992 if (ec.InLoop == false && ec.Switch == null){
993 Report.Error (139, loc, "No enclosing loop or switch to continue to");
997 if (ec.InTry || ec.InCatch)
998 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1000 ig.Emit (OpCodes.Br, ec.LoopEnd);
1006 public enum ExitType {
1017 public class Exit : Statement {
1018 public readonly ExitType type;
1019 public Exit (ExitType t, Location l)
1025 public override bool Resolve (EmitContext ec)
1027 ec.CurrentBranching.MayLeaveLoop = true;
1028 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1032 protected override bool DoEmit (EmitContext ec)
1034 ILGenerator ig = ec.ig;
1036 if (ec.InLoop == false && ec.Switch == null){
1037 Report.Error (139, loc, "No enclosing loop or switch to continue to");
1041 if (ec.InTry || ec.InCatch)
1042 ig.Emit (OpCodes.Leave, ec.LoopEnd);
1044 ig.Emit (OpCodes.Br, ec.LoopEnd);
1050 public class Continue : Statement {
1052 public Continue (Location l)
1057 public override bool Resolve (EmitContext ec)
1059 ec.CurrentBranching.CurrentUsageVector.Breaks = FlowReturns.ALWAYS;
1063 protected override bool DoEmit (EmitContext ec)
1065 Label begin = ec.LoopBegin;
1068 Report.Error (139, loc, "No enclosing loop to continue to");
1073 // UGH: Non trivial. This Br might cross a try/catch boundary
1077 // try { ... } catch { continue; }
1081 // try {} catch { while () { continue; }}
1083 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
1084 ec.ig.Emit (OpCodes.Leave, begin);
1085 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
1086 throw new Exception ("Should never happen");
1088 ec.ig.Emit (OpCodes.Br, begin);
1094 // This is used in the control flow analysis code to specify whether the
1095 // current code block may return to its enclosing block before reaching
1098 public enum FlowReturns {
1099 // It can never return.
1102 // This means that the block contains a conditional return statement
1106 // The code always returns, ie. there's an unconditional return / break
1110 // The code always throws an exception.
1113 // The current code block is unreachable. This happens if it's immediately
1114 // following a FlowReturns.ALWAYS block.
1119 // This is a special bit vector which can inherit from another bit vector doing a
1120 // copy-on-write strategy. The inherited vector may have a smaller size than the
1123 public class MyBitVector {
1124 public readonly int Count;
1125 public readonly MyBitVector InheritsFrom;
1130 public MyBitVector (int Count)
1131 : this (null, Count)
1134 public MyBitVector (MyBitVector InheritsFrom, int Count)
1136 this.InheritsFrom = InheritsFrom;
1141 // Checks whether this bit vector has been modified. After setting this to true,
1142 // we won't use the inherited vector anymore, but our own copy of it.
1144 public bool IsDirty {
1151 initialize_vector ();
1156 // Get/set bit `index' in the bit vector.
1158 public bool this [int index]
1162 throw new ArgumentOutOfRangeException ();
1164 // We're doing a "copy-on-write" strategy here; as long
1165 // as nobody writes to the array, we can use our parent's
1166 // copy instead of duplicating the vector.
1169 return vector [index];
1170 else if (InheritsFrom != null) {
1171 BitArray inherited = InheritsFrom.Vector;
1173 if (index < inherited.Count)
1174 return inherited [index];
1183 throw new ArgumentOutOfRangeException ();
1185 // Only copy the vector if we're actually modifying it.
1187 if (this [index] != value) {
1188 initialize_vector ();
1190 vector [index] = value;
1196 // If you explicitly convert the MyBitVector to a BitArray, you will get a deep
1197 // copy of the bit vector.
1199 public static explicit operator BitArray (MyBitVector vector)
1201 vector.initialize_vector ();
1202 return vector.Vector;
1206 // Performs an `or' operation on the bit vector. The `new_vector' may have a
1207 // different size than the current one.
1209 public void Or (MyBitVector new_vector)
1211 BitArray new_array = new_vector.Vector;
1213 initialize_vector ();
1216 if (vector.Count < new_array.Count)
1217 upper = vector.Count;
1219 upper = new_array.Count;
1221 for (int i = 0; i < upper; i++)
1222 vector [i] = vector [i] | new_array [i];
1226 // Perfonrms an `and' operation on the bit vector. The `new_vector' may have
1227 // a different size than the current one.
1229 public void And (MyBitVector new_vector)
1231 BitArray new_array = new_vector.Vector;
1233 initialize_vector ();
1236 if (vector.Count < new_array.Count)
1237 lower = upper = vector.Count;
1239 lower = new_array.Count;
1240 upper = vector.Count;
1243 for (int i = 0; i < lower; i++)
1244 vector [i] = vector [i] & new_array [i];
1246 for (int i = lower; i < upper; i++)
1251 // This does a deep copy of the bit vector.
1253 public MyBitVector Clone ()
1255 MyBitVector retval = new MyBitVector (Count);
1257 retval.Vector = Vector;
1266 else if (!is_dirty && (InheritsFrom != null))
1267 return InheritsFrom.Vector;
1269 initialize_vector ();
1275 initialize_vector ();
1277 for (int i = 0; i < Math.Min (vector.Count, value.Count); i++)
1278 vector [i] = value [i];
1282 void initialize_vector ()
1287 vector = new BitArray (Count, false);
1288 if (InheritsFrom != null)
1289 Vector = InheritsFrom.Vector;
1294 public override string ToString ()
1296 StringBuilder sb = new StringBuilder ("MyBitVector (");
1298 BitArray vector = Vector;
1302 sb.Append ("INHERITED - ");
1303 for (int i = 0; i < vector.Count; i++) {
1306 sb.Append (vector [i]);
1310 return sb.ToString ();
1315 // The type of a FlowBranching.
1317 public enum FlowBranchingType {
1318 // Normal (conditional or toplevel) block.
1335 // A new instance of this class is created every time a new block is resolved
1336 // and if there's branching in the block's control flow.
1338 public class FlowBranching {
1340 // The type of this flow branching.
1342 public readonly FlowBranchingType Type;
1345 // The block this branching is contained in. This may be null if it's not
1346 // a top-level block and it doesn't declare any local variables.
1348 public readonly Block Block;
1351 // The parent of this branching or null if this is the top-block.
1353 public readonly FlowBranching Parent;
1356 // Start-Location of this flow branching.
1358 public readonly Location Location;
1361 // A list of UsageVectors. A new vector is added each time control flow may
1362 // take a different path.
1364 public ArrayList Siblings;
1367 // If this is an infinite loop.
1369 public bool Infinite;
1372 // If we may leave the current loop.
1374 public bool MayLeaveLoop;
1379 InternalParameters param_info;
1381 MyStructInfo[] struct_params;
1383 ArrayList finally_vectors;
1385 static int next_id = 0;
1389 // Performs an `And' operation on the FlowReturns status
1390 // (for instance, a block only returns ALWAYS if all its siblings
1393 public static FlowReturns AndFlowReturns (FlowReturns a, FlowReturns b)
1395 if (b == FlowReturns.UNREACHABLE)
1399 case FlowReturns.NEVER:
1400 if (b == FlowReturns.NEVER)
1401 return FlowReturns.NEVER;
1403 return FlowReturns.SOMETIMES;
1405 case FlowReturns.SOMETIMES:
1406 return FlowReturns.SOMETIMES;
1408 case FlowReturns.ALWAYS:
1409 if ((b == FlowReturns.ALWAYS) || (b == FlowReturns.EXCEPTION))
1410 return FlowReturns.ALWAYS;
1412 return FlowReturns.SOMETIMES;
1414 case FlowReturns.EXCEPTION:
1415 if (b == FlowReturns.EXCEPTION)
1416 return FlowReturns.EXCEPTION;
1417 else if (b == FlowReturns.ALWAYS)
1418 return FlowReturns.ALWAYS;
1420 return FlowReturns.SOMETIMES;
1427 // The vector contains a BitArray with information about which local variables
1428 // and parameters are already initialized at the current code position.
1430 public class UsageVector {
1432 // If this is true, then the usage vector has been modified and must be
1433 // merged when we're done with this branching.
1435 public bool IsDirty;
1438 // The number of parameters in this block.
1440 public readonly int CountParameters;
1443 // The number of locals in this block.
1445 public readonly int CountLocals;
1448 // If not null, then we inherit our state from this vector and do a
1449 // copy-on-write. If null, then we're the first sibling in a top-level
1450 // block and inherit from the empty vector.
1452 public readonly UsageVector InheritsFrom;
1457 MyBitVector locals, parameters;
1458 FlowReturns real_returns, real_breaks;
1461 static int next_id = 0;
1465 // Normally, you should not use any of these constructors.
1467 public UsageVector (UsageVector parent, int num_params, int num_locals)
1469 this.InheritsFrom = parent;
1470 this.CountParameters = num_params;
1471 this.CountLocals = num_locals;
1472 this.real_returns = FlowReturns.NEVER;
1473 this.real_breaks = FlowReturns.NEVER;
1475 if (parent != null) {
1476 locals = new MyBitVector (parent.locals, CountLocals);
1478 parameters = new MyBitVector (parent.parameters, num_params);
1479 real_returns = parent.Returns;
1480 real_breaks = parent.Breaks;
1482 locals = new MyBitVector (null, CountLocals);
1484 parameters = new MyBitVector (null, num_params);
1490 public UsageVector (UsageVector parent)
1491 : this (parent, parent.CountParameters, parent.CountLocals)
1495 // This does a deep copy of the usage vector.
1497 public UsageVector Clone ()
1499 UsageVector retval = new UsageVector (null, CountParameters, CountLocals);
1501 retval.locals = locals.Clone ();
1502 if (parameters != null)
1503 retval.parameters = parameters.Clone ();
1504 retval.real_returns = real_returns;
1505 retval.real_breaks = real_breaks;
1511 // State of parameter `number'.
1513 public bool this [int number]
1518 else if (number == 0)
1519 throw new ArgumentException ();
1521 return parameters [number - 1];
1527 else if (number == 0)
1528 throw new ArgumentException ();
1530 parameters [number - 1] = value;
1535 // State of the local variable `vi'.
1536 // If the local variable is a struct, use a non-zero `field_idx'
1537 // to check an individual field in it.
1539 public bool this [VariableInfo vi, int field_idx]
1542 if (vi.Number == -1)
1544 else if (vi.Number == 0)
1545 throw new ArgumentException ();
1547 return locals [vi.Number + field_idx - 1];
1551 if (vi.Number == -1)
1553 else if (vi.Number == 0)
1554 throw new ArgumentException ();
1556 locals [vi.Number + field_idx - 1] = value;
1561 // Specifies when the current block returns.
1562 // If this is FlowReturns.UNREACHABLE, then control can never reach the
1563 // end of the method (so that we don't need to emit a return statement).
1564 // The same applies for FlowReturns.EXCEPTION, but in this case the return
1565 // value will never be used.
1567 public FlowReturns Returns {
1569 return real_returns;
1573 real_returns = value;
1578 // Specifies whether control may return to our containing block
1579 // before reaching the end of this block. This happens if there
1580 // is a break/continue/goto/return in it.
1581 // This can also be used to find out whether the statement immediately
1582 // following the current block may be reached or not.
1584 public FlowReturns Breaks {
1590 real_breaks = value;
1594 public bool AlwaysBreaks {
1596 return (Breaks == FlowReturns.ALWAYS) ||
1597 (Breaks == FlowReturns.EXCEPTION) ||
1598 (Breaks == FlowReturns.UNREACHABLE);
1602 public bool MayBreak {
1604 return Breaks != FlowReturns.NEVER;
1608 public bool AlwaysReturns {
1610 return (Returns == FlowReturns.ALWAYS) ||
1611 (Returns == FlowReturns.EXCEPTION);
1615 public bool MayReturn {
1617 return (Returns == FlowReturns.SOMETIMES) ||
1618 (Returns == FlowReturns.ALWAYS);
1623 // Merge a child branching.
1625 public FlowReturns MergeChildren (FlowBranching branching, ICollection children)
1627 MyBitVector new_locals = null;
1628 MyBitVector new_params = null;
1630 FlowReturns new_returns = FlowReturns.NEVER;
1631 FlowReturns new_breaks = FlowReturns.NEVER;
1632 bool new_returns_set = false, new_breaks_set = false;
1634 Report.Debug (2, "MERGING CHILDREN", branching, branching.Type,
1635 this, children.Count);
1637 foreach (UsageVector child in children) {
1638 Report.Debug (2, " MERGING CHILD", child, child.is_finally);
1640 if (!child.is_finally) {
1641 if (child.Breaks != FlowReturns.UNREACHABLE) {
1642 // If Returns is already set, perform an
1643 // `And' operation on it, otherwise just set just.
1644 if (!new_returns_set) {
1645 new_returns = child.Returns;
1646 new_returns_set = true;
1648 new_returns = AndFlowReturns (
1649 new_returns, child.Returns);
1652 // If Breaks is already set, perform an
1653 // `And' operation on it, otherwise just set just.
1654 if (!new_breaks_set) {
1655 new_breaks = child.Breaks;
1656 new_breaks_set = true;
1658 new_breaks = AndFlowReturns (
1659 new_breaks, child.Breaks);
1662 // Ignore unreachable children.
1663 if (child.Returns == FlowReturns.UNREACHABLE)
1666 // A local variable is initialized after a flow branching if it
1667 // has been initialized in all its branches which do neither
1668 // always return or always throw an exception.
1670 // If a branch may return, but does not always return, then we
1671 // can treat it like a never-returning branch here: control will
1672 // only reach the code position after the branching if we did not
1675 // It's important to distinguish between always and sometimes
1676 // returning branches here:
1679 // 2 if (something) {
1683 // 6 Console.WriteLine (a);
1685 // The if block in lines 3-4 always returns, so we must not look
1686 // at the initialization of `a' in line 4 - thus it'll still be
1687 // uninitialized in line 6.
1689 // On the other hand, the following is allowed:
1696 // 6 Console.WriteLine (a);
1698 // Here, `a' is initialized in line 3 and we must not look at
1699 // line 5 since it always returns.
1701 if (child.is_finally) {
1702 if (new_locals == null)
1703 new_locals = locals.Clone ();
1704 new_locals.Or (child.locals);
1706 if (parameters != null) {
1707 if (new_params == null)
1708 new_params = parameters.Clone ();
1709 new_params.Or (child.parameters);
1713 if (!child.AlwaysReturns && !child.AlwaysBreaks) {
1714 if (new_locals != null)
1715 new_locals.And (child.locals);
1717 new_locals = locals.Clone ();
1718 new_locals.Or (child.locals);
1720 } else if (children.Count == 1) {
1721 new_locals = locals.Clone ();
1722 new_locals.Or (child.locals);
1725 // An `out' parameter must be assigned in all branches which do
1726 // not always throw an exception.
1727 if (parameters != null) {
1728 if (child.Breaks != FlowReturns.EXCEPTION) {
1729 if (new_params != null)
1730 new_params.And (child.parameters);
1732 new_params = parameters.Clone ();
1733 new_params.Or (child.parameters);
1735 } else if (children.Count == 1) {
1736 new_params = parameters.Clone ();
1737 new_params.Or (child.parameters);
1743 Returns = new_returns;
1744 if ((branching.Type == FlowBranchingType.BLOCK) ||
1745 (branching.Type == FlowBranchingType.EXCEPTION) ||
1746 (new_breaks == FlowReturns.UNREACHABLE) ||
1747 (new_breaks == FlowReturns.EXCEPTION))
1748 Breaks = new_breaks;
1749 else if (branching.Type == FlowBranchingType.SWITCH_SECTION)
1750 Breaks = new_returns;
1751 else if (branching.Type == FlowBranchingType.SWITCH){
1752 if (new_breaks == FlowReturns.ALWAYS)
1753 Breaks = FlowReturns.ALWAYS;
1757 // We've now either reached the point after the branching or we will
1758 // never get there since we always return or always throw an exception.
1760 // If we can reach the point after the branching, mark all locals and
1761 // parameters as initialized which have been initialized in all branches
1762 // we need to look at (see above).
1765 if (((new_breaks != FlowReturns.ALWAYS) &&
1766 (new_breaks != FlowReturns.EXCEPTION) &&
1767 (new_breaks != FlowReturns.UNREACHABLE)) ||
1768 (children.Count == 1)) {
1769 if (new_locals != null)
1770 locals.Or (new_locals);
1772 if (new_params != null)
1773 parameters.Or (new_params);
1776 Report.Debug (2, "MERGING CHILDREN DONE", branching.Type,
1777 new_params, new_locals, new_returns, new_breaks,
1778 branching.Infinite, branching.MayLeaveLoop, this);
1780 if (branching.Type == FlowBranchingType.SWITCH_SECTION) {
1781 if ((new_breaks != FlowReturns.ALWAYS) &&
1782 (new_breaks != FlowReturns.EXCEPTION) &&
1783 (new_breaks != FlowReturns.UNREACHABLE))
1784 Report.Error (163, branching.Location,
1785 "Control cannot fall through from one " +
1786 "case label to another");
1789 if (branching.Infinite && !branching.MayLeaveLoop) {
1790 Report.Debug (1, "INFINITE", new_returns, new_breaks,
1791 Returns, Breaks, this);
1793 // We're actually infinite.
1794 if (new_returns == FlowReturns.NEVER) {
1795 Breaks = FlowReturns.UNREACHABLE;
1796 return FlowReturns.UNREACHABLE;
1799 // If we're an infinite loop and do not break, the code after
1800 // the loop can never be reached. However, if we may return
1801 // from the loop, then we do always return (or stay in the loop
1803 if ((new_returns == FlowReturns.SOMETIMES) ||
1804 (new_returns == FlowReturns.ALWAYS)) {
1805 Returns = FlowReturns.ALWAYS;
1806 return FlowReturns.ALWAYS;
1814 // Tells control flow analysis that the current code position may be reached with
1815 // a forward jump from any of the origins listed in `origin_vectors' which is a
1816 // list of UsageVectors.
1818 // This is used when resolving forward gotos - in the following example, the
1819 // variable `a' is uninitialized in line 8 becase this line may be reached via
1820 // the goto in line 4:
1830 // 8 Console.WriteLine (a);
1833 public void MergeJumpOrigins (ICollection origin_vectors)
1835 Report.Debug (1, "MERGING JUMP ORIGIN", this);
1837 real_breaks = FlowReturns.NEVER;
1838 real_returns = FlowReturns.NEVER;
1840 foreach (UsageVector vector in origin_vectors) {
1841 Report.Debug (1, " MERGING JUMP ORIGIN", vector);
1843 locals.And (vector.locals);
1844 if (parameters != null)
1845 parameters.And (vector.parameters);
1846 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1847 Returns = AndFlowReturns (Returns, vector.Returns);
1850 Report.Debug (1, "MERGING JUMP ORIGIN DONE", this);
1854 // This is used at the beginning of a finally block if there were
1855 // any return statements in the try block or one of the catch blocks.
1857 public void MergeFinallyOrigins (ICollection finally_vectors)
1859 Report.Debug (1, "MERGING FINALLY ORIGIN", this);
1861 real_breaks = FlowReturns.NEVER;
1863 foreach (UsageVector vector in finally_vectors) {
1864 Report.Debug (1, " MERGING FINALLY ORIGIN", vector);
1866 if (parameters != null)
1867 parameters.And (vector.parameters);
1868 Breaks = AndFlowReturns (Breaks, vector.Breaks);
1873 Report.Debug (1, "MERGING FINALLY ORIGIN DONE", this);
1876 public void CheckOutParameters (FlowBranching branching)
1878 if (parameters != null)
1879 branching.CheckOutParameters (parameters, branching.Location);
1883 // Performs an `or' operation on the locals and the parameters.
1885 public void Or (UsageVector new_vector)
1887 locals.Or (new_vector.locals);
1888 if (parameters != null)
1889 parameters.Or (new_vector.parameters);
1893 // Performs an `and' operation on the locals.
1895 public void AndLocals (UsageVector new_vector)
1897 locals.And (new_vector.locals);
1901 // Returns a deep copy of the parameters.
1903 public MyBitVector Parameters {
1905 if (parameters != null)
1906 return parameters.Clone ();
1913 // Returns a deep copy of the locals.
1915 public MyBitVector Locals {
1917 return locals.Clone ();
1925 public override string ToString ()
1927 StringBuilder sb = new StringBuilder ();
1929 sb.Append ("Vector (");
1932 sb.Append (Returns);
1935 if (parameters != null) {
1937 sb.Append (parameters);
1943 return sb.ToString ();
1947 FlowBranching (FlowBranchingType type, Location loc)
1949 this.Siblings = new ArrayList ();
1951 this.Location = loc;
1957 // Creates a new flow branching for `block'.
1958 // This is used from Block.Resolve to create the top-level branching of
1961 public FlowBranching (Block block, InternalParameters ip, Location loc)
1962 : this (FlowBranchingType.BLOCK, loc)
1967 int count = (ip != null) ? ip.Count : 0;
1970 param_map = new int [count];
1971 struct_params = new MyStructInfo [count];
1974 for (int i = 0; i < count; i++) {
1975 Parameter.Modifier mod = param_info.ParameterModifier (i);
1977 if ((mod & Parameter.Modifier.OUT) == 0)
1980 param_map [i] = ++num_params;
1982 Type param_type = param_info.ParameterType (i);
1984 struct_params [i] = MyStructInfo.GetStructInfo (param_type);
1985 if (struct_params [i] != null)
1986 num_params += struct_params [i].Count;
1989 Siblings = new ArrayList ();
1990 Siblings.Add (new UsageVector (null, num_params, block.CountVariables));
1994 // Creates a new flow branching which is contained in `parent'.
1995 // You should only pass non-null for the `block' argument if this block
1996 // introduces any new variables - in this case, we need to create a new
1997 // usage vector with a different size than our parent's one.
1999 public FlowBranching (FlowBranching parent, FlowBranchingType type,
2000 Block block, Location loc)
2006 if (parent != null) {
2007 param_info = parent.param_info;
2008 param_map = parent.param_map;
2009 struct_params = parent.struct_params;
2010 num_params = parent.num_params;
2015 vector = new UsageVector (parent.CurrentUsageVector, num_params,
2016 Block.CountVariables);
2018 vector = new UsageVector (Parent.CurrentUsageVector);
2020 Siblings.Add (vector);
2023 case FlowBranchingType.EXCEPTION:
2024 finally_vectors = new ArrayList ();
2033 // Returns the branching's current usage vector.
2035 public UsageVector CurrentUsageVector
2038 return (UsageVector) Siblings [Siblings.Count - 1];
2043 // Creates a sibling of the current usage vector.
2045 public void CreateSibling ()
2047 Siblings.Add (new UsageVector (Parent.CurrentUsageVector));
2049 Report.Debug (1, "CREATED SIBLING", CurrentUsageVector);
2053 // Creates a sibling for a `finally' block.
2055 public void CreateSiblingForFinally ()
2057 if (Type != FlowBranchingType.EXCEPTION)
2058 throw new NotSupportedException ();
2062 CurrentUsageVector.MergeFinallyOrigins (finally_vectors);
2066 // Check whether all `out' parameters have been assigned.
2068 public void CheckOutParameters (MyBitVector parameters, Location loc)
2073 for (int i = 0; i < param_map.Length; i++) {
2074 int index = param_map [i];
2079 if (parameters [index - 1])
2082 // If it's a struct, we must ensure that all its fields have
2083 // been assigned. If the struct has any non-public fields, this
2084 // can only be done by assigning the whole struct.
2086 MyStructInfo struct_info = struct_params [index - 1];
2087 if ((struct_info == null) || struct_info.HasNonPublicFields) {
2089 177, loc, "The out parameter `" +
2090 param_info.ParameterName (i) + "' must be " +
2091 "assigned before control leave the current method.");
2097 for (int j = 0; j < struct_info.Count; j++) {
2098 if (!parameters [index + j]) {
2100 177, loc, "The out parameter `" +
2101 param_info.ParameterName (i) + "' must be " +
2102 "assigned before control leave the current method.");
2111 // Merge a child branching.
2113 public FlowReturns MergeChild (FlowBranching child)
2115 FlowReturns returns = CurrentUsageVector.MergeChildren (child, child.Siblings);
2117 if (child.Type != FlowBranchingType.LOOP_BLOCK)
2118 MayLeaveLoop |= child.MayLeaveLoop;
2120 MayLeaveLoop = false;
2126 // Does the toplevel merging.
2128 public FlowReturns MergeTopBlock ()
2130 if ((Type != FlowBranchingType.BLOCK) || (Block == null))
2131 throw new NotSupportedException ();
2133 UsageVector vector = new UsageVector (null, num_params, Block.CountVariables);
2135 Report.Debug (1, "MERGING TOP BLOCK", Location, vector);
2137 vector.MergeChildren (this, Siblings);
2140 Siblings.Add (vector);
2142 Report.Debug (1, "MERGING TOP BLOCK DONE", Location, vector);
2144 if (vector.Breaks != FlowReturns.EXCEPTION) {
2145 if (!vector.AlwaysBreaks)
2146 CheckOutParameters (CurrentUsageVector.Parameters, Location);
2147 return vector.AlwaysBreaks ? FlowReturns.ALWAYS : vector.Returns;
2149 return FlowReturns.EXCEPTION;
2152 public bool InTryBlock ()
2154 if (finally_vectors != null)
2156 else if (Parent != null)
2157 return Parent.InTryBlock ();
2162 public void AddFinallyVector (UsageVector vector)
2164 if (finally_vectors != null) {
2165 finally_vectors.Add (vector.Clone ());
2170 Parent.AddFinallyVector (vector);
2172 throw new NotSupportedException ();
2175 public bool IsVariableAssigned (VariableInfo vi)
2177 if (CurrentUsageVector.AlwaysBreaks)
2180 return CurrentUsageVector [vi, 0];
2183 public bool IsVariableAssigned (VariableInfo vi, int field_idx)
2185 if (CurrentUsageVector.AlwaysBreaks)
2188 return CurrentUsageVector [vi, field_idx];
2191 public void SetVariableAssigned (VariableInfo vi)
2193 if (CurrentUsageVector.AlwaysBreaks)
2196 CurrentUsageVector [vi, 0] = true;
2199 public void SetVariableAssigned (VariableInfo vi, int field_idx)
2201 if (CurrentUsageVector.AlwaysBreaks)
2204 CurrentUsageVector [vi, field_idx] = true;
2207 public bool IsParameterAssigned (int number)
2209 int index = param_map [number];
2214 if (CurrentUsageVector [index])
2217 // Parameter is not assigned, so check whether it's a struct.
2218 // If it's either not a struct or a struct which non-public
2219 // fields, return false.
2220 MyStructInfo struct_info = struct_params [number];
2221 if ((struct_info == null) || struct_info.HasNonPublicFields)
2224 // Ok, so each field must be assigned.
2225 for (int i = 0; i < struct_info.Count; i++)
2226 if (!CurrentUsageVector [index + i])
2232 public bool IsParameterAssigned (int number, string field_name)
2234 int index = param_map [number];
2239 MyStructInfo info = (MyStructInfo) struct_params [number];
2243 int field_idx = info [field_name];
2245 return CurrentUsageVector [index + field_idx];
2248 public void SetParameterAssigned (int number)
2250 if (param_map [number] == 0)
2253 if (!CurrentUsageVector.AlwaysBreaks)
2254 CurrentUsageVector [param_map [number]] = true;
2257 public void SetParameterAssigned (int number, string field_name)
2259 int index = param_map [number];
2264 MyStructInfo info = (MyStructInfo) struct_params [number];
2268 int field_idx = info [field_name];
2270 if (!CurrentUsageVector.AlwaysBreaks)
2271 CurrentUsageVector [index + field_idx] = true;
2274 public bool IsReachable ()
2279 case FlowBranchingType.SWITCH_SECTION:
2280 // The code following a switch block is reachable unless the switch
2281 // block always returns.
2282 reachable = !CurrentUsageVector.AlwaysReturns;
2285 case FlowBranchingType.LOOP_BLOCK:
2286 // The code following a loop is reachable unless the loop always
2287 // returns or it's an infinite loop without any `break's in it.
2288 reachable = !CurrentUsageVector.AlwaysReturns &&
2289 (CurrentUsageVector.Breaks != FlowReturns.UNREACHABLE);
2293 // The code following a block or exception is reachable unless the
2294 // block either always returns or always breaks.
2295 reachable = !CurrentUsageVector.AlwaysBreaks &&
2296 !CurrentUsageVector.AlwaysReturns;
2300 Report.Debug (1, "REACHABLE", Type, CurrentUsageVector.Returns,
2301 CurrentUsageVector.Breaks, CurrentUsageVector, reachable);
2306 public override string ToString ()
2308 StringBuilder sb = new StringBuilder ("FlowBranching (");
2313 if (Block != null) {
2315 sb.Append (Block.ID);
2317 sb.Append (Block.StartLocation);
2320 sb.Append (Siblings.Count);
2322 sb.Append (CurrentUsageVector);
2324 return sb.ToString ();
2328 public class MyStructInfo {
2329 public readonly Type Type;
2330 public readonly FieldInfo[] Fields;
2331 public readonly FieldInfo[] NonPublicFields;
2332 public readonly int Count;
2333 public readonly int CountNonPublic;
2334 public readonly bool HasNonPublicFields;
2336 private static Hashtable field_type_hash = new Hashtable ();
2337 private Hashtable field_hash;
2339 // Private constructor. To save memory usage, we only need to create one instance
2340 // of this class per struct type.
2341 private MyStructInfo (Type type)
2345 if (type is TypeBuilder) {
2346 TypeContainer tc = TypeManager.LookupTypeContainer (type);
2348 ArrayList fields = tc.Fields;
2349 if (fields != null) {
2350 foreach (Field field in fields) {
2351 if ((field.ModFlags & Modifiers.STATIC) != 0)
2353 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2360 Fields = new FieldInfo [Count];
2361 NonPublicFields = new FieldInfo [CountNonPublic];
2363 Count = CountNonPublic = 0;
2364 if (fields != null) {
2365 foreach (Field field in fields) {
2366 if ((field.ModFlags & Modifiers.STATIC) != 0)
2368 if ((field.ModFlags & Modifiers.PUBLIC) != 0)
2369 Fields [Count++] = field.FieldBuilder;
2371 NonPublicFields [CountNonPublic++] =
2377 Fields = type.GetFields (BindingFlags.Instance|BindingFlags.Public);
2378 Count = Fields.Length;
2380 NonPublicFields = type.GetFields (BindingFlags.Instance|BindingFlags.NonPublic);
2381 CountNonPublic = NonPublicFields.Length;
2384 Count += NonPublicFields.Length;
2387 field_hash = new Hashtable ();
2388 foreach (FieldInfo field in Fields)
2389 field_hash.Add (field.Name, ++number);
2391 if (NonPublicFields.Length != 0)
2392 HasNonPublicFields = true;
2394 foreach (FieldInfo field in NonPublicFields)
2395 field_hash.Add (field.Name, ++number);
2398 public int this [string name] {
2400 if (field_hash.Contains (name))
2401 return (int) field_hash [name];
2407 public FieldInfo this [int index] {
2409 if (index >= Fields.Length)
2410 return NonPublicFields [index - Fields.Length];
2412 return Fields [index];
2416 public static MyStructInfo GetStructInfo (Type type)
2418 if (!TypeManager.IsValueType (type) || TypeManager.IsEnumType (type))
2421 if (!(type is TypeBuilder) && TypeManager.IsBuiltinType (type))
2424 MyStructInfo info = (MyStructInfo) field_type_hash [type];
2428 info = new MyStructInfo (type);
2429 field_type_hash.Add (type, info);
2433 public static MyStructInfo GetStructInfo (TypeContainer tc)
2435 MyStructInfo info = (MyStructInfo) field_type_hash [tc.TypeBuilder];
2439 info = new MyStructInfo (tc.TypeBuilder);
2440 field_type_hash.Add (tc.TypeBuilder, info);
2445 public class VariableInfo : IVariable {
2446 public Expression Type;
2447 public LocalBuilder LocalBuilder;
2448 public Type VariableType;
2449 public readonly string Name;
2450 public readonly Location Location;
2451 public readonly int Block;
2456 public bool Assigned;
2457 public bool ReadOnly;
2459 public VariableInfo (Expression type, string name, int block, Location l)
2464 LocalBuilder = null;
2468 public VariableInfo (TypeContainer tc, int block, Location l)
2470 VariableType = tc.TypeBuilder;
2471 struct_info = MyStructInfo.GetStructInfo (tc);
2473 LocalBuilder = null;
2477 MyStructInfo struct_info;
2478 public MyStructInfo StructInfo {
2484 public bool IsAssigned (EmitContext ec, Location loc)
2486 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this))
2489 MyStructInfo struct_info = StructInfo;
2490 if ((struct_info == null) || (struct_info.HasNonPublicFields && (Name != null))) {
2491 Report.Error (165, loc, "Use of unassigned local variable `" + Name + "'");
2492 ec.CurrentBranching.SetVariableAssigned (this);
2496 int count = struct_info.Count;
2498 for (int i = 0; i < count; i++) {
2499 if (!ec.CurrentBranching.IsVariableAssigned (this, i+1)) {
2501 Report.Error (165, loc,
2502 "Use of unassigned local variable `" +
2504 ec.CurrentBranching.SetVariableAssigned (this);
2508 FieldInfo field = struct_info [i];
2509 Report.Error (171, loc,
2510 "Field `" + TypeManager.CSharpName (VariableType) +
2511 "." + field.Name + "' must be fully initialized " +
2512 "before control leaves the constructor");
2520 public bool IsFieldAssigned (EmitContext ec, string name, Location loc)
2522 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsVariableAssigned (this) ||
2523 (struct_info == null))
2526 int field_idx = StructInfo [name];
2530 if (!ec.CurrentBranching.IsVariableAssigned (this, field_idx)) {
2531 Report.Error (170, loc,
2532 "Use of possibly unassigned field `" + name + "'");
2533 ec.CurrentBranching.SetVariableAssigned (this, field_idx);
2540 public void SetAssigned (EmitContext ec)
2542 if (ec.DoFlowAnalysis)
2543 ec.CurrentBranching.SetVariableAssigned (this);
2546 public void SetFieldAssigned (EmitContext ec, string name)
2548 if (ec.DoFlowAnalysis && (struct_info != null))
2549 ec.CurrentBranching.SetVariableAssigned (this, StructInfo [name]);
2552 public bool Resolve (DeclSpace decl)
2554 if (struct_info != null)
2557 if (VariableType == null)
2558 VariableType = decl.ResolveType (Type, false, Location);
2560 if (VariableType == null)
2563 struct_info = MyStructInfo.GetStructInfo (VariableType);
2568 public void MakePinned ()
2570 TypeManager.MakePinned (LocalBuilder);
2573 public override string ToString ()
2575 return "VariableInfo (" + Number + "," + Type + "," + Location + ")";
2580 /// Block represents a C# block.
2584 /// This class is used in a number of places: either to represent
2585 /// explicit blocks that the programmer places or implicit blocks.
2587 /// Implicit blocks are used as labels or to introduce variable
2590 public class Block : Statement {
2591 public readonly Block Parent;
2592 public readonly bool Implicit;
2593 public readonly Location StartLocation;
2594 public Location EndLocation;
2597 // The statements in this block
2599 public ArrayList statements;
2602 // An array of Blocks. We keep track of children just
2603 // to generate the local variable declarations.
2605 // Statements and child statements are handled through the
2611 // Labels. (label, block) pairs.
2616 // Keeps track of (name, type) pairs
2618 Hashtable variables;
2621 // Keeps track of constants
2622 Hashtable constants;
2625 // Maps variable names to ILGenerator.LocalBuilders
2627 Hashtable local_builders;
2635 public Block (Block parent)
2636 : this (parent, false, Location.Null, Location.Null)
2639 public Block (Block parent, bool implicit_block)
2640 : this (parent, implicit_block, Location.Null, Location.Null)
2643 public Block (Block parent, bool implicit_block, Parameters parameters)
2644 : this (parent, implicit_block, parameters, Location.Null, Location.Null)
2647 public Block (Block parent, Location start, Location end)
2648 : this (parent, false, start, end)
2651 public Block (Block parent, Parameters parameters, Location start, Location end)
2652 : this (parent, false, parameters, start, end)
2655 public Block (Block parent, bool implicit_block, Location start, Location end)
2656 : this (parent, implicit_block, Parameters.EmptyReadOnlyParameters,
2660 public Block (Block parent, bool implicit_block, Parameters parameters,
2661 Location start, Location end)
2664 parent.AddChild (this);
2666 this.Parent = parent;
2667 this.Implicit = implicit_block;
2668 this.parameters = parameters;
2669 this.StartLocation = start;
2670 this.EndLocation = end;
2673 statements = new ArrayList ();
2682 void AddChild (Block b)
2684 if (children == null)
2685 children = new ArrayList ();
2690 public void SetEndLocation (Location loc)
2696 /// Adds a label to the current block.
2700 /// false if the name already exists in this block. true
2704 public bool AddLabel (string name, LabeledStatement target)
2707 labels = new Hashtable ();
2708 if (labels.Contains (name))
2711 labels.Add (name, target);
2715 public LabeledStatement LookupLabel (string name)
2717 if (labels != null){
2718 if (labels.Contains (name))
2719 return ((LabeledStatement) labels [name]);
2723 return Parent.LookupLabel (name);
2728 VariableInfo this_variable = null;
2731 // Returns the "this" instance variable of this block.
2732 // See AddThisVariable() for more information.
2734 public VariableInfo ThisVariable {
2736 if (this_variable != null)
2737 return this_variable;
2738 else if (Parent != null)
2739 return Parent.ThisVariable;
2745 Hashtable child_variable_names;
2748 // Marks a variable with name @name as being used in a child block.
2749 // If a variable name has been used in a child block, it's illegal to
2750 // declare a variable with the same name in the current block.
2752 public void AddChildVariableName (string name)
2754 if (child_variable_names == null)
2755 child_variable_names = new Hashtable ();
2757 if (!child_variable_names.Contains (name))
2758 child_variable_names.Add (name, true);
2762 // Marks all variables from block @block and all its children as being
2763 // used in a child block.
2765 public void AddChildVariableNames (Block block)
2767 if (block.Variables != null) {
2768 foreach (string name in block.Variables.Keys)
2769 AddChildVariableName (name);
2772 foreach (Block child in block.children) {
2773 if (child.Variables != null) {
2774 foreach (string name in child.Variables.Keys)
2775 AddChildVariableName (name);
2781 // Checks whether a variable name has already been used in a child block.
2783 public bool IsVariableNameUsedInChildBlock (string name)
2785 if (child_variable_names == null)
2788 return child_variable_names.Contains (name);
2792 // This is used by non-static `struct' constructors which do not have an
2793 // initializer - in this case, the constructor must initialize all of the
2794 // struct's fields. To do this, we add a "this" variable and use the flow
2795 // analysis code to ensure that it's been fully initialized before control
2796 // leaves the constructor.
2798 public VariableInfo AddThisVariable (TypeContainer tc, Location l)
2800 if (this_variable != null)
2801 return this_variable;
2803 this_variable = new VariableInfo (tc, ID, l);
2805 if (variables == null)
2806 variables = new Hashtable ();
2807 variables.Add ("this", this_variable);
2809 return this_variable;
2812 public VariableInfo AddVariable (Expression type, string name, Parameters pars, Location l)
2814 if (variables == null)
2815 variables = new Hashtable ();
2817 VariableInfo vi = GetVariableInfo (name);
2820 Report.Error (136, l, "A local variable named `" + name + "' " +
2821 "cannot be declared in this scope since it would " +
2822 "give a different meaning to `" + name + "', which " +
2823 "is already used in a `parent or current' scope to " +
2824 "denote something else");
2826 Report.Error (128, l, "A local variable `" + name + "' is already " +
2827 "defined in this scope");
2831 if (IsVariableNameUsedInChildBlock (name)) {
2832 Report.Error (136, l, "A local variable named `" + name + "' " +
2833 "cannot be declared in this scope since it would " +
2834 "give a different meaning to `" + name + "', which " +
2835 "is already used in a `child' scope to denote something " +
2842 Parameter p = pars.GetParameterByName (name, out idx);
2844 Report.Error (136, l, "A local variable named `" + name + "' " +
2845 "cannot be declared in this scope since it would " +
2846 "give a different meaning to `" + name + "', which " +
2847 "is already used in a `parent or current' scope to " +
2848 "denote something else");
2853 vi = new VariableInfo (type, name, ID, l);
2855 variables.Add (name, vi);
2857 if (variables_initialized)
2858 throw new Exception ();
2860 // Console.WriteLine ("Adding {0} to {1}", name, ID);
2864 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
2866 if (AddVariable (type, name, pars, l) == null)
2869 if (constants == null)
2870 constants = new Hashtable ();
2872 constants.Add (name, value);
2876 public Hashtable Variables {
2882 public VariableInfo GetVariableInfo (string name)
2884 if (variables != null) {
2886 temp = variables [name];
2889 return (VariableInfo) temp;
2894 return Parent.GetVariableInfo (name);
2899 public Expression GetVariableType (string name)
2901 VariableInfo vi = GetVariableInfo (name);
2909 public Expression GetConstantExpression (string name)
2911 if (constants != null) {
2913 temp = constants [name];
2916 return (Expression) temp;
2920 return Parent.GetConstantExpression (name);
2926 /// True if the variable named @name has been defined
2929 public bool IsVariableDefined (string name)
2931 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
2932 if (variables != null) {
2933 if (variables.Contains (name))
2938 return Parent.IsVariableDefined (name);
2944 /// True if the variable named @name is a constant
2946 public bool IsConstant (string name)
2948 Expression e = null;
2950 e = GetConstantExpression (name);
2956 /// Use to fetch the statement associated with this label
2958 public Statement this [string name] {
2960 return (Statement) labels [name];
2964 Parameters parameters = null;
2965 public Parameters Parameters {
2968 return Parent.Parameters;
2975 /// A list of labels that were not used within this block
2977 public string [] GetUnreferenced ()
2979 // FIXME: Implement me
2983 public void AddStatement (Statement s)
3000 bool variables_initialized = false;
3001 int count_variables = 0, first_variable = 0;
3003 void UpdateVariableInfo (EmitContext ec)
3005 DeclSpace ds = ec.DeclSpace;
3010 first_variable += Parent.CountVariables;
3012 count_variables = first_variable;
3013 if (variables != null) {
3014 foreach (VariableInfo vi in variables.Values) {
3015 if (!vi.Resolve (ds)) {
3020 vi.Number = ++count_variables;
3022 if (vi.StructInfo != null)
3023 count_variables += vi.StructInfo.Count;
3027 variables_initialized = true;
3032 // The number of local variables in this block
3034 public int CountVariables
3037 if (!variables_initialized)
3038 throw new Exception ();
3040 return count_variables;
3045 /// Emits the variable declarations and labels.
3048 /// tc: is our typecontainer (to resolve type references)
3049 /// ig: is the code generator:
3050 /// toplevel: the toplevel block. This is used for checking
3051 /// that no two labels with the same name are used.
3053 public void EmitMeta (EmitContext ec, Block toplevel)
3055 DeclSpace ds = ec.DeclSpace;
3056 ILGenerator ig = ec.ig;
3058 if (!variables_initialized)
3059 UpdateVariableInfo (ec);
3062 // Process this block variables
3064 if (variables != null){
3065 local_builders = new Hashtable ();
3067 foreach (DictionaryEntry de in variables){
3068 string name = (string) de.Key;
3069 VariableInfo vi = (VariableInfo) de.Value;
3071 if (vi.VariableType == null)
3074 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
3076 if (CodeGen.SymbolWriter != null)
3077 vi.LocalBuilder.SetLocalSymInfo (name);
3079 if (constants == null)
3082 Expression cv = (Expression) constants [name];
3086 Expression e = cv.Resolve (ec);
3090 if (!(e is Constant)){
3091 Report.Error (133, vi.Location,
3092 "The expression being assigned to `" +
3093 name + "' must be constant (" + e + ")");
3097 constants.Remove (name);
3098 constants.Add (name, e);
3103 // Now, handle the children
3105 if (children != null){
3106 foreach (Block b in children)
3107 b.EmitMeta (ec, toplevel);
3111 public void UsageWarning ()
3115 if (variables != null){
3116 foreach (DictionaryEntry de in variables){
3117 VariableInfo vi = (VariableInfo) de.Value;
3122 name = (string) de.Key;
3126 219, vi.Location, "The variable `" + name +
3127 "' is assigned but its value is never used");
3130 168, vi.Location, "The variable `" +
3132 "' is declared but never used");
3137 if (children != null)
3138 foreach (Block b in children)
3142 bool has_ret = false;
3144 public override bool Resolve (EmitContext ec)
3146 Block prev_block = ec.CurrentBlock;
3149 ec.CurrentBlock = this;
3150 ec.StartFlowBranching (this);
3152 Report.Debug (1, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
3154 if (!variables_initialized)
3155 UpdateVariableInfo (ec);
3157 ArrayList new_statements = new ArrayList ();
3158 bool unreachable = false, warning_shown = false;
3160 foreach (Statement s in statements){
3161 if (unreachable && !(s is LabeledStatement)) {
3162 if (!warning_shown && !(s is EmptyStatement)) {
3163 warning_shown = true;
3164 Warning_DeadCodeFound (s.loc);
3170 if (s.Resolve (ec) == false) {
3175 if (s is LabeledStatement)
3176 unreachable = false;
3178 unreachable = ! ec.CurrentBranching.IsReachable ();
3180 new_statements.Add (s);
3183 statements = new_statements;
3185 Report.Debug (1, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
3187 FlowReturns returns = ec.EndFlowBranching ();
3188 ec.CurrentBlock = prev_block;
3190 // If we're a non-static `struct' constructor which doesn't have an
3191 // initializer, then we must initialize all of the struct's fields.
3192 if ((this_variable != null) && (returns != FlowReturns.EXCEPTION) &&
3193 !this_variable.IsAssigned (ec, loc))
3196 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
3197 foreach (LabeledStatement label in labels.Values)
3198 if (!label.HasBeenReferenced)
3199 Report.Warning (164, label.Location,
3200 "This label has not been referenced");
3203 if ((returns == FlowReturns.ALWAYS) ||
3204 (returns == FlowReturns.EXCEPTION) ||
3205 (returns == FlowReturns.UNREACHABLE))
3211 protected override bool DoEmit (EmitContext ec)
3213 Block prev_block = ec.CurrentBlock;
3215 ec.CurrentBlock = this;
3217 ec.Mark (StartLocation);
3218 foreach (Statement s in statements)
3221 ec.Mark (EndLocation);
3223 ec.CurrentBlock = prev_block;
3228 public class SwitchLabel {
3231 public Location loc;
3232 public Label ILLabel;
3233 public Label ILLabelCode;
3236 // if expr == null, then it is the default case.
3238 public SwitchLabel (Expression expr, Location l)
3244 public Expression Label {
3250 public object Converted {
3257 // Resolves the expression, reduces it to a literal if possible
3258 // and then converts it to the requested type.
3260 public bool ResolveAndReduce (EmitContext ec, Type required_type)
3262 ILLabel = ec.ig.DefineLabel ();
3263 ILLabelCode = ec.ig.DefineLabel ();
3268 Expression e = label.Resolve (ec);
3273 if (!(e is Constant)){
3274 Console.WriteLine ("Value is: " + label);
3275 Report.Error (150, loc, "A constant value is expected");
3279 if (e is StringConstant || e is NullLiteral){
3280 if (required_type == TypeManager.string_type){
3282 ILLabel = ec.ig.DefineLabel ();
3287 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
3288 if (converted == null)
3295 public class SwitchSection {
3296 // An array of SwitchLabels.
3297 public readonly ArrayList Labels;
3298 public readonly Block Block;
3300 public SwitchSection (ArrayList labels, Block block)
3307 public class Switch : Statement {
3308 public readonly ArrayList Sections;
3309 public Expression Expr;
3312 /// Maps constants whose type type SwitchType to their SwitchLabels.
3314 public Hashtable Elements;
3317 /// The governing switch type
3319 public Type SwitchType;
3325 Label default_target;
3326 Expression new_expr;
3329 // The types allowed to be implicitly cast from
3330 // on the governing type
3332 static Type [] allowed_types;
3334 public Switch (Expression e, ArrayList sects, Location l)
3341 public bool GotDefault {
3347 public Label DefaultTarget {
3349 return default_target;
3354 // Determines the governing type for a switch. The returned
3355 // expression might be the expression from the switch, or an
3356 // expression that includes any potential conversions to the
3357 // integral types or to string.
3359 Expression SwitchGoverningType (EmitContext ec, Type t)
3361 if (t == TypeManager.int32_type ||
3362 t == TypeManager.uint32_type ||
3363 t == TypeManager.char_type ||
3364 t == TypeManager.byte_type ||
3365 t == TypeManager.sbyte_type ||
3366 t == TypeManager.ushort_type ||
3367 t == TypeManager.short_type ||
3368 t == TypeManager.uint64_type ||
3369 t == TypeManager.int64_type ||
3370 t == TypeManager.string_type ||
3371 t == TypeManager.bool_type ||
3372 t.IsSubclassOf (TypeManager.enum_type))
3375 if (allowed_types == null){
3376 allowed_types = new Type [] {
3377 TypeManager.sbyte_type,
3378 TypeManager.byte_type,
3379 TypeManager.short_type,
3380 TypeManager.ushort_type,
3381 TypeManager.int32_type,
3382 TypeManager.uint32_type,
3383 TypeManager.int64_type,
3384 TypeManager.uint64_type,
3385 TypeManager.char_type,
3386 TypeManager.bool_type,
3387 TypeManager.string_type
3392 // Try to find a *user* defined implicit conversion.
3394 // If there is no implicit conversion, or if there are multiple
3395 // conversions, we have to report an error
3397 Expression converted = null;
3398 foreach (Type tt in allowed_types){
3401 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
3405 if (converted != null){
3406 Report.Error (-12, loc, "More than one conversion to an integral " +
3407 " type exists for type `" +
3408 TypeManager.CSharpName (Expr.Type)+"'");
3416 void error152 (string n)
3419 152, "The label `" + n + ":' " +
3420 "is already present on this switch statement");
3424 // Performs the basic sanity checks on the switch statement
3425 // (looks for duplicate keys and non-constant expressions).
3427 // It also returns a hashtable with the keys that we will later
3428 // use to compute the switch tables
3430 bool CheckSwitch (EmitContext ec)
3434 Elements = new Hashtable ();
3436 got_default = false;
3438 if (TypeManager.IsEnumType (SwitchType)){
3439 compare_type = TypeManager.EnumToUnderlying (SwitchType);
3441 compare_type = SwitchType;
3443 foreach (SwitchSection ss in Sections){
3444 foreach (SwitchLabel sl in ss.Labels){
3445 if (!sl.ResolveAndReduce (ec, SwitchType)){
3450 if (sl.Label == null){
3452 error152 ("default");
3459 object key = sl.Converted;
3461 if (key is Constant)
3462 key = ((Constant) key).GetValue ();
3465 key = NullLiteral.Null;
3467 string lname = null;
3468 if (compare_type == TypeManager.uint64_type){
3469 ulong v = (ulong) key;
3471 if (Elements.Contains (v))
3472 lname = v.ToString ();
3474 Elements.Add (v, sl);
3475 } else if (compare_type == TypeManager.int64_type){
3476 long v = (long) key;
3478 if (Elements.Contains (v))
3479 lname = v.ToString ();
3481 Elements.Add (v, sl);
3482 } else if (compare_type == TypeManager.uint32_type){
3483 uint v = (uint) key;
3485 if (Elements.Contains (v))
3486 lname = v.ToString ();
3488 Elements.Add (v, sl);
3489 } else if (compare_type == TypeManager.char_type){
3490 char v = (char) key;
3492 if (Elements.Contains (v))
3493 lname = v.ToString ();
3495 Elements.Add (v, sl);
3496 } else if (compare_type == TypeManager.byte_type){
3497 byte v = (byte) key;
3499 if (Elements.Contains (v))
3500 lname = v.ToString ();
3502 Elements.Add (v, sl);
3503 } else if (compare_type == TypeManager.sbyte_type){
3504 sbyte v = (sbyte) key;
3506 if (Elements.Contains (v))
3507 lname = v.ToString ();
3509 Elements.Add (v, sl);
3510 } else if (compare_type == TypeManager.short_type){
3511 short v = (short) key;
3513 if (Elements.Contains (v))
3514 lname = v.ToString ();
3516 Elements.Add (v, sl);
3517 } else if (compare_type == TypeManager.ushort_type){
3518 ushort v = (ushort) key;
3520 if (Elements.Contains (v))
3521 lname = v.ToString ();
3523 Elements.Add (v, sl);
3524 } else if (compare_type == TypeManager.string_type){
3525 if (key is NullLiteral){
3526 if (Elements.Contains (NullLiteral.Null))
3529 Elements.Add (NullLiteral.Null, null);
3531 string s = (string) key;
3533 if (Elements.Contains (s))
3536 Elements.Add (s, sl);
3538 } else if (compare_type == TypeManager.int32_type) {
3541 if (Elements.Contains (v))
3542 lname = v.ToString ();
3544 Elements.Add (v, sl);
3545 } else if (compare_type == TypeManager.bool_type) {
3546 bool v = (bool) key;
3548 if (Elements.Contains (v))
3549 lname = v.ToString ();
3551 Elements.Add (v, sl);
3555 throw new Exception ("Unknown switch type!" +
3556 SwitchType + " " + compare_type);
3560 error152 ("case + " + lname);
3571 void EmitObjectInteger (ILGenerator ig, object k)
3574 IntConstant.EmitInt (ig, (int) k);
3575 else if (k is Constant) {
3576 EmitObjectInteger (ig, ((Constant) k).GetValue ());
3579 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
3582 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
3584 IntConstant.EmitInt (ig, (int) (long) k);
3585 ig.Emit (OpCodes.Conv_I8);
3588 LongConstant.EmitLong (ig, (long) k);
3590 else if (k is ulong)
3592 if ((ulong) k < (1L<<32))
3594 IntConstant.EmitInt (ig, (int) (long) k);
3595 ig.Emit (OpCodes.Conv_U8);
3599 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
3603 IntConstant.EmitInt (ig, (int) ((char) k));
3604 else if (k is sbyte)
3605 IntConstant.EmitInt (ig, (int) ((sbyte) k));
3607 IntConstant.EmitInt (ig, (int) ((byte) k));
3608 else if (k is short)
3609 IntConstant.EmitInt (ig, (int) ((short) k));
3610 else if (k is ushort)
3611 IntConstant.EmitInt (ig, (int) ((ushort) k));
3613 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
3615 throw new Exception ("Unhandled case");
3618 // structure used to hold blocks of keys while calculating table switch
3619 class KeyBlock : IComparable
3621 public KeyBlock (long _nFirst)
3623 nFirst = nLast = _nFirst;
3627 public ArrayList rgKeys = null;
3630 get { return (int) (nLast - nFirst + 1); }
3632 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
3634 return kbLast.nLast - kbFirst.nFirst + 1;
3636 public int CompareTo (object obj)
3638 KeyBlock kb = (KeyBlock) obj;
3639 int nLength = Length;
3640 int nLengthOther = kb.Length;
3641 if (nLengthOther == nLength)
3642 return (int) (kb.nFirst - nFirst);
3643 return nLength - nLengthOther;
3648 /// This method emits code for a lookup-based switch statement (non-string)
3649 /// Basically it groups the cases into blocks that are at least half full,
3650 /// and then spits out individual lookup opcodes for each block.
3651 /// It emits the longest blocks first, and short blocks are just
3652 /// handled with direct compares.
3654 /// <param name="ec"></param>
3655 /// <param name="val"></param>
3656 /// <returns></returns>
3657 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
3659 int cElements = Elements.Count;
3660 object [] rgKeys = new object [cElements];
3661 Elements.Keys.CopyTo (rgKeys, 0);
3662 Array.Sort (rgKeys);
3664 // initialize the block list with one element per key
3665 ArrayList rgKeyBlocks = new ArrayList ();
3666 foreach (object key in rgKeys)
3667 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
3670 // iteratively merge the blocks while they are at least half full
3671 // there's probably a really cool way to do this with a tree...
3672 while (rgKeyBlocks.Count > 1)
3674 ArrayList rgKeyBlocksNew = new ArrayList ();
3675 kbCurr = (KeyBlock) rgKeyBlocks [0];
3676 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
3678 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
3679 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
3682 kbCurr.nLast = kb.nLast;
3686 // start a new block
3687 rgKeyBlocksNew.Add (kbCurr);
3691 rgKeyBlocksNew.Add (kbCurr);
3692 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
3694 rgKeyBlocks = rgKeyBlocksNew;
3697 // initialize the key lists
3698 foreach (KeyBlock kb in rgKeyBlocks)
3699 kb.rgKeys = new ArrayList ();
3701 // fill the key lists
3703 if (rgKeyBlocks.Count > 0) {
3704 kbCurr = (KeyBlock) rgKeyBlocks [0];
3705 foreach (object key in rgKeys)
3707 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
3709 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
3710 kbCurr.rgKeys.Add (key);
3714 // sort the blocks so we can tackle the largest ones first
3715 rgKeyBlocks.Sort ();
3717 // okay now we can start...
3718 ILGenerator ig = ec.ig;
3719 Label lblEnd = ig.DefineLabel (); // at the end ;-)
3720 Label lblDefault = ig.DefineLabel ();
3722 Type typeKeys = null;
3723 if (rgKeys.Length > 0)
3724 typeKeys = rgKeys [0].GetType (); // used for conversions
3726 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
3728 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
3729 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
3732 foreach (object key in kb.rgKeys)
3734 ig.Emit (OpCodes.Ldloc, val);
3735 EmitObjectInteger (ig, key);
3736 SwitchLabel sl = (SwitchLabel) Elements [key];
3737 ig.Emit (OpCodes.Beq, sl.ILLabel);
3742 // TODO: if all the keys in the block are the same and there are
3743 // no gaps/defaults then just use a range-check.
3744 if (SwitchType == TypeManager.int64_type ||
3745 SwitchType == TypeManager.uint64_type)
3747 // TODO: optimize constant/I4 cases
3749 // check block range (could be > 2^31)
3750 ig.Emit (OpCodes.Ldloc, val);
3751 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3752 ig.Emit (OpCodes.Blt, lblDefault);
3753 ig.Emit (OpCodes.Ldloc, val);
3754 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3755 ig.Emit (OpCodes.Bgt, lblDefault);
3758 ig.Emit (OpCodes.Ldloc, val);
3761 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
3762 ig.Emit (OpCodes.Sub);
3764 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
3769 ig.Emit (OpCodes.Ldloc, val);
3770 int nFirst = (int) kb.nFirst;
3773 IntConstant.EmitInt (ig, nFirst);
3774 ig.Emit (OpCodes.Sub);
3776 else if (nFirst < 0)
3778 IntConstant.EmitInt (ig, -nFirst);
3779 ig.Emit (OpCodes.Add);
3783 // first, build the list of labels for the switch
3785 int cJumps = kb.Length;
3786 Label [] rgLabels = new Label [cJumps];
3787 for (int iJump = 0; iJump < cJumps; iJump++)
3789 object key = kb.rgKeys [iKey];
3790 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
3792 SwitchLabel sl = (SwitchLabel) Elements [key];
3793 rgLabels [iJump] = sl.ILLabel;
3797 rgLabels [iJump] = lblDefault;
3799 // emit the switch opcode
3800 ig.Emit (OpCodes.Switch, rgLabels);
3803 // mark the default for this block
3805 ig.MarkLabel (lblDefault);
3808 // TODO: find the default case and emit it here,
3809 // to prevent having to do the following jump.
3810 // make sure to mark other labels in the default section
3812 // the last default just goes to the end
3813 ig.Emit (OpCodes.Br, lblDefault);
3815 // now emit the code for the sections
3816 bool fFoundDefault = false;
3817 bool fAllReturn = true;
3818 foreach (SwitchSection ss in Sections)
3820 foreach (SwitchLabel sl in ss.Labels)
3822 ig.MarkLabel (sl.ILLabel);
3823 ig.MarkLabel (sl.ILLabelCode);
3824 if (sl.Label == null)
3826 ig.MarkLabel (lblDefault);
3827 fFoundDefault = true;
3830 bool returns = ss.Block.Emit (ec);
3831 fAllReturn &= returns;
3832 //ig.Emit (OpCodes.Br, lblEnd);
3835 if (!fFoundDefault) {
3836 ig.MarkLabel (lblDefault);
3839 ig.MarkLabel (lblEnd);
3844 // This simple emit switch works, but does not take advantage of the
3846 // TODO: remove non-string logic from here
3847 // TODO: binary search strings?
3849 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
3851 ILGenerator ig = ec.ig;
3852 Label end_of_switch = ig.DefineLabel ();
3853 Label next_test = ig.DefineLabel ();
3854 Label null_target = ig.DefineLabel ();
3855 bool default_found = false;
3856 bool first_test = true;
3857 bool pending_goto_end = false;
3858 bool all_return = true;
3859 bool is_string = false;
3863 // Special processing for strings: we cant compare
3866 if (SwitchType == TypeManager.string_type){
3867 ig.Emit (OpCodes.Ldloc, val);
3870 if (Elements.Contains (NullLiteral.Null)){
3871 ig.Emit (OpCodes.Brfalse, null_target);
3873 ig.Emit (OpCodes.Brfalse, default_target);
3875 ig.Emit (OpCodes.Ldloc, val);
3876 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
3877 ig.Emit (OpCodes.Stloc, val);
3880 foreach (SwitchSection ss in Sections){
3881 Label sec_begin = ig.DefineLabel ();
3883 if (pending_goto_end)
3884 ig.Emit (OpCodes.Br, end_of_switch);
3886 int label_count = ss.Labels.Count;
3888 foreach (SwitchLabel sl in ss.Labels){
3889 ig.MarkLabel (sl.ILLabel);
3892 ig.MarkLabel (next_test);
3893 next_test = ig.DefineLabel ();
3896 // If we are the default target
3898 if (sl.Label == null){
3899 ig.MarkLabel (default_target);
3900 default_found = true;
3902 object lit = sl.Converted;
3904 if (lit is NullLiteral){
3906 if (label_count == 1)
3907 ig.Emit (OpCodes.Br, next_test);
3912 StringConstant str = (StringConstant) lit;
3914 ig.Emit (OpCodes.Ldloc, val);
3915 ig.Emit (OpCodes.Ldstr, str.Value);
3916 if (label_count == 1)
3917 ig.Emit (OpCodes.Bne_Un, next_test);
3919 ig.Emit (OpCodes.Beq, sec_begin);
3921 ig.Emit (OpCodes.Ldloc, val);
3922 EmitObjectInteger (ig, lit);
3923 ig.Emit (OpCodes.Ceq);
3924 if (label_count == 1)
3925 ig.Emit (OpCodes.Brfalse, next_test);
3927 ig.Emit (OpCodes.Brtrue, sec_begin);
3931 if (label_count != 1)
3932 ig.Emit (OpCodes.Br, next_test);
3935 ig.MarkLabel (null_target);
3936 ig.MarkLabel (sec_begin);
3937 foreach (SwitchLabel sl in ss.Labels)
3938 ig.MarkLabel (sl.ILLabelCode);
3940 bool returns = ss.Block.Emit (ec);
3942 pending_goto_end = false;
3945 pending_goto_end = true;
3949 if (!default_found){
3950 ig.MarkLabel (default_target);
3953 ig.MarkLabel (next_test);
3954 ig.MarkLabel (end_of_switch);
3959 public override bool Resolve (EmitContext ec)
3961 Expr = Expr.Resolve (ec);
3965 new_expr = SwitchGoverningType (ec, Expr.Type);
3966 if (new_expr == null){
3967 Report.Error (151, loc, "An integer type or string was expected for switch");
3972 SwitchType = new_expr.Type;
3974 if (!CheckSwitch (ec))
3977 Switch old_switch = ec.Switch;
3979 ec.Switch.SwitchType = SwitchType;
3981 ec.StartFlowBranching (FlowBranchingType.SWITCH, loc);
3984 foreach (SwitchSection ss in Sections){
3986 ec.CurrentBranching.CreateSibling ();
3990 if (ss.Block.Resolve (ec) != true)
3996 ec.CurrentBranching.CreateSibling ();
3998 ec.EndFlowBranching ();
3999 ec.Switch = old_switch;
4004 protected override bool DoEmit (EmitContext ec)
4006 // Store variable for comparission purposes
4007 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
4009 ec.ig.Emit (OpCodes.Stloc, value);
4011 ILGenerator ig = ec.ig;
4013 default_target = ig.DefineLabel ();
4016 // Setup the codegen context
4018 Label old_end = ec.LoopEnd;
4019 Switch old_switch = ec.Switch;
4021 ec.LoopEnd = ig.DefineLabel ();
4026 if (SwitchType == TypeManager.string_type)
4027 all_return = SimpleSwitchEmit (ec, value);
4029 all_return = TableSwitchEmit (ec, value);
4031 // Restore context state.
4032 ig.MarkLabel (ec.LoopEnd);
4035 // Restore the previous context
4037 ec.LoopEnd = old_end;
4038 ec.Switch = old_switch;
4044 public class Lock : Statement {
4046 Statement Statement;
4048 public Lock (Expression expr, Statement stmt, Location l)
4055 public override bool Resolve (EmitContext ec)
4057 expr = expr.Resolve (ec);
4058 return Statement.Resolve (ec) && expr != null;
4061 protected override bool DoEmit (EmitContext ec)
4063 Type type = expr.Type;
4066 if (type.IsValueType){
4067 Report.Error (185, loc, "lock statement requires the expression to be " +
4068 " a reference type (type is: `" +
4069 TypeManager.CSharpName (type) + "'");
4073 ILGenerator ig = ec.ig;
4074 LocalBuilder temp = ig.DeclareLocal (type);
4077 ig.Emit (OpCodes.Dup);
4078 ig.Emit (OpCodes.Stloc, temp);
4079 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
4082 Label end = ig.BeginExceptionBlock ();
4083 bool old_in_try = ec.InTry;
4085 Label finish = ig.DefineLabel ();
4086 val = Statement.Emit (ec);
4087 ec.InTry = old_in_try;
4088 // ig.Emit (OpCodes.Leave, finish);
4090 ig.MarkLabel (finish);
4093 ig.BeginFinallyBlock ();
4094 ig.Emit (OpCodes.Ldloc, temp);
4095 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
4096 ig.EndExceptionBlock ();
4102 public class Unchecked : Statement {
4103 public readonly Block Block;
4105 public Unchecked (Block b)
4110 public override bool Resolve (EmitContext ec)
4112 return Block.Resolve (ec);
4115 protected override bool DoEmit (EmitContext ec)
4117 bool previous_state = ec.CheckState;
4118 bool previous_state_const = ec.ConstantCheckState;
4121 ec.CheckState = false;
4122 ec.ConstantCheckState = false;
4123 val = Block.Emit (ec);
4124 ec.CheckState = previous_state;
4125 ec.ConstantCheckState = previous_state_const;
4131 public class Checked : Statement {
4132 public readonly Block Block;
4134 public Checked (Block b)
4139 public override bool Resolve (EmitContext ec)
4141 bool previous_state = ec.CheckState;
4142 bool previous_state_const = ec.ConstantCheckState;
4144 ec.CheckState = true;
4145 ec.ConstantCheckState = true;
4146 bool ret = Block.Resolve (ec);
4147 ec.CheckState = previous_state;
4148 ec.ConstantCheckState = previous_state_const;
4153 protected override bool DoEmit (EmitContext ec)
4155 bool previous_state = ec.CheckState;
4156 bool previous_state_const = ec.ConstantCheckState;
4159 ec.CheckState = true;
4160 ec.ConstantCheckState = true;
4161 val = Block.Emit (ec);
4162 ec.CheckState = previous_state;
4163 ec.ConstantCheckState = previous_state_const;
4169 public class Unsafe : Statement {
4170 public readonly Block Block;
4172 public Unsafe (Block b)
4177 public override bool Resolve (EmitContext ec)
4179 bool previous_state = ec.InUnsafe;
4183 val = Block.Resolve (ec);
4184 ec.InUnsafe = previous_state;
4189 protected override bool DoEmit (EmitContext ec)
4191 bool previous_state = ec.InUnsafe;
4195 val = Block.Emit (ec);
4196 ec.InUnsafe = previous_state;
4205 public class Fixed : Statement {
4207 ArrayList declarators;
4208 Statement statement;
4213 public bool is_object;
4214 public VariableInfo vi;
4215 public Expression expr;
4216 public Expression converted;
4219 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
4222 declarators = decls;
4227 public override bool Resolve (EmitContext ec)
4229 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
4230 if (expr_type == null)
4233 data = new FixedData [declarators.Count];
4236 foreach (Pair p in declarators){
4237 VariableInfo vi = (VariableInfo) p.First;
4238 Expression e = (Expression) p.Second;
4243 // The rules for the possible declarators are pretty wise,
4244 // but the production on the grammar is more concise.
4246 // So we have to enforce these rules here.
4248 // We do not resolve before doing the case 1 test,
4249 // because the grammar is explicit in that the token &
4250 // is present, so we need to test for this particular case.
4254 // Case 1: & object.
4256 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
4257 Expression child = ((Unary) e).Expr;
4260 if (child is ParameterReference || child is LocalVariableReference){
4263 "No need to use fixed statement for parameters or " +
4264 "local variable declarations (address is already " +
4273 child = ((Unary) e).Expr;
4275 if (!TypeManager.VerifyUnManaged (child.Type, loc))
4278 data [i].is_object = true;
4280 data [i].converted = null;
4294 if (e.Type.IsArray){
4295 Type array_type = e.Type.GetElementType ();
4299 // Provided that array_type is unmanaged,
4301 if (!TypeManager.VerifyUnManaged (array_type, loc))
4305 // and T* is implicitly convertible to the
4306 // pointer type given in the fixed statement.
4308 ArrayPtr array_ptr = new ArrayPtr (e, loc);
4310 Expression converted = Expression.ConvertImplicitRequired (
4311 ec, array_ptr, vi.VariableType, loc);
4312 if (converted == null)
4315 data [i].is_object = false;
4317 data [i].converted = converted;
4327 if (e.Type == TypeManager.string_type){
4328 data [i].is_object = false;
4330 data [i].converted = null;
4336 return statement.Resolve (ec);
4339 protected override bool DoEmit (EmitContext ec)
4341 ILGenerator ig = ec.ig;
4343 bool is_ret = false;
4345 for (int i = 0; i < data.Length; i++) {
4346 VariableInfo vi = data [i].vi;
4349 // Case 1: & object.
4351 if (data [i].is_object) {
4353 // Store pointer in pinned location
4355 data [i].expr.Emit (ec);
4356 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4358 is_ret = statement.Emit (ec);
4360 // Clear the pinned variable.
4361 ig.Emit (OpCodes.Ldc_I4_0);
4362 ig.Emit (OpCodes.Conv_U);
4363 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4371 if (data [i].expr.Type.IsArray){
4373 // Store pointer in pinned location
4375 data [i].converted.Emit (ec);
4377 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4379 is_ret = statement.Emit (ec);
4381 // Clear the pinned variable.
4382 ig.Emit (OpCodes.Ldc_I4_0);
4383 ig.Emit (OpCodes.Conv_U);
4384 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4392 if (data [i].expr.Type == TypeManager.string_type){
4393 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
4394 TypeManager.MakePinned (pinned_string);
4396 data [i].expr.Emit (ec);
4397 ig.Emit (OpCodes.Stloc, pinned_string);
4399 Expression sptr = new StringPtr (pinned_string, loc);
4400 Expression converted = Expression.ConvertImplicitRequired (
4401 ec, sptr, vi.VariableType, loc);
4403 if (converted == null)
4406 converted.Emit (ec);
4407 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4409 is_ret = statement.Emit (ec);
4411 // Clear the pinned variable
4412 ig.Emit (OpCodes.Ldnull);
4413 ig.Emit (OpCodes.Stloc, pinned_string);
4421 public class Catch {
4422 public readonly string Name;
4423 public readonly Block Block;
4424 public readonly Location Location;
4426 Expression type_expr;
4429 public Catch (Expression type, string name, Block block, Location l)
4437 public Type CatchType {
4443 public bool IsGeneral {
4445 return type_expr == null;
4449 public bool Resolve (EmitContext ec)
4451 if (type_expr != null) {
4452 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
4456 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
4457 Report.Error (155, Location,
4458 "The type caught or thrown must be derived " +
4459 "from System.Exception");
4465 if (!Block.Resolve (ec))
4472 public class Try : Statement {
4473 public readonly Block Fini, Block;
4474 public readonly ArrayList Specific;
4475 public readonly Catch General;
4478 // specific, general and fini might all be null.
4480 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
4482 if (specific == null && general == null){
4483 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
4487 this.Specific = specific;
4488 this.General = general;
4493 public override bool Resolve (EmitContext ec)
4497 ec.StartFlowBranching (FlowBranchingType.EXCEPTION, Block.StartLocation);
4499 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
4501 bool old_in_try = ec.InTry;
4504 if (!Block.Resolve (ec))
4507 ec.InTry = old_in_try;
4509 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
4511 Report.Debug (1, "START OF CATCH BLOCKS", vector);
4513 foreach (Catch c in Specific){
4514 ec.CurrentBranching.CreateSibling ();
4515 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
4517 if (c.Name != null) {
4518 VariableInfo vi = c.Block.GetVariableInfo (c.Name);
4520 throw new Exception ();
4525 bool old_in_catch = ec.InCatch;
4528 if (!c.Resolve (ec))
4531 ec.InCatch = old_in_catch;
4533 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4535 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4536 vector.AndLocals (current);
4539 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
4541 if (General != null){
4542 ec.CurrentBranching.CreateSibling ();
4543 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
4545 bool old_in_catch = ec.InCatch;
4548 if (!General.Resolve (ec))
4551 ec.InCatch = old_in_catch;
4553 FlowBranching.UsageVector current = ec.CurrentBranching.CurrentUsageVector;
4555 if (!current.AlwaysReturns && !current.AlwaysBreaks)
4556 vector.AndLocals (current);
4559 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
4562 ec.CurrentBranching.CreateSiblingForFinally ();
4563 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
4565 bool old_in_finally = ec.InFinally;
4566 ec.InFinally = true;
4568 if (!Fini.Resolve (ec))
4571 ec.InFinally = old_in_finally;
4574 FlowReturns returns = ec.EndFlowBranching ();
4576 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
4578 Report.Debug (1, "END OF FINALLY", ec.CurrentBranching, returns, vector, f_vector);
4580 if ((returns == FlowReturns.SOMETIMES) || (returns == FlowReturns.ALWAYS)) {
4581 ec.CurrentBranching.CheckOutParameters (f_vector.Parameters, loc);
4584 ec.CurrentBranching.CurrentUsageVector.Or (vector);
4586 Report.Debug (1, "END OF TRY", ec.CurrentBranching);
4591 protected override bool DoEmit (EmitContext ec)
4593 ILGenerator ig = ec.ig;
4595 Label finish = ig.DefineLabel ();;
4599 end = ig.BeginExceptionBlock ();
4600 bool old_in_try = ec.InTry;
4602 returns = Block.Emit (ec);
4603 ec.InTry = old_in_try;
4606 // System.Reflection.Emit provides this automatically:
4607 // ig.Emit (OpCodes.Leave, finish);
4609 bool old_in_catch = ec.InCatch;
4611 DeclSpace ds = ec.DeclSpace;
4613 foreach (Catch c in Specific){
4616 ig.BeginCatchBlock (c.CatchType);
4618 if (c.Name != null){
4619 vi = c.Block.GetVariableInfo (c.Name);
4621 throw new Exception ("Variable does not exist in this block");
4623 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
4625 ig.Emit (OpCodes.Pop);
4627 if (!c.Block.Emit (ec))
4631 if (General != null){
4632 ig.BeginCatchBlock (TypeManager.object_type);
4633 ig.Emit (OpCodes.Pop);
4634 if (!General.Block.Emit (ec))
4637 ec.InCatch = old_in_catch;
4639 ig.MarkLabel (finish);
4641 ig.BeginFinallyBlock ();
4642 bool old_in_finally = ec.InFinally;
4643 ec.InFinally = true;
4645 ec.InFinally = old_in_finally;
4648 ig.EndExceptionBlock ();
4651 if (!returns || ec.InTry || ec.InCatch)
4654 // Unfortunately, System.Reflection.Emit automatically emits a leave
4655 // to the end of the finally block. This is a problem if `returns'
4656 // is true since we may jump to a point after the end of the method.
4657 // As a workaround, emit an explicit ret here.
4659 if (ec.ReturnType != null)
4660 ec.ig.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
4661 ec.ig.Emit (OpCodes.Ret);
4667 public class Using : Statement {
4668 object expression_or_block;
4669 Statement Statement;
4674 Expression [] converted_vars;
4675 ExpressionStatement [] assign;
4677 public Using (object expression_or_block, Statement stmt, Location l)
4679 this.expression_or_block = expression_or_block;
4685 // Resolves for the case of using using a local variable declaration.
4687 bool ResolveLocalVariableDecls (EmitContext ec)
4689 bool need_conv = false;
4690 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
4693 if (expr_type == null)
4697 // The type must be an IDisposable or an implicit conversion
4700 converted_vars = new Expression [var_list.Count];
4701 assign = new ExpressionStatement [var_list.Count];
4702 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4703 foreach (DictionaryEntry e in var_list){
4704 Expression var = (Expression) e.Key;
4706 var = var.ResolveLValue (ec, new EmptyExpression ());
4710 converted_vars [i] = Expression.ConvertImplicitRequired (
4711 ec, var, TypeManager.idisposable_type, loc);
4713 if (converted_vars [i] == null)
4721 foreach (DictionaryEntry e in var_list){
4722 LocalVariableReference var = (LocalVariableReference) e.Key;
4723 Expression new_expr = (Expression) e.Value;
4726 a = new Assign (var, new_expr, loc);
4732 converted_vars [i] = var;
4733 assign [i] = (ExpressionStatement) a;
4740 bool ResolveExpression (EmitContext ec)
4742 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
4743 conv = Expression.ConvertImplicitRequired (
4744 ec, expr, TypeManager.idisposable_type, loc);
4754 // Emits the code for the case of using using a local variable declaration.
4756 bool EmitLocalVariableDecls (EmitContext ec)
4758 ILGenerator ig = ec.ig;
4761 bool old_in_try = ec.InTry;
4763 for (i = 0; i < assign.Length; i++) {
4764 assign [i].EmitStatement (ec);
4766 ig.BeginExceptionBlock ();
4768 Statement.Emit (ec);
4769 ec.InTry = old_in_try;
4771 bool old_in_finally = ec.InFinally;
4772 ec.InFinally = true;
4773 var_list.Reverse ();
4774 foreach (DictionaryEntry e in var_list){
4775 LocalVariableReference var = (LocalVariableReference) e.Key;
4776 Label skip = ig.DefineLabel ();
4779 ig.BeginFinallyBlock ();
4782 ig.Emit (OpCodes.Brfalse, skip);
4783 converted_vars [i].Emit (ec);
4784 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4785 ig.MarkLabel (skip);
4786 ig.EndExceptionBlock ();
4788 ec.InFinally = old_in_finally;
4793 bool EmitExpression (EmitContext ec)
4796 // Make a copy of the expression and operate on that.
4798 ILGenerator ig = ec.ig;
4799 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
4804 ig.Emit (OpCodes.Stloc, local_copy);
4806 bool old_in_try = ec.InTry;
4808 ig.BeginExceptionBlock ();
4809 Statement.Emit (ec);
4810 ec.InTry = old_in_try;
4812 Label skip = ig.DefineLabel ();
4813 bool old_in_finally = ec.InFinally;
4814 ig.BeginFinallyBlock ();
4815 ig.Emit (OpCodes.Ldloc, local_copy);
4816 ig.Emit (OpCodes.Brfalse, skip);
4817 ig.Emit (OpCodes.Ldloc, local_copy);
4818 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4819 ig.MarkLabel (skip);
4820 ec.InFinally = old_in_finally;
4821 ig.EndExceptionBlock ();
4826 public override bool Resolve (EmitContext ec)
4828 if (expression_or_block is DictionaryEntry){
4829 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4830 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4832 if (!ResolveLocalVariableDecls (ec))
4835 } else if (expression_or_block is Expression){
4836 expr = (Expression) expression_or_block;
4838 expr = expr.Resolve (ec);
4842 expr_type = expr.Type;
4844 if (!ResolveExpression (ec))
4848 return Statement.Resolve (ec);
4851 protected override bool DoEmit (EmitContext ec)
4853 if (expression_or_block is DictionaryEntry)
4854 return EmitLocalVariableDecls (ec);
4855 else if (expression_or_block is Expression)
4856 return EmitExpression (ec);
4863 /// Implementation of the foreach C# statement
4865 public class Foreach : Statement {
4867 LocalVariableReference variable;
4869 Statement statement;
4870 ForeachHelperMethods hm;
4871 Expression empty, conv;
4872 Type array_type, element_type;
4875 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4876 Statement stmt, Location l)
4883 VariableInfo vi = var.VariableInfo;
4884 this.type = vi.Type;
4886 this.variable = var;
4892 public override bool Resolve (EmitContext ec)
4894 expr = expr.Resolve (ec);
4898 var_type = ec.DeclSpace.ResolveType (type, false, loc);
4899 if (var_type == null)
4903 // We need an instance variable. Not sure this is the best
4904 // way of doing this.
4906 // FIXME: When we implement propertyaccess, will those turn
4907 // out to return values in ExprClass? I think they should.
4909 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4910 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4911 error1579 (expr.Type);
4915 if (expr.Type.IsArray) {
4916 array_type = expr.Type;
4917 element_type = array_type.GetElementType ();
4919 empty = new EmptyExpression (element_type);
4921 hm = ProbeCollectionType (ec, expr.Type);
4923 error1579 (expr.Type);
4927 array_type = expr.Type;
4928 element_type = hm.element_type;
4930 empty = new EmptyExpression (hm.element_type);
4933 ec.StartFlowBranching (FlowBranchingType.LOOP_BLOCK, loc);
4934 ec.CurrentBranching.CreateSibling ();
4938 // FIXME: maybe we can apply the same trick we do in the
4939 // array handling to avoid creating empty and conv in some cases.
4941 // Although it is not as important in this case, as the type
4942 // will not likely be object (what the enumerator will return).
4944 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
4948 if (variable.ResolveLValue (ec, empty) == null)
4951 if (!statement.Resolve (ec))
4954 FlowReturns returns = ec.EndFlowBranching ();
4960 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4962 static MethodInfo FetchMethodMoveNext (Type t)
4964 MemberList move_next_list;
4966 move_next_list = TypeContainer.FindMembers (
4967 t, MemberTypes.Method,
4968 BindingFlags.Public | BindingFlags.Instance,
4969 Type.FilterName, "MoveNext");
4970 if (move_next_list.Count == 0)
4973 foreach (MemberInfo m in move_next_list){
4974 MethodInfo mi = (MethodInfo) m;
4977 args = TypeManager.GetArgumentTypes (mi);
4978 if (args != null && args.Length == 0){
4979 if (mi.ReturnType == TypeManager.bool_type)
4987 // Retrieves a `public T get_Current ()' method from the Type `t'
4989 static MethodInfo FetchMethodGetCurrent (Type t)
4991 MemberList move_next_list;
4993 move_next_list = TypeContainer.FindMembers (
4994 t, MemberTypes.Method,
4995 BindingFlags.Public | BindingFlags.Instance,
4996 Type.FilterName, "get_Current");
4997 if (move_next_list.Count == 0)
5000 foreach (MemberInfo m in move_next_list){
5001 MethodInfo mi = (MethodInfo) m;
5004 args = TypeManager.GetArgumentTypes (mi);
5005 if (args != null && args.Length == 0)
5012 // This struct records the helper methods used by the Foreach construct
5014 class ForeachHelperMethods {
5015 public EmitContext ec;
5016 public MethodInfo get_enumerator;
5017 public MethodInfo move_next;
5018 public MethodInfo get_current;
5019 public Type element_type;
5020 public Type enumerator_type;
5021 public bool is_disposable;
5023 public ForeachHelperMethods (EmitContext ec)
5026 this.element_type = TypeManager.object_type;
5027 this.enumerator_type = TypeManager.ienumerator_type;
5028 this.is_disposable = true;
5032 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
5037 if (!(m is MethodInfo))
5040 if (m.Name != "GetEnumerator")
5043 MethodInfo mi = (MethodInfo) m;
5044 Type [] args = TypeManager.GetArgumentTypes (mi);
5046 if (args.Length != 0)
5049 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
5050 EmitContext ec = hm.ec;
5053 // Check whether GetEnumerator is accessible to us
5055 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
5057 Type declaring = mi.DeclaringType;
5058 if (prot == MethodAttributes.Private){
5059 if (declaring != ec.ContainerType)
5061 } else if (prot == MethodAttributes.FamANDAssem){
5062 // If from a different assembly, false
5063 if (!(mi is MethodBuilder))
5066 // Are we being invoked from the same class, or from a derived method?
5068 if (ec.ContainerType != declaring){
5069 if (!ec.ContainerType.IsSubclassOf (declaring))
5072 } else if (prot == MethodAttributes.FamORAssem){
5073 if (!(mi is MethodBuilder ||
5074 ec.ContainerType == declaring ||
5075 ec.ContainerType.IsSubclassOf (declaring)))
5077 } if (prot == MethodAttributes.Family){
5078 if (!(ec.ContainerType == declaring ||
5079 ec.ContainerType.IsSubclassOf (declaring)))
5084 // Ok, we can access it, now make sure that we can do something
5085 // with this `GetEnumerator'
5088 if (mi.ReturnType == TypeManager.ienumerator_type ||
5089 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
5090 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
5091 hm.move_next = TypeManager.bool_movenext_void;
5092 hm.get_current = TypeManager.object_getcurrent_void;
5097 // Ok, so they dont return an IEnumerable, we will have to
5098 // find if they support the GetEnumerator pattern.
5100 Type return_type = mi.ReturnType;
5102 hm.move_next = FetchMethodMoveNext (return_type);
5103 if (hm.move_next == null)
5105 hm.get_current = FetchMethodGetCurrent (return_type);
5106 if (hm.get_current == null)
5109 hm.element_type = hm.get_current.ReturnType;
5110 hm.enumerator_type = return_type;
5111 hm.is_disposable = TypeManager.ImplementsInterface (
5112 hm.enumerator_type, TypeManager.idisposable_type);
5118 /// This filter is used to find the GetEnumerator method
5119 /// on which IEnumerator operates
5121 static MemberFilter FilterEnumerator;
5125 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
5128 void error1579 (Type t)
5130 Report.Error (1579, loc,
5131 "foreach statement cannot operate on variables of type `" +
5132 t.FullName + "' because that class does not provide a " +
5133 " GetEnumerator method or it is inaccessible");
5136 static bool TryType (Type t, ForeachHelperMethods hm)
5140 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
5141 BindingFlags.Public | BindingFlags.NonPublic |
5142 BindingFlags.Instance,
5143 FilterEnumerator, hm);
5148 hm.get_enumerator = (MethodInfo) mi [0];
5153 // Looks for a usable GetEnumerator in the Type, and if found returns
5154 // the three methods that participate: GetEnumerator, MoveNext and get_Current
5156 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
5158 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
5160 if (TryType (t, hm))
5164 // Now try to find the method in the interfaces
5167 Type [] ifaces = t.GetInterfaces ();
5169 foreach (Type i in ifaces){
5170 if (TryType (i, hm))
5175 // Since TypeBuilder.GetInterfaces only returns the interface
5176 // types for this type, we have to keep looping, but once
5177 // we hit a non-TypeBuilder (ie, a Type), then we know we are
5178 // done, because it returns all the types
5180 if ((t is TypeBuilder))
5190 // FIXME: possible optimization.
5191 // We might be able to avoid creating `empty' if the type is the sam
5193 bool EmitCollectionForeach (EmitContext ec)
5195 ILGenerator ig = ec.ig;
5196 LocalBuilder enumerator, disposable;
5198 enumerator = ig.DeclareLocal (hm.enumerator_type);
5199 if (hm.is_disposable)
5200 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
5205 // Instantiate the enumerator
5207 if (expr.Type.IsValueType){
5208 if (expr is IMemoryLocation){
5209 IMemoryLocation ml = (IMemoryLocation) expr;
5211 ml.AddressOf (ec, AddressOp.Load);
5213 throw new Exception ("Expr " + expr + " of type " + expr.Type +
5214 " does not implement IMemoryLocation");
5215 ig.Emit (OpCodes.Call, hm.get_enumerator);
5218 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
5220 ig.Emit (OpCodes.Stloc, enumerator);
5223 // Protect the code in a try/finalize block, so that
5224 // if the beast implement IDisposable, we get rid of it
5227 bool old_in_try = ec.InTry;
5229 if (hm.is_disposable) {
5230 l = ig.BeginExceptionBlock ();
5234 Label end_try = ig.DefineLabel ();
5236 ig.MarkLabel (ec.LoopBegin);
5237 ig.Emit (OpCodes.Ldloc, enumerator);
5238 ig.Emit (OpCodes.Callvirt, hm.move_next);
5239 ig.Emit (OpCodes.Brfalse, end_try);
5240 ig.Emit (OpCodes.Ldloc, enumerator);
5241 ig.Emit (OpCodes.Callvirt, hm.get_current);
5242 variable.EmitAssign (ec, conv);
5243 statement.Emit (ec);
5244 ig.Emit (OpCodes.Br, ec.LoopBegin);
5245 ig.MarkLabel (end_try);
5246 ec.InTry = old_in_try;
5248 // The runtime provides this for us.
5249 // ig.Emit (OpCodes.Leave, end);
5252 // Now the finally block
5254 if (hm.is_disposable) {
5255 Label end_finally = ig.DefineLabel ();
5256 bool old_in_finally = ec.InFinally;
5257 ec.InFinally = true;
5258 ig.BeginFinallyBlock ();
5260 ig.Emit (OpCodes.Ldloc, enumerator);
5261 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
5262 ig.Emit (OpCodes.Stloc, disposable);
5263 ig.Emit (OpCodes.Ldloc, disposable);
5264 ig.Emit (OpCodes.Brfalse, end_finally);
5265 ig.Emit (OpCodes.Ldloc, disposable);
5266 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
5267 ig.MarkLabel (end_finally);
5268 ec.InFinally = old_in_finally;
5270 // The runtime generates this anyways.
5271 // ig.Emit (OpCodes.Endfinally);
5273 ig.EndExceptionBlock ();
5276 ig.MarkLabel (ec.LoopEnd);
5281 // FIXME: possible optimization.
5282 // We might be able to avoid creating `empty' if the type is the sam
5284 bool EmitArrayForeach (EmitContext ec)
5286 int rank = array_type.GetArrayRank ();
5287 ILGenerator ig = ec.ig;
5289 LocalBuilder copy = ig.DeclareLocal (array_type);
5292 // Make our copy of the array
5295 ig.Emit (OpCodes.Stloc, copy);
5298 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
5302 ig.Emit (OpCodes.Ldc_I4_0);
5303 ig.Emit (OpCodes.Stloc, counter);
5304 test = ig.DefineLabel ();
5305 ig.Emit (OpCodes.Br, test);
5307 loop = ig.DefineLabel ();
5308 ig.MarkLabel (loop);
5310 ig.Emit (OpCodes.Ldloc, copy);
5311 ig.Emit (OpCodes.Ldloc, counter);
5312 ArrayAccess.EmitLoadOpcode (ig, var_type);
5314 variable.EmitAssign (ec, conv);
5316 statement.Emit (ec);
5318 ig.MarkLabel (ec.LoopBegin);
5319 ig.Emit (OpCodes.Ldloc, counter);
5320 ig.Emit (OpCodes.Ldc_I4_1);
5321 ig.Emit (OpCodes.Add);
5322 ig.Emit (OpCodes.Stloc, counter);
5324 ig.MarkLabel (test);
5325 ig.Emit (OpCodes.Ldloc, counter);
5326 ig.Emit (OpCodes.Ldloc, copy);
5327 ig.Emit (OpCodes.Ldlen);
5328 ig.Emit (OpCodes.Conv_I4);
5329 ig.Emit (OpCodes.Blt, loop);
5331 LocalBuilder [] dim_len = new LocalBuilder [rank];
5332 LocalBuilder [] dim_count = new LocalBuilder [rank];
5333 Label [] loop = new Label [rank];
5334 Label [] test = new Label [rank];
5337 for (dim = 0; dim < rank; dim++){
5338 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
5339 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
5340 test [dim] = ig.DefineLabel ();
5341 loop [dim] = ig.DefineLabel ();
5344 for (dim = 0; dim < rank; dim++){
5345 ig.Emit (OpCodes.Ldloc, copy);
5346 IntLiteral.EmitInt (ig, dim);
5347 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
5348 ig.Emit (OpCodes.Stloc, dim_len [dim]);
5351 for (dim = 0; dim < rank; dim++){
5352 ig.Emit (OpCodes.Ldc_I4_0);
5353 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5354 ig.Emit (OpCodes.Br, test [dim]);
5355 ig.MarkLabel (loop [dim]);
5358 ig.Emit (OpCodes.Ldloc, copy);
5359 for (dim = 0; dim < rank; dim++)
5360 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5363 // FIXME: Maybe we can cache the computation of `get'?
5365 Type [] args = new Type [rank];
5368 for (int i = 0; i < rank; i++)
5369 args [i] = TypeManager.int32_type;
5371 ModuleBuilder mb = CodeGen.ModuleBuilder;
5372 get = mb.GetArrayMethod (
5374 CallingConventions.HasThis| CallingConventions.Standard,
5376 ig.Emit (OpCodes.Call, get);
5377 variable.EmitAssign (ec, conv);
5378 statement.Emit (ec);
5379 ig.MarkLabel (ec.LoopBegin);
5380 for (dim = rank - 1; dim >= 0; dim--){
5381 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5382 ig.Emit (OpCodes.Ldc_I4_1);
5383 ig.Emit (OpCodes.Add);
5384 ig.Emit (OpCodes.Stloc, dim_count [dim]);
5386 ig.MarkLabel (test [dim]);
5387 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
5388 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
5389 ig.Emit (OpCodes.Blt, loop [dim]);
5392 ig.MarkLabel (ec.LoopEnd);
5397 protected override bool DoEmit (EmitContext ec)
5401 ILGenerator ig = ec.ig;
5403 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
5404 bool old_inloop = ec.InLoop;
5405 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
5406 ec.LoopBegin = ig.DefineLabel ();
5407 ec.LoopEnd = ig.DefineLabel ();
5409 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
5412 ret_val = EmitCollectionForeach (ec);
5414 ret_val = EmitArrayForeach (ec);
5416 ec.LoopBegin = old_begin;
5417 ec.LoopEnd = old_end;
5418 ec.InLoop = old_inloop;
5419 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
5426 /// AddHandler statement
5428 public class AddHandler : Statement {
5430 Expression EvtHandler;
5431 Expression EvtTarget;
5433 public AddHandler (Expression evt_id, Expression evt_handler,
5434 Expression evt_target, Location l)
5437 EvtHandler = evt_handler;
5438 EvtTarget = evt_target;
5440 Console.WriteLine ("Adding handler '" + evt_handler + "' for Event '" + evt_id +"'");
5443 public override bool Resolve (EmitContext ec)
5445 EvtId = EvtId.Resolve(ec);
5446 EvtHandler = EvtHandler.Resolve(ec,ResolveFlags.MethodGroup);
5447 EvtTarget = EvtTarget.Resolve (ec,ResolveFlags.VariableOrValue);
5448 if (EvtId == null || (!(EvtId is EventExpr))) {
5449 Report.Error (999, "'AddHandler' statement needs an event designator.");
5453 if (EvtHandler == null)
5455 Report.Error (999, "'AddHandler' statement needs an event handler.");
5458 //EventExpr ee = (EventExpr) EvtId;
5459 //MethodGroupExpr me = (MethodGroupExpr) EvtHandler;
5460 //bool b = EvtId.Type.IsSubclassOf (TypeManager.delegate_type);
5461 //ee.EventInfo.AddEventHandler(EvtTarget, new System.Delegate())
5465 protected override bool DoEmit (EmitContext ec)
5468 ArrayList args = new ArrayList();
5469 Argument arg = new Argument (EvtHandler, Argument.AType.Expression);
5472 // The even type was already resolved to a delegate, so
5473 // we must un-resolve its name to generate a type expression
5474 string ts = (EvtId.Type.ToString()).Replace ('+','.');
5475 Expression dtype = Mono.MonoBASIC.Parser.DecomposeQI (ts, Location.Null);
5477 // which we can use to declare a new event handler
5479 d = new New (dtype, args, Location.Null);
5481 e = new CompoundAssign(Binary.Operator.Addition, EvtId, d, Location.Null);
5483 // we resolve it all and emit the code