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 == EmptyStatement.Value)
1743 s.loc = EndLocation;
1745 if (!s.ResolveUnreachable (ec, !warning_shown))
1748 if (s != EmptyStatement.Value)
1749 warning_shown = true;
1751 s.loc = Location.Null;
1753 statements [ix] = EmptyStatement.Value;
1757 if (s.Resolve (ec) == false) {
1759 statements [ix] = EmptyStatement.Value;
1763 num_statements = ix + 1;
1765 if (s is LabeledStatement)
1766 unreachable = false;
1768 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1771 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1772 ec.CurrentBranching, statement_count, num_statements);
1775 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1777 ec.CurrentBlock = prev_block;
1779 // If we're a non-static `struct' constructor which doesn't have an
1780 // initializer, then we must initialize all of the struct's fields.
1781 if ((this_variable != null) &&
1782 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1783 !this_variable.IsThisAssigned (ec, loc))
1786 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1787 foreach (LabeledStatement label in labels.Values)
1788 if (!label.HasBeenReferenced)
1789 Report.Warning (164, label.Location,
1790 "This label has not been referenced");
1793 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1795 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1796 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1797 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1798 flags |= Flags.HasRet;
1800 if (ok && (errors == Report.Errors)) {
1801 if (RootContext.WarningLevel >= 3)
1802 UsageWarning (vector);
1808 protected override void DoEmit (EmitContext ec)
1810 for (int ix = 0; ix < num_statements; ix++){
1811 Statement s = (Statement) statements [ix];
1813 // Check whether we are the last statement in a
1816 if ((Parent == null) && (ix+1 == num_statements))
1817 ec.IsLastStatement = true;
1819 ec.IsLastStatement = false;
1825 public override void Emit (EmitContext ec)
1827 Block prev_block = ec.CurrentBlock;
1829 ec.CurrentBlock = this;
1831 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1832 bool is_lexical_block = !Implicit && (Parent != null);
1834 if (emit_debug_info) {
1835 if (is_lexical_block)
1836 ec.ig.BeginScope ();
1838 if (variables != null) {
1839 foreach (DictionaryEntry de in variables) {
1840 string name = (string) de.Key;
1841 LocalInfo vi = (LocalInfo) de.Value;
1843 if (vi.LocalBuilder == null)
1846 vi.LocalBuilder.SetLocalSymInfo (name);
1851 ec.Mark (StartLocation, true);
1853 ec.Mark (EndLocation, true);
1855 if (emit_debug_info && is_lexical_block)
1858 ec.CurrentBlock = prev_block;
1864 public class ToplevelBlock : Block {
1865 public ToplevelBlock (Parameters parameters, Location start) :
1866 base (null, parameters, start, Location.Null)
1870 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1871 base (null, flags, parameters, start, Location.Null)
1876 public class SwitchLabel {
1879 public Location loc;
1880 public Label ILLabel;
1881 public Label ILLabelCode;
1884 // if expr == null, then it is the default case.
1886 public SwitchLabel (Expression expr, Location l)
1892 public Expression Label {
1898 public object Converted {
1905 // Resolves the expression, reduces it to a literal if possible
1906 // and then converts it to the requested type.
1908 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1910 ILLabel = ec.ig.DefineLabel ();
1911 ILLabelCode = ec.ig.DefineLabel ();
1916 Expression e = label.Resolve (ec);
1921 if (!(e is Constant)){
1922 Report.Error (150, loc, "A constant value is expected, got: " + e);
1926 if (e is StringConstant || e is NullLiteral){
1927 if (required_type == TypeManager.string_type){
1929 ILLabel = ec.ig.DefineLabel ();
1934 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1935 if (converted == null)
1942 public class SwitchSection {
1943 // An array of SwitchLabels.
1944 public readonly ArrayList Labels;
1945 public readonly Block Block;
1947 public SwitchSection (ArrayList labels, Block block)
1954 public class Switch : Statement {
1955 public readonly ArrayList Sections;
1956 public Expression Expr;
1959 /// Maps constants whose type type SwitchType to their SwitchLabels.
1961 public Hashtable Elements;
1964 /// The governing switch type
1966 public Type SwitchType;
1972 Label default_target;
1973 Expression new_expr;
1976 // The types allowed to be implicitly cast from
1977 // on the governing type
1979 static Type [] allowed_types;
1981 public Switch (Expression e, ArrayList sects, Location l)
1988 public bool GotDefault {
1994 public Label DefaultTarget {
1996 return default_target;
2001 // Determines the governing type for a switch. The returned
2002 // expression might be the expression from the switch, or an
2003 // expression that includes any potential conversions to the
2004 // integral types or to string.
2006 Expression SwitchGoverningType (EmitContext ec, Type t)
2008 if (t == TypeManager.int32_type ||
2009 t == TypeManager.uint32_type ||
2010 t == TypeManager.char_type ||
2011 t == TypeManager.byte_type ||
2012 t == TypeManager.sbyte_type ||
2013 t == TypeManager.ushort_type ||
2014 t == TypeManager.short_type ||
2015 t == TypeManager.uint64_type ||
2016 t == TypeManager.int64_type ||
2017 t == TypeManager.string_type ||
2018 t == TypeManager.bool_type ||
2019 t.IsSubclassOf (TypeManager.enum_type))
2022 if (allowed_types == null){
2023 allowed_types = new Type [] {
2024 TypeManager.sbyte_type,
2025 TypeManager.byte_type,
2026 TypeManager.short_type,
2027 TypeManager.ushort_type,
2028 TypeManager.int32_type,
2029 TypeManager.uint32_type,
2030 TypeManager.int64_type,
2031 TypeManager.uint64_type,
2032 TypeManager.char_type,
2033 TypeManager.bool_type,
2034 TypeManager.string_type
2039 // Try to find a *user* defined implicit conversion.
2041 // If there is no implicit conversion, or if there are multiple
2042 // conversions, we have to report an error
2044 Expression converted = null;
2045 foreach (Type tt in allowed_types){
2048 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2052 if (converted != null){
2053 Report.Error (-12, loc, "More than one conversion to an integral " +
2054 " type exists for type `" +
2055 TypeManager.CSharpName (Expr.Type)+"'");
2063 void error152 (string n)
2066 152, "The label `" + n + ":' " +
2067 "is already present on this switch statement");
2071 // Performs the basic sanity checks on the switch statement
2072 // (looks for duplicate keys and non-constant expressions).
2074 // It also returns a hashtable with the keys that we will later
2075 // use to compute the switch tables
2077 bool CheckSwitch (EmitContext ec)
2081 Elements = new Hashtable ();
2083 got_default = false;
2085 if (TypeManager.IsEnumType (SwitchType)){
2086 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2088 compare_type = SwitchType;
2090 foreach (SwitchSection ss in Sections){
2091 foreach (SwitchLabel sl in ss.Labels){
2092 if (!sl.ResolveAndReduce (ec, SwitchType)){
2097 if (sl.Label == null){
2099 error152 ("default");
2106 object key = sl.Converted;
2108 if (key is Constant)
2109 key = ((Constant) key).GetValue ();
2112 key = NullLiteral.Null;
2114 string lname = null;
2115 if (compare_type == TypeManager.uint64_type){
2116 ulong v = (ulong) key;
2118 if (Elements.Contains (v))
2119 lname = v.ToString ();
2121 Elements.Add (v, sl);
2122 } else if (compare_type == TypeManager.int64_type){
2123 long v = (long) key;
2125 if (Elements.Contains (v))
2126 lname = v.ToString ();
2128 Elements.Add (v, sl);
2129 } else if (compare_type == TypeManager.uint32_type){
2130 uint v = (uint) key;
2132 if (Elements.Contains (v))
2133 lname = v.ToString ();
2135 Elements.Add (v, sl);
2136 } else if (compare_type == TypeManager.char_type){
2137 char v = (char) key;
2139 if (Elements.Contains (v))
2140 lname = v.ToString ();
2142 Elements.Add (v, sl);
2143 } else if (compare_type == TypeManager.byte_type){
2144 byte v = (byte) key;
2146 if (Elements.Contains (v))
2147 lname = v.ToString ();
2149 Elements.Add (v, sl);
2150 } else if (compare_type == TypeManager.sbyte_type){
2151 sbyte v = (sbyte) key;
2153 if (Elements.Contains (v))
2154 lname = v.ToString ();
2156 Elements.Add (v, sl);
2157 } else if (compare_type == TypeManager.short_type){
2158 short v = (short) key;
2160 if (Elements.Contains (v))
2161 lname = v.ToString ();
2163 Elements.Add (v, sl);
2164 } else if (compare_type == TypeManager.ushort_type){
2165 ushort v = (ushort) key;
2167 if (Elements.Contains (v))
2168 lname = v.ToString ();
2170 Elements.Add (v, sl);
2171 } else if (compare_type == TypeManager.string_type){
2172 if (key is NullLiteral){
2173 if (Elements.Contains (NullLiteral.Null))
2176 Elements.Add (NullLiteral.Null, null);
2178 string s = (string) key;
2180 if (Elements.Contains (s))
2183 Elements.Add (s, sl);
2185 } else if (compare_type == TypeManager.int32_type) {
2188 if (Elements.Contains (v))
2189 lname = v.ToString ();
2191 Elements.Add (v, sl);
2192 } else if (compare_type == TypeManager.bool_type) {
2193 bool v = (bool) key;
2195 if (Elements.Contains (v))
2196 lname = v.ToString ();
2198 Elements.Add (v, sl);
2202 throw new Exception ("Unknown switch type!" +
2203 SwitchType + " " + compare_type);
2207 error152 ("case + " + lname);
2218 void EmitObjectInteger (ILGenerator ig, object k)
2221 IntConstant.EmitInt (ig, (int) k);
2222 else if (k is Constant) {
2223 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2226 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2229 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2231 IntConstant.EmitInt (ig, (int) (long) k);
2232 ig.Emit (OpCodes.Conv_I8);
2235 LongConstant.EmitLong (ig, (long) k);
2237 else if (k is ulong)
2239 if ((ulong) k < (1L<<32))
2241 IntConstant.EmitInt (ig, (int) (long) k);
2242 ig.Emit (OpCodes.Conv_U8);
2246 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2250 IntConstant.EmitInt (ig, (int) ((char) k));
2251 else if (k is sbyte)
2252 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2254 IntConstant.EmitInt (ig, (int) ((byte) k));
2255 else if (k is short)
2256 IntConstant.EmitInt (ig, (int) ((short) k));
2257 else if (k is ushort)
2258 IntConstant.EmitInt (ig, (int) ((ushort) k));
2260 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2262 throw new Exception ("Unhandled case");
2265 // structure used to hold blocks of keys while calculating table switch
2266 class KeyBlock : IComparable
2268 public KeyBlock (long _nFirst)
2270 nFirst = nLast = _nFirst;
2274 public ArrayList rgKeys = null;
2275 // how many items are in the bucket
2276 public int Size = 1;
2279 get { return (int) (nLast - nFirst + 1); }
2281 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2283 return kbLast.nLast - kbFirst.nFirst + 1;
2285 public int CompareTo (object obj)
2287 KeyBlock kb = (KeyBlock) obj;
2288 int nLength = Length;
2289 int nLengthOther = kb.Length;
2290 if (nLengthOther == nLength)
2291 return (int) (kb.nFirst - nFirst);
2292 return nLength - nLengthOther;
2297 /// This method emits code for a lookup-based switch statement (non-string)
2298 /// Basically it groups the cases into blocks that are at least half full,
2299 /// and then spits out individual lookup opcodes for each block.
2300 /// It emits the longest blocks first, and short blocks are just
2301 /// handled with direct compares.
2303 /// <param name="ec"></param>
2304 /// <param name="val"></param>
2305 /// <returns></returns>
2306 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2308 int cElements = Elements.Count;
2309 object [] rgKeys = new object [cElements];
2310 Elements.Keys.CopyTo (rgKeys, 0);
2311 Array.Sort (rgKeys);
2313 // initialize the block list with one element per key
2314 ArrayList rgKeyBlocks = new ArrayList ();
2315 foreach (object key in rgKeys)
2316 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2319 // iteratively merge the blocks while they are at least half full
2320 // there's probably a really cool way to do this with a tree...
2321 while (rgKeyBlocks.Count > 1)
2323 ArrayList rgKeyBlocksNew = new ArrayList ();
2324 kbCurr = (KeyBlock) rgKeyBlocks [0];
2325 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2327 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2328 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2331 kbCurr.nLast = kb.nLast;
2332 kbCurr.Size += kb.Size;
2336 // start a new block
2337 rgKeyBlocksNew.Add (kbCurr);
2341 rgKeyBlocksNew.Add (kbCurr);
2342 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2344 rgKeyBlocks = rgKeyBlocksNew;
2347 // initialize the key lists
2348 foreach (KeyBlock kb in rgKeyBlocks)
2349 kb.rgKeys = new ArrayList ();
2351 // fill the key lists
2353 if (rgKeyBlocks.Count > 0) {
2354 kbCurr = (KeyBlock) rgKeyBlocks [0];
2355 foreach (object key in rgKeys)
2357 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2358 System.Convert.ToInt64 (key) > kbCurr.nLast;
2360 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2361 kbCurr.rgKeys.Add (key);
2365 // sort the blocks so we can tackle the largest ones first
2366 rgKeyBlocks.Sort ();
2368 // okay now we can start...
2369 ILGenerator ig = ec.ig;
2370 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2371 Label lblDefault = ig.DefineLabel ();
2373 Type typeKeys = null;
2374 if (rgKeys.Length > 0)
2375 typeKeys = rgKeys [0].GetType (); // used for conversions
2379 if (TypeManager.IsEnumType (SwitchType))
2380 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2382 compare_type = SwitchType;
2384 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2386 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2387 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2390 foreach (object key in kb.rgKeys)
2392 ig.Emit (OpCodes.Ldloc, val);
2393 EmitObjectInteger (ig, key);
2394 SwitchLabel sl = (SwitchLabel) Elements [key];
2395 ig.Emit (OpCodes.Beq, sl.ILLabel);
2400 // TODO: if all the keys in the block are the same and there are
2401 // no gaps/defaults then just use a range-check.
2402 if (compare_type == TypeManager.int64_type ||
2403 compare_type == TypeManager.uint64_type)
2405 // TODO: optimize constant/I4 cases
2407 // check block range (could be > 2^31)
2408 ig.Emit (OpCodes.Ldloc, val);
2409 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2410 ig.Emit (OpCodes.Blt, lblDefault);
2411 ig.Emit (OpCodes.Ldloc, val);
2412 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2413 ig.Emit (OpCodes.Bgt, lblDefault);
2416 ig.Emit (OpCodes.Ldloc, val);
2419 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2420 ig.Emit (OpCodes.Sub);
2422 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2427 ig.Emit (OpCodes.Ldloc, val);
2428 int nFirst = (int) kb.nFirst;
2431 IntConstant.EmitInt (ig, nFirst);
2432 ig.Emit (OpCodes.Sub);
2434 else if (nFirst < 0)
2436 IntConstant.EmitInt (ig, -nFirst);
2437 ig.Emit (OpCodes.Add);
2441 // first, build the list of labels for the switch
2443 int cJumps = kb.Length;
2444 Label [] rgLabels = new Label [cJumps];
2445 for (int iJump = 0; iJump < cJumps; iJump++)
2447 object key = kb.rgKeys [iKey];
2448 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2450 SwitchLabel sl = (SwitchLabel) Elements [key];
2451 rgLabels [iJump] = sl.ILLabel;
2455 rgLabels [iJump] = lblDefault;
2457 // emit the switch opcode
2458 ig.Emit (OpCodes.Switch, rgLabels);
2461 // mark the default for this block
2463 ig.MarkLabel (lblDefault);
2466 // TODO: find the default case and emit it here,
2467 // to prevent having to do the following jump.
2468 // make sure to mark other labels in the default section
2470 // the last default just goes to the end
2471 ig.Emit (OpCodes.Br, lblDefault);
2473 // now emit the code for the sections
2474 bool fFoundDefault = false;
2475 foreach (SwitchSection ss in Sections)
2477 foreach (SwitchLabel sl in ss.Labels)
2479 ig.MarkLabel (sl.ILLabel);
2480 ig.MarkLabel (sl.ILLabelCode);
2481 if (sl.Label == null)
2483 ig.MarkLabel (lblDefault);
2484 fFoundDefault = true;
2488 //ig.Emit (OpCodes.Br, lblEnd);
2491 if (!fFoundDefault) {
2492 ig.MarkLabel (lblDefault);
2494 ig.MarkLabel (lblEnd);
2497 // This simple emit switch works, but does not take advantage of the
2499 // TODO: remove non-string logic from here
2500 // TODO: binary search strings?
2502 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2504 ILGenerator ig = ec.ig;
2505 Label end_of_switch = ig.DefineLabel ();
2506 Label next_test = ig.DefineLabel ();
2507 Label null_target = ig.DefineLabel ();
2508 bool default_found = false;
2509 bool first_test = true;
2510 bool pending_goto_end = false;
2512 bool default_at_end = false;
2514 ig.Emit (OpCodes.Ldloc, val);
2516 if (Elements.Contains (NullLiteral.Null)){
2517 ig.Emit (OpCodes.Brfalse, null_target);
2519 ig.Emit (OpCodes.Brfalse, default_target);
2521 ig.Emit (OpCodes.Ldloc, val);
2522 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2523 ig.Emit (OpCodes.Stloc, val);
2525 int section_count = Sections.Count;
2526 for (int section = 0; section < section_count; section++){
2527 SwitchSection ss = (SwitchSection) Sections [section];
2528 Label sec_begin = ig.DefineLabel ();
2530 if (pending_goto_end)
2531 ig.Emit (OpCodes.Br, end_of_switch);
2533 int label_count = ss.Labels.Count;
2534 bool mark_default = false;
2536 for (int label = 0; label < label_count; label++){
2537 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2538 ig.MarkLabel (sl.ILLabel);
2541 ig.MarkLabel (next_test);
2542 next_test = ig.DefineLabel ();
2545 // If we are the default target
2547 if (sl.Label == null){
2548 if (label+1 == label_count)
2549 default_at_end = true;
2550 mark_default = true;
2551 default_found = true;
2553 object lit = sl.Converted;
2555 if (lit is NullLiteral){
2557 if (label_count == 1)
2558 ig.Emit (OpCodes.Br, next_test);
2562 StringConstant str = (StringConstant) lit;
2564 ig.Emit (OpCodes.Ldloc, val);
2565 ig.Emit (OpCodes.Ldstr, str.Value);
2566 if (label_count == 1)
2567 ig.Emit (OpCodes.Bne_Un, next_test);
2569 if (label+1 == label_count)
2570 ig.Emit (OpCodes.Bne_Un, next_test);
2572 ig.Emit (OpCodes.Beq, sec_begin);
2577 ig.MarkLabel (null_target);
2578 ig.MarkLabel (sec_begin);
2579 foreach (SwitchLabel sl in ss.Labels)
2580 ig.MarkLabel (sl.ILLabelCode);
2583 ig.MarkLabel (default_target);
2585 pending_goto_end = !ss.Block.HasRet;
2588 ig.MarkLabel (next_test);
2590 if (!default_at_end)
2591 ig.Emit (OpCodes.Br, default_target);
2593 ig.MarkLabel (default_target);
2594 ig.MarkLabel (end_of_switch);
2597 public override bool Resolve (EmitContext ec)
2599 Expr = Expr.Resolve (ec);
2603 new_expr = SwitchGoverningType (ec, Expr.Type);
2604 if (new_expr == null){
2605 Report.Error (151, loc, "An integer type or string was expected for switch");
2610 SwitchType = new_expr.Type;
2612 if (!CheckSwitch (ec))
2615 Switch old_switch = ec.Switch;
2617 ec.Switch.SwitchType = SwitchType;
2619 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2620 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2623 foreach (SwitchSection ss in Sections){
2625 ec.CurrentBranching.CreateSibling (
2626 null, FlowBranching.SiblingType.SwitchSection);
2630 if (ss.Block.Resolve (ec) != true)
2636 ec.CurrentBranching.CreateSibling (
2637 null, FlowBranching.SiblingType.SwitchSection);
2639 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2640 ec.Switch = old_switch;
2642 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2648 protected override void DoEmit (EmitContext ec)
2650 // Store variable for comparission purposes
2651 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2653 ec.ig.Emit (OpCodes.Stloc, value);
2655 ILGenerator ig = ec.ig;
2657 default_target = ig.DefineLabel ();
2660 // Setup the codegen context
2662 Label old_end = ec.LoopEnd;
2663 Switch old_switch = ec.Switch;
2665 ec.LoopEnd = ig.DefineLabel ();
2669 if (SwitchType == TypeManager.string_type)
2670 SimpleSwitchEmit (ec, value);
2672 TableSwitchEmit (ec, value);
2674 // Restore context state.
2675 ig.MarkLabel (ec.LoopEnd);
2678 // Restore the previous context
2680 ec.LoopEnd = old_end;
2681 ec.Switch = old_switch;
2685 public class Lock : Statement {
2687 Statement Statement;
2689 public Lock (Expression expr, Statement stmt, Location l)
2696 public override bool Resolve (EmitContext ec)
2698 expr = expr.Resolve (ec);
2702 if (expr.Type.IsValueType){
2703 Error (185, "lock statement requires the expression to be " +
2704 " a reference type (type is: `{0}'",
2705 TypeManager.CSharpName (expr.Type));
2709 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2710 bool ok = Statement.Resolve (ec);
2711 ec.EndFlowBranching ();
2716 protected override void DoEmit (EmitContext ec)
2718 Type type = expr.Type;
2720 ILGenerator ig = ec.ig;
2721 LocalBuilder temp = ig.DeclareLocal (type);
2724 ig.Emit (OpCodes.Dup);
2725 ig.Emit (OpCodes.Stloc, temp);
2726 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2729 ig.BeginExceptionBlock ();
2730 Label finish = ig.DefineLabel ();
2731 Statement.Emit (ec);
2732 // ig.Emit (OpCodes.Leave, finish);
2734 ig.MarkLabel (finish);
2737 ig.BeginFinallyBlock ();
2738 ig.Emit (OpCodes.Ldloc, temp);
2739 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2740 ig.EndExceptionBlock ();
2744 public class Unchecked : Statement {
2745 public readonly Block Block;
2747 public Unchecked (Block b)
2753 public override bool Resolve (EmitContext ec)
2755 bool previous_state = ec.CheckState;
2756 bool previous_state_const = ec.ConstantCheckState;
2758 ec.CheckState = false;
2759 ec.ConstantCheckState = false;
2760 bool ret = Block.Resolve (ec);
2761 ec.CheckState = previous_state;
2762 ec.ConstantCheckState = previous_state_const;
2767 protected override void DoEmit (EmitContext ec)
2769 bool previous_state = ec.CheckState;
2770 bool previous_state_const = ec.ConstantCheckState;
2772 ec.CheckState = false;
2773 ec.ConstantCheckState = false;
2775 ec.CheckState = previous_state;
2776 ec.ConstantCheckState = previous_state_const;
2780 public class Checked : Statement {
2781 public readonly Block Block;
2783 public Checked (Block b)
2786 b.Unchecked = false;
2789 public override bool Resolve (EmitContext ec)
2791 bool previous_state = ec.CheckState;
2792 bool previous_state_const = ec.ConstantCheckState;
2794 ec.CheckState = true;
2795 ec.ConstantCheckState = true;
2796 bool ret = Block.Resolve (ec);
2797 ec.CheckState = previous_state;
2798 ec.ConstantCheckState = previous_state_const;
2803 protected override void DoEmit (EmitContext ec)
2805 bool previous_state = ec.CheckState;
2806 bool previous_state_const = ec.ConstantCheckState;
2808 ec.CheckState = true;
2809 ec.ConstantCheckState = true;
2811 ec.CheckState = previous_state;
2812 ec.ConstantCheckState = previous_state_const;
2816 public class Unsafe : Statement {
2817 public readonly Block Block;
2819 public Unsafe (Block b)
2824 public override bool Resolve (EmitContext ec)
2826 bool previous_state = ec.InUnsafe;
2830 val = Block.Resolve (ec);
2831 ec.InUnsafe = previous_state;
2836 protected override void DoEmit (EmitContext ec)
2838 bool previous_state = ec.InUnsafe;
2842 ec.InUnsafe = previous_state;
2849 public class Fixed : Statement {
2851 ArrayList declarators;
2852 Statement statement;
2858 public bool is_object;
2859 public LocalInfo vi;
2860 public Expression expr;
2861 public Expression converted;
2864 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2867 declarators = decls;
2872 public override bool Resolve (EmitContext ec)
2875 Expression.UnsafeError (loc);
2879 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2880 if (expr_type == null)
2883 if (ec.RemapToProxy){
2884 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2888 data = new FixedData [declarators.Count];
2890 if (!expr_type.IsPointer){
2891 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2896 foreach (Pair p in declarators){
2897 LocalInfo vi = (LocalInfo) p.First;
2898 Expression e = (Expression) p.Second;
2900 vi.VariableInfo = null;
2904 // The rules for the possible declarators are pretty wise,
2905 // but the production on the grammar is more concise.
2907 // So we have to enforce these rules here.
2909 // We do not resolve before doing the case 1 test,
2910 // because the grammar is explicit in that the token &
2911 // is present, so we need to test for this particular case.
2915 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2920 // Case 1: & object.
2922 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2923 Expression child = ((Unary) e).Expr;
2926 if (child is ParameterReference || child is LocalVariableReference){
2929 "No need to use fixed statement for parameters or " +
2930 "local variable declarations (address is already " +
2935 ec.InFixedInitializer = true;
2937 ec.InFixedInitializer = false;
2941 child = ((Unary) e).Expr;
2943 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2946 data [i].is_object = true;
2948 data [i].converted = null;
2955 ec.InFixedInitializer = true;
2957 ec.InFixedInitializer = false;
2964 if (e.Type.IsArray){
2965 Type array_type = TypeManager.GetElementType (e.Type);
2969 // Provided that array_type is unmanaged,
2971 if (!TypeManager.VerifyUnManaged (array_type, loc))
2975 // and T* is implicitly convertible to the
2976 // pointer type given in the fixed statement.
2978 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2980 Expression converted = Convert.ImplicitConversionRequired (
2981 ec, array_ptr, vi.VariableType, loc);
2982 if (converted == null)
2985 data [i].is_object = false;
2987 data [i].converted = converted;
2997 if (e.Type == TypeManager.string_type){
2998 data [i].is_object = false;
3000 data [i].converted = null;
3007 // For other cases, flag a `this is already fixed expression'
3009 if (e is LocalVariableReference || e is ParameterReference ||
3010 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3012 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3016 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3020 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3022 if (!statement.Resolve (ec)) {
3023 ec.KillFlowBranching ();
3027 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3028 has_ret = reachability.IsUnreachable;
3033 protected override void DoEmit (EmitContext ec)
3035 ILGenerator ig = ec.ig;
3037 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3039 for (int i = 0; i < data.Length; i++) {
3040 LocalInfo vi = data [i].vi;
3043 // Case 1: & object.
3045 if (data [i].is_object) {
3047 // Store pointer in pinned location
3049 data [i].expr.Emit (ec);
3050 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3051 clear_list [i] = vi.LocalBuilder;
3058 if (data [i].expr.Type.IsArray){
3060 // Store pointer in pinned location
3062 data [i].converted.Emit (ec);
3064 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3065 clear_list [i] = vi.LocalBuilder;
3072 if (data [i].expr.Type == TypeManager.string_type){
3073 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3074 TypeManager.MakePinned (pinned_string);
3075 clear_list [i] = pinned_string;
3077 data [i].expr.Emit (ec);
3078 ig.Emit (OpCodes.Stloc, pinned_string);
3080 Expression sptr = new StringPtr (pinned_string, loc);
3081 Expression converted = Convert.ImplicitConversionRequired (
3082 ec, sptr, vi.VariableType, loc);
3084 if (converted == null)
3087 converted.Emit (ec);
3088 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3092 statement.Emit (ec);
3098 // Clear the pinned variable
3100 for (int i = 0; i < data.Length; i++) {
3101 if (data [i].is_object || data [i].expr.Type.IsArray) {
3102 ig.Emit (OpCodes.Ldc_I4_0);
3103 ig.Emit (OpCodes.Conv_U);
3104 ig.Emit (OpCodes.Stloc, clear_list [i]);
3105 } else if (data [i].expr.Type == TypeManager.string_type){
3106 ig.Emit (OpCodes.Ldnull);
3107 ig.Emit (OpCodes.Stloc, clear_list [i]);
3113 public class Catch {
3114 public readonly string Name;
3115 public readonly Block Block;
3116 public readonly Location Location;
3118 Expression type_expr;
3121 public Catch (Expression type, string name, Block block, Location l)
3129 public Type CatchType {
3135 public bool IsGeneral {
3137 return type_expr == null;
3141 public bool Resolve (EmitContext ec)
3143 if (type_expr != null) {
3144 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3148 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3149 Report.Error (155, Location,
3150 "The type caught or thrown must be derived " +
3151 "from System.Exception");
3157 if (!Block.Resolve (ec))
3164 public class Try : Statement {
3165 public readonly Block Fini, Block;
3166 public readonly ArrayList Specific;
3167 public readonly Catch General;
3170 // specific, general and fini might all be null.
3172 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3174 if (specific == null && general == null){
3175 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3179 this.Specific = specific;
3180 this.General = general;
3185 public override bool Resolve (EmitContext ec)
3189 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3191 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3193 if (!Block.Resolve (ec))
3196 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3198 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3200 foreach (Catch c in Specific){
3201 ec.CurrentBranching.CreateSibling (
3202 c.Block, FlowBranching.SiblingType.Catch);
3204 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3206 if (c.Name != null) {
3207 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3209 throw new Exception ();
3211 vi.VariableInfo = null;
3214 if (!c.Resolve (ec))
3218 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3220 if (General != null){
3221 ec.CurrentBranching.CreateSibling (
3222 General.Block, FlowBranching.SiblingType.Catch);
3224 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3226 if (!General.Resolve (ec))
3230 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3234 ec.CurrentBranching.CreateSibling (
3235 Fini, FlowBranching.SiblingType.Finally);
3237 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3239 if (!Fini.Resolve (ec))
3243 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3245 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3247 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3249 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3250 // Unfortunately, System.Reflection.Emit automatically emits a leave
3251 // to the end of the finally block. This is a problem if `returns'
3252 // is true since we may jump to a point after the end of the method.
3253 // As a workaround, emit an explicit ret here.
3254 ec.NeedReturnLabel ();
3260 protected override void DoEmit (EmitContext ec)
3262 ILGenerator ig = ec.ig;
3263 Label finish = ig.DefineLabel ();;
3265 ig.BeginExceptionBlock ();
3269 // System.Reflection.Emit provides this automatically:
3270 // ig.Emit (OpCodes.Leave, finish);
3272 foreach (Catch c in Specific){
3275 ig.BeginCatchBlock (c.CatchType);
3277 if (c.Name != null){
3278 vi = c.Block.GetLocalInfo (c.Name);
3280 throw new Exception ("Variable does not exist in this block");
3282 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3284 ig.Emit (OpCodes.Pop);
3289 if (General != null){
3290 ig.BeginCatchBlock (TypeManager.object_type);
3291 ig.Emit (OpCodes.Pop);
3292 General.Block.Emit (ec);
3295 ig.MarkLabel (finish);
3297 ig.BeginFinallyBlock ();
3301 ig.EndExceptionBlock ();
3305 public class Using : Statement {
3306 object expression_or_block;
3307 Statement Statement;
3312 Expression [] converted_vars;
3313 ExpressionStatement [] assign;
3315 public Using (object expression_or_block, Statement stmt, Location l)
3317 this.expression_or_block = expression_or_block;
3323 // Resolves for the case of using using a local variable declaration.
3325 bool ResolveLocalVariableDecls (EmitContext ec)
3327 bool need_conv = false;
3328 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3331 if (expr_type == null)
3335 // The type must be an IDisposable or an implicit conversion
3338 converted_vars = new Expression [var_list.Count];
3339 assign = new ExpressionStatement [var_list.Count];
3340 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3341 foreach (DictionaryEntry e in var_list){
3342 Expression var = (Expression) e.Key;
3344 var = var.ResolveLValue (ec, new EmptyExpression ());
3348 converted_vars [i] = Convert.ImplicitConversionRequired (
3349 ec, var, TypeManager.idisposable_type, loc);
3351 if (converted_vars [i] == null)
3359 foreach (DictionaryEntry e in var_list){
3360 LocalVariableReference var = (LocalVariableReference) e.Key;
3361 Expression new_expr = (Expression) e.Value;
3364 a = new Assign (var, new_expr, loc);
3370 converted_vars [i] = var;
3371 assign [i] = (ExpressionStatement) a;
3378 bool ResolveExpression (EmitContext ec)
3380 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3381 conv = Convert.ImplicitConversionRequired (
3382 ec, expr, TypeManager.idisposable_type, loc);
3392 // Emits the code for the case of using using a local variable declaration.
3394 bool EmitLocalVariableDecls (EmitContext ec)
3396 ILGenerator ig = ec.ig;
3399 for (i = 0; i < assign.Length; i++) {
3400 assign [i].EmitStatement (ec);
3402 ig.BeginExceptionBlock ();
3404 Statement.Emit (ec);
3406 var_list.Reverse ();
3407 foreach (DictionaryEntry e in var_list){
3408 LocalVariableReference var = (LocalVariableReference) e.Key;
3409 Label skip = ig.DefineLabel ();
3412 ig.BeginFinallyBlock ();
3414 if (!var.Type.IsValueType) {
3416 ig.Emit (OpCodes.Brfalse, skip);
3417 converted_vars [i].Emit (ec);
3418 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3420 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3422 if (!(ml is MethodGroupExpr)) {
3424 ig.Emit (OpCodes.Box, var.Type);
3425 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3427 MethodInfo mi = null;
3429 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3430 if (mk.GetParameters().Length == 0) {
3437 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3441 var.AddressOf (ec, AddressOp.Load);
3442 ig.Emit (OpCodes.Call, mi);
3446 ig.MarkLabel (skip);
3447 ig.EndExceptionBlock ();
3453 bool EmitExpression (EmitContext ec)
3456 // Make a copy of the expression and operate on that.
3458 ILGenerator ig = ec.ig;
3459 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3464 ig.Emit (OpCodes.Stloc, local_copy);
3466 ig.BeginExceptionBlock ();
3467 Statement.Emit (ec);
3469 Label skip = ig.DefineLabel ();
3470 ig.BeginFinallyBlock ();
3471 ig.Emit (OpCodes.Ldloc, local_copy);
3472 ig.Emit (OpCodes.Brfalse, skip);
3473 ig.Emit (OpCodes.Ldloc, local_copy);
3474 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3475 ig.MarkLabel (skip);
3476 ig.EndExceptionBlock ();
3481 public override bool Resolve (EmitContext ec)
3483 if (expression_or_block is DictionaryEntry){
3484 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3485 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3487 if (!ResolveLocalVariableDecls (ec))
3490 } else if (expression_or_block is Expression){
3491 expr = (Expression) expression_or_block;
3493 expr = expr.Resolve (ec);
3497 expr_type = expr.Type;
3499 if (!ResolveExpression (ec))
3503 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3505 bool ok = Statement.Resolve (ec);
3508 ec.KillFlowBranching ();
3512 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3514 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3515 // Unfortunately, System.Reflection.Emit automatically emits a leave
3516 // to the end of the finally block. This is a problem if `returns'
3517 // is true since we may jump to a point after the end of the method.
3518 // As a workaround, emit an explicit ret here.
3519 ec.NeedReturnLabel ();
3525 protected override void DoEmit (EmitContext ec)
3527 if (expression_or_block is DictionaryEntry)
3528 EmitLocalVariableDecls (ec);
3529 else if (expression_or_block is Expression)
3530 EmitExpression (ec);
3535 /// Implementation of the foreach C# statement
3537 public class Foreach : Statement {
3539 Expression variable;
3541 Statement statement;
3542 ForeachHelperMethods hm;
3543 Expression empty, conv;
3544 Type array_type, element_type;
3547 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3548 Statement stmt, Location l)
3551 this.variable = var;
3557 public override bool Resolve (EmitContext ec)
3559 expr = expr.Resolve (ec);
3563 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3564 if (var_type == null)
3568 // We need an instance variable. Not sure this is the best
3569 // way of doing this.
3571 // FIXME: When we implement propertyaccess, will those turn
3572 // out to return values in ExprClass? I think they should.
3574 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3575 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3576 error1579 (expr.Type);
3580 if (expr.Type.IsArray) {
3581 array_type = expr.Type;
3582 element_type = TypeManager.GetElementType (array_type);
3584 empty = new EmptyExpression (element_type);
3586 hm = ProbeCollectionType (ec, expr.Type);
3588 error1579 (expr.Type);
3592 array_type = expr.Type;
3593 element_type = hm.element_type;
3595 empty = new EmptyExpression (hm.element_type);
3600 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3601 ec.CurrentBranching.CreateSibling ();
3605 // FIXME: maybe we can apply the same trick we do in the
3606 // array handling to avoid creating empty and conv in some cases.
3608 // Although it is not as important in this case, as the type
3609 // will not likely be object (what the enumerator will return).
3611 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3615 variable = variable.ResolveLValue (ec, empty);
3616 if (variable == null)
3619 bool disposable = (hm != null) && hm.is_disposable;
3621 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3623 if (!statement.Resolve (ec))
3627 ec.EndFlowBranching ();
3629 ec.EndFlowBranching ();
3635 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3637 static MethodInfo FetchMethodMoveNext (Type t)
3639 MemberList move_next_list;
3641 move_next_list = TypeContainer.FindMembers (
3642 t, MemberTypes.Method,
3643 BindingFlags.Public | BindingFlags.Instance,
3644 Type.FilterName, "MoveNext");
3645 if (move_next_list.Count == 0)
3648 foreach (MemberInfo m in move_next_list){
3649 MethodInfo mi = (MethodInfo) m;
3652 args = TypeManager.GetArgumentTypes (mi);
3653 if (args != null && args.Length == 0){
3654 if (mi.ReturnType == TypeManager.bool_type)
3662 // Retrieves a `public T get_Current ()' method from the Type `t'
3664 static MethodInfo FetchMethodGetCurrent (Type t)
3666 MemberList get_current_list;
3668 get_current_list = TypeContainer.FindMembers (
3669 t, MemberTypes.Method,
3670 BindingFlags.Public | BindingFlags.Instance,
3671 Type.FilterName, "get_Current");
3672 if (get_current_list.Count == 0)
3675 foreach (MemberInfo m in get_current_list){
3676 MethodInfo mi = (MethodInfo) m;
3679 args = TypeManager.GetArgumentTypes (mi);
3680 if (args != null && args.Length == 0)
3687 // This struct records the helper methods used by the Foreach construct
3689 class ForeachHelperMethods {
3690 public EmitContext ec;
3691 public MethodInfo get_enumerator;
3692 public MethodInfo move_next;
3693 public MethodInfo get_current;
3694 public Type element_type;
3695 public Type enumerator_type;
3696 public bool is_disposable;
3698 public ForeachHelperMethods (EmitContext ec)
3701 this.element_type = TypeManager.object_type;
3702 this.enumerator_type = TypeManager.ienumerator_type;
3703 this.is_disposable = true;
3707 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3712 if (!(m is MethodInfo))
3715 if (m.Name != "GetEnumerator")
3718 MethodInfo mi = (MethodInfo) m;
3719 Type [] args = TypeManager.GetArgumentTypes (mi);
3721 if (args.Length != 0)
3724 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3725 EmitContext ec = hm.ec;
3728 // Check whether GetEnumerator is accessible to us
3730 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3732 Type declaring = mi.DeclaringType;
3733 if (prot == MethodAttributes.Private){
3734 if (declaring != ec.ContainerType)
3736 } else if (prot == MethodAttributes.FamANDAssem){
3737 // If from a different assembly, false
3738 if (!(mi is MethodBuilder))
3741 // Are we being invoked from the same class, or from a derived method?
3743 if (ec.ContainerType != declaring){
3744 if (!ec.ContainerType.IsSubclassOf (declaring))
3747 } else if (prot == MethodAttributes.FamORAssem){
3748 if (!(mi is MethodBuilder ||
3749 ec.ContainerType == declaring ||
3750 ec.ContainerType.IsSubclassOf (declaring)))
3752 } if (prot == MethodAttributes.Family){
3753 if (!(ec.ContainerType == declaring ||
3754 ec.ContainerType.IsSubclassOf (declaring)))
3758 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3760 // Apply the same optimization as MS: skip the GetEnumerator
3761 // returning an IEnumerator, and use the one returning a
3762 // CharEnumerator instead. This allows us to avoid the
3763 // try-finally block and the boxing.
3768 // Ok, we can access it, now make sure that we can do something
3769 // with this `GetEnumerator'
3772 Type return_type = mi.ReturnType;
3773 if (mi.ReturnType == TypeManager.ienumerator_type ||
3774 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3775 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3778 // If it is not an interface, lets try to find the methods ourselves.
3779 // For example, if we have:
3780 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3781 // We can avoid the iface call. This is a runtime perf boost.
3782 // even bigger if we have a ValueType, because we avoid the cost
3785 // We have to make sure that both methods exist for us to take
3786 // this path. If one of the methods does not exist, we will just
3787 // use the interface. Sadly, this complex if statement is the only
3788 // way I could do this without a goto
3791 if (return_type.IsInterface ||
3792 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3793 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3795 hm.move_next = TypeManager.bool_movenext_void;
3796 hm.get_current = TypeManager.object_getcurrent_void;
3803 // Ok, so they dont return an IEnumerable, we will have to
3804 // find if they support the GetEnumerator pattern.
3807 hm.move_next = FetchMethodMoveNext (return_type);
3808 if (hm.move_next == null)
3811 hm.get_current = FetchMethodGetCurrent (return_type);
3812 if (hm.get_current == null)
3816 hm.element_type = hm.get_current.ReturnType;
3817 hm.enumerator_type = return_type;
3818 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3819 TypeManager.ImplementsInterface (
3820 hm.enumerator_type, TypeManager.idisposable_type);
3826 /// This filter is used to find the GetEnumerator method
3827 /// on which IEnumerator operates
3829 static MemberFilter FilterEnumerator;
3833 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3836 void error1579 (Type t)
3838 Report.Error (1579, loc,
3839 "foreach statement cannot operate on variables of type `" +
3840 t.FullName + "' because that class does not provide a " +
3841 " GetEnumerator method or it is inaccessible");
3844 static bool TryType (Type t, ForeachHelperMethods hm)
3848 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3849 BindingFlags.Public | BindingFlags.NonPublic |
3850 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3851 FilterEnumerator, hm);
3856 hm.get_enumerator = (MethodInfo) mi [0];
3861 // Looks for a usable GetEnumerator in the Type, and if found returns
3862 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3864 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3866 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3868 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3869 if (TryType (tt, hm))
3875 // Now try to find the method in the interfaces
3878 Type [] ifaces = t.GetInterfaces ();
3880 foreach (Type i in ifaces){
3881 if (TryType (i, hm))
3886 // Since TypeBuilder.GetInterfaces only returns the interface
3887 // types for this type, we have to keep looping, but once
3888 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3889 // done, because it returns all the types
3891 if ((t is TypeBuilder))
3901 // FIXME: possible optimization.
3902 // We might be able to avoid creating `empty' if the type is the sam
3904 bool EmitCollectionForeach (EmitContext ec)
3906 ILGenerator ig = ec.ig;
3907 VariableStorage enumerator;
3909 enumerator = new VariableStorage (ec, hm.enumerator_type);
3910 enumerator.EmitThis ();
3912 // Instantiate the enumerator
3914 if (expr.Type.IsValueType){
3915 if (expr is IMemoryLocation){
3916 IMemoryLocation ml = (IMemoryLocation) expr;
3918 Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
3920 if (!(ml1 is MethodGroupExpr)) {
3922 ec.ig.Emit(OpCodes.Box, expr.Type);
3924 ml.AddressOf (ec, AddressOp.Load);
3927 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3928 " does not implement IMemoryLocation");
3929 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3932 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3934 enumerator.EmitStore ();
3937 // Protect the code in a try/finalize block, so that
3938 // if the beast implement IDisposable, we get rid of it
3940 if (hm.is_disposable)
3941 ig.BeginExceptionBlock ();
3943 Label end_try = ig.DefineLabel ();
3945 ig.MarkLabel (ec.LoopBegin);
3947 enumerator.EmitCall (hm.move_next);
3949 ig.Emit (OpCodes.Brfalse, end_try);
3953 enumerator.EmitCall (hm.get_current);
3957 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3959 ((IAssignMethod)variable).EmitAssign (ec, conv);
3961 statement.Emit (ec);
3962 ig.Emit (OpCodes.Br, ec.LoopBegin);
3963 ig.MarkLabel (end_try);
3965 // The runtime provides this for us.
3966 // ig.Emit (OpCodes.Leave, end);
3969 // Now the finally block
3971 if (hm.is_disposable) {
3972 Label call_dispose = ig.DefineLabel ();
3973 ig.BeginFinallyBlock ();
3975 enumerator.EmitThis ();
3976 enumerator.EmitLoad ();
3977 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3978 ig.Emit (OpCodes.Dup);
3979 ig.Emit (OpCodes.Brtrue_S, call_dispose);
3980 ig.Emit (OpCodes.Pop);
3981 ig.Emit (OpCodes.Endfinally);
3983 ig.MarkLabel (call_dispose);
3984 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3987 // The runtime generates this anyways.
3988 // ig.Emit (OpCodes.Endfinally);
3990 ig.EndExceptionBlock ();
3993 ig.MarkLabel (ec.LoopEnd);
3998 // FIXME: possible optimization.
3999 // We might be able to avoid creating `empty' if the type is the sam
4001 bool EmitArrayForeach (EmitContext ec)
4003 int rank = array_type.GetArrayRank ();
4004 ILGenerator ig = ec.ig;
4006 VariableStorage copy = new VariableStorage (ec, array_type);
4009 // Make our copy of the array
4016 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4020 counter.EmitThis ();
4021 ig.Emit (OpCodes.Ldc_I4_0);
4022 counter.EmitStore ();
4023 test = ig.DefineLabel ();
4024 ig.Emit (OpCodes.Br, test);
4026 loop = ig.DefineLabel ();
4027 ig.MarkLabel (loop);
4034 counter.EmitThis ();
4035 counter.EmitLoad ();
4038 // Load the value, we load the value using the underlying type,
4039 // then we use the variable.EmitAssign to load using the proper cast.
4041 ArrayAccess.EmitLoadOpcode (ig, element_type);
4044 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4046 ((IAssignMethod)variable).EmitAssign (ec, conv);
4048 statement.Emit (ec);
4050 ig.MarkLabel (ec.LoopBegin);
4051 counter.EmitThis ();
4052 counter.EmitThis ();
4053 counter.EmitLoad ();
4054 ig.Emit (OpCodes.Ldc_I4_1);
4055 ig.Emit (OpCodes.Add);
4056 counter.EmitStore ();
4058 ig.MarkLabel (test);
4059 counter.EmitThis ();
4060 counter.EmitLoad ();
4063 ig.Emit (OpCodes.Ldlen);
4064 ig.Emit (OpCodes.Conv_I4);
4065 ig.Emit (OpCodes.Blt, loop);
4067 VariableStorage [] dim_len = new VariableStorage [rank];
4068 VariableStorage [] dim_count = new VariableStorage [rank];
4069 Label [] loop = new Label [rank];
4070 Label [] test = new Label [rank];
4073 for (dim = 0; dim < rank; dim++){
4074 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4075 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4076 test [dim] = ig.DefineLabel ();
4077 loop [dim] = ig.DefineLabel ();
4080 for (dim = 0; dim < rank; dim++){
4081 dim_len [dim].EmitThis ();
4084 IntLiteral.EmitInt (ig, dim);
4085 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4086 dim_len [dim].EmitStore ();
4090 for (dim = 0; dim < rank; dim++){
4091 dim_count [dim].EmitThis ();
4092 ig.Emit (OpCodes.Ldc_I4_0);
4093 dim_count [dim].EmitStore ();
4094 ig.Emit (OpCodes.Br, test [dim]);
4095 ig.MarkLabel (loop [dim]);
4102 for (dim = 0; dim < rank; dim++){
4103 dim_count [dim].EmitThis ();
4104 dim_count [dim].EmitLoad ();
4108 // FIXME: Maybe we can cache the computation of `get'?
4110 Type [] args = new Type [rank];
4113 for (int i = 0; i < rank; i++)
4114 args [i] = TypeManager.int32_type;
4116 ModuleBuilder mb = CodeGen.Module.Builder;
4117 get = mb.GetArrayMethod (
4119 CallingConventions.HasThis| CallingConventions.Standard,
4121 ig.Emit (OpCodes.Call, get);
4124 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4126 ((IAssignMethod)variable).EmitAssign (ec, conv);
4127 statement.Emit (ec);
4128 ig.MarkLabel (ec.LoopBegin);
4129 for (dim = rank - 1; dim >= 0; dim--){
4130 dim_count [dim].EmitThis ();
4131 dim_count [dim].EmitThis ();
4132 dim_count [dim].EmitLoad ();
4133 ig.Emit (OpCodes.Ldc_I4_1);
4134 ig.Emit (OpCodes.Add);
4135 dim_count [dim].EmitStore ();
4137 ig.MarkLabel (test [dim]);
4138 dim_count [dim].EmitThis ();
4139 dim_count [dim].EmitLoad ();
4140 dim_len [dim].EmitThis ();
4141 dim_len [dim].EmitLoad ();
4142 ig.Emit (OpCodes.Blt, loop [dim]);
4145 ig.MarkLabel (ec.LoopEnd);
4150 protected override void DoEmit (EmitContext ec)
4152 ILGenerator ig = ec.ig;
4154 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4155 ec.LoopBegin = ig.DefineLabel ();
4156 ec.LoopEnd = ig.DefineLabel ();
4159 EmitCollectionForeach (ec);
4161 EmitArrayForeach (ec);
4163 ec.LoopBegin = old_begin;
4164 ec.LoopEnd = old_end;