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 ();
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 ();
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)
602 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
606 ec.NeedReturnLabel ();
607 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
609 ec.ig.Emit (OpCodes.Ret);
614 public class Goto : Statement {
617 LabeledStatement label;
619 public override bool Resolve (EmitContext ec)
621 label = ec.CurrentBranching.LookupLabel (target, loc);
625 // If this is a forward goto.
626 if (!label.IsDefined)
627 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
629 ec.CurrentBranching.CurrentUsageVector.Goto ();
634 public Goto (Block parent_block, string label, Location l)
636 block = parent_block;
641 public string Target {
647 protected override void DoEmit (EmitContext ec)
649 Label l = label.LabelTarget (ec);
650 ec.ig.Emit (OpCodes.Br, l);
654 public class LabeledStatement : Statement {
655 public readonly Location Location;
660 FlowBranching.UsageVector vectors;
662 public LabeledStatement (string label_name, Location l)
667 public Label LabelTarget (EmitContext ec)
671 label = ec.ig.DefineLabel ();
677 public bool IsDefined {
683 public bool HasBeenReferenced {
689 public void AddUsageVector (FlowBranching.UsageVector vector)
691 vector = vector.Clone ();
692 vector.Next = vectors;
696 public override bool Resolve (EmitContext ec)
698 ec.CurrentBranching.Label (vectors);
705 protected override void DoEmit (EmitContext ec)
708 ec.ig.MarkLabel (label);
714 /// `goto default' statement
716 public class GotoDefault : Statement {
718 public GotoDefault (Location l)
723 public override bool Resolve (EmitContext ec)
725 ec.CurrentBranching.CurrentUsageVector.Goto ();
729 protected override void DoEmit (EmitContext ec)
731 if (ec.Switch == null){
732 Report.Error (153, loc, "goto default is only valid in a switch statement");
736 if (!ec.Switch.GotDefault){
737 Report.Error (159, loc, "No default target on switch statement");
740 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
745 /// `goto case' statement
747 public class GotoCase : Statement {
751 public GotoCase (Expression e, Location l)
757 public override bool Resolve (EmitContext ec)
759 if (ec.Switch == null){
760 Report.Error (153, loc, "goto case is only valid in a switch statement");
764 expr = expr.Resolve (ec);
768 if (!(expr is Constant)){
769 Report.Error (159, loc, "Target expression for goto case is not constant");
773 object val = Expression.ConvertIntLiteral (
774 (Constant) expr, ec.Switch.SwitchType, loc);
779 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
784 "No such label 'case " + val + "': for the goto case");
788 label = sl.ILLabelCode;
790 ec.CurrentBranching.CurrentUsageVector.Goto ();
794 protected override void DoEmit (EmitContext ec)
796 ec.ig.Emit (OpCodes.Br, label);
800 public class Throw : Statement {
803 public Throw (Expression expr, Location l)
809 public override bool Resolve (EmitContext ec)
811 bool in_catch = ec.CurrentBranching.InCatch ();
812 ec.CurrentBranching.CurrentUsageVector.Throw ();
815 expr = expr.Resolve (ec);
819 ExprClass eclass = expr.eclass;
821 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
822 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
823 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
829 if ((t != TypeManager.exception_type) &&
830 !t.IsSubclassOf (TypeManager.exception_type) &&
831 !(expr is NullLiteral)) {
833 "The type caught or thrown must be derived " +
834 "from System.Exception");
837 } else if (!in_catch) {
839 "A throw statement with no argument is only " +
840 "allowed in a catch clause");
847 protected override void DoEmit (EmitContext ec)
850 ec.ig.Emit (OpCodes.Rethrow);
854 ec.ig.Emit (OpCodes.Throw);
859 public class Break : Statement {
861 public Break (Location l)
868 public override bool Resolve (EmitContext ec)
870 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
871 Error (139, "No enclosing loop or switch to continue to");
873 } else if (ec.CurrentBranching.InFinally (false)) {
874 Error (157, "Control can not leave the body of the finally block");
876 } else if (ec.CurrentBranching.InTryOrCatch (false))
877 ec.CurrentBranching.AddFinallyVector (
878 ec.CurrentBranching.CurrentUsageVector);
879 else if (ec.CurrentBranching.InLoop ())
880 ec.CurrentBranching.AddBreakVector (
881 ec.CurrentBranching.CurrentUsageVector);
883 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
885 ec.CurrentBranching.CurrentUsageVector.Break ();
889 protected override void DoEmit (EmitContext ec)
891 ILGenerator ig = ec.ig;
894 ig.Emit (OpCodes.Leave, ec.LoopEnd);
896 ec.NeedReturnLabel ();
897 ig.Emit (OpCodes.Br, ec.LoopEnd);
902 public class Continue : Statement {
904 public Continue (Location l)
911 public override bool Resolve (EmitContext ec)
913 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
914 Error (139, "No enclosing loop to continue to");
916 } else if (ec.CurrentBranching.InFinally (false)) {
917 Error (157, "Control can not leave the body of the finally block");
919 } else if (ec.CurrentBranching.InTryOrCatch (false))
920 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
922 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
924 ec.CurrentBranching.CurrentUsageVector.Goto ();
928 protected override void DoEmit (EmitContext ec)
930 Label begin = ec.LoopBegin;
933 ec.ig.Emit (OpCodes.Leave, begin);
935 ec.ig.Emit (OpCodes.Br, begin);
939 public class LocalInfo {
940 public Expression Type;
943 // Most of the time a variable will be stored in a LocalBuilder
945 // But sometimes, it will be stored in a field. The context of the field will
946 // be stored in the EmitContext
949 public LocalBuilder LocalBuilder;
950 public FieldBuilder FieldBuilder;
952 public Type VariableType;
953 public readonly string Name;
954 public readonly Location Location;
955 public readonly Block Block;
957 public VariableInfo VariableInfo;
967 public LocalInfo (Expression type, string name, Block block, Location l)
975 public LocalInfo (TypeContainer tc, Block block, Location l)
977 VariableType = tc.TypeBuilder;
982 public bool IsThisAssigned (EmitContext ec, Location loc)
984 if (VariableInfo == null)
985 throw new Exception ();
987 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
990 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
993 public bool IsAssigned (EmitContext ec)
995 if (VariableInfo == null)
996 throw new Exception ();
998 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1001 public bool Resolve (DeclSpace decl)
1003 if (VariableType == null)
1004 VariableType = decl.ResolveType (Type, false, Location);
1006 if (VariableType == TypeManager.void_type) {
1007 Report.Error (1547, Location,
1008 "Keyword 'void' cannot be used in this context");
1012 if (VariableType == null)
1018 public void MakePinned ()
1020 TypeManager.MakePinned (LocalBuilder);
1021 flags |= Flags.Fixed;
1024 public bool IsFixed {
1026 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1033 public override string ToString ()
1035 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1036 Name, Type, VariableInfo, Location);
1041 return (flags & Flags.Used) != 0;
1044 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1048 public bool ReadOnly {
1050 return (flags & Flags.ReadOnly) != 0;
1053 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1062 /// Block represents a C# block.
1066 /// This class is used in a number of places: either to represent
1067 /// explicit blocks that the programmer places or implicit blocks.
1069 /// Implicit blocks are used as labels or to introduce variable
1072 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1073 /// they contain extra information that is not necessary on normal blocks.
1075 public class Block : Statement {
1076 public readonly Block Parent;
1077 public readonly Location StartLocation;
1078 public Location EndLocation = Location.Null;
1081 public enum Flags : byte {
1085 VariablesInitialized = 8,
1091 public bool Implicit {
1093 return (flags & Flags.Implicit) != 0;
1097 public bool Unchecked {
1099 return (flags & Flags.Unchecked) != 0;
1102 flags |= Flags.Unchecked;
1107 // The statements in this block
1109 ArrayList statements;
1113 // An array of Blocks. We keep track of children just
1114 // to generate the local variable declarations.
1116 // Statements and child statements are handled through the
1122 // Labels. (label, block) pairs.
1127 // Keeps track of (name, type) pairs
1129 Hashtable variables;
1132 // Keeps track of constants
1133 Hashtable constants;
1136 // If this is a switch section, the enclosing switch block.
1144 public Block (Block parent)
1145 : this (parent, (Flags) 0, Location.Null, Location.Null)
1148 public Block (Block parent, Flags flags)
1149 : this (parent, flags, Location.Null, Location.Null)
1152 public Block (Block parent, Flags flags, Parameters parameters)
1153 : this (parent, flags, parameters, Location.Null, Location.Null)
1156 public Block (Block parent, Location start, Location end)
1157 : this (parent, (Flags) 0, start, end)
1160 public Block (Block parent, Parameters parameters, Location start, Location end)
1161 : this (parent, (Flags) 0, parameters, start, end)
1164 public Block (Block parent, Flags flags, Location start, Location end)
1165 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1168 public Block (Block parent, Flags flags, Parameters parameters,
1169 Location start, Location end)
1172 parent.AddChild (this);
1174 this.Parent = parent;
1176 this.parameters = parameters;
1177 this.StartLocation = start;
1178 this.EndLocation = end;
1181 statements = new ArrayList ();
1183 if (parent != null && Implicit) {
1184 if (parent.child_variable_names == null)
1185 parent.child_variable_names = new Hashtable();
1186 // share with parent
1187 child_variable_names = parent.child_variable_names;
1192 public Block CreateSwitchBlock (Location start)
1194 Block new_block = new Block (this, start, start);
1195 new_block.switch_block = this;
1205 void AddChild (Block b)
1207 if (children == null)
1208 children = new ArrayList ();
1213 public void SetEndLocation (Location loc)
1219 /// Adds a label to the current block.
1223 /// false if the name already exists in this block. true
1227 public bool AddLabel (string name, LabeledStatement target, Location loc)
1229 if (switch_block != null)
1230 return switch_block.AddLabel (name, target, loc);
1233 while (cur != null) {
1234 if (cur.DoLookupLabel (name) != null) {
1236 140, loc, "The label '{0}' is a duplicate",
1247 while (cur != null) {
1248 if (cur.DoLookupLabel (name) != null) {
1251 "The label '{0}' shadows another label " +
1252 "by the same name in a containing scope.",
1257 if (children != null) {
1258 foreach (Block b in children) {
1259 LabeledStatement s = b.DoLookupLabel (name);
1265 "The label '{0}' shadows another " +
1266 "label by the same name in a " +
1267 "containing scope.",
1278 labels = new Hashtable ();
1280 labels.Add (name, target);
1284 public LabeledStatement LookupLabel (string name)
1286 LabeledStatement s = DoLookupLabel (name);
1290 if (children == null)
1293 foreach (Block child in children) {
1294 if (!child.Implicit)
1297 s = child.LookupLabel (name);
1305 LabeledStatement DoLookupLabel (string name)
1307 if (switch_block != null)
1308 return switch_block.LookupLabel (name);
1311 if (labels.Contains (name))
1312 return ((LabeledStatement) labels [name]);
1317 LocalInfo this_variable = null;
1320 // Returns the "this" instance variable of this block.
1321 // See AddThisVariable() for more information.
1323 public LocalInfo ThisVariable {
1325 if (this_variable != null)
1326 return this_variable;
1327 else if (Parent != null)
1328 return Parent.ThisVariable;
1334 Hashtable child_variable_names;
1337 // Marks a variable with name @name as being used in a child block.
1338 // If a variable name has been used in a child block, it's illegal to
1339 // declare a variable with the same name in the current block.
1341 public void AddChildVariableName (string name)
1343 if (child_variable_names == null)
1344 child_variable_names = new Hashtable ();
1346 if (!child_variable_names.Contains (name))
1347 child_variable_names.Add (name, true);
1351 // Checks whether a variable name has already been used in a child block.
1353 public bool IsVariableNameUsedInChildBlock (string name)
1355 if (child_variable_names == null)
1358 return child_variable_names.Contains (name);
1362 // This is used by non-static `struct' constructors which do not have an
1363 // initializer - in this case, the constructor must initialize all of the
1364 // struct's fields. To do this, we add a "this" variable and use the flow
1365 // analysis code to ensure that it's been fully initialized before control
1366 // leaves the constructor.
1368 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1370 if (this_variable != null)
1371 return this_variable;
1373 if (variables == null)
1374 variables = new Hashtable ();
1376 this_variable = new LocalInfo (tc, this, l);
1377 this_variable.Used = true;
1379 variables.Add ("this", this_variable);
1381 return this_variable;
1384 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1386 if (variables == null)
1387 variables = new Hashtable ();
1389 LocalInfo vi = GetLocalInfo (name);
1391 if (vi.Block != this)
1392 Report.Error (136, l, "A local variable named `" + name + "' " +
1393 "cannot be declared in this scope since it would " +
1394 "give a different meaning to `" + name + "', which " +
1395 "is already used in a `parent or current' scope to " +
1396 "denote something else");
1398 Report.Error (128, l, "A local variable `" + name + "' is already " +
1399 "defined in this scope");
1403 if (IsVariableNameUsedInChildBlock (name)) {
1404 Report.Error (136, l, "A local variable named `" + name + "' " +
1405 "cannot be declared in this scope since it would " +
1406 "give a different meaning to `" + name + "', which " +
1407 "is already used in a `child' scope to denote something " +
1414 Parameter p = pars.GetParameterByName (name, out idx);
1416 Report.Error (136, l, "A local variable named `" + name + "' " +
1417 "cannot be declared in this scope since it would " +
1418 "give a different meaning to `" + name + "', which " +
1419 "is already used in a `parent or current' scope to " +
1420 "denote something else");
1425 vi = new LocalInfo (type, name, this, l);
1427 variables.Add (name, vi);
1429 // Mark 'name' as "used by a child block" in every surrounding block
1431 while (cur != null && cur.Implicit)
1434 for (Block par = cur.Parent; par != null; par = par.Parent)
1435 par.AddChildVariableName (name);
1437 if ((flags & Flags.VariablesInitialized) != 0)
1438 throw new Exception ();
1440 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1444 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1446 if (AddVariable (type, name, pars, l) == null)
1449 if (constants == null)
1450 constants = new Hashtable ();
1452 constants.Add (name, value);
1456 public Hashtable Variables {
1462 public LocalInfo GetLocalInfo (string name)
1464 for (Block b = this; b != null; b = b.Parent) {
1465 if (b.variables != null) {
1466 LocalInfo ret = b.variables [name] as LocalInfo;
1474 public Expression GetVariableType (string name)
1476 LocalInfo vi = GetLocalInfo (name);
1484 public Expression GetConstantExpression (string name)
1486 for (Block b = this; b != null; b = b.Parent) {
1487 if (b.constants != null) {
1488 Expression ret = b.constants [name] as Expression;
1497 /// True if the variable named @name is a constant
1499 public bool IsConstant (string name)
1501 Expression e = null;
1503 e = GetConstantExpression (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 (
2621 null, FlowBranching.SiblingType.SwitchSection);
2625 if (ss.Block.Resolve (ec) != true)
2631 ec.CurrentBranching.CreateSibling (
2632 null, FlowBranching.SiblingType.SwitchSection);
2634 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2635 ec.Switch = old_switch;
2637 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2643 protected override void DoEmit (EmitContext ec)
2645 // Store variable for comparission purposes
2646 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2648 ec.ig.Emit (OpCodes.Stloc, value);
2650 ILGenerator ig = ec.ig;
2652 default_target = ig.DefineLabel ();
2655 // Setup the codegen context
2657 Label old_end = ec.LoopEnd;
2658 Switch old_switch = ec.Switch;
2660 ec.LoopEnd = ig.DefineLabel ();
2664 if (SwitchType == TypeManager.string_type)
2665 SimpleSwitchEmit (ec, value);
2667 TableSwitchEmit (ec, value);
2669 // Restore context state.
2670 ig.MarkLabel (ec.LoopEnd);
2673 // Restore the previous context
2675 ec.LoopEnd = old_end;
2676 ec.Switch = old_switch;
2680 public class Lock : Statement {
2682 Statement Statement;
2684 public Lock (Expression expr, Statement stmt, Location l)
2691 public override bool Resolve (EmitContext ec)
2693 expr = expr.Resolve (ec);
2697 if (expr.Type.IsValueType){
2698 Error (185, "lock statement requires the expression to be " +
2699 " a reference type (type is: `{0}'",
2700 TypeManager.CSharpName (expr.Type));
2704 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2705 bool ok = Statement.Resolve (ec);
2706 ec.EndFlowBranching ();
2711 protected override void DoEmit (EmitContext ec)
2713 Type type = expr.Type;
2715 ILGenerator ig = ec.ig;
2716 LocalBuilder temp = ig.DeclareLocal (type);
2719 ig.Emit (OpCodes.Dup);
2720 ig.Emit (OpCodes.Stloc, temp);
2721 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2724 ig.BeginExceptionBlock ();
2725 Label finish = ig.DefineLabel ();
2726 Statement.Emit (ec);
2727 // ig.Emit (OpCodes.Leave, finish);
2729 ig.MarkLabel (finish);
2732 ig.BeginFinallyBlock ();
2733 ig.Emit (OpCodes.Ldloc, temp);
2734 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2735 ig.EndExceptionBlock ();
2739 public class Unchecked : Statement {
2740 public readonly Block Block;
2742 public Unchecked (Block b)
2748 public override bool Resolve (EmitContext ec)
2750 bool previous_state = ec.CheckState;
2751 bool previous_state_const = ec.ConstantCheckState;
2753 ec.CheckState = false;
2754 ec.ConstantCheckState = false;
2755 bool ret = Block.Resolve (ec);
2756 ec.CheckState = previous_state;
2757 ec.ConstantCheckState = previous_state_const;
2762 protected override void DoEmit (EmitContext ec)
2764 bool previous_state = ec.CheckState;
2765 bool previous_state_const = ec.ConstantCheckState;
2767 ec.CheckState = false;
2768 ec.ConstantCheckState = false;
2770 ec.CheckState = previous_state;
2771 ec.ConstantCheckState = previous_state_const;
2775 public class Checked : Statement {
2776 public readonly Block Block;
2778 public Checked (Block b)
2781 b.Unchecked = false;
2784 public override bool Resolve (EmitContext ec)
2786 bool previous_state = ec.CheckState;
2787 bool previous_state_const = ec.ConstantCheckState;
2789 ec.CheckState = true;
2790 ec.ConstantCheckState = true;
2791 bool ret = Block.Resolve (ec);
2792 ec.CheckState = previous_state;
2793 ec.ConstantCheckState = previous_state_const;
2798 protected override void DoEmit (EmitContext ec)
2800 bool previous_state = ec.CheckState;
2801 bool previous_state_const = ec.ConstantCheckState;
2803 ec.CheckState = true;
2804 ec.ConstantCheckState = true;
2806 ec.CheckState = previous_state;
2807 ec.ConstantCheckState = previous_state_const;
2811 public class Unsafe : Statement {
2812 public readonly Block Block;
2814 public Unsafe (Block b)
2819 public override bool Resolve (EmitContext ec)
2821 bool previous_state = ec.InUnsafe;
2825 val = Block.Resolve (ec);
2826 ec.InUnsafe = previous_state;
2831 protected override void DoEmit (EmitContext ec)
2833 bool previous_state = ec.InUnsafe;
2837 ec.InUnsafe = previous_state;
2844 public class Fixed : Statement {
2846 ArrayList declarators;
2847 Statement statement;
2853 public bool is_object;
2854 public LocalInfo vi;
2855 public Expression expr;
2856 public Expression converted;
2859 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2862 declarators = decls;
2867 public override bool Resolve (EmitContext ec)
2870 Expression.UnsafeError (loc);
2874 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2875 if (expr_type == null)
2878 if (ec.RemapToProxy){
2879 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2883 data = new FixedData [declarators.Count];
2885 if (!expr_type.IsPointer){
2886 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2891 foreach (Pair p in declarators){
2892 LocalInfo vi = (LocalInfo) p.First;
2893 Expression e = (Expression) p.Second;
2895 vi.VariableInfo = null;
2899 // The rules for the possible declarators are pretty wise,
2900 // but the production on the grammar is more concise.
2902 // So we have to enforce these rules here.
2904 // We do not resolve before doing the case 1 test,
2905 // because the grammar is explicit in that the token &
2906 // is present, so we need to test for this particular case.
2910 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2915 // Case 1: & object.
2917 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2918 Expression child = ((Unary) e).Expr;
2921 if (child is ParameterReference || child is LocalVariableReference){
2924 "No need to use fixed statement for parameters or " +
2925 "local variable declarations (address is already " +
2930 ec.InFixedInitializer = true;
2932 ec.InFixedInitializer = false;
2936 child = ((Unary) e).Expr;
2938 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2941 data [i].is_object = true;
2943 data [i].converted = null;
2950 ec.InFixedInitializer = true;
2952 ec.InFixedInitializer = false;
2959 if (e.Type.IsArray){
2960 Type array_type = TypeManager.GetElementType (e.Type);
2964 // Provided that array_type is unmanaged,
2966 if (!TypeManager.VerifyUnManaged (array_type, loc))
2970 // and T* is implicitly convertible to the
2971 // pointer type given in the fixed statement.
2973 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2975 Expression converted = Convert.ImplicitConversionRequired (
2976 ec, array_ptr, vi.VariableType, loc);
2977 if (converted == null)
2980 data [i].is_object = false;
2982 data [i].converted = converted;
2992 if (e.Type == TypeManager.string_type){
2993 data [i].is_object = false;
2995 data [i].converted = null;
3002 // For other cases, flag a `this is already fixed expression'
3004 if (e is LocalVariableReference || e is ParameterReference ||
3005 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3007 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3011 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3015 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3017 if (!statement.Resolve (ec)) {
3018 ec.KillFlowBranching ();
3022 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3023 has_ret = reachability.IsUnreachable;
3028 protected override void DoEmit (EmitContext ec)
3030 ILGenerator ig = ec.ig;
3032 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3034 for (int i = 0; i < data.Length; i++) {
3035 LocalInfo vi = data [i].vi;
3038 // Case 1: & object.
3040 if (data [i].is_object) {
3042 // Store pointer in pinned location
3044 data [i].expr.Emit (ec);
3045 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3046 clear_list [i] = vi.LocalBuilder;
3053 if (data [i].expr.Type.IsArray){
3055 // Store pointer in pinned location
3057 data [i].converted.Emit (ec);
3059 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3060 clear_list [i] = vi.LocalBuilder;
3067 if (data [i].expr.Type == TypeManager.string_type){
3068 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3069 TypeManager.MakePinned (pinned_string);
3070 clear_list [i] = pinned_string;
3072 data [i].expr.Emit (ec);
3073 ig.Emit (OpCodes.Stloc, pinned_string);
3075 Expression sptr = new StringPtr (pinned_string, loc);
3076 Expression converted = Convert.ImplicitConversionRequired (
3077 ec, sptr, vi.VariableType, loc);
3079 if (converted == null)
3082 converted.Emit (ec);
3083 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3087 statement.Emit (ec);
3093 // Clear the pinned variable
3095 for (int i = 0; i < data.Length; i++) {
3096 if (data [i].is_object || data [i].expr.Type.IsArray) {
3097 ig.Emit (OpCodes.Ldc_I4_0);
3098 ig.Emit (OpCodes.Conv_U);
3099 ig.Emit (OpCodes.Stloc, clear_list [i]);
3100 } else if (data [i].expr.Type == TypeManager.string_type){
3101 ig.Emit (OpCodes.Ldnull);
3102 ig.Emit (OpCodes.Stloc, clear_list [i]);
3108 public class Catch {
3109 public readonly string Name;
3110 public readonly Block Block;
3111 public readonly Location Location;
3113 Expression type_expr;
3116 public Catch (Expression type, string name, Block block, Location l)
3124 public Type CatchType {
3130 public bool IsGeneral {
3132 return type_expr == null;
3136 public bool Resolve (EmitContext ec)
3138 if (type_expr != null) {
3139 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3143 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3144 Report.Error (155, Location,
3145 "The type caught or thrown must be derived " +
3146 "from System.Exception");
3152 if (!Block.Resolve (ec))
3159 public class Try : Statement {
3160 public readonly Block Fini, Block;
3161 public readonly ArrayList Specific;
3162 public readonly Catch General;
3165 // specific, general and fini might all be null.
3167 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3169 if (specific == null && general == null){
3170 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3174 this.Specific = specific;
3175 this.General = general;
3180 public override bool Resolve (EmitContext ec)
3184 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3186 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3188 if (!Block.Resolve (ec))
3191 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3193 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3195 foreach (Catch c in Specific){
3196 ec.CurrentBranching.CreateSibling (
3197 c.Block, FlowBranching.SiblingType.Catch);
3199 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3201 if (c.Name != null) {
3202 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3204 throw new Exception ();
3206 vi.VariableInfo = null;
3209 if (!c.Resolve (ec))
3213 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3215 if (General != null){
3216 ec.CurrentBranching.CreateSibling (
3217 General.Block, FlowBranching.SiblingType.Catch);
3219 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3221 if (!General.Resolve (ec))
3225 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3229 ec.CurrentBranching.CreateSibling (
3230 Fini, FlowBranching.SiblingType.Finally);
3232 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3234 if (!Fini.Resolve (ec))
3238 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3240 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3242 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3244 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3245 // Unfortunately, System.Reflection.Emit automatically emits a leave
3246 // to the end of the finally block. This is a problem if `returns'
3247 // is true since we may jump to a point after the end of the method.
3248 // As a workaround, emit an explicit ret here.
3249 ec.NeedReturnLabel ();
3255 protected override void DoEmit (EmitContext ec)
3257 ILGenerator ig = ec.ig;
3258 Label finish = ig.DefineLabel ();;
3260 ig.BeginExceptionBlock ();
3264 // System.Reflection.Emit provides this automatically:
3265 // ig.Emit (OpCodes.Leave, finish);
3267 foreach (Catch c in Specific){
3270 ig.BeginCatchBlock (c.CatchType);
3272 if (c.Name != null){
3273 vi = c.Block.GetLocalInfo (c.Name);
3275 throw new Exception ("Variable does not exist in this block");
3277 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3279 ig.Emit (OpCodes.Pop);
3284 if (General != null){
3285 ig.BeginCatchBlock (TypeManager.object_type);
3286 ig.Emit (OpCodes.Pop);
3287 General.Block.Emit (ec);
3290 ig.MarkLabel (finish);
3292 ig.BeginFinallyBlock ();
3296 ig.EndExceptionBlock ();
3300 public class Using : Statement {
3301 object expression_or_block;
3302 Statement Statement;
3307 Expression [] converted_vars;
3308 ExpressionStatement [] assign;
3310 public Using (object expression_or_block, Statement stmt, Location l)
3312 this.expression_or_block = expression_or_block;
3318 // Resolves for the case of using using a local variable declaration.
3320 bool ResolveLocalVariableDecls (EmitContext ec)
3322 bool need_conv = false;
3323 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3326 if (expr_type == null)
3330 // The type must be an IDisposable or an implicit conversion
3333 converted_vars = new Expression [var_list.Count];
3334 assign = new ExpressionStatement [var_list.Count];
3335 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3336 foreach (DictionaryEntry e in var_list){
3337 Expression var = (Expression) e.Key;
3339 var = var.ResolveLValue (ec, new EmptyExpression ());
3343 converted_vars [i] = Convert.ImplicitConversionRequired (
3344 ec, var, TypeManager.idisposable_type, loc);
3346 if (converted_vars [i] == null)
3354 foreach (DictionaryEntry e in var_list){
3355 LocalVariableReference var = (LocalVariableReference) e.Key;
3356 Expression new_expr = (Expression) e.Value;
3359 a = new Assign (var, new_expr, loc);
3365 converted_vars [i] = var;
3366 assign [i] = (ExpressionStatement) a;
3373 bool ResolveExpression (EmitContext ec)
3375 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3376 conv = Convert.ImplicitConversionRequired (
3377 ec, expr, TypeManager.idisposable_type, loc);
3387 // Emits the code for the case of using using a local variable declaration.
3389 bool EmitLocalVariableDecls (EmitContext ec)
3391 ILGenerator ig = ec.ig;
3394 for (i = 0; i < assign.Length; i++) {
3395 assign [i].EmitStatement (ec);
3397 ig.BeginExceptionBlock ();
3399 Statement.Emit (ec);
3401 var_list.Reverse ();
3402 foreach (DictionaryEntry e in var_list){
3403 LocalVariableReference var = (LocalVariableReference) e.Key;
3404 Label skip = ig.DefineLabel ();
3407 ig.BeginFinallyBlock ();
3409 if (!var.Type.IsValueType) {
3411 ig.Emit (OpCodes.Brfalse, skip);
3412 converted_vars [i].Emit (ec);
3413 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3415 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3417 if (!(ml is MethodGroupExpr)) {
3419 ig.Emit (OpCodes.Box, var.Type);
3420 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3422 MethodInfo mi = null;
3424 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3425 if (mk.GetParameters().Length == 0) {
3432 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3436 var.AddressOf (ec, AddressOp.Load);
3437 ig.Emit (OpCodes.Call, mi);
3441 ig.MarkLabel (skip);
3442 ig.EndExceptionBlock ();
3448 bool EmitExpression (EmitContext ec)
3451 // Make a copy of the expression and operate on that.
3453 ILGenerator ig = ec.ig;
3454 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3459 ig.Emit (OpCodes.Stloc, local_copy);
3461 ig.BeginExceptionBlock ();
3462 Statement.Emit (ec);
3464 Label skip = ig.DefineLabel ();
3465 ig.BeginFinallyBlock ();
3466 ig.Emit (OpCodes.Ldloc, local_copy);
3467 ig.Emit (OpCodes.Brfalse, skip);
3468 ig.Emit (OpCodes.Ldloc, local_copy);
3469 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3470 ig.MarkLabel (skip);
3471 ig.EndExceptionBlock ();
3476 public override bool Resolve (EmitContext ec)
3478 if (expression_or_block is DictionaryEntry){
3479 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3480 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3482 if (!ResolveLocalVariableDecls (ec))
3485 } else if (expression_or_block is Expression){
3486 expr = (Expression) expression_or_block;
3488 expr = expr.Resolve (ec);
3492 expr_type = expr.Type;
3494 if (!ResolveExpression (ec))
3498 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3500 bool ok = Statement.Resolve (ec);
3503 ec.KillFlowBranching ();
3507 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3509 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3510 // Unfortunately, System.Reflection.Emit automatically emits a leave
3511 // to the end of the finally block. This is a problem if `returns'
3512 // is true since we may jump to a point after the end of the method.
3513 // As a workaround, emit an explicit ret here.
3514 ec.NeedReturnLabel ();
3520 protected override void DoEmit (EmitContext ec)
3522 if (expression_or_block is DictionaryEntry)
3523 EmitLocalVariableDecls (ec);
3524 else if (expression_or_block is Expression)
3525 EmitExpression (ec);
3530 /// Implementation of the foreach C# statement
3532 public class Foreach : Statement {
3534 Expression variable;
3536 Statement statement;
3537 ForeachHelperMethods hm;
3538 Expression empty, conv;
3539 Type array_type, element_type;
3542 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3543 Statement stmt, Location l)
3546 this.variable = var;
3552 public override bool Resolve (EmitContext ec)
3554 expr = expr.Resolve (ec);
3558 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3559 if (var_type == null)
3563 // We need an instance variable. Not sure this is the best
3564 // way of doing this.
3566 // FIXME: When we implement propertyaccess, will those turn
3567 // out to return values in ExprClass? I think they should.
3569 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3570 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3571 error1579 (expr.Type);
3575 if (expr.Type.IsArray) {
3576 array_type = expr.Type;
3577 element_type = TypeManager.GetElementType (array_type);
3579 empty = new EmptyExpression (element_type);
3581 hm = ProbeCollectionType (ec, expr.Type);
3583 error1579 (expr.Type);
3587 array_type = expr.Type;
3588 element_type = hm.element_type;
3590 empty = new EmptyExpression (hm.element_type);
3595 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3596 ec.CurrentBranching.CreateSibling ();
3600 // FIXME: maybe we can apply the same trick we do in the
3601 // array handling to avoid creating empty and conv in some cases.
3603 // Although it is not as important in this case, as the type
3604 // will not likely be object (what the enumerator will return).
3606 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3610 variable = variable.ResolveLValue (ec, empty);
3611 if (variable == null)
3614 bool disposable = (hm != null) && hm.is_disposable;
3616 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3618 if (!statement.Resolve (ec))
3622 ec.EndFlowBranching ();
3624 ec.EndFlowBranching ();
3630 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3632 static MethodInfo FetchMethodMoveNext (Type t)
3634 MemberList move_next_list;
3636 move_next_list = TypeContainer.FindMembers (
3637 t, MemberTypes.Method,
3638 BindingFlags.Public | BindingFlags.Instance,
3639 Type.FilterName, "MoveNext");
3640 if (move_next_list.Count == 0)
3643 foreach (MemberInfo m in move_next_list){
3644 MethodInfo mi = (MethodInfo) m;
3647 args = TypeManager.GetArgumentTypes (mi);
3648 if (args != null && args.Length == 0){
3649 if (mi.ReturnType == TypeManager.bool_type)
3657 // Retrieves a `public T get_Current ()' method from the Type `t'
3659 static MethodInfo FetchMethodGetCurrent (Type t)
3661 MemberList get_current_list;
3663 get_current_list = TypeContainer.FindMembers (
3664 t, MemberTypes.Method,
3665 BindingFlags.Public | BindingFlags.Instance,
3666 Type.FilterName, "get_Current");
3667 if (get_current_list.Count == 0)
3670 foreach (MemberInfo m in get_current_list){
3671 MethodInfo mi = (MethodInfo) m;
3674 args = TypeManager.GetArgumentTypes (mi);
3675 if (args != null && args.Length == 0)
3682 // This struct records the helper methods used by the Foreach construct
3684 class ForeachHelperMethods {
3685 public EmitContext ec;
3686 public MethodInfo get_enumerator;
3687 public MethodInfo move_next;
3688 public MethodInfo get_current;
3689 public Type element_type;
3690 public Type enumerator_type;
3691 public bool is_disposable;
3693 public ForeachHelperMethods (EmitContext ec)
3696 this.element_type = TypeManager.object_type;
3697 this.enumerator_type = TypeManager.ienumerator_type;
3698 this.is_disposable = true;
3702 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3707 if (!(m is MethodInfo))
3710 if (m.Name != "GetEnumerator")
3713 MethodInfo mi = (MethodInfo) m;
3714 Type [] args = TypeManager.GetArgumentTypes (mi);
3716 if (args.Length != 0)
3719 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3720 EmitContext ec = hm.ec;
3723 // Check whether GetEnumerator is accessible to us
3725 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3727 Type declaring = mi.DeclaringType;
3728 if (prot == MethodAttributes.Private){
3729 if (declaring != ec.ContainerType)
3731 } else if (prot == MethodAttributes.FamANDAssem){
3732 // If from a different assembly, false
3733 if (!(mi is MethodBuilder))
3736 // Are we being invoked from the same class, or from a derived method?
3738 if (ec.ContainerType != declaring){
3739 if (!ec.ContainerType.IsSubclassOf (declaring))
3742 } else if (prot == MethodAttributes.FamORAssem){
3743 if (!(mi is MethodBuilder ||
3744 ec.ContainerType == declaring ||
3745 ec.ContainerType.IsSubclassOf (declaring)))
3747 } if (prot == MethodAttributes.Family){
3748 if (!(ec.ContainerType == declaring ||
3749 ec.ContainerType.IsSubclassOf (declaring)))
3753 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3755 // Apply the same optimization as MS: skip the GetEnumerator
3756 // returning an IEnumerator, and use the one returning a
3757 // CharEnumerator instead. This allows us to avoid the
3758 // try-finally block and the boxing.
3763 // Ok, we can access it, now make sure that we can do something
3764 // with this `GetEnumerator'
3767 Type return_type = mi.ReturnType;
3768 if (mi.ReturnType == TypeManager.ienumerator_type ||
3769 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3770 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3773 // If it is not an interface, lets try to find the methods ourselves.
3774 // For example, if we have:
3775 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3776 // We can avoid the iface call. This is a runtime perf boost.
3777 // even bigger if we have a ValueType, because we avoid the cost
3780 // We have to make sure that both methods exist for us to take
3781 // this path. If one of the methods does not exist, we will just
3782 // use the interface. Sadly, this complex if statement is the only
3783 // way I could do this without a goto
3786 if (return_type.IsInterface ||
3787 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3788 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3790 hm.move_next = TypeManager.bool_movenext_void;
3791 hm.get_current = TypeManager.object_getcurrent_void;
3798 // Ok, so they dont return an IEnumerable, we will have to
3799 // find if they support the GetEnumerator pattern.
3802 hm.move_next = FetchMethodMoveNext (return_type);
3803 if (hm.move_next == null)
3806 hm.get_current = FetchMethodGetCurrent (return_type);
3807 if (hm.get_current == null)
3811 hm.element_type = hm.get_current.ReturnType;
3812 hm.enumerator_type = return_type;
3813 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3814 TypeManager.ImplementsInterface (
3815 hm.enumerator_type, TypeManager.idisposable_type);
3821 /// This filter is used to find the GetEnumerator method
3822 /// on which IEnumerator operates
3824 static MemberFilter FilterEnumerator;
3828 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3831 void error1579 (Type t)
3833 Report.Error (1579, loc,
3834 "foreach statement cannot operate on variables of type `" +
3835 t.FullName + "' because that class does not provide a " +
3836 " GetEnumerator method or it is inaccessible");
3839 static bool TryType (Type t, ForeachHelperMethods hm)
3843 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3844 BindingFlags.Public | BindingFlags.NonPublic |
3845 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3846 FilterEnumerator, hm);
3851 hm.get_enumerator = (MethodInfo) mi [0];
3856 // Looks for a usable GetEnumerator in the Type, and if found returns
3857 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3859 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3861 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3863 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3864 if (TryType (tt, hm))
3870 // Now try to find the method in the interfaces
3873 Type [] ifaces = t.GetInterfaces ();
3875 foreach (Type i in ifaces){
3876 if (TryType (i, hm))
3881 // Since TypeBuilder.GetInterfaces only returns the interface
3882 // types for this type, we have to keep looping, but once
3883 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3884 // done, because it returns all the types
3886 if ((t is TypeBuilder))
3896 // FIXME: possible optimization.
3897 // We might be able to avoid creating `empty' if the type is the sam
3899 bool EmitCollectionForeach (EmitContext ec)
3901 ILGenerator ig = ec.ig;
3902 VariableStorage enumerator;
3904 enumerator = new VariableStorage (ec, hm.enumerator_type);
3905 enumerator.EmitThis ();
3907 // Instantiate the enumerator
3909 if (expr.Type.IsValueType){
3910 if (expr is IMemoryLocation){
3911 IMemoryLocation ml = (IMemoryLocation) expr;
3913 Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
3915 if (!(ml1 is MethodGroupExpr)) {
3917 ec.ig.Emit(OpCodes.Box, expr.Type);
3919 ml.AddressOf (ec, AddressOp.Load);
3922 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3923 " does not implement IMemoryLocation");
3924 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3927 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3929 enumerator.EmitStore ();
3932 // Protect the code in a try/finalize block, so that
3933 // if the beast implement IDisposable, we get rid of it
3935 if (hm.is_disposable)
3936 ig.BeginExceptionBlock ();
3938 Label end_try = ig.DefineLabel ();
3940 ig.MarkLabel (ec.LoopBegin);
3942 enumerator.EmitCall (hm.move_next);
3944 ig.Emit (OpCodes.Brfalse, end_try);
3948 enumerator.EmitCall (hm.get_current);
3952 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3954 ((IAssignMethod)variable).EmitAssign (ec, conv);
3956 statement.Emit (ec);
3957 ig.Emit (OpCodes.Br, ec.LoopBegin);
3958 ig.MarkLabel (end_try);
3960 // The runtime provides this for us.
3961 // ig.Emit (OpCodes.Leave, end);
3964 // Now the finally block
3966 if (hm.is_disposable) {
3967 Label call_dispose = ig.DefineLabel ();
3968 ig.BeginFinallyBlock ();
3970 enumerator.EmitThis ();
3971 enumerator.EmitLoad ();
3972 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3973 ig.Emit (OpCodes.Dup);
3974 ig.Emit (OpCodes.Brtrue_S, call_dispose);
3975 ig.Emit (OpCodes.Pop);
3976 ig.Emit (OpCodes.Endfinally);
3978 ig.MarkLabel (call_dispose);
3979 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3982 // The runtime generates this anyways.
3983 // ig.Emit (OpCodes.Endfinally);
3985 ig.EndExceptionBlock ();
3988 ig.MarkLabel (ec.LoopEnd);
3993 // FIXME: possible optimization.
3994 // We might be able to avoid creating `empty' if the type is the sam
3996 bool EmitArrayForeach (EmitContext ec)
3998 int rank = array_type.GetArrayRank ();
3999 ILGenerator ig = ec.ig;
4001 VariableStorage copy = new VariableStorage (ec, array_type);
4004 // Make our copy of the array
4011 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4015 counter.EmitThis ();
4016 ig.Emit (OpCodes.Ldc_I4_0);
4017 counter.EmitStore ();
4018 test = ig.DefineLabel ();
4019 ig.Emit (OpCodes.Br, test);
4021 loop = ig.DefineLabel ();
4022 ig.MarkLabel (loop);
4029 counter.EmitThis ();
4030 counter.EmitLoad ();
4033 // Load the value, we load the value using the underlying type,
4034 // then we use the variable.EmitAssign to load using the proper cast.
4036 ArrayAccess.EmitLoadOpcode (ig, element_type);
4039 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4041 ((IAssignMethod)variable).EmitAssign (ec, conv);
4043 statement.Emit (ec);
4045 ig.MarkLabel (ec.LoopBegin);
4046 counter.EmitThis ();
4047 counter.EmitThis ();
4048 counter.EmitLoad ();
4049 ig.Emit (OpCodes.Ldc_I4_1);
4050 ig.Emit (OpCodes.Add);
4051 counter.EmitStore ();
4053 ig.MarkLabel (test);
4054 counter.EmitThis ();
4055 counter.EmitLoad ();
4058 ig.Emit (OpCodes.Ldlen);
4059 ig.Emit (OpCodes.Conv_I4);
4060 ig.Emit (OpCodes.Blt, loop);
4062 VariableStorage [] dim_len = new VariableStorage [rank];
4063 VariableStorage [] dim_count = new VariableStorage [rank];
4064 Label [] loop = new Label [rank];
4065 Label [] test = new Label [rank];
4068 for (dim = 0; dim < rank; dim++){
4069 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4070 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4071 test [dim] = ig.DefineLabel ();
4072 loop [dim] = ig.DefineLabel ();
4075 for (dim = 0; dim < rank; dim++){
4076 dim_len [dim].EmitThis ();
4079 IntLiteral.EmitInt (ig, dim);
4080 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4081 dim_len [dim].EmitStore ();
4085 for (dim = 0; dim < rank; dim++){
4086 dim_count [dim].EmitThis ();
4087 ig.Emit (OpCodes.Ldc_I4_0);
4088 dim_count [dim].EmitStore ();
4089 ig.Emit (OpCodes.Br, test [dim]);
4090 ig.MarkLabel (loop [dim]);
4097 for (dim = 0; dim < rank; dim++){
4098 dim_count [dim].EmitThis ();
4099 dim_count [dim].EmitLoad ();
4103 // FIXME: Maybe we can cache the computation of `get'?
4105 Type [] args = new Type [rank];
4108 for (int i = 0; i < rank; i++)
4109 args [i] = TypeManager.int32_type;
4111 ModuleBuilder mb = CodeGen.Module.Builder;
4112 get = mb.GetArrayMethod (
4114 CallingConventions.HasThis| CallingConventions.Standard,
4116 ig.Emit (OpCodes.Call, get);
4119 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4121 ((IAssignMethod)variable).EmitAssign (ec, conv);
4122 statement.Emit (ec);
4123 ig.MarkLabel (ec.LoopBegin);
4124 for (dim = rank - 1; dim >= 0; dim--){
4125 dim_count [dim].EmitThis ();
4126 dim_count [dim].EmitThis ();
4127 dim_count [dim].EmitLoad ();
4128 ig.Emit (OpCodes.Ldc_I4_1);
4129 ig.Emit (OpCodes.Add);
4130 dim_count [dim].EmitStore ();
4132 ig.MarkLabel (test [dim]);
4133 dim_count [dim].EmitThis ();
4134 dim_count [dim].EmitLoad ();
4135 dim_len [dim].EmitThis ();
4136 dim_len [dim].EmitLoad ();
4137 ig.Emit (OpCodes.Blt, loop [dim]);
4140 ig.MarkLabel (ec.LoopEnd);
4145 protected override void DoEmit (EmitContext ec)
4147 ILGenerator ig = ec.ig;
4149 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4150 ec.LoopBegin = ig.DefineLabel ();
4151 ec.LoopEnd = ig.DefineLabel ();
4154 EmitCollectionForeach (ec);
4156 EmitArrayForeach (ec);
4158 ec.LoopBegin = old_begin;
4159 ec.LoopEnd = old_end;