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, 2003 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 /// We already know that the statement is unreachable, but we still
35 /// need to resolve it to catch errors.
37 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
40 // This conflicts with csc's way of doing this, but IMHO it's
41 // the right thing to do.
43 // If something is unreachable, we still check whether it's
44 // correct. This means that you cannot use unassigned variables
45 // in unreachable code, for instance.
48 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
49 bool ok = Resolve (ec);
50 ec.KillFlowBranching ();
56 Report.Warning (162, loc, "Unreachable code detected");
61 /// Return value indicates whether all code paths emitted return.
63 protected abstract void DoEmit (EmitContext ec);
66 /// Utility wrapper routine for Error, just to beautify the code
68 public void Error (int error, string format, params object[] args)
70 Error (error, String.Format (format, args));
73 public void Error (int error, string s)
75 if (!Location.IsNull (loc))
76 Report.Error (error, loc, s);
78 Report.Error (error, s);
82 /// Return value indicates whether all code paths emitted return.
84 public virtual void Emit (EmitContext ec)
91 public sealed class EmptyStatement : Statement {
93 private EmptyStatement () {}
95 public static readonly EmptyStatement Value = new EmptyStatement ();
97 public override bool Resolve (EmitContext ec)
102 protected override void DoEmit (EmitContext ec)
107 public class If : Statement {
109 public Statement TrueStatement;
110 public Statement FalseStatement;
114 public If (Expression expr, Statement trueStatement, Location l)
117 TrueStatement = trueStatement;
121 public If (Expression expr,
122 Statement trueStatement,
123 Statement falseStatement,
127 TrueStatement = trueStatement;
128 FalseStatement = falseStatement;
132 public override bool Resolve (EmitContext ec)
134 Report.Debug (1, "START IF BLOCK", loc);
136 expr = Expression.ResolveBoolean (ec, expr, loc);
142 // Dead code elimination
144 if (expr is BoolConstant){
145 bool take = ((BoolConstant) expr).Value;
148 if (!TrueStatement.Resolve (ec))
151 if ((FalseStatement != null) &&
152 !FalseStatement.ResolveUnreachable (ec, true))
154 FalseStatement = null;
156 if (!TrueStatement.ResolveUnreachable (ec, true))
158 TrueStatement = null;
160 if ((FalseStatement != null) &&
161 !FalseStatement.Resolve (ec))
168 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
170 bool ok = TrueStatement.Resolve (ec);
172 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
174 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
176 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
179 ec.EndFlowBranching ();
181 Report.Debug (1, "END IF BLOCK", loc);
186 protected override void DoEmit (EmitContext ec)
188 ILGenerator ig = ec.ig;
189 Label false_target = ig.DefineLabel ();
193 // If we're a boolean expression, Resolve() already
194 // eliminated dead code for us.
196 if (expr is BoolConstant){
197 bool take = ((BoolConstant) expr).Value;
200 TrueStatement.Emit (ec);
201 else if (FalseStatement != null)
202 FalseStatement.Emit (ec);
207 expr.EmitBranchable (ec, false_target, false);
209 TrueStatement.Emit (ec);
211 if (FalseStatement != null){
212 bool branch_emitted = false;
214 end = ig.DefineLabel ();
216 ig.Emit (OpCodes.Br, end);
217 branch_emitted = true;
220 ig.MarkLabel (false_target);
221 FalseStatement.Emit (ec);
226 ig.MarkLabel (false_target);
231 public class Do : Statement {
232 public Expression expr;
233 public readonly Statement EmbeddedStatement;
236 public Do (Statement statement, Expression boolExpr, Location l)
239 EmbeddedStatement = statement;
243 public override bool Resolve (EmitContext ec)
247 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
249 if (!EmbeddedStatement.Resolve (ec))
252 expr = Expression.ResolveBoolean (ec, expr, loc);
255 else if (expr is BoolConstant){
256 bool res = ((BoolConstant) expr).Value;
262 ec.CurrentBranching.Infinite = infinite;
263 ec.EndFlowBranching ();
268 protected override void DoEmit (EmitContext ec)
270 ILGenerator ig = ec.ig;
271 Label loop = ig.DefineLabel ();
272 Label old_begin = ec.LoopBegin;
273 Label old_end = ec.LoopEnd;
275 ec.LoopBegin = ig.DefineLabel ();
276 ec.LoopEnd = ig.DefineLabel ();
279 EmbeddedStatement.Emit (ec);
280 ig.MarkLabel (ec.LoopBegin);
283 // Dead code elimination
285 if (expr is BoolConstant){
286 bool res = ((BoolConstant) expr).Value;
289 ec.ig.Emit (OpCodes.Br, loop);
291 expr.EmitBranchable (ec, loop, true);
293 ig.MarkLabel (ec.LoopEnd);
295 ec.LoopBegin = old_begin;
296 ec.LoopEnd = old_end;
300 public class While : Statement {
301 public Expression expr;
302 public readonly Statement Statement;
303 bool infinite, empty;
305 public While (Expression boolExpr, Statement statement, Location l)
307 this.expr = boolExpr;
308 Statement = statement;
312 public override bool Resolve (EmitContext ec)
316 expr = Expression.ResolveBoolean (ec, expr, loc);
321 // Inform whether we are infinite or not
323 if (expr is BoolConstant){
324 BoolConstant bc = (BoolConstant) expr;
326 if (bc.Value == false){
327 if (!Statement.ResolveUnreachable (ec, true))
335 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
337 if (!Statement.Resolve (ec))
340 ec.CurrentBranching.Infinite = infinite;
341 ec.EndFlowBranching ();
346 protected override void DoEmit (EmitContext ec)
351 ILGenerator ig = ec.ig;
352 Label old_begin = ec.LoopBegin;
353 Label old_end = ec.LoopEnd;
355 ec.LoopBegin = ig.DefineLabel ();
356 ec.LoopEnd = ig.DefineLabel ();
359 // Inform whether we are infinite or not
361 if (expr is BoolConstant){
362 ig.MarkLabel (ec.LoopBegin);
364 ig.Emit (OpCodes.Br, ec.LoopBegin);
367 // Inform that we are infinite (ie, `we return'), only
368 // if we do not `break' inside the code.
370 ig.MarkLabel (ec.LoopEnd);
372 Label while_loop = ig.DefineLabel ();
374 ig.Emit (OpCodes.Br, ec.LoopBegin);
375 ig.MarkLabel (while_loop);
379 ig.MarkLabel (ec.LoopBegin);
381 expr.EmitBranchable (ec, while_loop, true);
383 ig.MarkLabel (ec.LoopEnd);
386 ec.LoopBegin = old_begin;
387 ec.LoopEnd = old_end;
391 public class For : Statement {
393 readonly Statement InitStatement;
394 readonly Statement Increment;
395 readonly Statement Statement;
396 bool infinite, empty;
398 public For (Statement initStatement,
404 InitStatement = initStatement;
406 Increment = increment;
407 Statement = statement;
411 public override bool Resolve (EmitContext ec)
415 if (InitStatement != null){
416 if (!InitStatement.Resolve (ec))
421 Test = Expression.ResolveBoolean (ec, Test, loc);
424 else if (Test is BoolConstant){
425 BoolConstant bc = (BoolConstant) Test;
427 if (bc.Value == false){
428 if (!Statement.ResolveUnreachable (ec, true))
430 if ((Increment != null) &&
431 !Increment.ResolveUnreachable (ec, false))
441 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
443 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
445 if (!Statement.Resolve (ec))
448 if (Increment != null){
449 if (!Increment.Resolve (ec))
453 ec.CurrentBranching.Infinite = infinite;
454 ec.EndFlowBranching ();
459 protected override void DoEmit (EmitContext ec)
464 ILGenerator ig = ec.ig;
465 Label old_begin = ec.LoopBegin;
466 Label old_end = ec.LoopEnd;
467 Label loop = ig.DefineLabel ();
468 Label test = ig.DefineLabel ();
470 if (InitStatement != null && InitStatement != EmptyStatement.Value)
471 InitStatement.Emit (ec);
473 ec.LoopBegin = ig.DefineLabel ();
474 ec.LoopEnd = ig.DefineLabel ();
476 ig.Emit (OpCodes.Br, test);
480 ig.MarkLabel (ec.LoopBegin);
481 if (Increment != EmptyStatement.Value)
486 // If test is null, there is no test, and we are just
491 // The Resolve code already catches the case for
492 // Test == BoolConstant (false) so we know that
495 if (Test is BoolConstant)
496 ig.Emit (OpCodes.Br, loop);
498 Test.EmitBranchable (ec, loop, true);
501 ig.Emit (OpCodes.Br, loop);
502 ig.MarkLabel (ec.LoopEnd);
504 ec.LoopBegin = old_begin;
505 ec.LoopEnd = old_end;
509 public class StatementExpression : Statement {
510 ExpressionStatement expr;
512 public StatementExpression (ExpressionStatement expr, Location l)
518 public override bool Resolve (EmitContext ec)
520 expr = expr.ResolveStatement (ec);
524 protected override void DoEmit (EmitContext ec)
526 expr.EmitStatement (ec);
529 public override string ToString ()
531 return "StatementExpression (" + expr + ")";
536 /// Implements the return statement
538 public class Return : Statement {
539 public Expression Expr;
541 public Return (Expression expr, Location l)
549 public override bool Resolve (EmitContext ec)
551 if (ec.ReturnType == null){
553 Error (127, "Return with a value not allowed here");
558 Error (126, "An object of type `{0}' is expected " +
559 "for the return statement",
560 TypeManager.CSharpName (ec.ReturnType));
564 Expr = Expr.Resolve (ec);
568 if (Expr.Type != ec.ReturnType) {
569 Expr = Convert.ImplicitConversionRequired (
570 ec, Expr, ec.ReturnType, loc);
577 Error (-206, "Return statement not allowed inside iterators");
581 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
583 if (ec.CurrentBranching.InTryOrCatch (true)) {
584 ec.CurrentBranching.AddFinallyVector (vector);
586 } else if (ec.CurrentBranching.InFinally (true)) {
587 Error (157, "Control can not leave the body of the finally block");
590 vector.CheckOutParameters (ec.CurrentBranching);
592 ec.CurrentBranching.CurrentUsageVector.Return ();
596 protected override void DoEmit (EmitContext ec)
601 if (in_exc || !ec.IsLastStatement)
602 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
606 ec.NeedReturnLabel ();
607 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
608 } else if (ec.IsLastStatement) {
609 // If we are the last statement in a top-level block, simply
611 ec.ig.Emit (OpCodes.Ret);
613 // Otherwise, we always create a return label and jump to
615 ec.NeedReturnLabel ();
616 ec.ig.Emit (OpCodes.Br, ec.ReturnLabel);
621 public class Goto : Statement {
624 LabeledStatement label;
626 public override bool Resolve (EmitContext ec)
628 label = block.LookupLabel (target);
632 "No such label `" + target + "' in this scope");
636 // If this is a forward goto.
637 if (!label.IsDefined)
638 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
640 ec.CurrentBranching.CurrentUsageVector.Goto ();
645 public Goto (Block parent_block, string label, Location l)
647 block = parent_block;
652 public string Target {
658 protected override void DoEmit (EmitContext ec)
660 Label l = label.LabelTarget (ec);
661 ec.ig.Emit (OpCodes.Br, l);
665 public class LabeledStatement : Statement {
666 public readonly Location Location;
671 FlowBranching.UsageVector vectors;
673 public LabeledStatement (string label_name, Location l)
678 public Label LabelTarget (EmitContext ec)
682 label = ec.ig.DefineLabel ();
688 public bool IsDefined {
694 public bool HasBeenReferenced {
700 public void AddUsageVector (FlowBranching.UsageVector vector)
702 vector = vector.Clone ();
703 vector.Next = vectors;
707 public override bool Resolve (EmitContext ec)
709 ec.CurrentBranching.Label (vectors);
716 protected override void DoEmit (EmitContext ec)
719 ec.ig.MarkLabel (label);
725 /// `goto default' statement
727 public class GotoDefault : Statement {
729 public GotoDefault (Location l)
734 public override bool Resolve (EmitContext ec)
736 ec.CurrentBranching.CurrentUsageVector.Goto ();
740 protected override void DoEmit (EmitContext ec)
742 if (ec.Switch == null){
743 Report.Error (153, loc, "goto default is only valid in a switch statement");
747 if (!ec.Switch.GotDefault){
748 Report.Error (159, loc, "No default target on switch statement");
751 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
756 /// `goto case' statement
758 public class GotoCase : Statement {
762 public GotoCase (Expression e, Location l)
768 public override bool Resolve (EmitContext ec)
770 if (ec.Switch == null){
771 Report.Error (153, loc, "goto case is only valid in a switch statement");
775 expr = expr.Resolve (ec);
779 if (!(expr is Constant)){
780 Report.Error (159, loc, "Target expression for goto case is not constant");
784 object val = Expression.ConvertIntLiteral (
785 (Constant) expr, ec.Switch.SwitchType, loc);
790 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
795 "No such label 'case " + val + "': for the goto case");
799 label = sl.ILLabelCode;
801 ec.CurrentBranching.CurrentUsageVector.Goto ();
805 protected override void DoEmit (EmitContext ec)
807 ec.ig.Emit (OpCodes.Br, label);
811 public class Throw : Statement {
814 public Throw (Expression expr, Location l)
820 public override bool Resolve (EmitContext ec)
822 bool in_catch = ec.CurrentBranching.InCatch ();
823 ec.CurrentBranching.CurrentUsageVector.Throw ();
826 expr = expr.Resolve (ec);
830 ExprClass eclass = expr.eclass;
832 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
833 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
834 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
840 if ((t != TypeManager.exception_type) &&
841 !t.IsSubclassOf (TypeManager.exception_type) &&
842 !(expr is NullLiteral)) {
844 "The type caught or thrown must be derived " +
845 "from System.Exception");
848 } else if (!in_catch) {
850 "A throw statement with no argument is only " +
851 "allowed in a catch clause");
858 protected override void DoEmit (EmitContext ec)
861 ec.ig.Emit (OpCodes.Rethrow);
865 ec.ig.Emit (OpCodes.Throw);
870 public class Break : Statement {
872 public Break (Location l)
879 public override bool Resolve (EmitContext ec)
881 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
882 Error (139, "No enclosing loop or switch to continue to");
884 } else if (ec.CurrentBranching.InFinally (false)) {
885 Error (157, "Control can not leave the body of the finally block");
887 } else if (ec.CurrentBranching.InTryOrCatch (false))
888 ec.CurrentBranching.AddFinallyVector (
889 ec.CurrentBranching.CurrentUsageVector);
890 else if (ec.CurrentBranching.InLoop ())
891 ec.CurrentBranching.AddBreakVector (
892 ec.CurrentBranching.CurrentUsageVector);
894 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
896 ec.CurrentBranching.CurrentUsageVector.Break ();
900 protected override void DoEmit (EmitContext ec)
902 ILGenerator ig = ec.ig;
905 ig.Emit (OpCodes.Leave, ec.LoopEnd);
907 ec.NeedReturnLabel ();
908 ig.Emit (OpCodes.Br, ec.LoopEnd);
913 public class Continue : Statement {
915 public Continue (Location l)
922 public override bool Resolve (EmitContext ec)
924 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
925 Error (139, "No enclosing loop to continue to");
927 } else if (ec.CurrentBranching.InFinally (false)) {
928 Error (157, "Control can not leave the body of the finally block");
930 } else if (ec.CurrentBranching.InTryOrCatch (false))
931 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
933 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
935 ec.CurrentBranching.CurrentUsageVector.Goto ();
939 protected override void DoEmit (EmitContext ec)
941 Label begin = ec.LoopBegin;
944 ec.ig.Emit (OpCodes.Leave, begin);
946 ec.ig.Emit (OpCodes.Br, begin);
950 public class LocalInfo {
951 public Expression Type;
954 // Most of the time a variable will be stored in a LocalBuilder
956 // But sometimes, it will be stored in a field. The context of the field will
957 // be stored in the EmitContext
960 public LocalBuilder LocalBuilder;
961 public FieldBuilder FieldBuilder;
963 public Type VariableType;
964 public readonly string Name;
965 public readonly Location Location;
966 public readonly Block Block;
968 public VariableInfo VariableInfo;
978 public LocalInfo (Expression type, string name, Block block, Location l)
986 public LocalInfo (TypeContainer tc, Block block, Location l)
988 VariableType = tc.TypeBuilder;
993 public bool IsThisAssigned (EmitContext ec, Location loc)
995 if (VariableInfo == null)
996 throw new Exception ();
998 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1001 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1004 public bool IsAssigned (EmitContext ec)
1006 if (VariableInfo == null)
1007 throw new Exception ();
1009 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1012 public bool Resolve (DeclSpace decl)
1014 if (VariableType == null)
1015 VariableType = decl.ResolveType (Type, false, Location);
1017 if (VariableType == null)
1023 public void MakePinned ()
1025 TypeManager.MakePinned (LocalBuilder);
1026 flags |= Flags.Fixed;
1029 public bool IsFixed {
1031 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1038 public override string ToString ()
1040 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1041 Name, Type, VariableInfo, Location);
1046 return (flags & Flags.Used) != 0;
1049 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1053 public bool ReadOnly {
1055 return (flags & Flags.ReadOnly) != 0;
1058 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1067 /// Block represents a C# block.
1071 /// This class is used in a number of places: either to represent
1072 /// explicit blocks that the programmer places or implicit blocks.
1074 /// Implicit blocks are used as labels or to introduce variable
1077 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1078 /// they contain extra information that is not necessary on normal blocks.
1080 public class Block : Statement {
1081 public readonly Block Parent;
1082 public readonly Location StartLocation;
1083 public Location EndLocation = Location.Null;
1086 public enum Flags : byte {
1090 VariablesInitialized = 8,
1096 public bool Implicit {
1098 return (flags & Flags.Implicit) != 0;
1102 public bool Unchecked {
1104 return (flags & Flags.Unchecked) != 0;
1107 flags |= Flags.Unchecked;
1112 // The statements in this block
1114 ArrayList statements;
1118 // An array of Blocks. We keep track of children just
1119 // to generate the local variable declarations.
1121 // Statements and child statements are handled through the
1127 // Labels. (label, block) pairs.
1132 // Keeps track of (name, type) pairs
1134 Hashtable variables;
1137 // Keeps track of constants
1138 Hashtable constants;
1141 // If this is a switch section, the enclosing switch block.
1149 public Block (Block parent)
1150 : this (parent, (Flags) 0, Location.Null, Location.Null)
1153 public Block (Block parent, Flags flags)
1154 : this (parent, flags, Location.Null, Location.Null)
1157 public Block (Block parent, Flags flags, Parameters parameters)
1158 : this (parent, flags, parameters, Location.Null, Location.Null)
1161 public Block (Block parent, Location start, Location end)
1162 : this (parent, (Flags) 0, start, end)
1165 public Block (Block parent, Parameters parameters, Location start, Location end)
1166 : this (parent, (Flags) 0, parameters, start, end)
1169 public Block (Block parent, Flags flags, Location start, Location end)
1170 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1173 public Block (Block parent, Flags flags, Parameters parameters,
1174 Location start, Location end)
1177 parent.AddChild (this);
1179 this.Parent = parent;
1181 this.parameters = parameters;
1182 this.StartLocation = start;
1183 this.EndLocation = end;
1186 statements = new ArrayList ();
1188 if (parent != null && Implicit) {
1189 if (parent.child_variable_names == null)
1190 parent.child_variable_names = new Hashtable();
1191 // share with parent
1192 child_variable_names = parent.child_variable_names;
1197 public Block CreateSwitchBlock (Location start)
1199 Block new_block = new Block (this, start, start);
1200 new_block.switch_block = this;
1210 void AddChild (Block b)
1212 if (children == null)
1213 children = new ArrayList ();
1218 public void SetEndLocation (Location loc)
1224 /// Adds a label to the current block.
1228 /// false if the name already exists in this block. true
1232 public bool AddLabel (string name, LabeledStatement target, Location loc)
1234 if (switch_block != null)
1235 return switch_block.AddLabel (name, target, loc);
1238 while (cur != null && cur.Implicit) {
1239 if (cur.LookupLabel (name) != null) {
1241 140, loc, "The label '{0}' is a duplicate",
1249 while (cur != null) {
1250 if (cur.LookupLabel (name) != null) {
1253 "The label '{0}' shadows another label " +
1254 "by the same name in a containing scope.",
1263 labels = new Hashtable ();
1265 labels.Add (name, target);
1269 public LabeledStatement LookupLabel (string name)
1271 Hashtable l = new Hashtable ();
1273 return LookupLabel (name, l);
1277 // Lookups a label in the current block, parents and children.
1278 // It skips during child recurssion on `source'
1280 LabeledStatement LookupLabel (string name, Hashtable seen)
1282 if (switch_block != null)
1283 return switch_block.LookupLabel (name, seen);
1285 if (seen [this] != null)
1291 if (labels.Contains (name))
1292 return ((LabeledStatement) labels [name]);
1294 if (children != null){
1295 foreach (Block b in children){
1296 LabeledStatement s = b.LookupLabel (name, seen);
1303 return Parent.LookupLabel (name, seen);
1308 LocalInfo this_variable = null;
1311 // Returns the "this" instance variable of this block.
1312 // See AddThisVariable() for more information.
1314 public LocalInfo ThisVariable {
1316 if (this_variable != null)
1317 return this_variable;
1318 else if (Parent != null)
1319 return Parent.ThisVariable;
1325 Hashtable child_variable_names;
1328 // Marks a variable with name @name as being used in a child block.
1329 // If a variable name has been used in a child block, it's illegal to
1330 // declare a variable with the same name in the current block.
1332 public void AddChildVariableName (string name)
1334 if (child_variable_names == null)
1335 child_variable_names = new Hashtable ();
1337 if (!child_variable_names.Contains (name))
1338 child_variable_names.Add (name, true);
1342 // Checks whether a variable name has already been used in a child block.
1344 public bool IsVariableNameUsedInChildBlock (string name)
1346 if (child_variable_names == null)
1349 return child_variable_names.Contains (name);
1353 // This is used by non-static `struct' constructors which do not have an
1354 // initializer - in this case, the constructor must initialize all of the
1355 // struct's fields. To do this, we add a "this" variable and use the flow
1356 // analysis code to ensure that it's been fully initialized before control
1357 // leaves the constructor.
1359 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1361 if (this_variable != null)
1362 return this_variable;
1364 if (variables == null)
1365 variables = new Hashtable ();
1367 this_variable = new LocalInfo (tc, this, l);
1368 this_variable.Used = true;
1370 variables.Add ("this", this_variable);
1372 return this_variable;
1375 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1377 if (variables == null)
1378 variables = new Hashtable ();
1380 LocalInfo vi = GetLocalInfo (name);
1382 if (vi.Block != this)
1383 Report.Error (136, l, "A local variable named `" + name + "' " +
1384 "cannot be declared in this scope since it would " +
1385 "give a different meaning to `" + name + "', which " +
1386 "is already used in a `parent or current' scope to " +
1387 "denote something else");
1389 Report.Error (128, l, "A local variable `" + name + "' is already " +
1390 "defined in this scope");
1394 if (IsVariableNameUsedInChildBlock (name)) {
1395 Report.Error (136, l, "A local variable named `" + name + "' " +
1396 "cannot be declared in this scope since it would " +
1397 "give a different meaning to `" + name + "', which " +
1398 "is already used in a `child' scope to denote something " +
1405 Parameter p = pars.GetParameterByName (name, out idx);
1407 Report.Error (136, l, "A local variable named `" + name + "' " +
1408 "cannot be declared in this scope since it would " +
1409 "give a different meaning to `" + name + "', which " +
1410 "is already used in a `parent or current' scope to " +
1411 "denote something else");
1416 vi = new LocalInfo (type, name, this, l);
1418 variables.Add (name, vi);
1420 // Mark 'name' as "used by a child block" in every surrounding block
1422 while (cur != null && cur.Implicit)
1425 for (Block par = cur.Parent; par != null; par = par.Parent)
1426 par.AddChildVariableName (name);
1428 if ((flags & Flags.VariablesInitialized) != 0)
1429 throw new Exception ();
1431 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1435 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1437 if (AddVariable (type, name, pars, l) == null)
1440 if (constants == null)
1441 constants = new Hashtable ();
1443 constants.Add (name, value);
1447 public Hashtable Variables {
1453 public LocalInfo GetLocalInfo (string name)
1455 for (Block b = this; b != null; b = b.Parent) {
1456 if (b.variables != null) {
1457 LocalInfo ret = b.variables [name] as LocalInfo;
1465 public Expression GetVariableType (string name)
1467 LocalInfo vi = GetLocalInfo (name);
1475 public Expression GetConstantExpression (string name)
1477 for (Block b = this; b != null; b = b.Parent) {
1478 if (b.constants != null) {
1479 Expression ret = b.constants [name] as Expression;
1488 /// True if the variable named @name is a constant
1490 public bool IsConstant (string name)
1492 Expression e = null;
1494 e = GetConstantExpression (name);
1500 /// Use to fetch the statement associated with this label
1502 public Statement this [string name] {
1504 return (Statement) labels [name];
1508 Parameters parameters = null;
1509 public Parameters Parameters {
1512 while (b.Parent != null)
1514 return b.parameters;
1519 /// A list of labels that were not used within this block
1521 public string [] GetUnreferenced ()
1523 // FIXME: Implement me
1527 public void AddStatement (Statement s)
1530 flags |= Flags.BlockUsed;
1535 return (flags & Flags.BlockUsed) != 0;
1541 flags |= Flags.BlockUsed;
1544 public bool HasRet {
1546 return (flags & Flags.HasRet) != 0;
1550 public bool IsDestructor {
1552 return (flags & Flags.IsDestructor) != 0;
1556 public void SetDestructor ()
1558 flags |= Flags.IsDestructor;
1561 VariableMap param_map, local_map;
1563 public VariableMap ParameterMap {
1565 if ((flags & Flags.VariablesInitialized) == 0)
1566 throw new Exception ();
1572 public VariableMap LocalMap {
1574 if ((flags & Flags.VariablesInitialized) == 0)
1575 throw new Exception ();
1581 public bool LiftVariable (LocalInfo local_info)
1587 /// Emits the variable declarations and labels.
1590 /// tc: is our typecontainer (to resolve type references)
1591 /// ig: is the code generator:
1593 public void EmitMeta (EmitContext ec, InternalParameters ip)
1595 ILGenerator ig = ec.ig;
1598 // Compute the VariableMap's.
1600 // Unfortunately, we don't know the type when adding variables with
1601 // AddVariable(), so we need to compute this info here.
1605 if (variables != null) {
1606 foreach (LocalInfo li in variables.Values)
1607 li.Resolve (ec.DeclSpace);
1609 locals = new LocalInfo [variables.Count];
1610 variables.Values.CopyTo (locals, 0);
1612 locals = new LocalInfo [0];
1615 local_map = new VariableMap (Parent.LocalMap, locals);
1617 local_map = new VariableMap (locals);
1619 param_map = new VariableMap (ip);
1620 flags |= Flags.VariablesInitialized;
1622 bool old_check_state = ec.ConstantCheckState;
1623 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1624 bool remap_locals = ec.RemapToProxy;
1627 // Process this block variables
1629 if (variables != null){
1630 foreach (DictionaryEntry de in variables){
1631 string name = (string) de.Key;
1632 LocalInfo vi = (LocalInfo) de.Value;
1634 if (vi.VariableType == null)
1637 Type variable_type = vi.VariableType;
1639 if (variable_type.IsPointer){
1641 // Am not really convinced that this test is required (Microsoft does it)
1642 // but the fact is that you would not be able to use the pointer variable
1645 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1651 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1653 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1655 if (constants == null)
1658 Expression cv = (Expression) constants [name];
1662 ec.CurrentBlock = this;
1663 Expression e = cv.Resolve (ec);
1667 Constant ce = e as Constant;
1669 Report.Error (133, vi.Location,
1670 "The expression being assigned to `" +
1671 name + "' must be constant (" + e + ")");
1675 if (e.Type != variable_type){
1676 e = Const.ChangeType (vi.Location, ce, variable_type);
1681 constants.Remove (name);
1682 constants.Add (name, e);
1685 ec.ConstantCheckState = old_check_state;
1688 // Now, handle the children
1690 if (children != null){
1691 foreach (Block b in children)
1692 b.EmitMeta (ec, ip);
1696 void UsageWarning (FlowBranching.UsageVector vector)
1700 if (variables != null){
1701 foreach (DictionaryEntry de in variables){
1702 LocalInfo vi = (LocalInfo) de.Value;
1707 name = (string) de.Key;
1709 if (vector.IsAssigned (vi.VariableInfo)){
1711 219, vi.Location, "The variable `" + name +
1712 "' is assigned but its value is never used");
1715 168, vi.Location, "The variable `" +
1717 "' is declared but never used");
1723 public override bool Resolve (EmitContext ec)
1725 Block prev_block = ec.CurrentBlock;
1728 int errors = Report.Errors;
1730 ec.CurrentBlock = this;
1731 ec.StartFlowBranching (this);
1733 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1735 bool unreachable = false, warning_shown = false;
1737 int statement_count = statements.Count;
1738 for (int ix = 0; ix < statement_count; ix++){
1739 Statement s = (Statement) statements [ix];
1741 if (unreachable && !(s is LabeledStatement)) {
1742 if (!s.ResolveUnreachable (ec, !warning_shown))
1745 if (s != EmptyStatement.Value)
1746 warning_shown = true;
1748 statements [ix] = EmptyStatement.Value;
1752 if (s.Resolve (ec) == false) {
1754 statements [ix] = EmptyStatement.Value;
1758 num_statements = ix + 1;
1760 if (s is LabeledStatement)
1761 unreachable = false;
1763 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1766 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1767 ec.CurrentBranching, statement_count, num_statements);
1770 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1772 ec.CurrentBlock = prev_block;
1774 // If we're a non-static `struct' constructor which doesn't have an
1775 // initializer, then we must initialize all of the struct's fields.
1776 if ((this_variable != null) &&
1777 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1778 !this_variable.IsThisAssigned (ec, loc))
1781 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1782 foreach (LabeledStatement label in labels.Values)
1783 if (!label.HasBeenReferenced)
1784 Report.Warning (164, label.Location,
1785 "This label has not been referenced");
1788 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1790 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1791 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1792 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1793 flags |= Flags.HasRet;
1795 if (ok && (errors == Report.Errors)) {
1796 if (RootContext.WarningLevel >= 3)
1797 UsageWarning (vector);
1803 protected override void DoEmit (EmitContext ec)
1805 for (int ix = 0; ix < num_statements; ix++){
1806 Statement s = (Statement) statements [ix];
1808 // Check whether we are the last statement in a
1811 if ((Parent == null) && (ix+1 == num_statements))
1812 ec.IsLastStatement = true;
1814 ec.IsLastStatement = false;
1820 public override void Emit (EmitContext ec)
1822 Block prev_block = ec.CurrentBlock;
1824 ec.CurrentBlock = this;
1826 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1827 bool is_lexical_block = !Implicit && (Parent != null);
1829 if (emit_debug_info) {
1830 if (is_lexical_block)
1831 ec.ig.BeginScope ();
1833 if (variables != null) {
1834 foreach (DictionaryEntry de in variables) {
1835 string name = (string) de.Key;
1836 LocalInfo vi = (LocalInfo) de.Value;
1838 if (vi.LocalBuilder == null)
1841 vi.LocalBuilder.SetLocalSymInfo (name);
1846 ec.Mark (StartLocation, true);
1848 ec.Mark (EndLocation, true);
1850 if (emit_debug_info && is_lexical_block)
1853 ec.CurrentBlock = prev_block;
1859 public class ToplevelBlock : Block {
1860 public ToplevelBlock (Parameters parameters, Location start) :
1861 base (null, parameters, start, Location.Null)
1865 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1866 base (null, flags, parameters, start, Location.Null)
1871 public class SwitchLabel {
1874 public Location loc;
1875 public Label ILLabel;
1876 public Label ILLabelCode;
1879 // if expr == null, then it is the default case.
1881 public SwitchLabel (Expression expr, Location l)
1887 public Expression Label {
1893 public object Converted {
1900 // Resolves the expression, reduces it to a literal if possible
1901 // and then converts it to the requested type.
1903 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1905 ILLabel = ec.ig.DefineLabel ();
1906 ILLabelCode = ec.ig.DefineLabel ();
1911 Expression e = label.Resolve (ec);
1916 if (!(e is Constant)){
1917 Report.Error (150, loc, "A constant value is expected, got: " + e);
1921 if (e is StringConstant || e is NullLiteral){
1922 if (required_type == TypeManager.string_type){
1924 ILLabel = ec.ig.DefineLabel ();
1929 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1930 if (converted == null)
1937 public class SwitchSection {
1938 // An array of SwitchLabels.
1939 public readonly ArrayList Labels;
1940 public readonly Block Block;
1942 public SwitchSection (ArrayList labels, Block block)
1949 public class Switch : Statement {
1950 public readonly ArrayList Sections;
1951 public Expression Expr;
1954 /// Maps constants whose type type SwitchType to their SwitchLabels.
1956 public Hashtable Elements;
1959 /// The governing switch type
1961 public Type SwitchType;
1967 Label default_target;
1968 Expression new_expr;
1971 // The types allowed to be implicitly cast from
1972 // on the governing type
1974 static Type [] allowed_types;
1976 public Switch (Expression e, ArrayList sects, Location l)
1983 public bool GotDefault {
1989 public Label DefaultTarget {
1991 return default_target;
1996 // Determines the governing type for a switch. The returned
1997 // expression might be the expression from the switch, or an
1998 // expression that includes any potential conversions to the
1999 // integral types or to string.
2001 Expression SwitchGoverningType (EmitContext ec, Type t)
2003 if (t == TypeManager.int32_type ||
2004 t == TypeManager.uint32_type ||
2005 t == TypeManager.char_type ||
2006 t == TypeManager.byte_type ||
2007 t == TypeManager.sbyte_type ||
2008 t == TypeManager.ushort_type ||
2009 t == TypeManager.short_type ||
2010 t == TypeManager.uint64_type ||
2011 t == TypeManager.int64_type ||
2012 t == TypeManager.string_type ||
2013 t == TypeManager.bool_type ||
2014 t.IsSubclassOf (TypeManager.enum_type))
2017 if (allowed_types == null){
2018 allowed_types = new Type [] {
2019 TypeManager.sbyte_type,
2020 TypeManager.byte_type,
2021 TypeManager.short_type,
2022 TypeManager.ushort_type,
2023 TypeManager.int32_type,
2024 TypeManager.uint32_type,
2025 TypeManager.int64_type,
2026 TypeManager.uint64_type,
2027 TypeManager.char_type,
2028 TypeManager.bool_type,
2029 TypeManager.string_type
2034 // Try to find a *user* defined implicit conversion.
2036 // If there is no implicit conversion, or if there are multiple
2037 // conversions, we have to report an error
2039 Expression converted = null;
2040 foreach (Type tt in allowed_types){
2043 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2047 if (converted != null){
2048 Report.Error (-12, loc, "More than one conversion to an integral " +
2049 " type exists for type `" +
2050 TypeManager.CSharpName (Expr.Type)+"'");
2058 void error152 (string n)
2061 152, "The label `" + n + ":' " +
2062 "is already present on this switch statement");
2066 // Performs the basic sanity checks on the switch statement
2067 // (looks for duplicate keys and non-constant expressions).
2069 // It also returns a hashtable with the keys that we will later
2070 // use to compute the switch tables
2072 bool CheckSwitch (EmitContext ec)
2076 Elements = new Hashtable ();
2078 got_default = false;
2080 if (TypeManager.IsEnumType (SwitchType)){
2081 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2083 compare_type = SwitchType;
2085 foreach (SwitchSection ss in Sections){
2086 foreach (SwitchLabel sl in ss.Labels){
2087 if (!sl.ResolveAndReduce (ec, SwitchType)){
2092 if (sl.Label == null){
2094 error152 ("default");
2101 object key = sl.Converted;
2103 if (key is Constant)
2104 key = ((Constant) key).GetValue ();
2107 key = NullLiteral.Null;
2109 string lname = null;
2110 if (compare_type == TypeManager.uint64_type){
2111 ulong v = (ulong) key;
2113 if (Elements.Contains (v))
2114 lname = v.ToString ();
2116 Elements.Add (v, sl);
2117 } else if (compare_type == TypeManager.int64_type){
2118 long v = (long) key;
2120 if (Elements.Contains (v))
2121 lname = v.ToString ();
2123 Elements.Add (v, sl);
2124 } else if (compare_type == TypeManager.uint32_type){
2125 uint v = (uint) key;
2127 if (Elements.Contains (v))
2128 lname = v.ToString ();
2130 Elements.Add (v, sl);
2131 } else if (compare_type == TypeManager.char_type){
2132 char v = (char) key;
2134 if (Elements.Contains (v))
2135 lname = v.ToString ();
2137 Elements.Add (v, sl);
2138 } else if (compare_type == TypeManager.byte_type){
2139 byte v = (byte) key;
2141 if (Elements.Contains (v))
2142 lname = v.ToString ();
2144 Elements.Add (v, sl);
2145 } else if (compare_type == TypeManager.sbyte_type){
2146 sbyte v = (sbyte) key;
2148 if (Elements.Contains (v))
2149 lname = v.ToString ();
2151 Elements.Add (v, sl);
2152 } else if (compare_type == TypeManager.short_type){
2153 short v = (short) key;
2155 if (Elements.Contains (v))
2156 lname = v.ToString ();
2158 Elements.Add (v, sl);
2159 } else if (compare_type == TypeManager.ushort_type){
2160 ushort v = (ushort) key;
2162 if (Elements.Contains (v))
2163 lname = v.ToString ();
2165 Elements.Add (v, sl);
2166 } else if (compare_type == TypeManager.string_type){
2167 if (key is NullLiteral){
2168 if (Elements.Contains (NullLiteral.Null))
2171 Elements.Add (NullLiteral.Null, null);
2173 string s = (string) key;
2175 if (Elements.Contains (s))
2178 Elements.Add (s, sl);
2180 } else if (compare_type == TypeManager.int32_type) {
2183 if (Elements.Contains (v))
2184 lname = v.ToString ();
2186 Elements.Add (v, sl);
2187 } else if (compare_type == TypeManager.bool_type) {
2188 bool v = (bool) key;
2190 if (Elements.Contains (v))
2191 lname = v.ToString ();
2193 Elements.Add (v, sl);
2197 throw new Exception ("Unknown switch type!" +
2198 SwitchType + " " + compare_type);
2202 error152 ("case + " + lname);
2213 void EmitObjectInteger (ILGenerator ig, object k)
2216 IntConstant.EmitInt (ig, (int) k);
2217 else if (k is Constant) {
2218 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2221 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2224 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2226 IntConstant.EmitInt (ig, (int) (long) k);
2227 ig.Emit (OpCodes.Conv_I8);
2230 LongConstant.EmitLong (ig, (long) k);
2232 else if (k is ulong)
2234 if ((ulong) k < (1L<<32))
2236 IntConstant.EmitInt (ig, (int) (long) k);
2237 ig.Emit (OpCodes.Conv_U8);
2241 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2245 IntConstant.EmitInt (ig, (int) ((char) k));
2246 else if (k is sbyte)
2247 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2249 IntConstant.EmitInt (ig, (int) ((byte) k));
2250 else if (k is short)
2251 IntConstant.EmitInt (ig, (int) ((short) k));
2252 else if (k is ushort)
2253 IntConstant.EmitInt (ig, (int) ((ushort) k));
2255 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2257 throw new Exception ("Unhandled case");
2260 // structure used to hold blocks of keys while calculating table switch
2261 class KeyBlock : IComparable
2263 public KeyBlock (long _nFirst)
2265 nFirst = nLast = _nFirst;
2269 public ArrayList rgKeys = null;
2270 // how many items are in the bucket
2271 public int Size = 1;
2274 get { return (int) (nLast - nFirst + 1); }
2276 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2278 return kbLast.nLast - kbFirst.nFirst + 1;
2280 public int CompareTo (object obj)
2282 KeyBlock kb = (KeyBlock) obj;
2283 int nLength = Length;
2284 int nLengthOther = kb.Length;
2285 if (nLengthOther == nLength)
2286 return (int) (kb.nFirst - nFirst);
2287 return nLength - nLengthOther;
2292 /// This method emits code for a lookup-based switch statement (non-string)
2293 /// Basically it groups the cases into blocks that are at least half full,
2294 /// and then spits out individual lookup opcodes for each block.
2295 /// It emits the longest blocks first, and short blocks are just
2296 /// handled with direct compares.
2298 /// <param name="ec"></param>
2299 /// <param name="val"></param>
2300 /// <returns></returns>
2301 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2303 int cElements = Elements.Count;
2304 object [] rgKeys = new object [cElements];
2305 Elements.Keys.CopyTo (rgKeys, 0);
2306 Array.Sort (rgKeys);
2308 // initialize the block list with one element per key
2309 ArrayList rgKeyBlocks = new ArrayList ();
2310 foreach (object key in rgKeys)
2311 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2314 // iteratively merge the blocks while they are at least half full
2315 // there's probably a really cool way to do this with a tree...
2316 while (rgKeyBlocks.Count > 1)
2318 ArrayList rgKeyBlocksNew = new ArrayList ();
2319 kbCurr = (KeyBlock) rgKeyBlocks [0];
2320 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2322 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2323 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2326 kbCurr.nLast = kb.nLast;
2327 kbCurr.Size += kb.Size;
2331 // start a new block
2332 rgKeyBlocksNew.Add (kbCurr);
2336 rgKeyBlocksNew.Add (kbCurr);
2337 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2339 rgKeyBlocks = rgKeyBlocksNew;
2342 // initialize the key lists
2343 foreach (KeyBlock kb in rgKeyBlocks)
2344 kb.rgKeys = new ArrayList ();
2346 // fill the key lists
2348 if (rgKeyBlocks.Count > 0) {
2349 kbCurr = (KeyBlock) rgKeyBlocks [0];
2350 foreach (object key in rgKeys)
2352 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2353 System.Convert.ToInt64 (key) > kbCurr.nLast;
2355 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2356 kbCurr.rgKeys.Add (key);
2360 // sort the blocks so we can tackle the largest ones first
2361 rgKeyBlocks.Sort ();
2363 // okay now we can start...
2364 ILGenerator ig = ec.ig;
2365 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2366 Label lblDefault = ig.DefineLabel ();
2368 Type typeKeys = null;
2369 if (rgKeys.Length > 0)
2370 typeKeys = rgKeys [0].GetType (); // used for conversions
2374 if (TypeManager.IsEnumType (SwitchType))
2375 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2377 compare_type = SwitchType;
2379 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2381 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2382 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2385 foreach (object key in kb.rgKeys)
2387 ig.Emit (OpCodes.Ldloc, val);
2388 EmitObjectInteger (ig, key);
2389 SwitchLabel sl = (SwitchLabel) Elements [key];
2390 ig.Emit (OpCodes.Beq, sl.ILLabel);
2395 // TODO: if all the keys in the block are the same and there are
2396 // no gaps/defaults then just use a range-check.
2397 if (compare_type == TypeManager.int64_type ||
2398 compare_type == TypeManager.uint64_type)
2400 // TODO: optimize constant/I4 cases
2402 // check block range (could be > 2^31)
2403 ig.Emit (OpCodes.Ldloc, val);
2404 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2405 ig.Emit (OpCodes.Blt, lblDefault);
2406 ig.Emit (OpCodes.Ldloc, val);
2407 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2408 ig.Emit (OpCodes.Bgt, lblDefault);
2411 ig.Emit (OpCodes.Ldloc, val);
2414 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2415 ig.Emit (OpCodes.Sub);
2417 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2422 ig.Emit (OpCodes.Ldloc, val);
2423 int nFirst = (int) kb.nFirst;
2426 IntConstant.EmitInt (ig, nFirst);
2427 ig.Emit (OpCodes.Sub);
2429 else if (nFirst < 0)
2431 IntConstant.EmitInt (ig, -nFirst);
2432 ig.Emit (OpCodes.Add);
2436 // first, build the list of labels for the switch
2438 int cJumps = kb.Length;
2439 Label [] rgLabels = new Label [cJumps];
2440 for (int iJump = 0; iJump < cJumps; iJump++)
2442 object key = kb.rgKeys [iKey];
2443 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2445 SwitchLabel sl = (SwitchLabel) Elements [key];
2446 rgLabels [iJump] = sl.ILLabel;
2450 rgLabels [iJump] = lblDefault;
2452 // emit the switch opcode
2453 ig.Emit (OpCodes.Switch, rgLabels);
2456 // mark the default for this block
2458 ig.MarkLabel (lblDefault);
2461 // TODO: find the default case and emit it here,
2462 // to prevent having to do the following jump.
2463 // make sure to mark other labels in the default section
2465 // the last default just goes to the end
2466 ig.Emit (OpCodes.Br, lblDefault);
2468 // now emit the code for the sections
2469 bool fFoundDefault = false;
2470 foreach (SwitchSection ss in Sections)
2472 foreach (SwitchLabel sl in ss.Labels)
2474 ig.MarkLabel (sl.ILLabel);
2475 ig.MarkLabel (sl.ILLabelCode);
2476 if (sl.Label == null)
2478 ig.MarkLabel (lblDefault);
2479 fFoundDefault = true;
2483 //ig.Emit (OpCodes.Br, lblEnd);
2486 if (!fFoundDefault) {
2487 ig.MarkLabel (lblDefault);
2489 ig.MarkLabel (lblEnd);
2492 // This simple emit switch works, but does not take advantage of the
2494 // TODO: remove non-string logic from here
2495 // TODO: binary search strings?
2497 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2499 ILGenerator ig = ec.ig;
2500 Label end_of_switch = ig.DefineLabel ();
2501 Label next_test = ig.DefineLabel ();
2502 Label null_target = ig.DefineLabel ();
2503 bool default_found = false;
2504 bool first_test = true;
2505 bool pending_goto_end = false;
2507 bool default_at_end = false;
2509 ig.Emit (OpCodes.Ldloc, val);
2511 if (Elements.Contains (NullLiteral.Null)){
2512 ig.Emit (OpCodes.Brfalse, null_target);
2514 ig.Emit (OpCodes.Brfalse, default_target);
2516 ig.Emit (OpCodes.Ldloc, val);
2517 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2518 ig.Emit (OpCodes.Stloc, val);
2520 int section_count = Sections.Count;
2521 for (int section = 0; section < section_count; section++){
2522 SwitchSection ss = (SwitchSection) Sections [section];
2523 Label sec_begin = ig.DefineLabel ();
2525 if (pending_goto_end)
2526 ig.Emit (OpCodes.Br, end_of_switch);
2528 int label_count = ss.Labels.Count;
2529 bool mark_default = false;
2531 for (int label = 0; label < label_count; label++){
2532 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2533 ig.MarkLabel (sl.ILLabel);
2536 ig.MarkLabel (next_test);
2537 next_test = ig.DefineLabel ();
2540 // If we are the default target
2542 if (sl.Label == null){
2543 if (label+1 == label_count)
2544 default_at_end = true;
2545 mark_default = true;
2546 default_found = true;
2548 object lit = sl.Converted;
2550 if (lit is NullLiteral){
2552 if (label_count == 1)
2553 ig.Emit (OpCodes.Br, next_test);
2557 StringConstant str = (StringConstant) lit;
2559 ig.Emit (OpCodes.Ldloc, val);
2560 ig.Emit (OpCodes.Ldstr, str.Value);
2561 if (label_count == 1)
2562 ig.Emit (OpCodes.Bne_Un, next_test);
2564 if (label+1 == label_count)
2565 ig.Emit (OpCodes.Bne_Un, next_test);
2567 ig.Emit (OpCodes.Beq, sec_begin);
2572 ig.MarkLabel (null_target);
2573 ig.MarkLabel (sec_begin);
2574 foreach (SwitchLabel sl in ss.Labels)
2575 ig.MarkLabel (sl.ILLabelCode);
2578 ig.MarkLabel (default_target);
2580 pending_goto_end = !ss.Block.HasRet;
2583 ig.MarkLabel (next_test);
2585 if (!default_at_end)
2586 ig.Emit (OpCodes.Br, default_target);
2588 ig.MarkLabel (default_target);
2589 ig.MarkLabel (end_of_switch);
2592 public override bool Resolve (EmitContext ec)
2594 Expr = Expr.Resolve (ec);
2598 new_expr = SwitchGoverningType (ec, Expr.Type);
2599 if (new_expr == null){
2600 Report.Error (151, loc, "An integer type or string was expected for switch");
2605 SwitchType = new_expr.Type;
2607 if (!CheckSwitch (ec))
2610 Switch old_switch = ec.Switch;
2612 ec.Switch.SwitchType = SwitchType;
2614 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2615 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2618 foreach (SwitchSection ss in Sections){
2620 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2624 if (ss.Block.Resolve (ec) != true)
2630 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2632 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2633 ec.Switch = old_switch;
2635 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2641 protected override void DoEmit (EmitContext ec)
2643 // Store variable for comparission purposes
2644 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2646 ec.ig.Emit (OpCodes.Stloc, value);
2648 ILGenerator ig = ec.ig;
2650 default_target = ig.DefineLabel ();
2653 // Setup the codegen context
2655 Label old_end = ec.LoopEnd;
2656 Switch old_switch = ec.Switch;
2658 ec.LoopEnd = ig.DefineLabel ();
2662 if (SwitchType == TypeManager.string_type)
2663 SimpleSwitchEmit (ec, value);
2665 TableSwitchEmit (ec, value);
2667 // Restore context state.
2668 ig.MarkLabel (ec.LoopEnd);
2671 // Restore the previous context
2673 ec.LoopEnd = old_end;
2674 ec.Switch = old_switch;
2678 public class Lock : Statement {
2680 Statement Statement;
2682 public Lock (Expression expr, Statement stmt, Location l)
2689 public override bool Resolve (EmitContext ec)
2691 expr = expr.Resolve (ec);
2695 if (expr.Type.IsValueType){
2696 Error (185, "lock statement requires the expression to be " +
2697 " a reference type (type is: `{0}'",
2698 TypeManager.CSharpName (expr.Type));
2702 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2703 bool ok = Statement.Resolve (ec);
2704 ec.EndFlowBranching ();
2709 protected override void DoEmit (EmitContext ec)
2711 Type type = expr.Type;
2713 ILGenerator ig = ec.ig;
2714 LocalBuilder temp = ig.DeclareLocal (type);
2717 ig.Emit (OpCodes.Dup);
2718 ig.Emit (OpCodes.Stloc, temp);
2719 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2722 ig.BeginExceptionBlock ();
2723 Label finish = ig.DefineLabel ();
2724 Statement.Emit (ec);
2725 // ig.Emit (OpCodes.Leave, finish);
2727 ig.MarkLabel (finish);
2730 ig.BeginFinallyBlock ();
2731 ig.Emit (OpCodes.Ldloc, temp);
2732 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2733 ig.EndExceptionBlock ();
2737 public class Unchecked : Statement {
2738 public readonly Block Block;
2740 public Unchecked (Block b)
2746 public override bool Resolve (EmitContext ec)
2748 bool previous_state = ec.CheckState;
2749 bool previous_state_const = ec.ConstantCheckState;
2751 ec.CheckState = false;
2752 ec.ConstantCheckState = false;
2753 bool ret = Block.Resolve (ec);
2754 ec.CheckState = previous_state;
2755 ec.ConstantCheckState = previous_state_const;
2760 protected override void DoEmit (EmitContext ec)
2762 bool previous_state = ec.CheckState;
2763 bool previous_state_const = ec.ConstantCheckState;
2765 ec.CheckState = false;
2766 ec.ConstantCheckState = false;
2768 ec.CheckState = previous_state;
2769 ec.ConstantCheckState = previous_state_const;
2773 public class Checked : Statement {
2774 public readonly Block Block;
2776 public Checked (Block b)
2779 b.Unchecked = false;
2782 public override bool Resolve (EmitContext ec)
2784 bool previous_state = ec.CheckState;
2785 bool previous_state_const = ec.ConstantCheckState;
2787 ec.CheckState = true;
2788 ec.ConstantCheckState = true;
2789 bool ret = Block.Resolve (ec);
2790 ec.CheckState = previous_state;
2791 ec.ConstantCheckState = previous_state_const;
2796 protected override void DoEmit (EmitContext ec)
2798 bool previous_state = ec.CheckState;
2799 bool previous_state_const = ec.ConstantCheckState;
2801 ec.CheckState = true;
2802 ec.ConstantCheckState = true;
2804 ec.CheckState = previous_state;
2805 ec.ConstantCheckState = previous_state_const;
2809 public class Unsafe : Statement {
2810 public readonly Block Block;
2812 public Unsafe (Block b)
2817 public override bool Resolve (EmitContext ec)
2819 bool previous_state = ec.InUnsafe;
2823 val = Block.Resolve (ec);
2824 ec.InUnsafe = previous_state;
2829 protected override void DoEmit (EmitContext ec)
2831 bool previous_state = ec.InUnsafe;
2835 ec.InUnsafe = previous_state;
2842 public class Fixed : Statement {
2844 ArrayList declarators;
2845 Statement statement;
2851 public bool is_object;
2852 public LocalInfo vi;
2853 public Expression expr;
2854 public Expression converted;
2857 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2860 declarators = decls;
2865 public override bool Resolve (EmitContext ec)
2868 Expression.UnsafeError (loc);
2872 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2873 if (expr_type == null)
2876 if (ec.RemapToProxy){
2877 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2881 data = new FixedData [declarators.Count];
2883 if (!expr_type.IsPointer){
2884 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2889 foreach (Pair p in declarators){
2890 LocalInfo vi = (LocalInfo) p.First;
2891 Expression e = (Expression) p.Second;
2893 vi.VariableInfo = null;
2897 // The rules for the possible declarators are pretty wise,
2898 // but the production on the grammar is more concise.
2900 // So we have to enforce these rules here.
2902 // We do not resolve before doing the case 1 test,
2903 // because the grammar is explicit in that the token &
2904 // is present, so we need to test for this particular case.
2908 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2913 // Case 1: & object.
2915 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2916 Expression child = ((Unary) e).Expr;
2919 if (child is ParameterReference || child is LocalVariableReference){
2922 "No need to use fixed statement for parameters or " +
2923 "local variable declarations (address is already " +
2928 ec.InFixedInitializer = true;
2930 ec.InFixedInitializer = false;
2934 child = ((Unary) e).Expr;
2936 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2939 data [i].is_object = true;
2941 data [i].converted = null;
2948 ec.InFixedInitializer = true;
2950 ec.InFixedInitializer = false;
2957 if (e.Type.IsArray){
2958 Type array_type = TypeManager.GetElementType (e.Type);
2962 // Provided that array_type is unmanaged,
2964 if (!TypeManager.VerifyUnManaged (array_type, loc))
2968 // and T* is implicitly convertible to the
2969 // pointer type given in the fixed statement.
2971 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2973 Expression converted = Convert.ImplicitConversionRequired (
2974 ec, array_ptr, vi.VariableType, loc);
2975 if (converted == null)
2978 data [i].is_object = false;
2980 data [i].converted = converted;
2990 if (e.Type == TypeManager.string_type){
2991 data [i].is_object = false;
2993 data [i].converted = null;
3000 // For other cases, flag a `this is already fixed expression'
3002 if (e is LocalVariableReference || e is ParameterReference ||
3003 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3005 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3009 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3013 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3015 if (!statement.Resolve (ec)) {
3016 ec.KillFlowBranching ();
3020 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3021 has_ret = reachability.IsUnreachable;
3026 protected override void DoEmit (EmitContext ec)
3028 ILGenerator ig = ec.ig;
3030 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3032 for (int i = 0; i < data.Length; i++) {
3033 LocalInfo vi = data [i].vi;
3036 // Case 1: & object.
3038 if (data [i].is_object) {
3040 // Store pointer in pinned location
3042 data [i].expr.Emit (ec);
3043 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3044 clear_list [i] = vi.LocalBuilder;
3051 if (data [i].expr.Type.IsArray){
3053 // Store pointer in pinned location
3055 data [i].converted.Emit (ec);
3057 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3058 clear_list [i] = vi.LocalBuilder;
3065 if (data [i].expr.Type == TypeManager.string_type){
3066 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3067 TypeManager.MakePinned (pinned_string);
3068 clear_list [i] = pinned_string;
3070 data [i].expr.Emit (ec);
3071 ig.Emit (OpCodes.Stloc, pinned_string);
3073 Expression sptr = new StringPtr (pinned_string, loc);
3074 Expression converted = Convert.ImplicitConversionRequired (
3075 ec, sptr, vi.VariableType, loc);
3077 if (converted == null)
3080 converted.Emit (ec);
3081 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3085 statement.Emit (ec);
3091 // Clear the pinned variable
3093 for (int i = 0; i < data.Length; i++) {
3094 if (data [i].is_object || data [i].expr.Type.IsArray) {
3095 ig.Emit (OpCodes.Ldc_I4_0);
3096 ig.Emit (OpCodes.Conv_U);
3097 ig.Emit (OpCodes.Stloc, clear_list [i]);
3098 } else if (data [i].expr.Type == TypeManager.string_type){
3099 ig.Emit (OpCodes.Ldnull);
3100 ig.Emit (OpCodes.Stloc, clear_list [i]);
3106 public class Catch {
3107 public readonly string Name;
3108 public readonly Block Block;
3109 public readonly Location Location;
3111 Expression type_expr;
3114 public Catch (Expression type, string name, Block block, Location l)
3122 public Type CatchType {
3128 public bool IsGeneral {
3130 return type_expr == null;
3134 public bool Resolve (EmitContext ec)
3136 if (type_expr != null) {
3137 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3141 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3142 Report.Error (155, Location,
3143 "The type caught or thrown must be derived " +
3144 "from System.Exception");
3150 if (!Block.Resolve (ec))
3157 public class Try : Statement {
3158 public readonly Block Fini, Block;
3159 public readonly ArrayList Specific;
3160 public readonly Catch General;
3163 // specific, general and fini might all be null.
3165 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3167 if (specific == null && general == null){
3168 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3172 this.Specific = specific;
3173 this.General = general;
3178 public override bool Resolve (EmitContext ec)
3182 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3184 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3186 if (!Block.Resolve (ec))
3189 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3191 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3193 foreach (Catch c in Specific){
3194 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3195 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3197 if (c.Name != null) {
3198 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3200 throw new Exception ();
3202 vi.VariableInfo = null;
3205 if (!c.Resolve (ec))
3209 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3211 if (General != null){
3212 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3213 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3215 if (!General.Resolve (ec))
3219 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3223 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
3224 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3226 if (!Fini.Resolve (ec))
3230 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3232 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3234 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3236 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3237 // Unfortunately, System.Reflection.Emit automatically emits a leave
3238 // to the end of the finally block. This is a problem if `returns'
3239 // is true since we may jump to a point after the end of the method.
3240 // As a workaround, emit an explicit ret here.
3241 ec.NeedReturnLabel ();
3247 protected override void DoEmit (EmitContext ec)
3249 ILGenerator ig = ec.ig;
3250 Label finish = ig.DefineLabel ();;
3252 ig.BeginExceptionBlock ();
3256 // System.Reflection.Emit provides this automatically:
3257 // ig.Emit (OpCodes.Leave, finish);
3259 foreach (Catch c in Specific){
3262 ig.BeginCatchBlock (c.CatchType);
3264 if (c.Name != null){
3265 vi = c.Block.GetLocalInfo (c.Name);
3267 throw new Exception ("Variable does not exist in this block");
3269 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3271 ig.Emit (OpCodes.Pop);
3276 if (General != null){
3277 ig.BeginCatchBlock (TypeManager.object_type);
3278 ig.Emit (OpCodes.Pop);
3279 General.Block.Emit (ec);
3282 ig.MarkLabel (finish);
3284 ig.BeginFinallyBlock ();
3288 ig.EndExceptionBlock ();
3292 public class Using : Statement {
3293 object expression_or_block;
3294 Statement Statement;
3299 Expression [] converted_vars;
3300 ExpressionStatement [] assign;
3302 public Using (object expression_or_block, Statement stmt, Location l)
3304 this.expression_or_block = expression_or_block;
3310 // Resolves for the case of using using a local variable declaration.
3312 bool ResolveLocalVariableDecls (EmitContext ec)
3314 bool need_conv = false;
3315 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3318 if (expr_type == null)
3322 // The type must be an IDisposable or an implicit conversion
3325 converted_vars = new Expression [var_list.Count];
3326 assign = new ExpressionStatement [var_list.Count];
3327 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3328 foreach (DictionaryEntry e in var_list){
3329 Expression var = (Expression) e.Key;
3331 var = var.ResolveLValue (ec, new EmptyExpression ());
3335 converted_vars [i] = Convert.ImplicitConversionRequired (
3336 ec, var, TypeManager.idisposable_type, loc);
3338 if (converted_vars [i] == null)
3346 foreach (DictionaryEntry e in var_list){
3347 LocalVariableReference var = (LocalVariableReference) e.Key;
3348 Expression new_expr = (Expression) e.Value;
3351 a = new Assign (var, new_expr, loc);
3357 converted_vars [i] = var;
3358 assign [i] = (ExpressionStatement) a;
3365 bool ResolveExpression (EmitContext ec)
3367 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3368 conv = Convert.ImplicitConversionRequired (
3369 ec, expr, TypeManager.idisposable_type, loc);
3379 // Emits the code for the case of using using a local variable declaration.
3381 bool EmitLocalVariableDecls (EmitContext ec)
3383 ILGenerator ig = ec.ig;
3386 for (i = 0; i < assign.Length; i++) {
3387 assign [i].EmitStatement (ec);
3389 ig.BeginExceptionBlock ();
3391 Statement.Emit (ec);
3393 var_list.Reverse ();
3394 foreach (DictionaryEntry e in var_list){
3395 LocalVariableReference var = (LocalVariableReference) e.Key;
3396 Label skip = ig.DefineLabel ();
3399 ig.BeginFinallyBlock ();
3401 if (!var.Type.IsValueType) {
3403 ig.Emit (OpCodes.Brfalse, skip);
3404 converted_vars [i].Emit (ec);
3405 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3407 Expression ml = Expression.MemberLookup(ec, typeof(IDisposable), var.Type, "Dispose", Mono.CSharp.Location.Null);
3409 if (!(ml is MethodGroupExpr)) {
3411 ig.Emit (OpCodes.Box, var.Type);
3412 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3414 MethodInfo mi = null;
3416 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3417 if (mk.GetParameters().Length == 0) {
3424 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3428 var.AddressOf (ec, AddressOp.Load);
3429 ig.Emit (OpCodes.Call, mi);
3433 ig.MarkLabel (skip);
3434 ig.EndExceptionBlock ();
3440 bool EmitExpression (EmitContext ec)
3443 // Make a copy of the expression and operate on that.
3445 ILGenerator ig = ec.ig;
3446 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3451 ig.Emit (OpCodes.Stloc, local_copy);
3453 ig.BeginExceptionBlock ();
3454 Statement.Emit (ec);
3456 Label skip = ig.DefineLabel ();
3457 ig.BeginFinallyBlock ();
3458 ig.Emit (OpCodes.Ldloc, local_copy);
3459 ig.Emit (OpCodes.Brfalse, skip);
3460 ig.Emit (OpCodes.Ldloc, local_copy);
3461 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3462 ig.MarkLabel (skip);
3463 ig.EndExceptionBlock ();
3468 public override bool Resolve (EmitContext ec)
3470 if (expression_or_block is DictionaryEntry){
3471 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3472 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3474 if (!ResolveLocalVariableDecls (ec))
3477 } else if (expression_or_block is Expression){
3478 expr = (Expression) expression_or_block;
3480 expr = expr.Resolve (ec);
3484 expr_type = expr.Type;
3486 if (!ResolveExpression (ec))
3490 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3492 bool ok = Statement.Resolve (ec);
3495 ec.KillFlowBranching ();
3499 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3501 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3502 // Unfortunately, System.Reflection.Emit automatically emits a leave
3503 // to the end of the finally block. This is a problem if `returns'
3504 // is true since we may jump to a point after the end of the method.
3505 // As a workaround, emit an explicit ret here.
3506 ec.NeedReturnLabel ();
3512 protected override void DoEmit (EmitContext ec)
3514 if (expression_or_block is DictionaryEntry)
3515 EmitLocalVariableDecls (ec);
3516 else if (expression_or_block is Expression)
3517 EmitExpression (ec);
3522 /// Implementation of the foreach C# statement
3524 public class Foreach : Statement {
3526 Expression variable;
3528 Statement statement;
3529 ForeachHelperMethods hm;
3530 Expression empty, conv;
3531 Type array_type, element_type;
3534 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3535 Statement stmt, Location l)
3538 this.variable = var;
3544 public override bool Resolve (EmitContext ec)
3546 expr = expr.Resolve (ec);
3550 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3551 if (var_type == null)
3555 // We need an instance variable. Not sure this is the best
3556 // way of doing this.
3558 // FIXME: When we implement propertyaccess, will those turn
3559 // out to return values in ExprClass? I think they should.
3561 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3562 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3563 error1579 (expr.Type);
3567 if (expr.Type.IsArray) {
3568 array_type = expr.Type;
3569 element_type = TypeManager.GetElementType (array_type);
3571 empty = new EmptyExpression (element_type);
3573 hm = ProbeCollectionType (ec, expr.Type);
3575 error1579 (expr.Type);
3579 array_type = expr.Type;
3580 element_type = hm.element_type;
3582 empty = new EmptyExpression (hm.element_type);
3587 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3588 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
3592 // FIXME: maybe we can apply the same trick we do in the
3593 // array handling to avoid creating empty and conv in some cases.
3595 // Although it is not as important in this case, as the type
3596 // will not likely be object (what the enumerator will return).
3598 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3602 variable = variable.ResolveLValue (ec, empty);
3603 if (variable == null)
3606 bool disposable = (hm != null) && hm.is_disposable;
3608 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3610 if (!statement.Resolve (ec))
3614 ec.EndFlowBranching ();
3616 ec.EndFlowBranching ();
3622 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3624 static MethodInfo FetchMethodMoveNext (Type t)
3626 MemberList move_next_list;
3628 move_next_list = TypeContainer.FindMembers (
3629 t, MemberTypes.Method,
3630 BindingFlags.Public | BindingFlags.Instance,
3631 Type.FilterName, "MoveNext");
3632 if (move_next_list.Count == 0)
3635 foreach (MemberInfo m in move_next_list){
3636 MethodInfo mi = (MethodInfo) m;
3639 args = TypeManager.GetArgumentTypes (mi);
3640 if (args != null && args.Length == 0){
3641 if (mi.ReturnType == TypeManager.bool_type)
3649 // Retrieves a `public T get_Current ()' method from the Type `t'
3651 static MethodInfo FetchMethodGetCurrent (Type t)
3653 MemberList get_current_list;
3655 get_current_list = TypeContainer.FindMembers (
3656 t, MemberTypes.Method,
3657 BindingFlags.Public | BindingFlags.Instance,
3658 Type.FilterName, "get_Current");
3659 if (get_current_list.Count == 0)
3662 foreach (MemberInfo m in get_current_list){
3663 MethodInfo mi = (MethodInfo) m;
3666 args = TypeManager.GetArgumentTypes (mi);
3667 if (args != null && args.Length == 0)
3674 // This struct records the helper methods used by the Foreach construct
3676 class ForeachHelperMethods {
3677 public EmitContext ec;
3678 public MethodInfo get_enumerator;
3679 public MethodInfo move_next;
3680 public MethodInfo get_current;
3681 public Type element_type;
3682 public Type enumerator_type;
3683 public bool is_disposable;
3685 public ForeachHelperMethods (EmitContext ec)
3688 this.element_type = TypeManager.object_type;
3689 this.enumerator_type = TypeManager.ienumerator_type;
3690 this.is_disposable = true;
3694 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3699 if (!(m is MethodInfo))
3702 if (m.Name != "GetEnumerator")
3705 MethodInfo mi = (MethodInfo) m;
3706 Type [] args = TypeManager.GetArgumentTypes (mi);
3708 if (args.Length != 0)
3711 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3712 EmitContext ec = hm.ec;
3715 // Check whether GetEnumerator is accessible to us
3717 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3719 Type declaring = mi.DeclaringType;
3720 if (prot == MethodAttributes.Private){
3721 if (declaring != ec.ContainerType)
3723 } else if (prot == MethodAttributes.FamANDAssem){
3724 // If from a different assembly, false
3725 if (!(mi is MethodBuilder))
3728 // Are we being invoked from the same class, or from a derived method?
3730 if (ec.ContainerType != declaring){
3731 if (!ec.ContainerType.IsSubclassOf (declaring))
3734 } else if (prot == MethodAttributes.FamORAssem){
3735 if (!(mi is MethodBuilder ||
3736 ec.ContainerType == declaring ||
3737 ec.ContainerType.IsSubclassOf (declaring)))
3739 } if (prot == MethodAttributes.Family){
3740 if (!(ec.ContainerType == declaring ||
3741 ec.ContainerType.IsSubclassOf (declaring)))
3745 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3747 // Apply the same optimization as MS: skip the GetEnumerator
3748 // returning an IEnumerator, and use the one returning a
3749 // CharEnumerator instead. This allows us to avoid the
3750 // try-finally block and the boxing.
3755 // Ok, we can access it, now make sure that we can do something
3756 // with this `GetEnumerator'
3759 Type return_type = mi.ReturnType;
3760 if (mi.ReturnType == TypeManager.ienumerator_type ||
3761 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3762 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3765 // If it is not an interface, lets try to find the methods ourselves.
3766 // For example, if we have:
3767 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3768 // We can avoid the iface call. This is a runtime perf boost.
3769 // even bigger if we have a ValueType, because we avoid the cost
3772 // We have to make sure that both methods exist for us to take
3773 // this path. If one of the methods does not exist, we will just
3774 // use the interface. Sadly, this complex if statement is the only
3775 // way I could do this without a goto
3778 if (return_type.IsInterface ||
3779 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3780 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3782 hm.move_next = TypeManager.bool_movenext_void;
3783 hm.get_current = TypeManager.object_getcurrent_void;
3790 // Ok, so they dont return an IEnumerable, we will have to
3791 // find if they support the GetEnumerator pattern.
3794 hm.move_next = FetchMethodMoveNext (return_type);
3795 if (hm.move_next == null)
3798 hm.get_current = FetchMethodGetCurrent (return_type);
3799 if (hm.get_current == null)
3803 hm.element_type = hm.get_current.ReturnType;
3804 hm.enumerator_type = return_type;
3805 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3806 TypeManager.ImplementsInterface (
3807 hm.enumerator_type, TypeManager.idisposable_type);
3813 /// This filter is used to find the GetEnumerator method
3814 /// on which IEnumerator operates
3816 static MemberFilter FilterEnumerator;
3820 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3823 void error1579 (Type t)
3825 Report.Error (1579, loc,
3826 "foreach statement cannot operate on variables of type `" +
3827 t.FullName + "' because that class does not provide a " +
3828 " GetEnumerator method or it is inaccessible");
3831 static bool TryType (Type t, ForeachHelperMethods hm)
3835 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3836 BindingFlags.Public | BindingFlags.NonPublic |
3837 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3838 FilterEnumerator, hm);
3843 hm.get_enumerator = (MethodInfo) mi [0];
3848 // Looks for a usable GetEnumerator in the Type, and if found returns
3849 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3851 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3853 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3855 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3856 if (TryType (tt, hm))
3862 // Now try to find the method in the interfaces
3865 Type [] ifaces = t.GetInterfaces ();
3867 foreach (Type i in ifaces){
3868 if (TryType (i, hm))
3873 // Since TypeBuilder.GetInterfaces only returns the interface
3874 // types for this type, we have to keep looping, but once
3875 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3876 // done, because it returns all the types
3878 if ((t is TypeBuilder))
3888 // FIXME: possible optimization.
3889 // We might be able to avoid creating `empty' if the type is the sam
3891 bool EmitCollectionForeach (EmitContext ec)
3893 ILGenerator ig = ec.ig;
3894 VariableStorage enumerator;
3896 enumerator = new VariableStorage (ec, hm.enumerator_type);
3897 enumerator.EmitThis ();
3899 // Instantiate the enumerator
3901 if (expr.Type.IsValueType){
3902 if (expr is IMemoryLocation){
3903 IMemoryLocation ml = (IMemoryLocation) expr;
3905 ml.AddressOf (ec, AddressOp.Load);
3907 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3908 " does not implement IMemoryLocation");
3909 ig.Emit (OpCodes.Call, hm.get_enumerator);
3912 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3914 enumerator.EmitStore ();
3917 // Protect the code in a try/finalize block, so that
3918 // if the beast implement IDisposable, we get rid of it
3920 if (hm.is_disposable)
3921 ig.BeginExceptionBlock ();
3923 Label end_try = ig.DefineLabel ();
3925 ig.MarkLabel (ec.LoopBegin);
3927 enumerator.EmitCall (hm.move_next);
3929 ig.Emit (OpCodes.Brfalse, end_try);
3933 enumerator.EmitCall (hm.get_current);
3937 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3939 ((IAssignMethod)variable).EmitAssign (ec, conv);
3941 statement.Emit (ec);
3942 ig.Emit (OpCodes.Br, ec.LoopBegin);
3943 ig.MarkLabel (end_try);
3945 // The runtime provides this for us.
3946 // ig.Emit (OpCodes.Leave, end);
3949 // Now the finally block
3951 if (hm.is_disposable) {
3952 Label call_dispose = ig.DefineLabel ();
3953 ig.BeginFinallyBlock ();
3955 enumerator.EmitThis ();
3956 enumerator.EmitLoad ();
3957 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3958 ig.Emit (OpCodes.Dup);
3959 ig.Emit (OpCodes.Brtrue_S, call_dispose);
3960 ig.Emit (OpCodes.Pop);
3961 ig.Emit (OpCodes.Endfinally);
3963 ig.MarkLabel (call_dispose);
3964 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3967 // The runtime generates this anyways.
3968 // ig.Emit (OpCodes.Endfinally);
3970 ig.EndExceptionBlock ();
3973 ig.MarkLabel (ec.LoopEnd);
3978 // FIXME: possible optimization.
3979 // We might be able to avoid creating `empty' if the type is the sam
3981 bool EmitArrayForeach (EmitContext ec)
3983 int rank = array_type.GetArrayRank ();
3984 ILGenerator ig = ec.ig;
3986 VariableStorage copy = new VariableStorage (ec, array_type);
3989 // Make our copy of the array
3996 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4000 counter.EmitThis ();
4001 ig.Emit (OpCodes.Ldc_I4_0);
4002 counter.EmitStore ();
4003 test = ig.DefineLabel ();
4004 ig.Emit (OpCodes.Br, test);
4006 loop = ig.DefineLabel ();
4007 ig.MarkLabel (loop);
4014 counter.EmitThis ();
4015 counter.EmitLoad ();
4018 // Load the value, we load the value using the underlying type,
4019 // then we use the variable.EmitAssign to load using the proper cast.
4021 ArrayAccess.EmitLoadOpcode (ig, element_type);
4024 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4026 ((IAssignMethod)variable).EmitAssign (ec, conv);
4028 statement.Emit (ec);
4030 ig.MarkLabel (ec.LoopBegin);
4031 counter.EmitThis ();
4032 counter.EmitThis ();
4033 counter.EmitLoad ();
4034 ig.Emit (OpCodes.Ldc_I4_1);
4035 ig.Emit (OpCodes.Add);
4036 counter.EmitStore ();
4038 ig.MarkLabel (test);
4039 counter.EmitThis ();
4040 counter.EmitLoad ();
4043 ig.Emit (OpCodes.Ldlen);
4044 ig.Emit (OpCodes.Conv_I4);
4045 ig.Emit (OpCodes.Blt, loop);
4047 VariableStorage [] dim_len = new VariableStorage [rank];
4048 VariableStorage [] dim_count = new VariableStorage [rank];
4049 Label [] loop = new Label [rank];
4050 Label [] test = new Label [rank];
4053 for (dim = 0; dim < rank; dim++){
4054 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4055 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4056 test [dim] = ig.DefineLabel ();
4057 loop [dim] = ig.DefineLabel ();
4060 for (dim = 0; dim < rank; dim++){
4061 dim_len [dim].EmitThis ();
4064 IntLiteral.EmitInt (ig, dim);
4065 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4066 dim_len [dim].EmitStore ();
4070 for (dim = 0; dim < rank; dim++){
4071 dim_count [dim].EmitThis ();
4072 ig.Emit (OpCodes.Ldc_I4_0);
4073 dim_count [dim].EmitStore ();
4074 ig.Emit (OpCodes.Br, test [dim]);
4075 ig.MarkLabel (loop [dim]);
4082 for (dim = 0; dim < rank; dim++){
4083 dim_count [dim].EmitThis ();
4084 dim_count [dim].EmitLoad ();
4088 // FIXME: Maybe we can cache the computation of `get'?
4090 Type [] args = new Type [rank];
4093 for (int i = 0; i < rank; i++)
4094 args [i] = TypeManager.int32_type;
4096 ModuleBuilder mb = CodeGen.Module.Builder;
4097 get = mb.GetArrayMethod (
4099 CallingConventions.HasThis| CallingConventions.Standard,
4101 ig.Emit (OpCodes.Call, get);
4104 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4106 ((IAssignMethod)variable).EmitAssign (ec, conv);
4107 statement.Emit (ec);
4108 ig.MarkLabel (ec.LoopBegin);
4109 for (dim = rank - 1; dim >= 0; dim--){
4110 dim_count [dim].EmitThis ();
4111 dim_count [dim].EmitThis ();
4112 dim_count [dim].EmitLoad ();
4113 ig.Emit (OpCodes.Ldc_I4_1);
4114 ig.Emit (OpCodes.Add);
4115 dim_count [dim].EmitStore ();
4117 ig.MarkLabel (test [dim]);
4118 dim_count [dim].EmitThis ();
4119 dim_count [dim].EmitLoad ();
4120 dim_len [dim].EmitThis ();
4121 dim_len [dim].EmitLoad ();
4122 ig.Emit (OpCodes.Blt, loop [dim]);
4125 ig.MarkLabel (ec.LoopEnd);
4130 protected override void DoEmit (EmitContext ec)
4132 ILGenerator ig = ec.ig;
4134 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4135 ec.LoopBegin = ig.DefineLabel ();
4136 ec.LoopEnd = ig.DefineLabel ();
4139 EmitCollectionForeach (ec);
4141 EmitArrayForeach (ec);
4143 ec.LoopBegin = old_begin;
4144 ec.LoopEnd = old_end;