2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 using System.Collections;
21 public abstract class Statement {
25 /// Resolves the statement, true means that all sub-statements
28 public virtual bool Resolve (EmitContext ec)
34 /// We already know that the statement is unreachable, but we still
35 /// need to resolve it to catch errors.
37 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
40 // This conflicts with csc's way of doing this, but IMHO it's
41 // the right thing to do.
43 // If something is unreachable, we still check whether it's
44 // correct. This means that you cannot use unassigned variables
45 // in unreachable code, for instance.
48 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
49 bool ok = Resolve (ec);
50 ec.KillFlowBranching ();
56 Report.Warning (162, loc, "Unreachable code detected");
61 /// Return value indicates whether all code paths emitted return.
63 protected abstract void DoEmit (EmitContext ec);
66 /// Utility wrapper routine for Error, just to beautify the code
68 public void Error (int error, string format, params object[] args)
70 Error (error, String.Format (format, args));
73 public void Error (int error, string s)
75 if (!Location.IsNull (loc))
76 Report.Error (error, loc, s);
78 Report.Error (error, s);
82 /// Return value indicates whether all code paths emitted return.
84 public virtual void Emit (EmitContext ec)
91 public sealed class EmptyStatement : Statement {
93 private EmptyStatement () {}
95 public static readonly EmptyStatement Value = new EmptyStatement ();
97 public override bool Resolve (EmitContext ec)
102 protected override void DoEmit (EmitContext ec)
107 public class If : Statement {
109 public Statement TrueStatement;
110 public Statement FalseStatement;
114 public If (Expression expr, Statement trueStatement, Location l)
117 TrueStatement = trueStatement;
121 public If (Expression expr,
122 Statement trueStatement,
123 Statement falseStatement,
127 TrueStatement = trueStatement;
128 FalseStatement = falseStatement;
132 public override bool Resolve (EmitContext ec)
134 Report.Debug (1, "START IF BLOCK", loc);
136 expr = Expression.ResolveBoolean (ec, expr, loc);
142 // Dead code elimination
144 if (expr is BoolConstant){
145 bool take = ((BoolConstant) expr).Value;
148 if (!TrueStatement.Resolve (ec))
151 if ((FalseStatement != null) &&
152 !FalseStatement.ResolveUnreachable (ec, true))
154 FalseStatement = null;
156 if (!TrueStatement.ResolveUnreachable (ec, true))
158 TrueStatement = null;
160 if ((FalseStatement != null) &&
161 !FalseStatement.Resolve (ec))
168 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
170 bool ok = TrueStatement.Resolve (ec);
172 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
174 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
176 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
179 ec.EndFlowBranching ();
181 Report.Debug (1, "END IF BLOCK", loc);
186 protected override void DoEmit (EmitContext ec)
188 ILGenerator ig = ec.ig;
189 Label false_target = ig.DefineLabel ();
193 // If we're a boolean expression, Resolve() already
194 // eliminated dead code for us.
196 if (expr is BoolConstant){
197 bool take = ((BoolConstant) expr).Value;
200 TrueStatement.Emit (ec);
201 else if (FalseStatement != null)
202 FalseStatement.Emit (ec);
207 expr.EmitBranchable (ec, false_target, false);
209 TrueStatement.Emit (ec);
211 if (FalseStatement != null){
212 bool branch_emitted = false;
214 end = ig.DefineLabel ();
216 ig.Emit (OpCodes.Br, end);
217 branch_emitted = true;
220 ig.MarkLabel (false_target);
221 FalseStatement.Emit (ec);
226 ig.MarkLabel (false_target);
231 public class Do : Statement {
232 public Expression expr;
233 public readonly Statement EmbeddedStatement;
236 public Do (Statement statement, Expression boolExpr, Location l)
239 EmbeddedStatement = statement;
243 public override bool Resolve (EmitContext ec)
247 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
249 if (!EmbeddedStatement.Resolve (ec))
252 expr = Expression.ResolveBoolean (ec, expr, loc);
255 else if (expr is BoolConstant){
256 bool res = ((BoolConstant) expr).Value;
262 ec.CurrentBranching.Infinite = infinite;
263 ec.EndFlowBranching ();
268 protected override void DoEmit (EmitContext ec)
270 ILGenerator ig = ec.ig;
271 Label loop = ig.DefineLabel ();
272 Label old_begin = ec.LoopBegin;
273 Label old_end = ec.LoopEnd;
275 ec.LoopBegin = ig.DefineLabel ();
276 ec.LoopEnd = ig.DefineLabel ();
279 EmbeddedStatement.Emit (ec);
280 ig.MarkLabel (ec.LoopBegin);
283 // Dead code elimination
285 if (expr is BoolConstant){
286 bool res = ((BoolConstant) expr).Value;
289 ec.ig.Emit (OpCodes.Br, loop);
291 expr.EmitBranchable (ec, loop, true);
293 ig.MarkLabel (ec.LoopEnd);
295 ec.LoopBegin = old_begin;
296 ec.LoopEnd = old_end;
300 public class While : Statement {
301 public Expression expr;
302 public readonly Statement Statement;
303 bool infinite, empty;
305 public While (Expression boolExpr, Statement statement, Location l)
307 this.expr = boolExpr;
308 Statement = statement;
312 public override bool Resolve (EmitContext ec)
316 expr = Expression.ResolveBoolean (ec, expr, loc);
321 // Inform whether we are infinite or not
323 if (expr is BoolConstant){
324 BoolConstant bc = (BoolConstant) expr;
326 if (bc.Value == false){
327 if (!Statement.ResolveUnreachable (ec, true))
335 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
337 if (!Statement.Resolve (ec))
340 ec.CurrentBranching.Infinite = infinite;
341 ec.EndFlowBranching ();
346 protected override void DoEmit (EmitContext ec)
351 ILGenerator ig = ec.ig;
352 Label old_begin = ec.LoopBegin;
353 Label old_end = ec.LoopEnd;
355 ec.LoopBegin = ig.DefineLabel ();
356 ec.LoopEnd = ig.DefineLabel ();
359 // Inform whether we are infinite or not
361 if (expr is BoolConstant){
362 ig.MarkLabel (ec.LoopBegin);
364 ig.Emit (OpCodes.Br, ec.LoopBegin);
367 // Inform that we are infinite (ie, `we return'), only
368 // if we do not `break' inside the code.
370 ig.MarkLabel (ec.LoopEnd);
372 Label while_loop = ig.DefineLabel ();
374 ig.Emit (OpCodes.Br, ec.LoopBegin);
375 ig.MarkLabel (while_loop);
379 ig.MarkLabel (ec.LoopBegin);
381 expr.EmitBranchable (ec, while_loop, true);
383 ig.MarkLabel (ec.LoopEnd);
386 ec.LoopBegin = old_begin;
387 ec.LoopEnd = old_end;
391 public class For : Statement {
393 readonly Statement InitStatement;
394 readonly Statement Increment;
395 readonly Statement Statement;
396 bool infinite, empty;
398 public For (Statement initStatement,
404 InitStatement = initStatement;
406 Increment = increment;
407 Statement = statement;
411 public override bool Resolve (EmitContext ec)
415 if (InitStatement != null){
416 if (!InitStatement.Resolve (ec))
421 Test = Expression.ResolveBoolean (ec, Test, loc);
424 else if (Test is BoolConstant){
425 BoolConstant bc = (BoolConstant) Test;
427 if (bc.Value == false){
428 if (!Statement.ResolveUnreachable (ec, true))
430 if ((Increment != null) &&
431 !Increment.ResolveUnreachable (ec, false))
441 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
443 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
445 if (!Statement.Resolve (ec))
448 if (Increment != null){
449 if (!Increment.Resolve (ec))
453 ec.CurrentBranching.Infinite = infinite;
454 ec.EndFlowBranching ();
459 protected override void DoEmit (EmitContext ec)
464 ILGenerator ig = ec.ig;
465 Label old_begin = ec.LoopBegin;
466 Label old_end = ec.LoopEnd;
467 Label loop = ig.DefineLabel ();
468 Label test = ig.DefineLabel ();
470 if (InitStatement != null && InitStatement != EmptyStatement.Value)
471 InitStatement.Emit (ec);
473 ec.LoopBegin = ig.DefineLabel ();
474 ec.LoopEnd = ig.DefineLabel ();
476 ig.Emit (OpCodes.Br, test);
480 ig.MarkLabel (ec.LoopBegin);
481 if (Increment != EmptyStatement.Value)
486 // If test is null, there is no test, and we are just
491 // The Resolve code already catches the case for
492 // Test == BoolConstant (false) so we know that
495 if (Test is BoolConstant)
496 ig.Emit (OpCodes.Br, loop);
498 Test.EmitBranchable (ec, loop, true);
501 ig.Emit (OpCodes.Br, loop);
502 ig.MarkLabel (ec.LoopEnd);
504 ec.LoopBegin = old_begin;
505 ec.LoopEnd = old_end;
509 public class StatementExpression : Statement {
510 ExpressionStatement expr;
512 public StatementExpression (ExpressionStatement expr, Location l)
518 public override bool Resolve (EmitContext ec)
520 expr = expr.ResolveStatement (ec);
524 protected override void DoEmit (EmitContext ec)
526 expr.EmitStatement (ec);
529 public override string ToString ()
531 return "StatementExpression (" + expr + ")";
536 /// Implements the return statement
538 public class Return : Statement {
539 public Expression Expr;
541 public Return (Expression expr, Location l)
549 public override bool Resolve (EmitContext ec)
551 if (ec.ReturnType == null){
553 Error (127, "Return with a value not allowed here");
558 Error (126, "An object of type `{0}' is expected " +
559 "for the return statement",
560 TypeManager.CSharpName (ec.ReturnType));
564 Expr = Expr.Resolve (ec);
568 if (Expr.Type != ec.ReturnType) {
569 Expr = Convert.ImplicitConversionRequired (
570 ec, Expr, ec.ReturnType, loc);
577 Error (-206, "Return statement not allowed inside iterators");
581 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
583 if (ec.CurrentBranching.InTryOrCatch (true)) {
584 ec.CurrentBranching.AddFinallyVector (vector);
586 } else if (ec.CurrentBranching.InFinally (true)) {
587 Error (157, "Control can not leave the body of the finally block");
590 vector.CheckOutParameters (ec.CurrentBranching);
592 ec.CurrentBranching.CurrentUsageVector.Return ();
596 protected override void DoEmit (EmitContext ec)
601 if (in_exc || !ec.IsLastStatement)
602 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
606 ec.NeedReturnLabel ();
607 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
608 } else if (ec.IsLastStatement) {
609 // If we are the last statement in a top-level block, simply
611 ec.ig.Emit (OpCodes.Ret);
613 // Otherwise, we always create a return label and jump to
615 ec.NeedReturnLabel ();
616 ec.ig.Emit (OpCodes.Br, ec.ReturnLabel);
621 public class Goto : Statement {
624 LabeledStatement label;
626 public override bool Resolve (EmitContext ec)
628 label = block.LookupLabel (target);
632 "No such label `" + target + "' in this scope");
636 // If this is a forward goto.
637 if (!label.IsDefined)
638 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
640 ec.CurrentBranching.CurrentUsageVector.Goto ();
645 public Goto (Block parent_block, string label, Location l)
647 block = parent_block;
652 public string Target {
658 protected override void DoEmit (EmitContext ec)
660 Label l = label.LabelTarget (ec);
661 ec.ig.Emit (OpCodes.Br, l);
665 public class LabeledStatement : Statement {
666 public readonly Location Location;
673 public LabeledStatement (string label_name, Location l)
678 public Label LabelTarget (EmitContext ec)
682 label = ec.ig.DefineLabel ();
688 public bool IsDefined {
694 public bool HasBeenReferenced {
700 public void AddUsageVector (FlowBranching.UsageVector vector)
703 vectors = new ArrayList ();
705 vectors.Add (vector.Clone ());
708 public override bool Resolve (EmitContext ec)
710 ec.CurrentBranching.Label (vectors);
717 protected override void DoEmit (EmitContext ec)
720 ec.ig.MarkLabel (label);
726 /// `goto default' statement
728 public class GotoDefault : Statement {
730 public GotoDefault (Location l)
735 public override bool Resolve (EmitContext ec)
737 ec.CurrentBranching.CurrentUsageVector.Goto ();
741 protected override void DoEmit (EmitContext ec)
743 if (ec.Switch == null){
744 Report.Error (153, loc, "goto default is only valid in a switch statement");
748 if (!ec.Switch.GotDefault){
749 Report.Error (159, loc, "No default target on switch statement");
752 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
757 /// `goto case' statement
759 public class GotoCase : Statement {
763 public GotoCase (Expression e, Location l)
769 public override bool Resolve (EmitContext ec)
771 if (ec.Switch == null){
772 Report.Error (153, loc, "goto case is only valid in a switch statement");
776 expr = expr.Resolve (ec);
780 if (!(expr is Constant)){
781 Report.Error (159, loc, "Target expression for goto case is not constant");
785 object val = Expression.ConvertIntLiteral (
786 (Constant) expr, ec.Switch.SwitchType, loc);
791 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
796 "No such label 'case " + val + "': for the goto case");
800 label = sl.ILLabelCode;
802 ec.CurrentBranching.CurrentUsageVector.Goto ();
806 protected override void DoEmit (EmitContext ec)
808 ec.ig.Emit (OpCodes.Br, label);
812 public class Throw : Statement {
815 public Throw (Expression expr, Location l)
821 public override bool Resolve (EmitContext ec)
823 bool in_catch = ec.CurrentBranching.InCatch ();
824 ec.CurrentBranching.CurrentUsageVector.Throw ();
827 expr = expr.Resolve (ec);
831 ExprClass eclass = expr.eclass;
833 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
834 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
835 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
841 if ((t != TypeManager.exception_type) &&
842 !t.IsSubclassOf (TypeManager.exception_type) &&
843 !(expr is NullLiteral)) {
845 "The type caught or thrown must be derived " +
846 "from System.Exception");
849 } else if (!in_catch) {
851 "A throw statement with no argument is only " +
852 "allowed in a catch clause");
859 protected override void DoEmit (EmitContext ec)
862 ec.ig.Emit (OpCodes.Rethrow);
866 ec.ig.Emit (OpCodes.Throw);
871 public class Break : Statement {
873 public Break (Location l)
880 public override bool Resolve (EmitContext ec)
882 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
883 Error (139, "No enclosing loop or switch to continue to");
885 } else if (ec.CurrentBranching.InFinally (false)) {
886 Error (157, "Control can not leave the body of the finally block");
888 } else if (ec.CurrentBranching.InTryOrCatch (false))
889 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
891 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
893 ec.CurrentBranching.CurrentUsageVector.Break ();
897 protected override void DoEmit (EmitContext ec)
899 ILGenerator ig = ec.ig;
902 ig.Emit (OpCodes.Leave, ec.LoopEnd);
904 ec.NeedReturnLabel ();
905 ig.Emit (OpCodes.Br, ec.LoopEnd);
910 public class Continue : Statement {
912 public Continue (Location l)
919 public override bool Resolve (EmitContext ec)
921 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
922 Error (139, "No enclosing loop to continue to");
924 } else if (ec.CurrentBranching.InFinally (false)) {
925 Error (157, "Control can not leave the body of the finally block");
927 } else if (ec.CurrentBranching.InTryOrCatch (false))
928 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
930 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
932 ec.CurrentBranching.CurrentUsageVector.Goto ();
936 protected override void DoEmit (EmitContext ec)
938 Label begin = ec.LoopBegin;
941 ec.ig.Emit (OpCodes.Leave, begin);
943 ec.ig.Emit (OpCodes.Br, begin);
947 public class LocalInfo {
948 public Expression Type;
951 // Most of the time a variable will be stored in a LocalBuilder
953 // But sometimes, it will be stored in a field. The context of the field will
954 // be stored in the EmitContext
957 public LocalBuilder LocalBuilder;
958 public FieldBuilder FieldBuilder;
960 public Type VariableType;
961 public readonly string Name;
962 public readonly Location Location;
963 public readonly Block Block;
965 public VariableInfo VariableInfo;
975 public LocalInfo (Expression type, string name, Block block, Location l)
983 public LocalInfo (TypeContainer tc, Block block, Location l)
985 VariableType = tc.TypeBuilder;
990 public bool IsThisAssigned (EmitContext ec, Location loc)
992 if (VariableInfo == null)
993 throw new Exception ();
995 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
998 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1001 public bool IsAssigned (EmitContext ec)
1003 if (VariableInfo == null)
1004 throw new Exception ();
1006 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1009 public bool Resolve (DeclSpace decl)
1011 if (VariableType == null)
1012 VariableType = decl.ResolveType (Type, false, Location);
1014 if (VariableType == null)
1020 public void MakePinned ()
1022 TypeManager.MakePinned (LocalBuilder);
1023 flags |= Flags.Fixed;
1026 public bool IsFixed {
1028 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1035 public override string ToString ()
1037 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1038 Name, Type, VariableInfo, Location);
1043 return (flags & Flags.Used) != 0;
1046 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1050 public bool ReadOnly {
1052 return (flags & Flags.ReadOnly) != 0;
1055 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1064 /// Block represents a C# block.
1068 /// This class is used in a number of places: either to represent
1069 /// explicit blocks that the programmer places or implicit blocks.
1071 /// Implicit blocks are used as labels or to introduce variable
1074 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1075 /// they contain extra information that is not necessary on normal blocks.
1077 public class Block : Statement {
1078 public readonly Block Parent;
1079 public readonly Location StartLocation;
1080 public Location EndLocation = Location.Null;
1083 public enum Flags : byte {
1087 VariablesInitialized = 8,
1093 public bool Implicit {
1095 return (flags & Flags.Implicit) != 0;
1099 public bool Unchecked {
1101 return (flags & Flags.Unchecked) != 0;
1104 flags |= Flags.Unchecked;
1109 // The statements in this block
1111 ArrayList statements;
1115 // An array of Blocks. We keep track of children just
1116 // to generate the local variable declarations.
1118 // Statements and child statements are handled through the
1124 // Labels. (label, block) pairs.
1129 // Keeps track of (name, type) pairs
1131 Hashtable variables;
1134 // Keeps track of constants
1135 Hashtable constants;
1138 // If this is a switch section, the enclosing switch block.
1146 public Block (Block parent)
1147 : this (parent, (Flags) 0, Location.Null, Location.Null)
1150 public Block (Block parent, Flags flags)
1151 : this (parent, flags, Location.Null, Location.Null)
1154 public Block (Block parent, Flags flags, Parameters parameters)
1155 : this (parent, flags, parameters, Location.Null, Location.Null)
1158 public Block (Block parent, Location start, Location end)
1159 : this (parent, (Flags) 0, start, end)
1162 public Block (Block parent, Parameters parameters, Location start, Location end)
1163 : this (parent, (Flags) 0, parameters, start, end)
1166 public Block (Block parent, Flags flags, Location start, Location end)
1167 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1170 public Block (Block parent, Flags flags, Parameters parameters,
1171 Location start, Location end)
1174 parent.AddChild (this);
1176 this.Parent = parent;
1178 this.parameters = parameters;
1179 this.StartLocation = start;
1180 this.EndLocation = end;
1183 statements = new ArrayList ();
1186 public Block CreateSwitchBlock (Location start)
1188 Block new_block = new Block (this, start, start);
1189 new_block.switch_block = this;
1199 void AddChild (Block b)
1201 if (children == null)
1202 children = new ArrayList ();
1207 public void SetEndLocation (Location loc)
1213 /// Adds a label to the current block.
1217 /// false if the name already exists in this block. true
1221 public bool AddLabel (string name, LabeledStatement target)
1223 if (switch_block != null)
1224 return switch_block.AddLabel (name, target);
1227 labels = new Hashtable ();
1228 if (labels.Contains (name))
1231 labels.Add (name, target);
1235 public LabeledStatement LookupLabel (string name)
1237 Hashtable l = new Hashtable ();
1239 return LookupLabel (name, l);
1243 // Lookups a label in the current block, parents and children.
1244 // It skips during child recurssion on `source'
1246 LabeledStatement LookupLabel (string name, Hashtable seen)
1248 if (switch_block != null)
1249 return switch_block.LookupLabel (name, seen);
1251 if (seen [this] != null)
1257 if (labels.Contains (name))
1258 return ((LabeledStatement) labels [name]);
1260 if (children != null){
1261 foreach (Block b in children){
1262 LabeledStatement s = b.LookupLabel (name, seen);
1269 return Parent.LookupLabel (name, seen);
1274 LocalInfo this_variable = null;
1277 // Returns the "this" instance variable of this block.
1278 // See AddThisVariable() for more information.
1280 public LocalInfo ThisVariable {
1282 if (this_variable != null)
1283 return this_variable;
1284 else if (Parent != null)
1285 return Parent.ThisVariable;
1291 Hashtable child_variable_names;
1294 // Marks a variable with name @name as being used in a child block.
1295 // If a variable name has been used in a child block, it's illegal to
1296 // declare a variable with the same name in the current block.
1298 public void AddChildVariableName (string name)
1300 if (child_variable_names == null)
1301 child_variable_names = new Hashtable ();
1303 if (!child_variable_names.Contains (name))
1304 child_variable_names.Add (name, true);
1308 // Marks all variables from block @block and all its children as being
1309 // used in a child block.
1311 public void AddChildVariableNames (Block block)
1313 if (block.Variables != null) {
1314 foreach (string name in block.Variables.Keys)
1315 AddChildVariableName (name);
1318 if (block.children != null) {
1319 foreach (Block child in block.children)
1320 AddChildVariableNames (child);
1323 if (block.child_variable_names != null) {
1324 foreach (string name in block.child_variable_names.Keys)
1325 AddChildVariableName (name);
1330 // Checks whether a variable name has already been used in a child block.
1332 public bool IsVariableNameUsedInChildBlock (string name)
1334 if (child_variable_names == null)
1337 return child_variable_names.Contains (name);
1341 // This is used by non-static `struct' constructors which do not have an
1342 // initializer - in this case, the constructor must initialize all of the
1343 // struct's fields. To do this, we add a "this" variable and use the flow
1344 // analysis code to ensure that it's been fully initialized before control
1345 // leaves the constructor.
1347 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1349 if (this_variable != null)
1350 return this_variable;
1352 if (variables == null)
1353 variables = new Hashtable ();
1355 this_variable = new LocalInfo (tc, this, l);
1356 this_variable.Used = true;
1358 variables.Add ("this", this_variable);
1360 return this_variable;
1363 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1365 if (variables == null)
1366 variables = new Hashtable ();
1368 LocalInfo vi = GetLocalInfo (name);
1370 if (vi.Block != this)
1371 Report.Error (136, l, "A local variable named `" + name + "' " +
1372 "cannot be declared in this scope since it would " +
1373 "give a different meaning to `" + name + "', which " +
1374 "is already used in a `parent or current' scope to " +
1375 "denote something else");
1377 Report.Error (128, l, "A local variable `" + name + "' is already " +
1378 "defined in this scope");
1382 if (IsVariableNameUsedInChildBlock (name)) {
1383 Report.Error (136, l, "A local variable named `" + name + "' " +
1384 "cannot be declared in this scope since it would " +
1385 "give a different meaning to `" + name + "', which " +
1386 "is already used in a `child' scope to denote something " +
1393 Parameter p = pars.GetParameterByName (name, out idx);
1395 Report.Error (136, l, "A local variable named `" + name + "' " +
1396 "cannot be declared in this scope since it would " +
1397 "give a different meaning to `" + name + "', which " +
1398 "is already used in a `parent or current' scope to " +
1399 "denote something else");
1404 vi = new LocalInfo (type, name, this, l);
1406 variables.Add (name, vi);
1408 if ((flags & Flags.VariablesInitialized) != 0)
1409 throw new Exception ();
1411 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1415 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1417 if (AddVariable (type, name, pars, l) == null)
1420 if (constants == null)
1421 constants = new Hashtable ();
1423 constants.Add (name, value);
1427 public Hashtable Variables {
1433 public LocalInfo GetLocalInfo (string name)
1435 for (Block b = this; b != null; b = b.Parent) {
1436 if (b.variables != null) {
1437 LocalInfo ret = b.variables [name] as LocalInfo;
1445 public Expression GetVariableType (string name)
1447 LocalInfo vi = GetLocalInfo (name);
1455 public Expression GetConstantExpression (string name)
1457 for (Block b = this; b != null; b = b.Parent) {
1458 if (b.constants != null) {
1459 Expression ret = b.constants [name] as Expression;
1468 /// True if the variable named @name is a constant
1470 public bool IsConstant (string name)
1472 Expression e = null;
1474 e = GetConstantExpression (name);
1480 /// Use to fetch the statement associated with this label
1482 public Statement this [string name] {
1484 return (Statement) labels [name];
1488 Parameters parameters = null;
1489 public Parameters Parameters {
1492 while (b.Parent != null)
1494 return b.parameters;
1499 /// A list of labels that were not used within this block
1501 public string [] GetUnreferenced ()
1503 // FIXME: Implement me
1507 public void AddStatement (Statement s)
1510 flags |= Flags.BlockUsed;
1515 return (flags & Flags.BlockUsed) != 0;
1521 flags |= Flags.BlockUsed;
1524 public bool HasRet {
1526 return (flags & Flags.HasRet) != 0;
1530 public bool IsDestructor {
1532 return (flags & Flags.IsDestructor) != 0;
1536 public void SetDestructor ()
1538 flags |= Flags.IsDestructor;
1541 VariableMap param_map, local_map;
1543 public VariableMap ParameterMap {
1545 if ((flags & Flags.VariablesInitialized) == 0)
1546 throw new Exception ();
1552 public VariableMap LocalMap {
1554 if ((flags & Flags.VariablesInitialized) == 0)
1555 throw new Exception ();
1561 public bool LiftVariable (LocalInfo local_info)
1567 /// Emits the variable declarations and labels.
1570 /// tc: is our typecontainer (to resolve type references)
1571 /// ig: is the code generator:
1573 public void EmitMeta (EmitContext ec, InternalParameters ip)
1575 ILGenerator ig = ec.ig;
1578 // Compute the VariableMap's.
1580 // Unfortunately, we don't know the type when adding variables with
1581 // AddVariable(), so we need to compute this info here.
1585 if (variables != null) {
1586 foreach (LocalInfo li in variables.Values)
1587 li.Resolve (ec.DeclSpace);
1589 locals = new LocalInfo [variables.Count];
1590 variables.Values.CopyTo (locals, 0);
1592 locals = new LocalInfo [0];
1595 local_map = new VariableMap (Parent.LocalMap, locals);
1597 local_map = new VariableMap (locals);
1599 param_map = new VariableMap (ip);
1600 flags |= Flags.VariablesInitialized;
1602 bool old_check_state = ec.ConstantCheckState;
1603 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1604 bool remap_locals = ec.RemapToProxy;
1607 // Process this block variables
1609 if (variables != null){
1610 foreach (DictionaryEntry de in variables){
1611 string name = (string) de.Key;
1612 LocalInfo vi = (LocalInfo) de.Value;
1614 if (vi.VariableType == null)
1617 Type variable_type = vi.VariableType;
1619 if (variable_type.IsPointer){
1621 // Am not really convinced that this test is required (Microsoft does it)
1622 // but the fact is that you would not be able to use the pointer variable
1625 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1631 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1633 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1635 if (constants == null)
1638 Expression cv = (Expression) constants [name];
1642 ec.CurrentBlock = this;
1643 Expression e = cv.Resolve (ec);
1647 Constant ce = e as Constant;
1649 Report.Error (133, vi.Location,
1650 "The expression being assigned to `" +
1651 name + "' must be constant (" + e + ")");
1655 if (e.Type != variable_type){
1656 e = Const.ChangeType (vi.Location, ce, variable_type);
1661 constants.Remove (name);
1662 constants.Add (name, e);
1665 ec.ConstantCheckState = old_check_state;
1668 // Now, handle the children
1670 if (children != null){
1671 foreach (Block b in children)
1672 b.EmitMeta (ec, ip);
1676 void UsageWarning (FlowBranching.UsageVector vector)
1680 if (variables != null){
1681 foreach (DictionaryEntry de in variables){
1682 LocalInfo vi = (LocalInfo) de.Value;
1687 name = (string) de.Key;
1689 if (vector.IsAssigned (vi.VariableInfo)){
1691 219, vi.Location, "The variable `" + name +
1692 "' is assigned but its value is never used");
1695 168, vi.Location, "The variable `" +
1697 "' is declared but never used");
1703 public override bool Resolve (EmitContext ec)
1705 Block prev_block = ec.CurrentBlock;
1708 int errors = Report.Errors;
1710 ec.CurrentBlock = this;
1711 ec.StartFlowBranching (this);
1713 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1715 bool unreachable = false, warning_shown = false;
1717 int statement_count = statements.Count;
1718 for (int ix = 0; ix < statement_count; ix++){
1719 Statement s = (Statement) statements [ix];
1721 if (unreachable && !(s is LabeledStatement)) {
1722 if (!s.ResolveUnreachable (ec, !warning_shown))
1725 if (s != EmptyStatement.Value)
1726 warning_shown = true;
1728 statements [ix] = EmptyStatement.Value;
1732 if (s.Resolve (ec) == false) {
1734 statements [ix] = EmptyStatement.Value;
1738 num_statements = ix + 1;
1740 if (s is LabeledStatement)
1741 unreachable = false;
1743 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1746 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1747 ec.CurrentBranching, statement_count, num_statements);
1750 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1752 ec.CurrentBlock = prev_block;
1754 // If we're a non-static `struct' constructor which doesn't have an
1755 // initializer, then we must initialize all of the struct's fields.
1756 if ((this_variable != null) &&
1757 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1758 !this_variable.IsThisAssigned (ec, loc))
1761 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1762 foreach (LabeledStatement label in labels.Values)
1763 if (!label.HasBeenReferenced)
1764 Report.Warning (164, label.Location,
1765 "This label has not been referenced");
1768 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1770 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1771 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1772 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1773 flags |= Flags.HasRet;
1775 if (ok && (errors == Report.Errors)) {
1776 if (RootContext.WarningLevel >= 3)
1777 UsageWarning (vector);
1783 protected override void DoEmit (EmitContext ec)
1785 for (int ix = 0; ix < num_statements; ix++){
1786 Statement s = (Statement) statements [ix];
1788 // Check whether we are the last statement in a
1791 if ((Parent == null) && (ix+1 == num_statements))
1792 ec.IsLastStatement = true;
1794 ec.IsLastStatement = false;
1800 public override void Emit (EmitContext ec)
1802 Block prev_block = ec.CurrentBlock;
1804 ec.CurrentBlock = this;
1806 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1807 bool is_lexical_block = !Implicit && (Parent != null);
1809 if (emit_debug_info) {
1810 if (is_lexical_block)
1811 ec.ig.BeginScope ();
1813 if (variables != null) {
1814 foreach (DictionaryEntry de in variables) {
1815 string name = (string) de.Key;
1816 LocalInfo vi = (LocalInfo) de.Value;
1818 if (vi.LocalBuilder == null)
1821 vi.LocalBuilder.SetLocalSymInfo (name);
1826 ec.Mark (StartLocation, true);
1828 ec.Mark (EndLocation, true);
1830 if (emit_debug_info && is_lexical_block)
1833 ec.CurrentBlock = prev_block;
1839 public class ToplevelBlock : Block {
1840 public ToplevelBlock (Parameters parameters, Location start) :
1841 base (null, parameters, start, Location.Null)
1845 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1846 base (null, flags, parameters, start, Location.Null)
1851 public class SwitchLabel {
1854 public Location loc;
1855 public Label ILLabel;
1856 public Label ILLabelCode;
1859 // if expr == null, then it is the default case.
1861 public SwitchLabel (Expression expr, Location l)
1867 public Expression Label {
1873 public object Converted {
1880 // Resolves the expression, reduces it to a literal if possible
1881 // and then converts it to the requested type.
1883 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1885 ILLabel = ec.ig.DefineLabel ();
1886 ILLabelCode = ec.ig.DefineLabel ();
1891 Expression e = label.Resolve (ec);
1896 if (!(e is Constant)){
1897 Report.Error (150, loc, "A constant value is expected, got: " + e);
1901 if (e is StringConstant || e is NullLiteral){
1902 if (required_type == TypeManager.string_type){
1904 ILLabel = ec.ig.DefineLabel ();
1909 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1910 if (converted == null)
1917 public class SwitchSection {
1918 // An array of SwitchLabels.
1919 public readonly ArrayList Labels;
1920 public readonly Block Block;
1922 public SwitchSection (ArrayList labels, Block block)
1929 public class Switch : Statement {
1930 public readonly ArrayList Sections;
1931 public Expression Expr;
1934 /// Maps constants whose type type SwitchType to their SwitchLabels.
1936 public Hashtable Elements;
1939 /// The governing switch type
1941 public Type SwitchType;
1947 Label default_target;
1948 Expression new_expr;
1951 // The types allowed to be implicitly cast from
1952 // on the governing type
1954 static Type [] allowed_types;
1956 public Switch (Expression e, ArrayList sects, Location l)
1963 public bool GotDefault {
1969 public Label DefaultTarget {
1971 return default_target;
1976 // Determines the governing type for a switch. The returned
1977 // expression might be the expression from the switch, or an
1978 // expression that includes any potential conversions to the
1979 // integral types or to string.
1981 Expression SwitchGoverningType (EmitContext ec, Type t)
1983 if (t == TypeManager.int32_type ||
1984 t == TypeManager.uint32_type ||
1985 t == TypeManager.char_type ||
1986 t == TypeManager.byte_type ||
1987 t == TypeManager.sbyte_type ||
1988 t == TypeManager.ushort_type ||
1989 t == TypeManager.short_type ||
1990 t == TypeManager.uint64_type ||
1991 t == TypeManager.int64_type ||
1992 t == TypeManager.string_type ||
1993 t == TypeManager.bool_type ||
1994 t.IsSubclassOf (TypeManager.enum_type))
1997 if (allowed_types == null){
1998 allowed_types = new Type [] {
1999 TypeManager.sbyte_type,
2000 TypeManager.byte_type,
2001 TypeManager.short_type,
2002 TypeManager.ushort_type,
2003 TypeManager.int32_type,
2004 TypeManager.uint32_type,
2005 TypeManager.int64_type,
2006 TypeManager.uint64_type,
2007 TypeManager.char_type,
2008 TypeManager.bool_type,
2009 TypeManager.string_type
2014 // Try to find a *user* defined implicit conversion.
2016 // If there is no implicit conversion, or if there are multiple
2017 // conversions, we have to report an error
2019 Expression converted = null;
2020 foreach (Type tt in allowed_types){
2023 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2027 if (converted != null){
2028 Report.Error (-12, loc, "More than one conversion to an integral " +
2029 " type exists for type `" +
2030 TypeManager.CSharpName (Expr.Type)+"'");
2038 void error152 (string n)
2041 152, "The label `" + n + ":' " +
2042 "is already present on this switch statement");
2046 // Performs the basic sanity checks on the switch statement
2047 // (looks for duplicate keys and non-constant expressions).
2049 // It also returns a hashtable with the keys that we will later
2050 // use to compute the switch tables
2052 bool CheckSwitch (EmitContext ec)
2056 Elements = new Hashtable ();
2058 got_default = false;
2060 if (TypeManager.IsEnumType (SwitchType)){
2061 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2063 compare_type = SwitchType;
2065 foreach (SwitchSection ss in Sections){
2066 foreach (SwitchLabel sl in ss.Labels){
2067 if (!sl.ResolveAndReduce (ec, SwitchType)){
2072 if (sl.Label == null){
2074 error152 ("default");
2081 object key = sl.Converted;
2083 if (key is Constant)
2084 key = ((Constant) key).GetValue ();
2087 key = NullLiteral.Null;
2089 string lname = null;
2090 if (compare_type == TypeManager.uint64_type){
2091 ulong v = (ulong) key;
2093 if (Elements.Contains (v))
2094 lname = v.ToString ();
2096 Elements.Add (v, sl);
2097 } else if (compare_type == TypeManager.int64_type){
2098 long v = (long) key;
2100 if (Elements.Contains (v))
2101 lname = v.ToString ();
2103 Elements.Add (v, sl);
2104 } else if (compare_type == TypeManager.uint32_type){
2105 uint v = (uint) key;
2107 if (Elements.Contains (v))
2108 lname = v.ToString ();
2110 Elements.Add (v, sl);
2111 } else if (compare_type == TypeManager.char_type){
2112 char v = (char) key;
2114 if (Elements.Contains (v))
2115 lname = v.ToString ();
2117 Elements.Add (v, sl);
2118 } else if (compare_type == TypeManager.byte_type){
2119 byte v = (byte) key;
2121 if (Elements.Contains (v))
2122 lname = v.ToString ();
2124 Elements.Add (v, sl);
2125 } else if (compare_type == TypeManager.sbyte_type){
2126 sbyte v = (sbyte) key;
2128 if (Elements.Contains (v))
2129 lname = v.ToString ();
2131 Elements.Add (v, sl);
2132 } else if (compare_type == TypeManager.short_type){
2133 short v = (short) key;
2135 if (Elements.Contains (v))
2136 lname = v.ToString ();
2138 Elements.Add (v, sl);
2139 } else if (compare_type == TypeManager.ushort_type){
2140 ushort v = (ushort) key;
2142 if (Elements.Contains (v))
2143 lname = v.ToString ();
2145 Elements.Add (v, sl);
2146 } else if (compare_type == TypeManager.string_type){
2147 if (key is NullLiteral){
2148 if (Elements.Contains (NullLiteral.Null))
2151 Elements.Add (NullLiteral.Null, null);
2153 string s = (string) key;
2155 if (Elements.Contains (s))
2158 Elements.Add (s, sl);
2160 } else if (compare_type == TypeManager.int32_type) {
2163 if (Elements.Contains (v))
2164 lname = v.ToString ();
2166 Elements.Add (v, sl);
2167 } else if (compare_type == TypeManager.bool_type) {
2168 bool v = (bool) key;
2170 if (Elements.Contains (v))
2171 lname = v.ToString ();
2173 Elements.Add (v, sl);
2177 throw new Exception ("Unknown switch type!" +
2178 SwitchType + " " + compare_type);
2182 error152 ("case + " + lname);
2193 void EmitObjectInteger (ILGenerator ig, object k)
2196 IntConstant.EmitInt (ig, (int) k);
2197 else if (k is Constant) {
2198 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2201 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2204 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2206 IntConstant.EmitInt (ig, (int) (long) k);
2207 ig.Emit (OpCodes.Conv_I8);
2210 LongConstant.EmitLong (ig, (long) k);
2212 else if (k is ulong)
2214 if ((ulong) k < (1L<<32))
2216 IntConstant.EmitInt (ig, (int) (long) k);
2217 ig.Emit (OpCodes.Conv_U8);
2221 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2225 IntConstant.EmitInt (ig, (int) ((char) k));
2226 else if (k is sbyte)
2227 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2229 IntConstant.EmitInt (ig, (int) ((byte) k));
2230 else if (k is short)
2231 IntConstant.EmitInt (ig, (int) ((short) k));
2232 else if (k is ushort)
2233 IntConstant.EmitInt (ig, (int) ((ushort) k));
2235 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2237 throw new Exception ("Unhandled case");
2240 // structure used to hold blocks of keys while calculating table switch
2241 class KeyBlock : IComparable
2243 public KeyBlock (long _nFirst)
2245 nFirst = nLast = _nFirst;
2249 public ArrayList rgKeys = null;
2252 get { return (int) (nLast - nFirst + 1); }
2254 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2256 return kbLast.nLast - kbFirst.nFirst + 1;
2258 public int CompareTo (object obj)
2260 KeyBlock kb = (KeyBlock) obj;
2261 int nLength = Length;
2262 int nLengthOther = kb.Length;
2263 if (nLengthOther == nLength)
2264 return (int) (kb.nFirst - nFirst);
2265 return nLength - nLengthOther;
2270 /// This method emits code for a lookup-based switch statement (non-string)
2271 /// Basically it groups the cases into blocks that are at least half full,
2272 /// and then spits out individual lookup opcodes for each block.
2273 /// It emits the longest blocks first, and short blocks are just
2274 /// handled with direct compares.
2276 /// <param name="ec"></param>
2277 /// <param name="val"></param>
2278 /// <returns></returns>
2279 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2281 int cElements = Elements.Count;
2282 object [] rgKeys = new object [cElements];
2283 Elements.Keys.CopyTo (rgKeys, 0);
2284 Array.Sort (rgKeys);
2286 // initialize the block list with one element per key
2287 ArrayList rgKeyBlocks = new ArrayList ();
2288 foreach (object key in rgKeys)
2289 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2292 // iteratively merge the blocks while they are at least half full
2293 // there's probably a really cool way to do this with a tree...
2294 while (rgKeyBlocks.Count > 1)
2296 ArrayList rgKeyBlocksNew = new ArrayList ();
2297 kbCurr = (KeyBlock) rgKeyBlocks [0];
2298 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2300 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2301 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2304 kbCurr.nLast = kb.nLast;
2308 // start a new block
2309 rgKeyBlocksNew.Add (kbCurr);
2313 rgKeyBlocksNew.Add (kbCurr);
2314 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2316 rgKeyBlocks = rgKeyBlocksNew;
2319 // initialize the key lists
2320 foreach (KeyBlock kb in rgKeyBlocks)
2321 kb.rgKeys = new ArrayList ();
2323 // fill the key lists
2325 if (rgKeyBlocks.Count > 0) {
2326 kbCurr = (KeyBlock) rgKeyBlocks [0];
2327 foreach (object key in rgKeys)
2329 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2330 System.Convert.ToInt64 (key) > kbCurr.nLast;
2332 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2333 kbCurr.rgKeys.Add (key);
2337 // sort the blocks so we can tackle the largest ones first
2338 rgKeyBlocks.Sort ();
2340 // okay now we can start...
2341 ILGenerator ig = ec.ig;
2342 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2343 Label lblDefault = ig.DefineLabel ();
2345 Type typeKeys = null;
2346 if (rgKeys.Length > 0)
2347 typeKeys = rgKeys [0].GetType (); // used for conversions
2351 if (TypeManager.IsEnumType (SwitchType))
2352 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2354 compare_type = SwitchType;
2356 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2358 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2359 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2362 foreach (object key in kb.rgKeys)
2364 ig.Emit (OpCodes.Ldloc, val);
2365 EmitObjectInteger (ig, key);
2366 SwitchLabel sl = (SwitchLabel) Elements [key];
2367 ig.Emit (OpCodes.Beq, sl.ILLabel);
2372 // TODO: if all the keys in the block are the same and there are
2373 // no gaps/defaults then just use a range-check.
2374 if (compare_type == TypeManager.int64_type ||
2375 compare_type == TypeManager.uint64_type)
2377 // TODO: optimize constant/I4 cases
2379 // check block range (could be > 2^31)
2380 ig.Emit (OpCodes.Ldloc, val);
2381 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2382 ig.Emit (OpCodes.Blt, lblDefault);
2383 ig.Emit (OpCodes.Ldloc, val);
2384 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2385 ig.Emit (OpCodes.Bgt, lblDefault);
2388 ig.Emit (OpCodes.Ldloc, val);
2391 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2392 ig.Emit (OpCodes.Sub);
2394 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2399 ig.Emit (OpCodes.Ldloc, val);
2400 int nFirst = (int) kb.nFirst;
2403 IntConstant.EmitInt (ig, nFirst);
2404 ig.Emit (OpCodes.Sub);
2406 else if (nFirst < 0)
2408 IntConstant.EmitInt (ig, -nFirst);
2409 ig.Emit (OpCodes.Add);
2413 // first, build the list of labels for the switch
2415 int cJumps = kb.Length;
2416 Label [] rgLabels = new Label [cJumps];
2417 for (int iJump = 0; iJump < cJumps; iJump++)
2419 object key = kb.rgKeys [iKey];
2420 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2422 SwitchLabel sl = (SwitchLabel) Elements [key];
2423 rgLabels [iJump] = sl.ILLabel;
2427 rgLabels [iJump] = lblDefault;
2429 // emit the switch opcode
2430 ig.Emit (OpCodes.Switch, rgLabels);
2433 // mark the default for this block
2435 ig.MarkLabel (lblDefault);
2438 // TODO: find the default case and emit it here,
2439 // to prevent having to do the following jump.
2440 // make sure to mark other labels in the default section
2442 // the last default just goes to the end
2443 ig.Emit (OpCodes.Br, lblDefault);
2445 // now emit the code for the sections
2446 bool fFoundDefault = false;
2447 foreach (SwitchSection ss in Sections)
2449 foreach (SwitchLabel sl in ss.Labels)
2451 ig.MarkLabel (sl.ILLabel);
2452 ig.MarkLabel (sl.ILLabelCode);
2453 if (sl.Label == null)
2455 ig.MarkLabel (lblDefault);
2456 fFoundDefault = true;
2460 //ig.Emit (OpCodes.Br, lblEnd);
2463 if (!fFoundDefault) {
2464 ig.MarkLabel (lblDefault);
2466 ig.MarkLabel (lblEnd);
2469 // This simple emit switch works, but does not take advantage of the
2471 // TODO: remove non-string logic from here
2472 // TODO: binary search strings?
2474 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2476 ILGenerator ig = ec.ig;
2477 Label end_of_switch = ig.DefineLabel ();
2478 Label next_test = ig.DefineLabel ();
2479 Label null_target = ig.DefineLabel ();
2480 bool default_found = false;
2481 bool first_test = true;
2482 bool pending_goto_end = false;
2485 ig.Emit (OpCodes.Ldloc, val);
2487 if (Elements.Contains (NullLiteral.Null)){
2488 ig.Emit (OpCodes.Brfalse, null_target);
2490 ig.Emit (OpCodes.Brfalse, default_target);
2492 ig.Emit (OpCodes.Ldloc, val);
2493 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2494 ig.Emit (OpCodes.Stloc, val);
2496 int section_count = Sections.Count;
2497 for (int section = 0; section < section_count; section++){
2498 SwitchSection ss = (SwitchSection) Sections [section];
2499 Label sec_begin = ig.DefineLabel ();
2501 if (pending_goto_end)
2502 ig.Emit (OpCodes.Br, end_of_switch);
2504 int label_count = ss.Labels.Count;
2506 for (int label = 0; label < label_count; label++){
2507 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2508 ig.MarkLabel (sl.ILLabel);
2511 ig.MarkLabel (next_test);
2512 next_test = ig.DefineLabel ();
2515 // If we are the default target
2517 if (sl.Label == null){
2518 ig.MarkLabel (default_target);
2519 default_found = true;
2521 object lit = sl.Converted;
2523 if (lit is NullLiteral){
2525 if (label_count == 1)
2526 ig.Emit (OpCodes.Br, next_test);
2530 StringConstant str = (StringConstant) lit;
2532 ig.Emit (OpCodes.Ldloc, val);
2533 ig.Emit (OpCodes.Ldstr, str.Value);
2534 if (label_count == 1)
2535 ig.Emit (OpCodes.Bne_Un, next_test);
2537 if (label+1 == label_count)
2538 ig.Emit (OpCodes.Bne_Un, next_test);
2540 ig.Emit (OpCodes.Beq, sec_begin);
2545 ig.MarkLabel (null_target);
2546 ig.MarkLabel (sec_begin);
2547 foreach (SwitchLabel sl in ss.Labels)
2548 ig.MarkLabel (sl.ILLabelCode);
2551 pending_goto_end = !ss.Block.HasRet;
2554 if (!default_found){
2555 ig.MarkLabel (default_target);
2557 ig.MarkLabel (next_test);
2558 ig.MarkLabel (end_of_switch);
2561 public override bool Resolve (EmitContext ec)
2563 Expr = Expr.Resolve (ec);
2567 new_expr = SwitchGoverningType (ec, Expr.Type);
2568 if (new_expr == null){
2569 Report.Error (151, loc, "An integer type or string was expected for switch");
2574 SwitchType = new_expr.Type;
2576 if (!CheckSwitch (ec))
2579 Switch old_switch = ec.Switch;
2581 ec.Switch.SwitchType = SwitchType;
2583 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2584 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2587 foreach (SwitchSection ss in Sections){
2589 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2593 if (ss.Block.Resolve (ec) != true)
2599 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2601 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2602 ec.Switch = old_switch;
2604 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2610 protected override void DoEmit (EmitContext ec)
2612 // Store variable for comparission purposes
2613 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2615 ec.ig.Emit (OpCodes.Stloc, value);
2617 ILGenerator ig = ec.ig;
2619 default_target = ig.DefineLabel ();
2622 // Setup the codegen context
2624 Label old_end = ec.LoopEnd;
2625 Switch old_switch = ec.Switch;
2627 ec.LoopEnd = ig.DefineLabel ();
2631 if (SwitchType == TypeManager.string_type)
2632 SimpleSwitchEmit (ec, value);
2634 TableSwitchEmit (ec, value);
2636 // Restore context state.
2637 ig.MarkLabel (ec.LoopEnd);
2640 // Restore the previous context
2642 ec.LoopEnd = old_end;
2643 ec.Switch = old_switch;
2647 public class Lock : Statement {
2649 Statement Statement;
2651 public Lock (Expression expr, Statement stmt, Location l)
2658 public override bool Resolve (EmitContext ec)
2660 expr = expr.Resolve (ec);
2664 if (expr.Type.IsValueType){
2665 Error (185, "lock statement requires the expression to be " +
2666 " a reference type (type is: `{0}'",
2667 TypeManager.CSharpName (expr.Type));
2671 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2672 bool ok = Statement.Resolve (ec);
2673 ec.EndFlowBranching ();
2678 protected override void DoEmit (EmitContext ec)
2680 Type type = expr.Type;
2682 ILGenerator ig = ec.ig;
2683 LocalBuilder temp = ig.DeclareLocal (type);
2686 ig.Emit (OpCodes.Dup);
2687 ig.Emit (OpCodes.Stloc, temp);
2688 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2691 ig.BeginExceptionBlock ();
2692 Label finish = ig.DefineLabel ();
2693 Statement.Emit (ec);
2694 // ig.Emit (OpCodes.Leave, finish);
2696 ig.MarkLabel (finish);
2699 ig.BeginFinallyBlock ();
2700 ig.Emit (OpCodes.Ldloc, temp);
2701 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2702 ig.EndExceptionBlock ();
2706 public class Unchecked : Statement {
2707 public readonly Block Block;
2709 public Unchecked (Block b)
2715 public override bool Resolve (EmitContext ec)
2717 bool previous_state = ec.CheckState;
2718 bool previous_state_const = ec.ConstantCheckState;
2720 ec.CheckState = false;
2721 ec.ConstantCheckState = false;
2722 bool ret = Block.Resolve (ec);
2723 ec.CheckState = previous_state;
2724 ec.ConstantCheckState = previous_state_const;
2729 protected override void DoEmit (EmitContext ec)
2731 bool previous_state = ec.CheckState;
2732 bool previous_state_const = ec.ConstantCheckState;
2734 ec.CheckState = false;
2735 ec.ConstantCheckState = false;
2737 ec.CheckState = previous_state;
2738 ec.ConstantCheckState = previous_state_const;
2742 public class Checked : Statement {
2743 public readonly Block Block;
2745 public Checked (Block b)
2748 b.Unchecked = false;
2751 public override bool Resolve (EmitContext ec)
2753 bool previous_state = ec.CheckState;
2754 bool previous_state_const = ec.ConstantCheckState;
2756 ec.CheckState = true;
2757 ec.ConstantCheckState = true;
2758 bool ret = Block.Resolve (ec);
2759 ec.CheckState = previous_state;
2760 ec.ConstantCheckState = previous_state_const;
2765 protected override void DoEmit (EmitContext ec)
2767 bool previous_state = ec.CheckState;
2768 bool previous_state_const = ec.ConstantCheckState;
2770 ec.CheckState = true;
2771 ec.ConstantCheckState = true;
2773 ec.CheckState = previous_state;
2774 ec.ConstantCheckState = previous_state_const;
2778 public class Unsafe : Statement {
2779 public readonly Block Block;
2781 public Unsafe (Block b)
2786 public override bool Resolve (EmitContext ec)
2788 bool previous_state = ec.InUnsafe;
2792 val = Block.Resolve (ec);
2793 ec.InUnsafe = previous_state;
2798 protected override void DoEmit (EmitContext ec)
2800 bool previous_state = ec.InUnsafe;
2804 ec.InUnsafe = previous_state;
2811 public class Fixed : Statement {
2813 ArrayList declarators;
2814 Statement statement;
2820 public bool is_object;
2821 public LocalInfo vi;
2822 public Expression expr;
2823 public Expression converted;
2826 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2829 declarators = decls;
2834 public override bool Resolve (EmitContext ec)
2837 Expression.UnsafeError (loc);
2841 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2842 if (expr_type == null)
2845 if (ec.RemapToProxy){
2846 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2850 data = new FixedData [declarators.Count];
2852 if (!expr_type.IsPointer){
2853 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2858 foreach (Pair p in declarators){
2859 LocalInfo vi = (LocalInfo) p.First;
2860 Expression e = (Expression) p.Second;
2862 vi.VariableInfo = null;
2866 // The rules for the possible declarators are pretty wise,
2867 // but the production on the grammar is more concise.
2869 // So we have to enforce these rules here.
2871 // We do not resolve before doing the case 1 test,
2872 // because the grammar is explicit in that the token &
2873 // is present, so we need to test for this particular case.
2877 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2882 // Case 1: & object.
2884 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2885 Expression child = ((Unary) e).Expr;
2888 if (child is ParameterReference || child is LocalVariableReference){
2891 "No need to use fixed statement for parameters or " +
2892 "local variable declarations (address is already " +
2897 ec.InFixedInitializer = true;
2899 ec.InFixedInitializer = false;
2903 child = ((Unary) e).Expr;
2905 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2908 data [i].is_object = true;
2910 data [i].converted = null;
2917 ec.InFixedInitializer = true;
2919 ec.InFixedInitializer = false;
2926 if (e.Type.IsArray){
2927 Type array_type = TypeManager.GetElementType (e.Type);
2931 // Provided that array_type is unmanaged,
2933 if (!TypeManager.VerifyUnManaged (array_type, loc))
2937 // and T* is implicitly convertible to the
2938 // pointer type given in the fixed statement.
2940 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2942 Expression converted = Convert.ImplicitConversionRequired (
2943 ec, array_ptr, vi.VariableType, loc);
2944 if (converted == null)
2947 data [i].is_object = false;
2949 data [i].converted = converted;
2959 if (e.Type == TypeManager.string_type){
2960 data [i].is_object = false;
2962 data [i].converted = null;
2969 // For other cases, flag a `this is already fixed expression'
2971 if (e is LocalVariableReference || e is ParameterReference ||
2972 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
2974 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
2978 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
2982 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
2984 if (!statement.Resolve (ec)) {
2985 ec.KillFlowBranching ();
2989 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2990 has_ret = reachability.IsUnreachable;
2995 protected override void DoEmit (EmitContext ec)
2997 ILGenerator ig = ec.ig;
2999 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3001 for (int i = 0; i < data.Length; i++) {
3002 LocalInfo vi = data [i].vi;
3005 // Case 1: & object.
3007 if (data [i].is_object) {
3009 // Store pointer in pinned location
3011 data [i].expr.Emit (ec);
3012 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3013 clear_list [i] = vi.LocalBuilder;
3020 if (data [i].expr.Type.IsArray){
3022 // Store pointer in pinned location
3024 data [i].converted.Emit (ec);
3026 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3027 clear_list [i] = vi.LocalBuilder;
3034 if (data [i].expr.Type == TypeManager.string_type){
3035 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3036 TypeManager.MakePinned (pinned_string);
3037 clear_list [i] = pinned_string;
3039 data [i].expr.Emit (ec);
3040 ig.Emit (OpCodes.Stloc, pinned_string);
3042 Expression sptr = new StringPtr (pinned_string, loc);
3043 Expression converted = Convert.ImplicitConversionRequired (
3044 ec, sptr, vi.VariableType, loc);
3046 if (converted == null)
3049 converted.Emit (ec);
3050 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3054 statement.Emit (ec);
3060 // Clear the pinned variable
3062 for (int i = 0; i < data.Length; i++) {
3063 if (data [i].is_object || data [i].expr.Type.IsArray) {
3064 ig.Emit (OpCodes.Ldc_I4_0);
3065 ig.Emit (OpCodes.Conv_U);
3066 ig.Emit (OpCodes.Stloc, clear_list [i]);
3067 } else if (data [i].expr.Type == TypeManager.string_type){
3068 ig.Emit (OpCodes.Ldnull);
3069 ig.Emit (OpCodes.Stloc, clear_list [i]);
3075 public class Catch {
3076 public readonly string Name;
3077 public readonly Block Block;
3078 public readonly Location Location;
3080 Expression type_expr;
3083 public Catch (Expression type, string name, Block block, Location l)
3091 public Type CatchType {
3097 public bool IsGeneral {
3099 return type_expr == null;
3103 public bool Resolve (EmitContext ec)
3105 if (type_expr != null) {
3106 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3110 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3111 Report.Error (155, Location,
3112 "The type caught or thrown must be derived " +
3113 "from System.Exception");
3119 if (!Block.Resolve (ec))
3126 public class Try : Statement {
3127 public readonly Block Fini, Block;
3128 public readonly ArrayList Specific;
3129 public readonly Catch General;
3132 // specific, general and fini might all be null.
3134 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3136 if (specific == null && general == null){
3137 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3141 this.Specific = specific;
3142 this.General = general;
3147 public override bool Resolve (EmitContext ec)
3151 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3153 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3155 if (!Block.Resolve (ec))
3158 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3160 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3162 foreach (Catch c in Specific){
3163 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3164 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3166 if (c.Name != null) {
3167 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3169 throw new Exception ();
3171 vi.VariableInfo = null;
3174 if (!c.Resolve (ec))
3178 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3180 if (General != null){
3181 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3182 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3184 if (!General.Resolve (ec))
3188 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3192 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
3193 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3195 if (!Fini.Resolve (ec))
3199 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3201 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3203 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3205 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3206 // Unfortunately, System.Reflection.Emit automatically emits a leave
3207 // to the end of the finally block. This is a problem if `returns'
3208 // is true since we may jump to a point after the end of the method.
3209 // As a workaround, emit an explicit ret here.
3210 ec.NeedReturnLabel ();
3216 protected override void DoEmit (EmitContext ec)
3218 ILGenerator ig = ec.ig;
3219 Label finish = ig.DefineLabel ();;
3221 ig.BeginExceptionBlock ();
3225 // System.Reflection.Emit provides this automatically:
3226 // ig.Emit (OpCodes.Leave, finish);
3228 foreach (Catch c in Specific){
3231 ig.BeginCatchBlock (c.CatchType);
3233 if (c.Name != null){
3234 vi = c.Block.GetLocalInfo (c.Name);
3236 throw new Exception ("Variable does not exist in this block");
3238 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3240 ig.Emit (OpCodes.Pop);
3245 if (General != null){
3246 ig.BeginCatchBlock (TypeManager.object_type);
3247 ig.Emit (OpCodes.Pop);
3248 General.Block.Emit (ec);
3251 ig.MarkLabel (finish);
3253 ig.BeginFinallyBlock ();
3257 ig.EndExceptionBlock ();
3261 public class Using : Statement {
3262 object expression_or_block;
3263 Statement Statement;
3268 Expression [] converted_vars;
3269 ExpressionStatement [] assign;
3271 public Using (object expression_or_block, Statement stmt, Location l)
3273 this.expression_or_block = expression_or_block;
3279 // Resolves for the case of using using a local variable declaration.
3281 bool ResolveLocalVariableDecls (EmitContext ec)
3283 bool need_conv = false;
3284 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3287 if (expr_type == null)
3291 // The type must be an IDisposable or an implicit conversion
3294 converted_vars = new Expression [var_list.Count];
3295 assign = new ExpressionStatement [var_list.Count];
3296 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3297 foreach (DictionaryEntry e in var_list){
3298 Expression var = (Expression) e.Key;
3300 var = var.ResolveLValue (ec, new EmptyExpression ());
3304 converted_vars [i] = Convert.ImplicitConversionRequired (
3305 ec, var, TypeManager.idisposable_type, loc);
3307 if (converted_vars [i] == null)
3315 foreach (DictionaryEntry e in var_list){
3316 LocalVariableReference var = (LocalVariableReference) e.Key;
3317 Expression new_expr = (Expression) e.Value;
3320 a = new Assign (var, new_expr, loc);
3326 converted_vars [i] = var;
3327 assign [i] = (ExpressionStatement) a;
3334 bool ResolveExpression (EmitContext ec)
3336 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3337 conv = Convert.ImplicitConversionRequired (
3338 ec, expr, TypeManager.idisposable_type, loc);
3348 // Emits the code for the case of using using a local variable declaration.
3350 bool EmitLocalVariableDecls (EmitContext ec)
3352 ILGenerator ig = ec.ig;
3355 for (i = 0; i < assign.Length; i++) {
3356 assign [i].EmitStatement (ec);
3358 ig.BeginExceptionBlock ();
3360 Statement.Emit (ec);
3362 var_list.Reverse ();
3363 foreach (DictionaryEntry e in var_list){
3364 LocalVariableReference var = (LocalVariableReference) e.Key;
3365 Label skip = ig.DefineLabel ();
3368 ig.BeginFinallyBlock ();
3370 if (!var.Type.IsValueType) {
3372 ig.Emit (OpCodes.Brfalse, skip);
3373 converted_vars [i].Emit (ec);
3374 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3376 Expression ml = Expression.MemberLookup(ec, typeof(IDisposable), var.Type, "Dispose", Mono.CSharp.Location.Null);
3378 if (!(ml is MethodGroupExpr)) {
3380 ig.Emit (OpCodes.Box, var.Type);
3381 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3383 MethodInfo mi = null;
3385 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3386 if (mk.GetParameters().Length == 0) {
3393 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3397 var.AddressOf (ec, AddressOp.Load);
3398 ig.Emit (OpCodes.Call, mi);
3402 ig.MarkLabel (skip);
3403 ig.EndExceptionBlock ();
3409 bool EmitExpression (EmitContext ec)
3412 // Make a copy of the expression and operate on that.
3414 ILGenerator ig = ec.ig;
3415 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3420 ig.Emit (OpCodes.Stloc, local_copy);
3422 ig.BeginExceptionBlock ();
3423 Statement.Emit (ec);
3425 Label skip = ig.DefineLabel ();
3426 ig.BeginFinallyBlock ();
3427 ig.Emit (OpCodes.Ldloc, local_copy);
3428 ig.Emit (OpCodes.Brfalse, skip);
3429 ig.Emit (OpCodes.Ldloc, local_copy);
3430 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3431 ig.MarkLabel (skip);
3432 ig.EndExceptionBlock ();
3437 public override bool Resolve (EmitContext ec)
3439 if (expression_or_block is DictionaryEntry){
3440 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3441 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3443 if (!ResolveLocalVariableDecls (ec))
3446 } else if (expression_or_block is Expression){
3447 expr = (Expression) expression_or_block;
3449 expr = expr.Resolve (ec);
3453 expr_type = expr.Type;
3455 if (!ResolveExpression (ec))
3459 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3461 bool ok = Statement.Resolve (ec);
3464 ec.KillFlowBranching ();
3468 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3470 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3471 // Unfortunately, System.Reflection.Emit automatically emits a leave
3472 // to the end of the finally block. This is a problem if `returns'
3473 // is true since we may jump to a point after the end of the method.
3474 // As a workaround, emit an explicit ret here.
3475 ec.NeedReturnLabel ();
3481 protected override void DoEmit (EmitContext ec)
3483 if (expression_or_block is DictionaryEntry)
3484 EmitLocalVariableDecls (ec);
3485 else if (expression_or_block is Expression)
3486 EmitExpression (ec);
3491 /// Implementation of the foreach C# statement
3493 public class Foreach : Statement {
3495 Expression variable;
3497 Statement statement;
3498 ForeachHelperMethods hm;
3499 Expression empty, conv;
3500 Type array_type, element_type;
3503 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3504 Statement stmt, Location l)
3507 this.variable = var;
3513 public override bool Resolve (EmitContext ec)
3515 expr = expr.Resolve (ec);
3519 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3520 if (var_type == null)
3524 // We need an instance variable. Not sure this is the best
3525 // way of doing this.
3527 // FIXME: When we implement propertyaccess, will those turn
3528 // out to return values in ExprClass? I think they should.
3530 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3531 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3532 error1579 (expr.Type);
3536 if (expr.Type.IsArray) {
3537 array_type = expr.Type;
3538 element_type = TypeManager.GetElementType (array_type);
3540 empty = new EmptyExpression (element_type);
3542 hm = ProbeCollectionType (ec, expr.Type);
3544 error1579 (expr.Type);
3548 array_type = expr.Type;
3549 element_type = hm.element_type;
3551 empty = new EmptyExpression (hm.element_type);
3556 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3557 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
3561 // FIXME: maybe we can apply the same trick we do in the
3562 // array handling to avoid creating empty and conv in some cases.
3564 // Although it is not as important in this case, as the type
3565 // will not likely be object (what the enumerator will return).
3567 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3571 variable = variable.ResolveLValue (ec, empty);
3572 if (variable == null)
3575 bool disposable = (hm != null) && hm.is_disposable;
3577 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3579 if (!statement.Resolve (ec))
3583 ec.EndFlowBranching ();
3585 ec.EndFlowBranching ();
3591 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3593 static MethodInfo FetchMethodMoveNext (Type t)
3595 MemberList move_next_list;
3597 move_next_list = TypeContainer.FindMembers (
3598 t, MemberTypes.Method,
3599 BindingFlags.Public | BindingFlags.Instance,
3600 Type.FilterName, "MoveNext");
3601 if (move_next_list.Count == 0)
3604 foreach (MemberInfo m in move_next_list){
3605 MethodInfo mi = (MethodInfo) m;
3608 args = TypeManager.GetArgumentTypes (mi);
3609 if (args != null && args.Length == 0){
3610 if (mi.ReturnType == TypeManager.bool_type)
3618 // Retrieves a `public T get_Current ()' method from the Type `t'
3620 static MethodInfo FetchMethodGetCurrent (Type t)
3622 MemberList get_current_list;
3624 get_current_list = TypeContainer.FindMembers (
3625 t, MemberTypes.Method,
3626 BindingFlags.Public | BindingFlags.Instance,
3627 Type.FilterName, "get_Current");
3628 if (get_current_list.Count == 0)
3631 foreach (MemberInfo m in get_current_list){
3632 MethodInfo mi = (MethodInfo) m;
3635 args = TypeManager.GetArgumentTypes (mi);
3636 if (args != null && args.Length == 0)
3643 // This struct records the helper methods used by the Foreach construct
3645 class ForeachHelperMethods {
3646 public EmitContext ec;
3647 public MethodInfo get_enumerator;
3648 public MethodInfo move_next;
3649 public MethodInfo get_current;
3650 public Type element_type;
3651 public Type enumerator_type;
3652 public bool is_disposable;
3654 public ForeachHelperMethods (EmitContext ec)
3657 this.element_type = TypeManager.object_type;
3658 this.enumerator_type = TypeManager.ienumerator_type;
3659 this.is_disposable = true;
3663 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3668 if (!(m is MethodInfo))
3671 if (m.Name != "GetEnumerator")
3674 MethodInfo mi = (MethodInfo) m;
3675 Type [] args = TypeManager.GetArgumentTypes (mi);
3677 if (args.Length != 0)
3680 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3681 EmitContext ec = hm.ec;
3684 // Check whether GetEnumerator is accessible to us
3686 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3688 Type declaring = mi.DeclaringType;
3689 if (prot == MethodAttributes.Private){
3690 if (declaring != ec.ContainerType)
3692 } else if (prot == MethodAttributes.FamANDAssem){
3693 // If from a different assembly, false
3694 if (!(mi is MethodBuilder))
3697 // Are we being invoked from the same class, or from a derived method?
3699 if (ec.ContainerType != declaring){
3700 if (!ec.ContainerType.IsSubclassOf (declaring))
3703 } else if (prot == MethodAttributes.FamORAssem){
3704 if (!(mi is MethodBuilder ||
3705 ec.ContainerType == declaring ||
3706 ec.ContainerType.IsSubclassOf (declaring)))
3708 } if (prot == MethodAttributes.Family){
3709 if (!(ec.ContainerType == declaring ||
3710 ec.ContainerType.IsSubclassOf (declaring)))
3714 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3716 // Apply the same optimization as MS: skip the GetEnumerator
3717 // returning an IEnumerator, and use the one returning a
3718 // CharEnumerator instead. This allows us to avoid the
3719 // try-finally block and the boxing.
3724 // Ok, we can access it, now make sure that we can do something
3725 // with this `GetEnumerator'
3728 if (mi.ReturnType == TypeManager.ienumerator_type ||
3729 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
3730 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
3731 if (declaring != TypeManager.string_type) {
3732 hm.move_next = TypeManager.bool_movenext_void;
3733 hm.get_current = TypeManager.object_getcurrent_void;
3739 // Ok, so they dont return an IEnumerable, we will have to
3740 // find if they support the GetEnumerator pattern.
3742 Type return_type = mi.ReturnType;
3744 hm.move_next = FetchMethodMoveNext (return_type);
3745 if (hm.move_next == null)
3747 hm.get_current = FetchMethodGetCurrent (return_type);
3748 if (hm.get_current == null)
3751 hm.element_type = hm.get_current.ReturnType;
3752 hm.enumerator_type = return_type;
3753 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3754 TypeManager.ImplementsInterface (
3755 hm.enumerator_type, TypeManager.idisposable_type);
3761 /// This filter is used to find the GetEnumerator method
3762 /// on which IEnumerator operates
3764 static MemberFilter FilterEnumerator;
3768 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3771 void error1579 (Type t)
3773 Report.Error (1579, loc,
3774 "foreach statement cannot operate on variables of type `" +
3775 t.FullName + "' because that class does not provide a " +
3776 " GetEnumerator method or it is inaccessible");
3779 static bool TryType (Type t, ForeachHelperMethods hm)
3783 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3784 BindingFlags.Public | BindingFlags.NonPublic |
3785 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3786 FilterEnumerator, hm);
3791 hm.get_enumerator = (MethodInfo) mi [0];
3796 // Looks for a usable GetEnumerator in the Type, and if found returns
3797 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3799 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3801 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3803 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3804 if (TryType (tt, hm))
3810 // Now try to find the method in the interfaces
3813 Type [] ifaces = t.GetInterfaces ();
3815 foreach (Type i in ifaces){
3816 if (TryType (i, hm))
3821 // Since TypeBuilder.GetInterfaces only returns the interface
3822 // types for this type, we have to keep looping, but once
3823 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3824 // done, because it returns all the types
3826 if ((t is TypeBuilder))
3836 // FIXME: possible optimization.
3837 // We might be able to avoid creating `empty' if the type is the sam
3839 bool EmitCollectionForeach (EmitContext ec)
3841 ILGenerator ig = ec.ig;
3842 VariableStorage enumerator, disposable;
3844 enumerator = new VariableStorage (ec, hm.enumerator_type);
3845 if (hm.is_disposable)
3846 disposable = new VariableStorage (ec, TypeManager.idisposable_type);
3850 enumerator.EmitThis ();
3852 // Instantiate the enumerator
3854 if (expr.Type.IsValueType){
3855 if (expr is IMemoryLocation){
3856 IMemoryLocation ml = (IMemoryLocation) expr;
3858 ml.AddressOf (ec, AddressOp.Load);
3860 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3861 " does not implement IMemoryLocation");
3862 ig.Emit (OpCodes.Call, hm.get_enumerator);
3865 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3867 enumerator.EmitStore ();
3870 // Protect the code in a try/finalize block, so that
3871 // if the beast implement IDisposable, we get rid of it
3873 if (hm.is_disposable)
3874 ig.BeginExceptionBlock ();
3876 Label end_try = ig.DefineLabel ();
3878 ig.MarkLabel (ec.LoopBegin);
3879 enumerator.EmitLoad ();
3880 ig.Emit (OpCodes.Callvirt, hm.move_next);
3881 ig.Emit (OpCodes.Brfalse, end_try);
3885 enumerator.EmitLoad ();
3886 ig.Emit (OpCodes.Callvirt, hm.get_current);
3890 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3892 ((IAssignMethod)variable).EmitAssign (ec, conv);
3894 statement.Emit (ec);
3895 ig.Emit (OpCodes.Br, ec.LoopBegin);
3896 ig.MarkLabel (end_try);
3898 // The runtime provides this for us.
3899 // ig.Emit (OpCodes.Leave, end);
3902 // Now the finally block
3904 if (hm.is_disposable) {
3905 Label end_finally = ig.DefineLabel ();
3906 ig.BeginFinallyBlock ();
3908 disposable.EmitThis ();
3909 enumerator.EmitThis ();
3910 enumerator.EmitLoad ();
3911 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3912 disposable.EmitStore ();
3913 disposable.EmitLoad ();
3914 ig.Emit (OpCodes.Brfalse, end_finally);
3915 disposable.EmitThis ();
3916 disposable.EmitLoad ();
3917 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3918 ig.MarkLabel (end_finally);
3920 // The runtime generates this anyways.
3921 // ig.Emit (OpCodes.Endfinally);
3923 ig.EndExceptionBlock ();
3926 ig.MarkLabel (ec.LoopEnd);
3931 // FIXME: possible optimization.
3932 // We might be able to avoid creating `empty' if the type is the sam
3934 bool EmitArrayForeach (EmitContext ec)
3936 int rank = array_type.GetArrayRank ();
3937 ILGenerator ig = ec.ig;
3939 VariableStorage copy = new VariableStorage (ec, array_type);
3942 // Make our copy of the array
3949 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
3953 counter.EmitThis ();
3954 ig.Emit (OpCodes.Ldc_I4_0);
3955 counter.EmitStore ();
3956 test = ig.DefineLabel ();
3957 ig.Emit (OpCodes.Br, test);
3959 loop = ig.DefineLabel ();
3960 ig.MarkLabel (loop);
3967 counter.EmitThis ();
3968 counter.EmitLoad ();
3971 // Load the value, we load the value using the underlying type,
3972 // then we use the variable.EmitAssign to load using the proper cast.
3974 ArrayAccess.EmitLoadOpcode (ig, element_type);
3977 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3979 ((IAssignMethod)variable).EmitAssign (ec, conv);
3981 statement.Emit (ec);
3983 ig.MarkLabel (ec.LoopBegin);
3984 counter.EmitThis ();
3985 counter.EmitThis ();
3986 counter.EmitLoad ();
3987 ig.Emit (OpCodes.Ldc_I4_1);
3988 ig.Emit (OpCodes.Add);
3989 counter.EmitStore ();
3991 ig.MarkLabel (test);
3992 counter.EmitThis ();
3993 counter.EmitLoad ();
3996 ig.Emit (OpCodes.Ldlen);
3997 ig.Emit (OpCodes.Conv_I4);
3998 ig.Emit (OpCodes.Blt, loop);
4000 VariableStorage [] dim_len = new VariableStorage [rank];
4001 VariableStorage [] dim_count = new VariableStorage [rank];
4002 Label [] loop = new Label [rank];
4003 Label [] test = new Label [rank];
4006 for (dim = 0; dim < rank; dim++){
4007 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4008 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4009 test [dim] = ig.DefineLabel ();
4010 loop [dim] = ig.DefineLabel ();
4013 for (dim = 0; dim < rank; dim++){
4014 dim_len [dim].EmitThis ();
4017 IntLiteral.EmitInt (ig, dim);
4018 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4019 dim_len [dim].EmitStore ();
4023 for (dim = 0; dim < rank; dim++){
4024 dim_count [dim].EmitThis ();
4025 ig.Emit (OpCodes.Ldc_I4_0);
4026 dim_count [dim].EmitStore ();
4027 ig.Emit (OpCodes.Br, test [dim]);
4028 ig.MarkLabel (loop [dim]);
4035 for (dim = 0; dim < rank; dim++){
4036 dim_count [dim].EmitThis ();
4037 dim_count [dim].EmitLoad ();
4041 // FIXME: Maybe we can cache the computation of `get'?
4043 Type [] args = new Type [rank];
4046 for (int i = 0; i < rank; i++)
4047 args [i] = TypeManager.int32_type;
4049 ModuleBuilder mb = CodeGen.ModuleBuilder;
4050 get = mb.GetArrayMethod (
4052 CallingConventions.HasThis| CallingConventions.Standard,
4054 ig.Emit (OpCodes.Call, get);
4057 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4059 ((IAssignMethod)variable).EmitAssign (ec, conv);
4060 statement.Emit (ec);
4061 ig.MarkLabel (ec.LoopBegin);
4062 for (dim = rank - 1; dim >= 0; dim--){
4063 dim_count [dim].EmitThis ();
4064 dim_count [dim].EmitThis ();
4065 dim_count [dim].EmitLoad ();
4066 ig.Emit (OpCodes.Ldc_I4_1);
4067 ig.Emit (OpCodes.Add);
4068 dim_count [dim].EmitStore ();
4070 ig.MarkLabel (test [dim]);
4071 dim_count [dim].EmitThis ();
4072 dim_count [dim].EmitLoad ();
4073 dim_len [dim].EmitThis ();
4074 dim_len [dim].EmitLoad ();
4075 ig.Emit (OpCodes.Blt, loop [dim]);
4078 ig.MarkLabel (ec.LoopEnd);
4083 protected override void DoEmit (EmitContext ec)
4085 ILGenerator ig = ec.ig;
4087 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4088 ec.LoopBegin = ig.DefineLabel ();
4089 ec.LoopEnd = ig.DefineLabel ();
4092 EmitCollectionForeach (ec);
4094 EmitArrayForeach (ec);
4096 ec.LoopBegin = old_begin;
4097 ec.LoopEnd = old_end;