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 (EmitContext ec)
1003 if (VariableType == null)
1004 VariableType = ec.DeclSpace.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)
1015 // TODO: breaks the build
1016 // if (VariableType.IsPointer && !ec.InUnsafe)
1017 // Expression.UnsafeError (Location);
1022 public void MakePinned ()
1024 TypeManager.MakePinned (LocalBuilder);
1025 flags |= Flags.Fixed;
1028 public bool IsFixed {
1030 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1037 public override string ToString ()
1039 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1040 Name, Type, VariableInfo, Location);
1045 return (flags & Flags.Used) != 0;
1048 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1052 public bool ReadOnly {
1054 return (flags & Flags.ReadOnly) != 0;
1057 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1066 /// Block represents a C# block.
1070 /// This class is used in a number of places: either to represent
1071 /// explicit blocks that the programmer places or implicit blocks.
1073 /// Implicit blocks are used as labels or to introduce variable
1076 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1077 /// they contain extra information that is not necessary on normal blocks.
1079 public class Block : Statement {
1080 public readonly Block Parent;
1081 public readonly Location StartLocation;
1082 public Location EndLocation = Location.Null;
1085 public enum Flags : byte {
1089 VariablesInitialized = 8,
1095 public bool Implicit {
1097 return (flags & Flags.Implicit) != 0;
1101 public bool Unchecked {
1103 return (flags & Flags.Unchecked) != 0;
1106 flags |= Flags.Unchecked;
1111 // The statements in this block
1113 ArrayList statements;
1117 // An array of Blocks. We keep track of children just
1118 // to generate the local variable declarations.
1120 // Statements and child statements are handled through the
1126 // Labels. (label, block) pairs.
1131 // Keeps track of (name, type) pairs
1133 Hashtable variables;
1136 // Keeps track of constants
1137 Hashtable constants;
1140 // If this is a switch section, the enclosing switch block.
1148 public Block (Block parent)
1149 : this (parent, (Flags) 0, Location.Null, Location.Null)
1152 public Block (Block parent, Flags flags)
1153 : this (parent, flags, Location.Null, Location.Null)
1156 public Block (Block parent, Flags flags, Parameters parameters)
1157 : this (parent, flags, parameters, Location.Null, Location.Null)
1160 public Block (Block parent, Location start, Location end)
1161 : this (parent, (Flags) 0, start, end)
1164 public Block (Block parent, Parameters parameters, Location start, Location end)
1165 : this (parent, (Flags) 0, parameters, start, end)
1168 public Block (Block parent, Flags flags, Location start, Location end)
1169 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1172 public Block (Block parent, Flags flags, Parameters parameters,
1173 Location start, Location end)
1176 parent.AddChild (this);
1178 this.Parent = parent;
1180 this.parameters = parameters;
1181 this.StartLocation = start;
1182 this.EndLocation = end;
1185 statements = new ArrayList ();
1187 if (parent != null && Implicit) {
1188 if (parent.child_variable_names == null)
1189 parent.child_variable_names = new Hashtable();
1190 // share with parent
1191 child_variable_names = parent.child_variable_names;
1196 public Block CreateSwitchBlock (Location start)
1198 Block new_block = new Block (this, start, start);
1199 new_block.switch_block = this;
1209 void AddChild (Block b)
1211 if (children == null)
1212 children = new ArrayList ();
1217 public void SetEndLocation (Location loc)
1223 /// Adds a label to the current block.
1227 /// false if the name already exists in this block. true
1231 public bool AddLabel (string name, LabeledStatement target, Location loc)
1233 if (switch_block != null)
1234 return switch_block.AddLabel (name, target, loc);
1237 while (cur != null) {
1238 if (cur.DoLookupLabel (name) != null) {
1240 140, loc, "The label '{0}' is a duplicate",
1251 while (cur != null) {
1252 if (cur.DoLookupLabel (name) != null) {
1255 "The label '{0}' shadows another label " +
1256 "by the same name in a containing scope.",
1261 if (children != null) {
1262 foreach (Block b in children) {
1263 LabeledStatement s = b.DoLookupLabel (name);
1269 "The label '{0}' shadows another " +
1270 "label by the same name in a " +
1271 "containing scope.",
1282 labels = new Hashtable ();
1284 labels.Add (name, target);
1288 public LabeledStatement LookupLabel (string name)
1290 LabeledStatement s = DoLookupLabel (name);
1294 if (children == null)
1297 foreach (Block child in children) {
1298 if (!child.Implicit)
1301 s = child.LookupLabel (name);
1309 LabeledStatement DoLookupLabel (string name)
1311 if (switch_block != null)
1312 return switch_block.LookupLabel (name);
1315 if (labels.Contains (name))
1316 return ((LabeledStatement) labels [name]);
1321 LocalInfo this_variable = null;
1324 // Returns the "this" instance variable of this block.
1325 // See AddThisVariable() for more information.
1327 public LocalInfo ThisVariable {
1329 if (this_variable != null)
1330 return this_variable;
1331 else if (Parent != null)
1332 return Parent.ThisVariable;
1338 Hashtable child_variable_names;
1341 // Marks a variable with name @name as being used in a child block.
1342 // If a variable name has been used in a child block, it's illegal to
1343 // declare a variable with the same name in the current block.
1345 public void AddChildVariableName (string name)
1347 if (child_variable_names == null)
1348 child_variable_names = new Hashtable ();
1350 if (!child_variable_names.Contains (name))
1351 child_variable_names.Add (name, true);
1355 // Checks whether a variable name has already been used in a child block.
1357 public bool IsVariableNameUsedInChildBlock (string name)
1359 if (child_variable_names == null)
1362 return child_variable_names.Contains (name);
1366 // This is used by non-static `struct' constructors which do not have an
1367 // initializer - in this case, the constructor must initialize all of the
1368 // struct's fields. To do this, we add a "this" variable and use the flow
1369 // analysis code to ensure that it's been fully initialized before control
1370 // leaves the constructor.
1372 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1374 if (this_variable != null)
1375 return this_variable;
1377 if (variables == null)
1378 variables = new Hashtable ();
1380 this_variable = new LocalInfo (tc, this, l);
1381 this_variable.Used = true;
1383 variables.Add ("this", this_variable);
1385 return this_variable;
1388 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1390 if (variables == null)
1391 variables = new Hashtable ();
1393 LocalInfo vi = GetLocalInfo (name);
1395 if (vi.Block != this)
1396 Report.Error (136, l, "A local variable named `" + name + "' " +
1397 "cannot be declared in this scope since it would " +
1398 "give a different meaning to `" + name + "', which " +
1399 "is already used in a `parent or current' scope to " +
1400 "denote something else");
1402 Report.Error (128, l, "A local variable `" + name + "' is already " +
1403 "defined in this scope");
1407 if (IsVariableNameUsedInChildBlock (name)) {
1408 Report.Error (136, l, "A local variable named `" + name + "' " +
1409 "cannot be declared in this scope since it would " +
1410 "give a different meaning to `" + name + "', which " +
1411 "is already used in a `child' scope to denote something " +
1418 Parameter p = pars.GetParameterByName (name, out idx);
1420 Report.Error (136, l, "A local variable named `" + name + "' " +
1421 "cannot be declared in this scope since it would " +
1422 "give a different meaning to `" + name + "', which " +
1423 "is already used in a `parent or current' scope to " +
1424 "denote something else");
1429 vi = new LocalInfo (type, name, this, l);
1431 variables.Add (name, vi);
1433 // Mark 'name' as "used by a child block" in every surrounding block
1435 while (cur != null && cur.Implicit)
1438 for (Block par = cur.Parent; par != null; par = par.Parent)
1439 par.AddChildVariableName (name);
1441 if ((flags & Flags.VariablesInitialized) != 0)
1442 throw new Exception ();
1444 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1448 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1450 if (AddVariable (type, name, pars, l) == null)
1453 if (constants == null)
1454 constants = new Hashtable ();
1456 constants.Add (name, value);
1460 public Hashtable Variables {
1466 public LocalInfo GetLocalInfo (string name)
1468 for (Block b = this; b != null; b = b.Parent) {
1469 if (b.variables != null) {
1470 LocalInfo ret = b.variables [name] as LocalInfo;
1478 public Expression GetVariableType (string name)
1480 LocalInfo vi = GetLocalInfo (name);
1488 public Expression GetConstantExpression (string name)
1490 for (Block b = this; b != null; b = b.Parent) {
1491 if (b.constants != null) {
1492 Expression ret = b.constants [name] as Expression;
1501 /// True if the variable named @name is a constant
1503 public bool IsConstant (string name)
1505 Expression e = null;
1507 e = GetConstantExpression (name);
1512 Parameters parameters = null;
1513 public Parameters Parameters {
1516 while (b.Parent != null)
1518 return b.parameters;
1523 /// A list of labels that were not used within this block
1525 public string [] GetUnreferenced ()
1527 // FIXME: Implement me
1531 public void AddStatement (Statement s)
1534 flags |= Flags.BlockUsed;
1539 return (flags & Flags.BlockUsed) != 0;
1545 flags |= Flags.BlockUsed;
1548 public bool HasRet {
1550 return (flags & Flags.HasRet) != 0;
1554 public bool IsDestructor {
1556 return (flags & Flags.IsDestructor) != 0;
1560 public void SetDestructor ()
1562 flags |= Flags.IsDestructor;
1565 VariableMap param_map, local_map;
1567 public VariableMap ParameterMap {
1569 if ((flags & Flags.VariablesInitialized) == 0)
1570 throw new Exception ();
1576 public VariableMap LocalMap {
1578 if ((flags & Flags.VariablesInitialized) == 0)
1579 throw new Exception ();
1585 public bool LiftVariable (LocalInfo local_info)
1591 /// Emits the variable declarations and labels.
1594 /// tc: is our typecontainer (to resolve type references)
1595 /// ig: is the code generator:
1597 public void EmitMeta (EmitContext ec, InternalParameters ip)
1599 ILGenerator ig = ec.ig;
1602 // Compute the VariableMap's.
1604 // Unfortunately, we don't know the type when adding variables with
1605 // AddVariable(), so we need to compute this info here.
1609 if (variables != null) {
1610 foreach (LocalInfo li in variables.Values)
1613 locals = new LocalInfo [variables.Count];
1614 variables.Values.CopyTo (locals, 0);
1616 locals = new LocalInfo [0];
1619 local_map = new VariableMap (Parent.LocalMap, locals);
1621 local_map = new VariableMap (locals);
1623 param_map = new VariableMap (ip);
1624 flags |= Flags.VariablesInitialized;
1626 bool old_check_state = ec.ConstantCheckState;
1627 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1628 bool remap_locals = ec.RemapToProxy;
1631 // Process this block variables
1633 if (variables != null){
1634 foreach (DictionaryEntry de in variables){
1635 string name = (string) de.Key;
1636 LocalInfo vi = (LocalInfo) de.Value;
1638 if (vi.VariableType == null)
1641 Type variable_type = vi.VariableType;
1643 if (variable_type.IsPointer){
1645 // Am not really convinced that this test is required (Microsoft does it)
1646 // but the fact is that you would not be able to use the pointer variable
1649 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1655 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1657 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1659 if (constants == null)
1662 Expression cv = (Expression) constants [name];
1666 ec.CurrentBlock = this;
1667 Expression e = cv.Resolve (ec);
1671 Constant ce = e as Constant;
1673 Report.Error (133, vi.Location,
1674 "The expression being assigned to `" +
1675 name + "' must be constant (" + e + ")");
1679 if (e.Type != variable_type){
1680 e = Const.ChangeType (vi.Location, ce, variable_type);
1685 constants.Remove (name);
1686 constants.Add (name, e);
1689 ec.ConstantCheckState = old_check_state;
1692 // Now, handle the children
1694 if (children != null){
1695 foreach (Block b in children)
1696 b.EmitMeta (ec, ip);
1700 void UsageWarning (FlowBranching.UsageVector vector)
1704 if (variables != null){
1705 foreach (DictionaryEntry de in variables){
1706 LocalInfo vi = (LocalInfo) de.Value;
1711 name = (string) de.Key;
1713 if (vector.IsAssigned (vi.VariableInfo)){
1715 219, vi.Location, "The variable `" + name +
1716 "' is assigned but its value is never used");
1719 168, vi.Location, "The variable `" +
1721 "' is declared but never used");
1727 public override bool Resolve (EmitContext ec)
1729 Block prev_block = ec.CurrentBlock;
1732 int errors = Report.Errors;
1734 ec.CurrentBlock = this;
1735 ec.StartFlowBranching (this);
1737 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1739 bool unreachable = false, warning_shown = false;
1741 int statement_count = statements.Count;
1742 for (int ix = 0; ix < statement_count; ix++){
1743 Statement s = (Statement) statements [ix];
1745 if (unreachable && !(s is LabeledStatement)) {
1746 if (s == EmptyStatement.Value)
1747 s.loc = EndLocation;
1749 if (!s.ResolveUnreachable (ec, !warning_shown))
1752 if (s != EmptyStatement.Value)
1753 warning_shown = true;
1755 s.loc = Location.Null;
1757 statements [ix] = EmptyStatement.Value;
1761 if (s.Resolve (ec) == false) {
1763 statements [ix] = EmptyStatement.Value;
1767 num_statements = ix + 1;
1769 if (s is LabeledStatement)
1770 unreachable = false;
1772 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1775 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1776 ec.CurrentBranching, statement_count, num_statements);
1779 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1781 ec.CurrentBlock = prev_block;
1783 // If we're a non-static `struct' constructor which doesn't have an
1784 // initializer, then we must initialize all of the struct's fields.
1785 if ((this_variable != null) &&
1786 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1787 !this_variable.IsThisAssigned (ec, loc))
1790 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1791 foreach (LabeledStatement label in labels.Values)
1792 if (!label.HasBeenReferenced)
1793 Report.Warning (164, label.Location,
1794 "This label has not been referenced");
1797 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1799 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1800 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1801 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1802 flags |= Flags.HasRet;
1804 if (ok && (errors == Report.Errors)) {
1805 if (RootContext.WarningLevel >= 3)
1806 UsageWarning (vector);
1812 protected override void DoEmit (EmitContext ec)
1814 for (int ix = 0; ix < num_statements; ix++){
1815 Statement s = (Statement) statements [ix];
1817 // Check whether we are the last statement in a
1820 if ((Parent == null) && (ix+1 == num_statements))
1821 ec.IsLastStatement = true;
1823 ec.IsLastStatement = false;
1829 public override void Emit (EmitContext ec)
1831 Block prev_block = ec.CurrentBlock;
1833 ec.CurrentBlock = this;
1835 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1836 bool is_lexical_block = !Implicit && (Parent != null);
1838 if (emit_debug_info) {
1839 if (is_lexical_block)
1840 ec.ig.BeginScope ();
1842 if (variables != null) {
1843 foreach (DictionaryEntry de in variables) {
1844 string name = (string) de.Key;
1845 LocalInfo vi = (LocalInfo) de.Value;
1847 if (vi.LocalBuilder == null)
1850 vi.LocalBuilder.SetLocalSymInfo (name);
1855 ec.Mark (StartLocation, true);
1857 ec.Mark (EndLocation, true);
1859 if (emit_debug_info && is_lexical_block)
1862 ec.CurrentBlock = prev_block;
1868 public class ToplevelBlock : Block {
1869 public ToplevelBlock (Parameters parameters, Location start) :
1870 base (null, parameters, start, Location.Null)
1874 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1875 base (null, flags, parameters, start, Location.Null)
1880 public class SwitchLabel {
1883 public Location loc;
1884 public Label ILLabel;
1885 public Label ILLabelCode;
1888 // if expr == null, then it is the default case.
1890 public SwitchLabel (Expression expr, Location l)
1896 public Expression Label {
1902 public object Converted {
1909 // Resolves the expression, reduces it to a literal if possible
1910 // and then converts it to the requested type.
1912 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1914 ILLabel = ec.ig.DefineLabel ();
1915 ILLabelCode = ec.ig.DefineLabel ();
1920 Expression e = label.Resolve (ec);
1925 if (!(e is Constant)){
1926 Report.Error (150, loc, "A constant value is expected, got: " + e);
1930 if (e is StringConstant || e is NullLiteral){
1931 if (required_type == TypeManager.string_type){
1933 ILLabel = ec.ig.DefineLabel ();
1938 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1939 if (converted == null)
1946 public class SwitchSection {
1947 // An array of SwitchLabels.
1948 public readonly ArrayList Labels;
1949 public readonly Block Block;
1951 public SwitchSection (ArrayList labels, Block block)
1958 public class Switch : Statement {
1959 public readonly ArrayList Sections;
1960 public Expression Expr;
1963 /// Maps constants whose type type SwitchType to their SwitchLabels.
1965 public Hashtable Elements;
1968 /// The governing switch type
1970 public Type SwitchType;
1976 Label default_target;
1977 Expression new_expr;
1980 // The types allowed to be implicitly cast from
1981 // on the governing type
1983 static Type [] allowed_types;
1985 public Switch (Expression e, ArrayList sects, Location l)
1992 public bool GotDefault {
1998 public Label DefaultTarget {
2000 return default_target;
2005 // Determines the governing type for a switch. The returned
2006 // expression might be the expression from the switch, or an
2007 // expression that includes any potential conversions to the
2008 // integral types or to string.
2010 Expression SwitchGoverningType (EmitContext ec, Type t)
2012 if (t == TypeManager.int32_type ||
2013 t == TypeManager.uint32_type ||
2014 t == TypeManager.char_type ||
2015 t == TypeManager.byte_type ||
2016 t == TypeManager.sbyte_type ||
2017 t == TypeManager.ushort_type ||
2018 t == TypeManager.short_type ||
2019 t == TypeManager.uint64_type ||
2020 t == TypeManager.int64_type ||
2021 t == TypeManager.string_type ||
2022 t == TypeManager.bool_type ||
2023 t.IsSubclassOf (TypeManager.enum_type))
2026 if (allowed_types == null){
2027 allowed_types = new Type [] {
2028 TypeManager.sbyte_type,
2029 TypeManager.byte_type,
2030 TypeManager.short_type,
2031 TypeManager.ushort_type,
2032 TypeManager.int32_type,
2033 TypeManager.uint32_type,
2034 TypeManager.int64_type,
2035 TypeManager.uint64_type,
2036 TypeManager.char_type,
2037 TypeManager.bool_type,
2038 TypeManager.string_type
2043 // Try to find a *user* defined implicit conversion.
2045 // If there is no implicit conversion, or if there are multiple
2046 // conversions, we have to report an error
2048 Expression converted = null;
2049 foreach (Type tt in allowed_types){
2052 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2056 if (converted != null){
2057 Report.Error (-12, loc, "More than one conversion to an integral " +
2058 " type exists for type `" +
2059 TypeManager.CSharpName (Expr.Type)+"'");
2067 void error152 (string n)
2070 152, "The label `" + n + ":' " +
2071 "is already present on this switch statement");
2075 // Performs the basic sanity checks on the switch statement
2076 // (looks for duplicate keys and non-constant expressions).
2078 // It also returns a hashtable with the keys that we will later
2079 // use to compute the switch tables
2081 bool CheckSwitch (EmitContext ec)
2085 Elements = new Hashtable ();
2087 got_default = false;
2089 if (TypeManager.IsEnumType (SwitchType)){
2090 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2092 compare_type = SwitchType;
2094 foreach (SwitchSection ss in Sections){
2095 foreach (SwitchLabel sl in ss.Labels){
2096 if (!sl.ResolveAndReduce (ec, SwitchType)){
2101 if (sl.Label == null){
2103 error152 ("default");
2110 object key = sl.Converted;
2112 if (key is Constant)
2113 key = ((Constant) key).GetValue ();
2116 key = NullLiteral.Null;
2118 string lname = null;
2119 if (compare_type == TypeManager.uint64_type){
2120 ulong v = (ulong) key;
2122 if (Elements.Contains (v))
2123 lname = v.ToString ();
2125 Elements.Add (v, sl);
2126 } else if (compare_type == TypeManager.int64_type){
2127 long v = (long) key;
2129 if (Elements.Contains (v))
2130 lname = v.ToString ();
2132 Elements.Add (v, sl);
2133 } else if (compare_type == TypeManager.uint32_type){
2134 uint v = (uint) key;
2136 if (Elements.Contains (v))
2137 lname = v.ToString ();
2139 Elements.Add (v, sl);
2140 } else if (compare_type == TypeManager.char_type){
2141 char v = (char) key;
2143 if (Elements.Contains (v))
2144 lname = v.ToString ();
2146 Elements.Add (v, sl);
2147 } else if (compare_type == TypeManager.byte_type){
2148 byte v = (byte) key;
2150 if (Elements.Contains (v))
2151 lname = v.ToString ();
2153 Elements.Add (v, sl);
2154 } else if (compare_type == TypeManager.sbyte_type){
2155 sbyte v = (sbyte) key;
2157 if (Elements.Contains (v))
2158 lname = v.ToString ();
2160 Elements.Add (v, sl);
2161 } else if (compare_type == TypeManager.short_type){
2162 short v = (short) key;
2164 if (Elements.Contains (v))
2165 lname = v.ToString ();
2167 Elements.Add (v, sl);
2168 } else if (compare_type == TypeManager.ushort_type){
2169 ushort v = (ushort) key;
2171 if (Elements.Contains (v))
2172 lname = v.ToString ();
2174 Elements.Add (v, sl);
2175 } else if (compare_type == TypeManager.string_type){
2176 if (key is NullLiteral){
2177 if (Elements.Contains (NullLiteral.Null))
2180 Elements.Add (NullLiteral.Null, null);
2182 string s = (string) key;
2184 if (Elements.Contains (s))
2187 Elements.Add (s, sl);
2189 } else if (compare_type == TypeManager.int32_type) {
2192 if (Elements.Contains (v))
2193 lname = v.ToString ();
2195 Elements.Add (v, sl);
2196 } else if (compare_type == TypeManager.bool_type) {
2197 bool v = (bool) key;
2199 if (Elements.Contains (v))
2200 lname = v.ToString ();
2202 Elements.Add (v, sl);
2206 throw new Exception ("Unknown switch type!" +
2207 SwitchType + " " + compare_type);
2211 error152 ("case + " + lname);
2222 void EmitObjectInteger (ILGenerator ig, object k)
2225 IntConstant.EmitInt (ig, (int) k);
2226 else if (k is Constant) {
2227 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2230 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2233 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2235 IntConstant.EmitInt (ig, (int) (long) k);
2236 ig.Emit (OpCodes.Conv_I8);
2239 LongConstant.EmitLong (ig, (long) k);
2241 else if (k is ulong)
2243 if ((ulong) k < (1L<<32))
2245 IntConstant.EmitInt (ig, (int) (long) k);
2246 ig.Emit (OpCodes.Conv_U8);
2250 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2254 IntConstant.EmitInt (ig, (int) ((char) k));
2255 else if (k is sbyte)
2256 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2258 IntConstant.EmitInt (ig, (int) ((byte) k));
2259 else if (k is short)
2260 IntConstant.EmitInt (ig, (int) ((short) k));
2261 else if (k is ushort)
2262 IntConstant.EmitInt (ig, (int) ((ushort) k));
2264 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2266 throw new Exception ("Unhandled case");
2269 // structure used to hold blocks of keys while calculating table switch
2270 class KeyBlock : IComparable
2272 public KeyBlock (long _nFirst)
2274 nFirst = nLast = _nFirst;
2278 public ArrayList rgKeys = null;
2279 // how many items are in the bucket
2280 public int Size = 1;
2283 get { return (int) (nLast - nFirst + 1); }
2285 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2287 return kbLast.nLast - kbFirst.nFirst + 1;
2289 public int CompareTo (object obj)
2291 KeyBlock kb = (KeyBlock) obj;
2292 int nLength = Length;
2293 int nLengthOther = kb.Length;
2294 if (nLengthOther == nLength)
2295 return (int) (kb.nFirst - nFirst);
2296 return nLength - nLengthOther;
2301 /// This method emits code for a lookup-based switch statement (non-string)
2302 /// Basically it groups the cases into blocks that are at least half full,
2303 /// and then spits out individual lookup opcodes for each block.
2304 /// It emits the longest blocks first, and short blocks are just
2305 /// handled with direct compares.
2307 /// <param name="ec"></param>
2308 /// <param name="val"></param>
2309 /// <returns></returns>
2310 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2312 int cElements = Elements.Count;
2313 object [] rgKeys = new object [cElements];
2314 Elements.Keys.CopyTo (rgKeys, 0);
2315 Array.Sort (rgKeys);
2317 // initialize the block list with one element per key
2318 ArrayList rgKeyBlocks = new ArrayList ();
2319 foreach (object key in rgKeys)
2320 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2323 // iteratively merge the blocks while they are at least half full
2324 // there's probably a really cool way to do this with a tree...
2325 while (rgKeyBlocks.Count > 1)
2327 ArrayList rgKeyBlocksNew = new ArrayList ();
2328 kbCurr = (KeyBlock) rgKeyBlocks [0];
2329 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2331 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2332 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2335 kbCurr.nLast = kb.nLast;
2336 kbCurr.Size += kb.Size;
2340 // start a new block
2341 rgKeyBlocksNew.Add (kbCurr);
2345 rgKeyBlocksNew.Add (kbCurr);
2346 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2348 rgKeyBlocks = rgKeyBlocksNew;
2351 // initialize the key lists
2352 foreach (KeyBlock kb in rgKeyBlocks)
2353 kb.rgKeys = new ArrayList ();
2355 // fill the key lists
2357 if (rgKeyBlocks.Count > 0) {
2358 kbCurr = (KeyBlock) rgKeyBlocks [0];
2359 foreach (object key in rgKeys)
2361 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2362 System.Convert.ToInt64 (key) > kbCurr.nLast;
2364 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2365 kbCurr.rgKeys.Add (key);
2369 // sort the blocks so we can tackle the largest ones first
2370 rgKeyBlocks.Sort ();
2372 // okay now we can start...
2373 ILGenerator ig = ec.ig;
2374 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2375 Label lblDefault = ig.DefineLabel ();
2377 Type typeKeys = null;
2378 if (rgKeys.Length > 0)
2379 typeKeys = rgKeys [0].GetType (); // used for conversions
2383 if (TypeManager.IsEnumType (SwitchType))
2384 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2386 compare_type = SwitchType;
2388 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2390 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2391 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2394 foreach (object key in kb.rgKeys)
2396 ig.Emit (OpCodes.Ldloc, val);
2397 EmitObjectInteger (ig, key);
2398 SwitchLabel sl = (SwitchLabel) Elements [key];
2399 ig.Emit (OpCodes.Beq, sl.ILLabel);
2404 // TODO: if all the keys in the block are the same and there are
2405 // no gaps/defaults then just use a range-check.
2406 if (compare_type == TypeManager.int64_type ||
2407 compare_type == TypeManager.uint64_type)
2409 // TODO: optimize constant/I4 cases
2411 // check block range (could be > 2^31)
2412 ig.Emit (OpCodes.Ldloc, val);
2413 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2414 ig.Emit (OpCodes.Blt, lblDefault);
2415 ig.Emit (OpCodes.Ldloc, val);
2416 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2417 ig.Emit (OpCodes.Bgt, lblDefault);
2420 ig.Emit (OpCodes.Ldloc, val);
2423 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2424 ig.Emit (OpCodes.Sub);
2426 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2431 ig.Emit (OpCodes.Ldloc, val);
2432 int nFirst = (int) kb.nFirst;
2435 IntConstant.EmitInt (ig, nFirst);
2436 ig.Emit (OpCodes.Sub);
2438 else if (nFirst < 0)
2440 IntConstant.EmitInt (ig, -nFirst);
2441 ig.Emit (OpCodes.Add);
2445 // first, build the list of labels for the switch
2447 int cJumps = kb.Length;
2448 Label [] rgLabels = new Label [cJumps];
2449 for (int iJump = 0; iJump < cJumps; iJump++)
2451 object key = kb.rgKeys [iKey];
2452 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2454 SwitchLabel sl = (SwitchLabel) Elements [key];
2455 rgLabels [iJump] = sl.ILLabel;
2459 rgLabels [iJump] = lblDefault;
2461 // emit the switch opcode
2462 ig.Emit (OpCodes.Switch, rgLabels);
2465 // mark the default for this block
2467 ig.MarkLabel (lblDefault);
2470 // TODO: find the default case and emit it here,
2471 // to prevent having to do the following jump.
2472 // make sure to mark other labels in the default section
2474 // the last default just goes to the end
2475 ig.Emit (OpCodes.Br, lblDefault);
2477 // now emit the code for the sections
2478 bool fFoundDefault = false;
2479 foreach (SwitchSection ss in Sections)
2481 foreach (SwitchLabel sl in ss.Labels)
2483 ig.MarkLabel (sl.ILLabel);
2484 ig.MarkLabel (sl.ILLabelCode);
2485 if (sl.Label == null)
2487 ig.MarkLabel (lblDefault);
2488 fFoundDefault = true;
2492 //ig.Emit (OpCodes.Br, lblEnd);
2495 if (!fFoundDefault) {
2496 ig.MarkLabel (lblDefault);
2498 ig.MarkLabel (lblEnd);
2501 // This simple emit switch works, but does not take advantage of the
2503 // TODO: remove non-string logic from here
2504 // TODO: binary search strings?
2506 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2508 ILGenerator ig = ec.ig;
2509 Label end_of_switch = ig.DefineLabel ();
2510 Label next_test = ig.DefineLabel ();
2511 Label null_target = ig.DefineLabel ();
2512 bool default_found = false;
2513 bool first_test = true;
2514 bool pending_goto_end = false;
2516 bool default_at_end = false;
2518 ig.Emit (OpCodes.Ldloc, val);
2520 if (Elements.Contains (NullLiteral.Null)){
2521 ig.Emit (OpCodes.Brfalse, null_target);
2523 ig.Emit (OpCodes.Brfalse, default_target);
2525 ig.Emit (OpCodes.Ldloc, val);
2526 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2527 ig.Emit (OpCodes.Stloc, val);
2529 int section_count = Sections.Count;
2530 for (int section = 0; section < section_count; section++){
2531 SwitchSection ss = (SwitchSection) Sections [section];
2532 Label sec_begin = ig.DefineLabel ();
2534 if (pending_goto_end)
2535 ig.Emit (OpCodes.Br, end_of_switch);
2537 int label_count = ss.Labels.Count;
2538 bool mark_default = false;
2540 for (int label = 0; label < label_count; label++){
2541 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2542 ig.MarkLabel (sl.ILLabel);
2545 ig.MarkLabel (next_test);
2546 next_test = ig.DefineLabel ();
2549 // If we are the default target
2551 if (sl.Label == null){
2552 if (label+1 == label_count)
2553 default_at_end = true;
2554 mark_default = true;
2555 default_found = true;
2557 object lit = sl.Converted;
2559 if (lit is NullLiteral){
2561 if (label_count == 1)
2562 ig.Emit (OpCodes.Br, next_test);
2566 StringConstant str = (StringConstant) lit;
2568 ig.Emit (OpCodes.Ldloc, val);
2569 ig.Emit (OpCodes.Ldstr, str.Value);
2570 if (label_count == 1)
2571 ig.Emit (OpCodes.Bne_Un, next_test);
2573 if (label+1 == label_count)
2574 ig.Emit (OpCodes.Bne_Un, next_test);
2576 ig.Emit (OpCodes.Beq, sec_begin);
2581 ig.MarkLabel (null_target);
2582 ig.MarkLabel (sec_begin);
2583 foreach (SwitchLabel sl in ss.Labels)
2584 ig.MarkLabel (sl.ILLabelCode);
2587 ig.MarkLabel (default_target);
2589 pending_goto_end = !ss.Block.HasRet;
2592 ig.MarkLabel (next_test);
2594 if (!default_at_end)
2595 ig.Emit (OpCodes.Br, default_target);
2597 ig.MarkLabel (default_target);
2598 ig.MarkLabel (end_of_switch);
2601 public override bool Resolve (EmitContext ec)
2603 Expr = Expr.Resolve (ec);
2607 new_expr = SwitchGoverningType (ec, Expr.Type);
2608 if (new_expr == null){
2609 Report.Error (151, loc, "An integer type or string was expected for switch");
2614 SwitchType = new_expr.Type;
2616 if (!CheckSwitch (ec))
2619 Switch old_switch = ec.Switch;
2621 ec.Switch.SwitchType = SwitchType;
2623 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2624 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2627 foreach (SwitchSection ss in Sections){
2629 ec.CurrentBranching.CreateSibling (
2630 null, FlowBranching.SiblingType.SwitchSection);
2634 if (ss.Block.Resolve (ec) != true)
2640 ec.CurrentBranching.CreateSibling (
2641 null, FlowBranching.SiblingType.SwitchSection);
2643 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2644 ec.Switch = old_switch;
2646 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2652 protected override void DoEmit (EmitContext ec)
2654 // Store variable for comparission purposes
2655 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2657 ec.ig.Emit (OpCodes.Stloc, value);
2659 ILGenerator ig = ec.ig;
2661 default_target = ig.DefineLabel ();
2664 // Setup the codegen context
2666 Label old_end = ec.LoopEnd;
2667 Switch old_switch = ec.Switch;
2669 ec.LoopEnd = ig.DefineLabel ();
2673 if (SwitchType == TypeManager.string_type)
2674 SimpleSwitchEmit (ec, value);
2676 TableSwitchEmit (ec, value);
2678 // Restore context state.
2679 ig.MarkLabel (ec.LoopEnd);
2682 // Restore the previous context
2684 ec.LoopEnd = old_end;
2685 ec.Switch = old_switch;
2689 public class Lock : Statement {
2691 Statement Statement;
2693 public Lock (Expression expr, Statement stmt, Location l)
2700 public override bool Resolve (EmitContext ec)
2702 expr = expr.Resolve (ec);
2706 if (expr.Type.IsValueType){
2707 Error (185, "lock statement requires the expression to be " +
2708 " a reference type (type is: `{0}'",
2709 TypeManager.CSharpName (expr.Type));
2713 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2714 bool ok = Statement.Resolve (ec);
2715 ec.EndFlowBranching ();
2720 protected override void DoEmit (EmitContext ec)
2722 Type type = expr.Type;
2724 ILGenerator ig = ec.ig;
2725 LocalBuilder temp = ig.DeclareLocal (type);
2728 ig.Emit (OpCodes.Dup);
2729 ig.Emit (OpCodes.Stloc, temp);
2730 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2733 ig.BeginExceptionBlock ();
2734 Label finish = ig.DefineLabel ();
2735 Statement.Emit (ec);
2736 // ig.Emit (OpCodes.Leave, finish);
2738 ig.MarkLabel (finish);
2741 ig.BeginFinallyBlock ();
2742 ig.Emit (OpCodes.Ldloc, temp);
2743 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2744 ig.EndExceptionBlock ();
2748 public class Unchecked : Statement {
2749 public readonly Block Block;
2751 public Unchecked (Block b)
2757 public override bool Resolve (EmitContext ec)
2759 bool previous_state = ec.CheckState;
2760 bool previous_state_const = ec.ConstantCheckState;
2762 ec.CheckState = false;
2763 ec.ConstantCheckState = false;
2764 bool ret = Block.Resolve (ec);
2765 ec.CheckState = previous_state;
2766 ec.ConstantCheckState = previous_state_const;
2771 protected override void DoEmit (EmitContext ec)
2773 bool previous_state = ec.CheckState;
2774 bool previous_state_const = ec.ConstantCheckState;
2776 ec.CheckState = false;
2777 ec.ConstantCheckState = false;
2779 ec.CheckState = previous_state;
2780 ec.ConstantCheckState = previous_state_const;
2784 public class Checked : Statement {
2785 public readonly Block Block;
2787 public Checked (Block b)
2790 b.Unchecked = false;
2793 public override bool Resolve (EmitContext ec)
2795 bool previous_state = ec.CheckState;
2796 bool previous_state_const = ec.ConstantCheckState;
2798 ec.CheckState = true;
2799 ec.ConstantCheckState = true;
2800 bool ret = Block.Resolve (ec);
2801 ec.CheckState = previous_state;
2802 ec.ConstantCheckState = previous_state_const;
2807 protected override void DoEmit (EmitContext ec)
2809 bool previous_state = ec.CheckState;
2810 bool previous_state_const = ec.ConstantCheckState;
2812 ec.CheckState = true;
2813 ec.ConstantCheckState = true;
2815 ec.CheckState = previous_state;
2816 ec.ConstantCheckState = previous_state_const;
2820 public class Unsafe : Statement {
2821 public readonly Block Block;
2823 public Unsafe (Block b)
2828 public override bool Resolve (EmitContext ec)
2830 bool previous_state = ec.InUnsafe;
2834 val = Block.Resolve (ec);
2835 ec.InUnsafe = previous_state;
2840 protected override void DoEmit (EmitContext ec)
2842 bool previous_state = ec.InUnsafe;
2846 ec.InUnsafe = previous_state;
2853 public class Fixed : Statement {
2855 ArrayList declarators;
2856 Statement statement;
2862 public bool is_object;
2863 public LocalInfo vi;
2864 public Expression expr;
2865 public Expression converted;
2868 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2871 declarators = decls;
2876 public override bool Resolve (EmitContext ec)
2879 Expression.UnsafeError (loc);
2883 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2884 if (expr_type == null)
2887 if (ec.RemapToProxy){
2888 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2892 data = new FixedData [declarators.Count];
2894 if (!expr_type.IsPointer){
2895 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2900 foreach (Pair p in declarators){
2901 LocalInfo vi = (LocalInfo) p.First;
2902 Expression e = (Expression) p.Second;
2904 vi.VariableInfo = null;
2908 // The rules for the possible declarators are pretty wise,
2909 // but the production on the grammar is more concise.
2911 // So we have to enforce these rules here.
2913 // We do not resolve before doing the case 1 test,
2914 // because the grammar is explicit in that the token &
2915 // is present, so we need to test for this particular case.
2919 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2924 // Case 1: & object.
2926 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2927 Expression child = ((Unary) e).Expr;
2930 if (child is ParameterReference || child is LocalVariableReference){
2933 "No need to use fixed statement for parameters or " +
2934 "local variable declarations (address is already " +
2939 ec.InFixedInitializer = true;
2941 ec.InFixedInitializer = false;
2945 child = ((Unary) e).Expr;
2947 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2950 data [i].is_object = true;
2952 data [i].converted = null;
2959 ec.InFixedInitializer = true;
2961 ec.InFixedInitializer = false;
2968 if (e.Type.IsArray){
2969 Type array_type = TypeManager.GetElementType (e.Type);
2973 // Provided that array_type is unmanaged,
2975 if (!TypeManager.VerifyUnManaged (array_type, loc))
2979 // and T* is implicitly convertible to the
2980 // pointer type given in the fixed statement.
2982 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2984 Expression converted = Convert.ImplicitConversionRequired (
2985 ec, array_ptr, vi.VariableType, loc);
2986 if (converted == null)
2989 data [i].is_object = false;
2991 data [i].converted = converted;
3001 if (e.Type == TypeManager.string_type){
3002 data [i].is_object = false;
3004 data [i].converted = null;
3011 // For other cases, flag a `this is already fixed expression'
3013 if (e is LocalVariableReference || e is ParameterReference ||
3014 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3016 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3020 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3024 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3026 if (!statement.Resolve (ec)) {
3027 ec.KillFlowBranching ();
3031 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3032 has_ret = reachability.IsUnreachable;
3037 protected override void DoEmit (EmitContext ec)
3039 ILGenerator ig = ec.ig;
3041 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3043 for (int i = 0; i < data.Length; i++) {
3044 LocalInfo vi = data [i].vi;
3047 // Case 1: & object.
3049 if (data [i].is_object) {
3051 // Store pointer in pinned location
3053 data [i].expr.Emit (ec);
3054 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3055 clear_list [i] = vi.LocalBuilder;
3062 if (data [i].expr.Type.IsArray){
3064 // Store pointer in pinned location
3066 data [i].converted.Emit (ec);
3068 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3069 clear_list [i] = vi.LocalBuilder;
3076 if (data [i].expr.Type == TypeManager.string_type){
3077 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3078 TypeManager.MakePinned (pinned_string);
3079 clear_list [i] = pinned_string;
3081 data [i].expr.Emit (ec);
3082 ig.Emit (OpCodes.Stloc, pinned_string);
3084 Expression sptr = new StringPtr (pinned_string, loc);
3085 Expression converted = Convert.ImplicitConversionRequired (
3086 ec, sptr, vi.VariableType, loc);
3088 if (converted == null)
3091 converted.Emit (ec);
3092 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3096 statement.Emit (ec);
3102 // Clear the pinned variable
3104 for (int i = 0; i < data.Length; i++) {
3105 if (data [i].is_object || data [i].expr.Type.IsArray) {
3106 ig.Emit (OpCodes.Ldc_I4_0);
3107 ig.Emit (OpCodes.Conv_U);
3108 ig.Emit (OpCodes.Stloc, clear_list [i]);
3109 } else if (data [i].expr.Type == TypeManager.string_type){
3110 ig.Emit (OpCodes.Ldnull);
3111 ig.Emit (OpCodes.Stloc, clear_list [i]);
3117 public class Catch {
3118 public readonly string Name;
3119 public readonly Block Block;
3120 public readonly Location Location;
3122 Expression type_expr;
3125 public Catch (Expression type, string name, Block block, Location l)
3133 public Type CatchType {
3139 public bool IsGeneral {
3141 return type_expr == null;
3145 public bool Resolve (EmitContext ec)
3147 if (type_expr != null) {
3148 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3152 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3153 Report.Error (155, Location,
3154 "The type caught or thrown must be derived " +
3155 "from System.Exception");
3161 if (!Block.Resolve (ec))
3168 public class Try : Statement {
3169 public readonly Block Fini, Block;
3170 public readonly ArrayList Specific;
3171 public readonly Catch General;
3174 // specific, general and fini might all be null.
3176 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3178 if (specific == null && general == null){
3179 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3183 this.Specific = specific;
3184 this.General = general;
3189 public override bool Resolve (EmitContext ec)
3193 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3195 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3197 if (!Block.Resolve (ec))
3200 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3202 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3204 foreach (Catch c in Specific){
3205 ec.CurrentBranching.CreateSibling (
3206 c.Block, FlowBranching.SiblingType.Catch);
3208 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3210 if (c.Name != null) {
3211 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3213 throw new Exception ();
3215 vi.VariableInfo = null;
3218 if (!c.Resolve (ec))
3222 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3224 if (General != null){
3225 ec.CurrentBranching.CreateSibling (
3226 General.Block, FlowBranching.SiblingType.Catch);
3228 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3230 if (!General.Resolve (ec))
3234 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3238 ec.CurrentBranching.CreateSibling (
3239 Fini, FlowBranching.SiblingType.Finally);
3241 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3243 if (!Fini.Resolve (ec))
3247 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3249 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3251 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3253 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3254 // Unfortunately, System.Reflection.Emit automatically emits a leave
3255 // to the end of the finally block. This is a problem if `returns'
3256 // is true since we may jump to a point after the end of the method.
3257 // As a workaround, emit an explicit ret here.
3258 ec.NeedReturnLabel ();
3264 protected override void DoEmit (EmitContext ec)
3266 ILGenerator ig = ec.ig;
3267 Label finish = ig.DefineLabel ();;
3269 ig.BeginExceptionBlock ();
3273 // System.Reflection.Emit provides this automatically:
3274 // ig.Emit (OpCodes.Leave, finish);
3276 foreach (Catch c in Specific){
3279 ig.BeginCatchBlock (c.CatchType);
3281 if (c.Name != null){
3282 vi = c.Block.GetLocalInfo (c.Name);
3284 throw new Exception ("Variable does not exist in this block");
3286 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3288 ig.Emit (OpCodes.Pop);
3293 if (General != null){
3294 ig.BeginCatchBlock (TypeManager.object_type);
3295 ig.Emit (OpCodes.Pop);
3296 General.Block.Emit (ec);
3299 ig.MarkLabel (finish);
3301 ig.BeginFinallyBlock ();
3305 ig.EndExceptionBlock ();
3309 public class Using : Statement {
3310 object expression_or_block;
3311 Statement Statement;
3316 Expression [] converted_vars;
3317 ExpressionStatement [] assign;
3319 public Using (object expression_or_block, Statement stmt, Location l)
3321 this.expression_or_block = expression_or_block;
3327 // Resolves for the case of using using a local variable declaration.
3329 bool ResolveLocalVariableDecls (EmitContext ec)
3331 bool need_conv = false;
3332 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3335 if (expr_type == null)
3339 // The type must be an IDisposable or an implicit conversion
3342 converted_vars = new Expression [var_list.Count];
3343 assign = new ExpressionStatement [var_list.Count];
3344 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3345 foreach (DictionaryEntry e in var_list){
3346 Expression var = (Expression) e.Key;
3348 var = var.ResolveLValue (ec, new EmptyExpression ());
3352 converted_vars [i] = Convert.ImplicitConversionRequired (
3353 ec, var, TypeManager.idisposable_type, loc);
3355 if (converted_vars [i] == null)
3363 foreach (DictionaryEntry e in var_list){
3364 LocalVariableReference var = (LocalVariableReference) e.Key;
3365 Expression new_expr = (Expression) e.Value;
3368 a = new Assign (var, new_expr, loc);
3374 converted_vars [i] = var;
3375 assign [i] = (ExpressionStatement) a;
3382 bool ResolveExpression (EmitContext ec)
3384 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3385 conv = Convert.ImplicitConversionRequired (
3386 ec, expr, TypeManager.idisposable_type, loc);
3396 // Emits the code for the case of using using a local variable declaration.
3398 bool EmitLocalVariableDecls (EmitContext ec)
3400 ILGenerator ig = ec.ig;
3403 for (i = 0; i < assign.Length; i++) {
3404 assign [i].EmitStatement (ec);
3406 ig.BeginExceptionBlock ();
3408 Statement.Emit (ec);
3410 var_list.Reverse ();
3411 foreach (DictionaryEntry e in var_list){
3412 LocalVariableReference var = (LocalVariableReference) e.Key;
3413 Label skip = ig.DefineLabel ();
3416 ig.BeginFinallyBlock ();
3418 if (!var.Type.IsValueType) {
3420 ig.Emit (OpCodes.Brfalse, skip);
3421 converted_vars [i].Emit (ec);
3422 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3424 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3426 if (!(ml is MethodGroupExpr)) {
3428 ig.Emit (OpCodes.Box, var.Type);
3429 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3431 MethodInfo mi = null;
3433 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3434 if (mk.GetParameters().Length == 0) {
3441 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3445 var.AddressOf (ec, AddressOp.Load);
3446 ig.Emit (OpCodes.Call, mi);
3450 ig.MarkLabel (skip);
3451 ig.EndExceptionBlock ();
3457 bool EmitExpression (EmitContext ec)
3460 // Make a copy of the expression and operate on that.
3462 ILGenerator ig = ec.ig;
3463 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3468 ig.Emit (OpCodes.Stloc, local_copy);
3470 ig.BeginExceptionBlock ();
3471 Statement.Emit (ec);
3473 Label skip = ig.DefineLabel ();
3474 ig.BeginFinallyBlock ();
3475 ig.Emit (OpCodes.Ldloc, local_copy);
3476 ig.Emit (OpCodes.Brfalse, skip);
3477 ig.Emit (OpCodes.Ldloc, local_copy);
3478 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3479 ig.MarkLabel (skip);
3480 ig.EndExceptionBlock ();
3485 public override bool Resolve (EmitContext ec)
3487 if (expression_or_block is DictionaryEntry){
3488 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3489 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3491 if (!ResolveLocalVariableDecls (ec))
3494 } else if (expression_or_block is Expression){
3495 expr = (Expression) expression_or_block;
3497 expr = expr.Resolve (ec);
3501 expr_type = expr.Type;
3503 if (!ResolveExpression (ec))
3507 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3509 bool ok = Statement.Resolve (ec);
3512 ec.KillFlowBranching ();
3516 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3518 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3519 // Unfortunately, System.Reflection.Emit automatically emits a leave
3520 // to the end of the finally block. This is a problem if `returns'
3521 // is true since we may jump to a point after the end of the method.
3522 // As a workaround, emit an explicit ret here.
3523 ec.NeedReturnLabel ();
3529 protected override void DoEmit (EmitContext ec)
3531 if (expression_or_block is DictionaryEntry)
3532 EmitLocalVariableDecls (ec);
3533 else if (expression_or_block is Expression)
3534 EmitExpression (ec);
3539 /// Implementation of the foreach C# statement
3541 public class Foreach : Statement {
3543 Expression variable;
3545 Statement statement;
3546 ForeachHelperMethods hm;
3547 Expression empty, conv;
3548 Type array_type, element_type;
3551 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3552 Statement stmt, Location l)
3555 this.variable = var;
3561 public override bool Resolve (EmitContext ec)
3563 expr = expr.Resolve (ec);
3567 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3568 if (var_type == null)
3572 // We need an instance variable. Not sure this is the best
3573 // way of doing this.
3575 // FIXME: When we implement propertyaccess, will those turn
3576 // out to return values in ExprClass? I think they should.
3578 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3579 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3580 error1579 (expr.Type);
3584 if (expr.Type.IsArray) {
3585 array_type = expr.Type;
3586 element_type = TypeManager.GetElementType (array_type);
3588 empty = new EmptyExpression (element_type);
3590 hm = ProbeCollectionType (ec, expr.Type);
3592 error1579 (expr.Type);
3596 array_type = expr.Type;
3597 element_type = hm.element_type;
3599 empty = new EmptyExpression (hm.element_type);
3604 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3605 ec.CurrentBranching.CreateSibling ();
3609 // FIXME: maybe we can apply the same trick we do in the
3610 // array handling to avoid creating empty and conv in some cases.
3612 // Although it is not as important in this case, as the type
3613 // will not likely be object (what the enumerator will return).
3615 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3619 variable = variable.ResolveLValue (ec, empty);
3620 if (variable == null)
3623 bool disposable = (hm != null) && hm.is_disposable;
3625 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3627 if (!statement.Resolve (ec))
3631 ec.EndFlowBranching ();
3633 ec.EndFlowBranching ();
3639 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3641 static MethodInfo FetchMethodMoveNext (Type t)
3643 MemberList move_next_list;
3645 move_next_list = TypeContainer.FindMembers (
3646 t, MemberTypes.Method,
3647 BindingFlags.Public | BindingFlags.Instance,
3648 Type.FilterName, "MoveNext");
3649 if (move_next_list.Count == 0)
3652 foreach (MemberInfo m in move_next_list){
3653 MethodInfo mi = (MethodInfo) m;
3656 args = TypeManager.GetArgumentTypes (mi);
3657 if (args != null && args.Length == 0){
3658 if (mi.ReturnType == TypeManager.bool_type)
3666 // Retrieves a `public T get_Current ()' method from the Type `t'
3668 static MethodInfo FetchMethodGetCurrent (Type t)
3670 MemberList get_current_list;
3672 get_current_list = TypeContainer.FindMembers (
3673 t, MemberTypes.Method,
3674 BindingFlags.Public | BindingFlags.Instance,
3675 Type.FilterName, "get_Current");
3676 if (get_current_list.Count == 0)
3679 foreach (MemberInfo m in get_current_list){
3680 MethodInfo mi = (MethodInfo) m;
3683 args = TypeManager.GetArgumentTypes (mi);
3684 if (args != null && args.Length == 0)
3691 // This struct records the helper methods used by the Foreach construct
3693 class ForeachHelperMethods {
3694 public EmitContext ec;
3695 public MethodInfo get_enumerator;
3696 public MethodInfo move_next;
3697 public MethodInfo get_current;
3698 public Type element_type;
3699 public Type enumerator_type;
3700 public bool is_disposable;
3702 public ForeachHelperMethods (EmitContext ec)
3705 this.element_type = TypeManager.object_type;
3706 this.enumerator_type = TypeManager.ienumerator_type;
3707 this.is_disposable = true;
3711 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3716 if (!(m is MethodInfo))
3719 if (m.Name != "GetEnumerator")
3722 MethodInfo mi = (MethodInfo) m;
3723 Type [] args = TypeManager.GetArgumentTypes (mi);
3725 if (args.Length != 0)
3728 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3729 EmitContext ec = hm.ec;
3732 // Check whether GetEnumerator is accessible to us
3734 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3736 Type declaring = mi.DeclaringType;
3737 if (prot == MethodAttributes.Private){
3738 if (declaring != ec.ContainerType)
3740 } else if (prot == MethodAttributes.FamANDAssem){
3741 // If from a different assembly, false
3742 if (!(mi is MethodBuilder))
3745 // Are we being invoked from the same class, or from a derived method?
3747 if (ec.ContainerType != declaring){
3748 if (!ec.ContainerType.IsSubclassOf (declaring))
3751 } else if (prot == MethodAttributes.FamORAssem){
3752 if (!(mi is MethodBuilder ||
3753 ec.ContainerType == declaring ||
3754 ec.ContainerType.IsSubclassOf (declaring)))
3756 } if (prot == MethodAttributes.Family){
3757 if (!(ec.ContainerType == declaring ||
3758 ec.ContainerType.IsSubclassOf (declaring)))
3762 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3764 // Apply the same optimization as MS: skip the GetEnumerator
3765 // returning an IEnumerator, and use the one returning a
3766 // CharEnumerator instead. This allows us to avoid the
3767 // try-finally block and the boxing.
3772 // Ok, we can access it, now make sure that we can do something
3773 // with this `GetEnumerator'
3776 Type return_type = mi.ReturnType;
3777 if (mi.ReturnType == TypeManager.ienumerator_type ||
3778 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3779 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3782 // If it is not an interface, lets try to find the methods ourselves.
3783 // For example, if we have:
3784 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3785 // We can avoid the iface call. This is a runtime perf boost.
3786 // even bigger if we have a ValueType, because we avoid the cost
3789 // We have to make sure that both methods exist for us to take
3790 // this path. If one of the methods does not exist, we will just
3791 // use the interface. Sadly, this complex if statement is the only
3792 // way I could do this without a goto
3795 if (return_type.IsInterface ||
3796 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3797 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3799 hm.move_next = TypeManager.bool_movenext_void;
3800 hm.get_current = TypeManager.object_getcurrent_void;
3807 // Ok, so they dont return an IEnumerable, we will have to
3808 // find if they support the GetEnumerator pattern.
3811 hm.move_next = FetchMethodMoveNext (return_type);
3812 if (hm.move_next == null)
3815 hm.get_current = FetchMethodGetCurrent (return_type);
3816 if (hm.get_current == null)
3820 hm.element_type = hm.get_current.ReturnType;
3821 hm.enumerator_type = return_type;
3822 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3823 TypeManager.ImplementsInterface (
3824 hm.enumerator_type, TypeManager.idisposable_type);
3830 /// This filter is used to find the GetEnumerator method
3831 /// on which IEnumerator operates
3833 static MemberFilter FilterEnumerator;
3837 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3840 void error1579 (Type t)
3842 Report.Error (1579, loc,
3843 "foreach statement cannot operate on variables of type `" +
3844 t.FullName + "' because that class does not provide a " +
3845 " GetEnumerator method or it is inaccessible");
3848 static bool TryType (Type t, ForeachHelperMethods hm)
3852 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3853 BindingFlags.Public | BindingFlags.NonPublic |
3854 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3855 FilterEnumerator, hm);
3860 hm.get_enumerator = (MethodInfo) mi [0];
3865 // Looks for a usable GetEnumerator in the Type, and if found returns
3866 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3868 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3870 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3872 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3873 if (TryType (tt, hm))
3879 // Now try to find the method in the interfaces
3882 Type [] ifaces = t.GetInterfaces ();
3884 foreach (Type i in ifaces){
3885 if (TryType (i, hm))
3890 // Since TypeBuilder.GetInterfaces only returns the interface
3891 // types for this type, we have to keep looping, but once
3892 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3893 // done, because it returns all the types
3895 if ((t is TypeBuilder))
3905 // FIXME: possible optimization.
3906 // We might be able to avoid creating `empty' if the type is the sam
3908 bool EmitCollectionForeach (EmitContext ec)
3910 ILGenerator ig = ec.ig;
3911 VariableStorage enumerator;
3913 enumerator = new VariableStorage (ec, hm.enumerator_type);
3914 enumerator.EmitThis ();
3916 // Instantiate the enumerator
3918 if (expr.Type.IsValueType){
3919 if (expr is IMemoryLocation){
3920 IMemoryLocation ml = (IMemoryLocation) expr;
3922 Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
3924 if (!(ml1 is MethodGroupExpr)) {
3926 ec.ig.Emit(OpCodes.Box, expr.Type);
3928 ml.AddressOf (ec, AddressOp.Load);
3931 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3932 " does not implement IMemoryLocation");
3933 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3936 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3938 enumerator.EmitStore ();
3941 // Protect the code in a try/finalize block, so that
3942 // if the beast implement IDisposable, we get rid of it
3944 if (hm.is_disposable)
3945 ig.BeginExceptionBlock ();
3947 Label end_try = ig.DefineLabel ();
3949 ig.MarkLabel (ec.LoopBegin);
3951 enumerator.EmitCall (hm.move_next);
3953 ig.Emit (OpCodes.Brfalse, end_try);
3957 enumerator.EmitCall (hm.get_current);
3961 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3963 ((IAssignMethod)variable).EmitAssign (ec, conv);
3965 statement.Emit (ec);
3966 ig.Emit (OpCodes.Br, ec.LoopBegin);
3967 ig.MarkLabel (end_try);
3969 // The runtime provides this for us.
3970 // ig.Emit (OpCodes.Leave, end);
3973 // Now the finally block
3975 if (hm.is_disposable) {
3976 Label call_dispose = ig.DefineLabel ();
3977 ig.BeginFinallyBlock ();
3979 enumerator.EmitThis ();
3980 enumerator.EmitLoad ();
3981 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3982 ig.Emit (OpCodes.Dup);
3983 ig.Emit (OpCodes.Brtrue_S, call_dispose);
3984 ig.Emit (OpCodes.Pop);
3985 ig.Emit (OpCodes.Endfinally);
3987 ig.MarkLabel (call_dispose);
3988 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3991 // The runtime generates this anyways.
3992 // ig.Emit (OpCodes.Endfinally);
3994 ig.EndExceptionBlock ();
3997 ig.MarkLabel (ec.LoopEnd);
4002 // FIXME: possible optimization.
4003 // We might be able to avoid creating `empty' if the type is the sam
4005 bool EmitArrayForeach (EmitContext ec)
4007 int rank = array_type.GetArrayRank ();
4008 ILGenerator ig = ec.ig;
4010 VariableStorage copy = new VariableStorage (ec, array_type);
4013 // Make our copy of the array
4020 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4024 counter.EmitThis ();
4025 ig.Emit (OpCodes.Ldc_I4_0);
4026 counter.EmitStore ();
4027 test = ig.DefineLabel ();
4028 ig.Emit (OpCodes.Br, test);
4030 loop = ig.DefineLabel ();
4031 ig.MarkLabel (loop);
4038 counter.EmitThis ();
4039 counter.EmitLoad ();
4042 // Load the value, we load the value using the underlying type,
4043 // then we use the variable.EmitAssign to load using the proper cast.
4045 ArrayAccess.EmitLoadOpcode (ig, element_type);
4048 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4050 ((IAssignMethod)variable).EmitAssign (ec, conv);
4052 statement.Emit (ec);
4054 ig.MarkLabel (ec.LoopBegin);
4055 counter.EmitThis ();
4056 counter.EmitThis ();
4057 counter.EmitLoad ();
4058 ig.Emit (OpCodes.Ldc_I4_1);
4059 ig.Emit (OpCodes.Add);
4060 counter.EmitStore ();
4062 ig.MarkLabel (test);
4063 counter.EmitThis ();
4064 counter.EmitLoad ();
4067 ig.Emit (OpCodes.Ldlen);
4068 ig.Emit (OpCodes.Conv_I4);
4069 ig.Emit (OpCodes.Blt, loop);
4071 VariableStorage [] dim_len = new VariableStorage [rank];
4072 VariableStorage [] dim_count = new VariableStorage [rank];
4073 Label [] loop = new Label [rank];
4074 Label [] test = new Label [rank];
4077 for (dim = 0; dim < rank; dim++){
4078 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4079 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4080 test [dim] = ig.DefineLabel ();
4081 loop [dim] = ig.DefineLabel ();
4084 for (dim = 0; dim < rank; dim++){
4085 dim_len [dim].EmitThis ();
4088 IntLiteral.EmitInt (ig, dim);
4089 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4090 dim_len [dim].EmitStore ();
4094 for (dim = 0; dim < rank; dim++){
4095 dim_count [dim].EmitThis ();
4096 ig.Emit (OpCodes.Ldc_I4_0);
4097 dim_count [dim].EmitStore ();
4098 ig.Emit (OpCodes.Br, test [dim]);
4099 ig.MarkLabel (loop [dim]);
4106 for (dim = 0; dim < rank; dim++){
4107 dim_count [dim].EmitThis ();
4108 dim_count [dim].EmitLoad ();
4112 // FIXME: Maybe we can cache the computation of `get'?
4114 Type [] args = new Type [rank];
4117 for (int i = 0; i < rank; i++)
4118 args [i] = TypeManager.int32_type;
4120 ModuleBuilder mb = CodeGen.Module.Builder;
4121 get = mb.GetArrayMethod (
4123 CallingConventions.HasThis| CallingConventions.Standard,
4125 ig.Emit (OpCodes.Call, get);
4128 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4130 ((IAssignMethod)variable).EmitAssign (ec, conv);
4131 statement.Emit (ec);
4132 ig.MarkLabel (ec.LoopBegin);
4133 for (dim = rank - 1; dim >= 0; dim--){
4134 dim_count [dim].EmitThis ();
4135 dim_count [dim].EmitThis ();
4136 dim_count [dim].EmitLoad ();
4137 ig.Emit (OpCodes.Ldc_I4_1);
4138 ig.Emit (OpCodes.Add);
4139 dim_count [dim].EmitStore ();
4141 ig.MarkLabel (test [dim]);
4142 dim_count [dim].EmitThis ();
4143 dim_count [dim].EmitLoad ();
4144 dim_len [dim].EmitThis ();
4145 dim_len [dim].EmitLoad ();
4146 ig.Emit (OpCodes.Blt, loop [dim]);
4149 ig.MarkLabel (ec.LoopEnd);
4154 protected override void DoEmit (EmitContext ec)
4156 ILGenerator ig = ec.ig;
4158 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4159 ec.LoopBegin = ig.DefineLabel ();
4160 ec.LoopEnd = ig.DefineLabel ();
4163 EmitCollectionForeach (ec);
4165 EmitArrayForeach (ec);
4167 ec.LoopBegin = old_begin;
4168 ec.LoopEnd = old_end;