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;
2484 bool default_at_end = false;
2486 ig.Emit (OpCodes.Ldloc, val);
2488 if (Elements.Contains (NullLiteral.Null)){
2489 ig.Emit (OpCodes.Brfalse, null_target);
2491 ig.Emit (OpCodes.Brfalse, default_target);
2493 ig.Emit (OpCodes.Ldloc, val);
2494 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2495 ig.Emit (OpCodes.Stloc, val);
2497 int section_count = Sections.Count;
2498 for (int section = 0; section < section_count; section++){
2499 SwitchSection ss = (SwitchSection) Sections [section];
2500 Label sec_begin = ig.DefineLabel ();
2502 if (pending_goto_end)
2503 ig.Emit (OpCodes.Br, end_of_switch);
2505 int label_count = ss.Labels.Count;
2506 bool mark_default = false;
2508 for (int label = 0; label < label_count; label++){
2509 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2510 ig.MarkLabel (sl.ILLabel);
2513 ig.MarkLabel (next_test);
2514 next_test = ig.DefineLabel ();
2517 // If we are the default target
2519 if (sl.Label == null){
2520 if (label+1 == label_count)
2521 default_at_end = true;
2522 mark_default = true;
2523 default_found = true;
2525 object lit = sl.Converted;
2527 if (lit is NullLiteral){
2529 if (label_count == 1)
2530 ig.Emit (OpCodes.Br, next_test);
2534 StringConstant str = (StringConstant) lit;
2536 ig.Emit (OpCodes.Ldloc, val);
2537 ig.Emit (OpCodes.Ldstr, str.Value);
2538 if (label_count == 1)
2539 ig.Emit (OpCodes.Bne_Un, next_test);
2541 if (label+1 == label_count)
2542 ig.Emit (OpCodes.Bne_Un, next_test);
2544 ig.Emit (OpCodes.Beq, sec_begin);
2549 ig.MarkLabel (null_target);
2550 ig.MarkLabel (sec_begin);
2551 foreach (SwitchLabel sl in ss.Labels)
2552 ig.MarkLabel (sl.ILLabelCode);
2555 ig.MarkLabel (default_target);
2557 pending_goto_end = !ss.Block.HasRet;
2560 ig.MarkLabel (next_test);
2562 if (!default_at_end)
2563 ig.Emit (OpCodes.Br, default_target);
2565 ig.MarkLabel (default_target);
2566 ig.MarkLabel (end_of_switch);
2569 public override bool Resolve (EmitContext ec)
2571 Expr = Expr.Resolve (ec);
2575 new_expr = SwitchGoverningType (ec, Expr.Type);
2576 if (new_expr == null){
2577 Report.Error (151, loc, "An integer type or string was expected for switch");
2582 SwitchType = new_expr.Type;
2584 if (!CheckSwitch (ec))
2587 Switch old_switch = ec.Switch;
2589 ec.Switch.SwitchType = SwitchType;
2591 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2592 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2595 foreach (SwitchSection ss in Sections){
2597 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2601 if (ss.Block.Resolve (ec) != true)
2607 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2609 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2610 ec.Switch = old_switch;
2612 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2618 protected override void DoEmit (EmitContext ec)
2620 // Store variable for comparission purposes
2621 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2623 ec.ig.Emit (OpCodes.Stloc, value);
2625 ILGenerator ig = ec.ig;
2627 default_target = ig.DefineLabel ();
2630 // Setup the codegen context
2632 Label old_end = ec.LoopEnd;
2633 Switch old_switch = ec.Switch;
2635 ec.LoopEnd = ig.DefineLabel ();
2639 if (SwitchType == TypeManager.string_type)
2640 SimpleSwitchEmit (ec, value);
2642 TableSwitchEmit (ec, value);
2644 // Restore context state.
2645 ig.MarkLabel (ec.LoopEnd);
2648 // Restore the previous context
2650 ec.LoopEnd = old_end;
2651 ec.Switch = old_switch;
2655 public class Lock : Statement {
2657 Statement Statement;
2659 public Lock (Expression expr, Statement stmt, Location l)
2666 public override bool Resolve (EmitContext ec)
2668 expr = expr.Resolve (ec);
2672 if (expr.Type.IsValueType){
2673 Error (185, "lock statement requires the expression to be " +
2674 " a reference type (type is: `{0}'",
2675 TypeManager.CSharpName (expr.Type));
2679 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2680 bool ok = Statement.Resolve (ec);
2681 ec.EndFlowBranching ();
2686 protected override void DoEmit (EmitContext ec)
2688 Type type = expr.Type;
2690 ILGenerator ig = ec.ig;
2691 LocalBuilder temp = ig.DeclareLocal (type);
2694 ig.Emit (OpCodes.Dup);
2695 ig.Emit (OpCodes.Stloc, temp);
2696 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2699 ig.BeginExceptionBlock ();
2700 Label finish = ig.DefineLabel ();
2701 Statement.Emit (ec);
2702 // ig.Emit (OpCodes.Leave, finish);
2704 ig.MarkLabel (finish);
2707 ig.BeginFinallyBlock ();
2708 ig.Emit (OpCodes.Ldloc, temp);
2709 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2710 ig.EndExceptionBlock ();
2714 public class Unchecked : Statement {
2715 public readonly Block Block;
2717 public Unchecked (Block b)
2723 public override bool Resolve (EmitContext ec)
2725 bool previous_state = ec.CheckState;
2726 bool previous_state_const = ec.ConstantCheckState;
2728 ec.CheckState = false;
2729 ec.ConstantCheckState = false;
2730 bool ret = Block.Resolve (ec);
2731 ec.CheckState = previous_state;
2732 ec.ConstantCheckState = previous_state_const;
2737 protected override void DoEmit (EmitContext ec)
2739 bool previous_state = ec.CheckState;
2740 bool previous_state_const = ec.ConstantCheckState;
2742 ec.CheckState = false;
2743 ec.ConstantCheckState = false;
2745 ec.CheckState = previous_state;
2746 ec.ConstantCheckState = previous_state_const;
2750 public class Checked : Statement {
2751 public readonly Block Block;
2753 public Checked (Block b)
2756 b.Unchecked = false;
2759 public override bool Resolve (EmitContext ec)
2761 bool previous_state = ec.CheckState;
2762 bool previous_state_const = ec.ConstantCheckState;
2764 ec.CheckState = true;
2765 ec.ConstantCheckState = true;
2766 bool ret = Block.Resolve (ec);
2767 ec.CheckState = previous_state;
2768 ec.ConstantCheckState = previous_state_const;
2773 protected override void DoEmit (EmitContext ec)
2775 bool previous_state = ec.CheckState;
2776 bool previous_state_const = ec.ConstantCheckState;
2778 ec.CheckState = true;
2779 ec.ConstantCheckState = true;
2781 ec.CheckState = previous_state;
2782 ec.ConstantCheckState = previous_state_const;
2786 public class Unsafe : Statement {
2787 public readonly Block Block;
2789 public Unsafe (Block b)
2794 public override bool Resolve (EmitContext ec)
2796 bool previous_state = ec.InUnsafe;
2800 val = Block.Resolve (ec);
2801 ec.InUnsafe = previous_state;
2806 protected override void DoEmit (EmitContext ec)
2808 bool previous_state = ec.InUnsafe;
2812 ec.InUnsafe = previous_state;
2819 public class Fixed : Statement {
2821 ArrayList declarators;
2822 Statement statement;
2828 public bool is_object;
2829 public LocalInfo vi;
2830 public Expression expr;
2831 public Expression converted;
2834 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2837 declarators = decls;
2842 public override bool Resolve (EmitContext ec)
2845 Expression.UnsafeError (loc);
2849 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2850 if (expr_type == null)
2853 if (ec.RemapToProxy){
2854 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2858 data = new FixedData [declarators.Count];
2860 if (!expr_type.IsPointer){
2861 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2866 foreach (Pair p in declarators){
2867 LocalInfo vi = (LocalInfo) p.First;
2868 Expression e = (Expression) p.Second;
2870 vi.VariableInfo = null;
2874 // The rules for the possible declarators are pretty wise,
2875 // but the production on the grammar is more concise.
2877 // So we have to enforce these rules here.
2879 // We do not resolve before doing the case 1 test,
2880 // because the grammar is explicit in that the token &
2881 // is present, so we need to test for this particular case.
2885 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2890 // Case 1: & object.
2892 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2893 Expression child = ((Unary) e).Expr;
2896 if (child is ParameterReference || child is LocalVariableReference){
2899 "No need to use fixed statement for parameters or " +
2900 "local variable declarations (address is already " +
2905 ec.InFixedInitializer = true;
2907 ec.InFixedInitializer = false;
2911 child = ((Unary) e).Expr;
2913 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2916 data [i].is_object = true;
2918 data [i].converted = null;
2925 ec.InFixedInitializer = true;
2927 ec.InFixedInitializer = false;
2934 if (e.Type.IsArray){
2935 Type array_type = TypeManager.GetElementType (e.Type);
2939 // Provided that array_type is unmanaged,
2941 if (!TypeManager.VerifyUnManaged (array_type, loc))
2945 // and T* is implicitly convertible to the
2946 // pointer type given in the fixed statement.
2948 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2950 Expression converted = Convert.ImplicitConversionRequired (
2951 ec, array_ptr, vi.VariableType, loc);
2952 if (converted == null)
2955 data [i].is_object = false;
2957 data [i].converted = converted;
2967 if (e.Type == TypeManager.string_type){
2968 data [i].is_object = false;
2970 data [i].converted = null;
2977 // For other cases, flag a `this is already fixed expression'
2979 if (e is LocalVariableReference || e is ParameterReference ||
2980 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
2982 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
2986 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
2990 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
2992 if (!statement.Resolve (ec)) {
2993 ec.KillFlowBranching ();
2997 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2998 has_ret = reachability.IsUnreachable;
3003 protected override void DoEmit (EmitContext ec)
3005 ILGenerator ig = ec.ig;
3007 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3009 for (int i = 0; i < data.Length; i++) {
3010 LocalInfo vi = data [i].vi;
3013 // Case 1: & object.
3015 if (data [i].is_object) {
3017 // Store pointer in pinned location
3019 data [i].expr.Emit (ec);
3020 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3021 clear_list [i] = vi.LocalBuilder;
3028 if (data [i].expr.Type.IsArray){
3030 // Store pointer in pinned location
3032 data [i].converted.Emit (ec);
3034 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3035 clear_list [i] = vi.LocalBuilder;
3042 if (data [i].expr.Type == TypeManager.string_type){
3043 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3044 TypeManager.MakePinned (pinned_string);
3045 clear_list [i] = pinned_string;
3047 data [i].expr.Emit (ec);
3048 ig.Emit (OpCodes.Stloc, pinned_string);
3050 Expression sptr = new StringPtr (pinned_string, loc);
3051 Expression converted = Convert.ImplicitConversionRequired (
3052 ec, sptr, vi.VariableType, loc);
3054 if (converted == null)
3057 converted.Emit (ec);
3058 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3062 statement.Emit (ec);
3068 // Clear the pinned variable
3070 for (int i = 0; i < data.Length; i++) {
3071 if (data [i].is_object || data [i].expr.Type.IsArray) {
3072 ig.Emit (OpCodes.Ldc_I4_0);
3073 ig.Emit (OpCodes.Conv_U);
3074 ig.Emit (OpCodes.Stloc, clear_list [i]);
3075 } else if (data [i].expr.Type == TypeManager.string_type){
3076 ig.Emit (OpCodes.Ldnull);
3077 ig.Emit (OpCodes.Stloc, clear_list [i]);
3083 public class Catch {
3084 public readonly string Name;
3085 public readonly Block Block;
3086 public readonly Location Location;
3088 Expression type_expr;
3091 public Catch (Expression type, string name, Block block, Location l)
3099 public Type CatchType {
3105 public bool IsGeneral {
3107 return type_expr == null;
3111 public bool Resolve (EmitContext ec)
3113 if (type_expr != null) {
3114 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3118 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3119 Report.Error (155, Location,
3120 "The type caught or thrown must be derived " +
3121 "from System.Exception");
3127 if (!Block.Resolve (ec))
3134 public class Try : Statement {
3135 public readonly Block Fini, Block;
3136 public readonly ArrayList Specific;
3137 public readonly Catch General;
3140 // specific, general and fini might all be null.
3142 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3144 if (specific == null && general == null){
3145 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3149 this.Specific = specific;
3150 this.General = general;
3155 public override bool Resolve (EmitContext ec)
3159 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3161 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3163 if (!Block.Resolve (ec))
3166 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3168 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3170 foreach (Catch c in Specific){
3171 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3172 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3174 if (c.Name != null) {
3175 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3177 throw new Exception ();
3179 vi.VariableInfo = null;
3182 if (!c.Resolve (ec))
3186 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3188 if (General != null){
3189 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3190 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3192 if (!General.Resolve (ec))
3196 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3200 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
3201 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3203 if (!Fini.Resolve (ec))
3207 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3209 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3211 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3213 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3214 // Unfortunately, System.Reflection.Emit automatically emits a leave
3215 // to the end of the finally block. This is a problem if `returns'
3216 // is true since we may jump to a point after the end of the method.
3217 // As a workaround, emit an explicit ret here.
3218 ec.NeedReturnLabel ();
3224 protected override void DoEmit (EmitContext ec)
3226 ILGenerator ig = ec.ig;
3227 Label finish = ig.DefineLabel ();;
3229 ig.BeginExceptionBlock ();
3233 // System.Reflection.Emit provides this automatically:
3234 // ig.Emit (OpCodes.Leave, finish);
3236 foreach (Catch c in Specific){
3239 ig.BeginCatchBlock (c.CatchType);
3241 if (c.Name != null){
3242 vi = c.Block.GetLocalInfo (c.Name);
3244 throw new Exception ("Variable does not exist in this block");
3246 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3248 ig.Emit (OpCodes.Pop);
3253 if (General != null){
3254 ig.BeginCatchBlock (TypeManager.object_type);
3255 ig.Emit (OpCodes.Pop);
3256 General.Block.Emit (ec);
3259 ig.MarkLabel (finish);
3261 ig.BeginFinallyBlock ();
3265 ig.EndExceptionBlock ();
3269 public class Using : Statement {
3270 object expression_or_block;
3271 Statement Statement;
3276 Expression [] converted_vars;
3277 ExpressionStatement [] assign;
3279 public Using (object expression_or_block, Statement stmt, Location l)
3281 this.expression_or_block = expression_or_block;
3287 // Resolves for the case of using using a local variable declaration.
3289 bool ResolveLocalVariableDecls (EmitContext ec)
3291 bool need_conv = false;
3292 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3295 if (expr_type == null)
3299 // The type must be an IDisposable or an implicit conversion
3302 converted_vars = new Expression [var_list.Count];
3303 assign = new ExpressionStatement [var_list.Count];
3304 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3305 foreach (DictionaryEntry e in var_list){
3306 Expression var = (Expression) e.Key;
3308 var = var.ResolveLValue (ec, new EmptyExpression ());
3312 converted_vars [i] = Convert.ImplicitConversionRequired (
3313 ec, var, TypeManager.idisposable_type, loc);
3315 if (converted_vars [i] == null)
3323 foreach (DictionaryEntry e in var_list){
3324 LocalVariableReference var = (LocalVariableReference) e.Key;
3325 Expression new_expr = (Expression) e.Value;
3328 a = new Assign (var, new_expr, loc);
3334 converted_vars [i] = var;
3335 assign [i] = (ExpressionStatement) a;
3342 bool ResolveExpression (EmitContext ec)
3344 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3345 conv = Convert.ImplicitConversionRequired (
3346 ec, expr, TypeManager.idisposable_type, loc);
3356 // Emits the code for the case of using using a local variable declaration.
3358 bool EmitLocalVariableDecls (EmitContext ec)
3360 ILGenerator ig = ec.ig;
3363 for (i = 0; i < assign.Length; i++) {
3364 assign [i].EmitStatement (ec);
3366 ig.BeginExceptionBlock ();
3368 Statement.Emit (ec);
3370 var_list.Reverse ();
3371 foreach (DictionaryEntry e in var_list){
3372 LocalVariableReference var = (LocalVariableReference) e.Key;
3373 Label skip = ig.DefineLabel ();
3376 ig.BeginFinallyBlock ();
3378 if (!var.Type.IsValueType) {
3380 ig.Emit (OpCodes.Brfalse, skip);
3381 converted_vars [i].Emit (ec);
3382 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3384 Expression ml = Expression.MemberLookup(ec, typeof(IDisposable), var.Type, "Dispose", Mono.CSharp.Location.Null);
3386 if (!(ml is MethodGroupExpr)) {
3388 ig.Emit (OpCodes.Box, var.Type);
3389 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3391 MethodInfo mi = null;
3393 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3394 if (mk.GetParameters().Length == 0) {
3401 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3405 var.AddressOf (ec, AddressOp.Load);
3406 ig.Emit (OpCodes.Call, mi);
3410 ig.MarkLabel (skip);
3411 ig.EndExceptionBlock ();
3417 bool EmitExpression (EmitContext ec)
3420 // Make a copy of the expression and operate on that.
3422 ILGenerator ig = ec.ig;
3423 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3428 ig.Emit (OpCodes.Stloc, local_copy);
3430 ig.BeginExceptionBlock ();
3431 Statement.Emit (ec);
3433 Label skip = ig.DefineLabel ();
3434 ig.BeginFinallyBlock ();
3435 ig.Emit (OpCodes.Ldloc, local_copy);
3436 ig.Emit (OpCodes.Brfalse, skip);
3437 ig.Emit (OpCodes.Ldloc, local_copy);
3438 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3439 ig.MarkLabel (skip);
3440 ig.EndExceptionBlock ();
3445 public override bool Resolve (EmitContext ec)
3447 if (expression_or_block is DictionaryEntry){
3448 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3449 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3451 if (!ResolveLocalVariableDecls (ec))
3454 } else if (expression_or_block is Expression){
3455 expr = (Expression) expression_or_block;
3457 expr = expr.Resolve (ec);
3461 expr_type = expr.Type;
3463 if (!ResolveExpression (ec))
3467 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3469 bool ok = Statement.Resolve (ec);
3472 ec.KillFlowBranching ();
3476 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3478 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3479 // Unfortunately, System.Reflection.Emit automatically emits a leave
3480 // to the end of the finally block. This is a problem if `returns'
3481 // is true since we may jump to a point after the end of the method.
3482 // As a workaround, emit an explicit ret here.
3483 ec.NeedReturnLabel ();
3489 protected override void DoEmit (EmitContext ec)
3491 if (expression_or_block is DictionaryEntry)
3492 EmitLocalVariableDecls (ec);
3493 else if (expression_or_block is Expression)
3494 EmitExpression (ec);
3499 /// Implementation of the foreach C# statement
3501 public class Foreach : Statement {
3503 Expression variable;
3505 Statement statement;
3506 ForeachHelperMethods hm;
3507 Expression empty, conv;
3508 Type array_type, element_type;
3511 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3512 Statement stmt, Location l)
3515 this.variable = var;
3521 public override bool Resolve (EmitContext ec)
3523 expr = expr.Resolve (ec);
3527 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3528 if (var_type == null)
3532 // We need an instance variable. Not sure this is the best
3533 // way of doing this.
3535 // FIXME: When we implement propertyaccess, will those turn
3536 // out to return values in ExprClass? I think they should.
3538 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3539 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3540 error1579 (expr.Type);
3544 if (expr.Type.IsArray) {
3545 array_type = expr.Type;
3546 element_type = TypeManager.GetElementType (array_type);
3548 empty = new EmptyExpression (element_type);
3550 hm = ProbeCollectionType (ec, expr.Type);
3552 error1579 (expr.Type);
3556 array_type = expr.Type;
3557 element_type = hm.element_type;
3559 empty = new EmptyExpression (hm.element_type);
3564 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3565 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
3569 // FIXME: maybe we can apply the same trick we do in the
3570 // array handling to avoid creating empty and conv in some cases.
3572 // Although it is not as important in this case, as the type
3573 // will not likely be object (what the enumerator will return).
3575 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3579 variable = variable.ResolveLValue (ec, empty);
3580 if (variable == null)
3583 bool disposable = (hm != null) && hm.is_disposable;
3585 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3587 if (!statement.Resolve (ec))
3591 ec.EndFlowBranching ();
3593 ec.EndFlowBranching ();
3599 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3601 static MethodInfo FetchMethodMoveNext (Type t)
3603 MemberList move_next_list;
3605 move_next_list = TypeContainer.FindMembers (
3606 t, MemberTypes.Method,
3607 BindingFlags.Public | BindingFlags.Instance,
3608 Type.FilterName, "MoveNext");
3609 if (move_next_list.Count == 0)
3612 foreach (MemberInfo m in move_next_list){
3613 MethodInfo mi = (MethodInfo) m;
3616 args = TypeManager.GetArgumentTypes (mi);
3617 if (args != null && args.Length == 0){
3618 if (mi.ReturnType == TypeManager.bool_type)
3626 // Retrieves a `public T get_Current ()' method from the Type `t'
3628 static MethodInfo FetchMethodGetCurrent (Type t)
3630 MemberList get_current_list;
3632 get_current_list = TypeContainer.FindMembers (
3633 t, MemberTypes.Method,
3634 BindingFlags.Public | BindingFlags.Instance,
3635 Type.FilterName, "get_Current");
3636 if (get_current_list.Count == 0)
3639 foreach (MemberInfo m in get_current_list){
3640 MethodInfo mi = (MethodInfo) m;
3643 args = TypeManager.GetArgumentTypes (mi);
3644 if (args != null && args.Length == 0)
3651 // This struct records the helper methods used by the Foreach construct
3653 class ForeachHelperMethods {
3654 public EmitContext ec;
3655 public MethodInfo get_enumerator;
3656 public MethodInfo move_next;
3657 public MethodInfo get_current;
3658 public Type element_type;
3659 public Type enumerator_type;
3660 public bool is_disposable;
3662 public ForeachHelperMethods (EmitContext ec)
3665 this.element_type = TypeManager.object_type;
3666 this.enumerator_type = TypeManager.ienumerator_type;
3667 this.is_disposable = true;
3671 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3676 if (!(m is MethodInfo))
3679 if (m.Name != "GetEnumerator")
3682 MethodInfo mi = (MethodInfo) m;
3683 Type [] args = TypeManager.GetArgumentTypes (mi);
3685 if (args.Length != 0)
3688 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3689 EmitContext ec = hm.ec;
3692 // Check whether GetEnumerator is accessible to us
3694 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3696 Type declaring = mi.DeclaringType;
3697 if (prot == MethodAttributes.Private){
3698 if (declaring != ec.ContainerType)
3700 } else if (prot == MethodAttributes.FamANDAssem){
3701 // If from a different assembly, false
3702 if (!(mi is MethodBuilder))
3705 // Are we being invoked from the same class, or from a derived method?
3707 if (ec.ContainerType != declaring){
3708 if (!ec.ContainerType.IsSubclassOf (declaring))
3711 } else if (prot == MethodAttributes.FamORAssem){
3712 if (!(mi is MethodBuilder ||
3713 ec.ContainerType == declaring ||
3714 ec.ContainerType.IsSubclassOf (declaring)))
3716 } if (prot == MethodAttributes.Family){
3717 if (!(ec.ContainerType == declaring ||
3718 ec.ContainerType.IsSubclassOf (declaring)))
3722 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3724 // Apply the same optimization as MS: skip the GetEnumerator
3725 // returning an IEnumerator, and use the one returning a
3726 // CharEnumerator instead. This allows us to avoid the
3727 // try-finally block and the boxing.
3732 // Ok, we can access it, now make sure that we can do something
3733 // with this `GetEnumerator'
3736 Type return_type = mi.ReturnType;
3737 if (mi.ReturnType == TypeManager.ienumerator_type ||
3738 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3739 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3742 // If it is not an interface, lets try to find the methods ourselves.
3743 // For example, if we have:
3744 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3745 // We can avoid the iface call. This is a runtime perf boost.
3746 // even bigger if we have a ValueType, because we avoid the cost
3749 // We have to make sure that both methods exist for us to take
3750 // this path. If one of the methods does not exist, we will just
3751 // use the interface. Sadly, this complex if statement is the only
3752 // way I could do this without a goto
3755 if (return_type.IsInterface ||
3756 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3757 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3759 hm.move_next = TypeManager.bool_movenext_void;
3760 hm.get_current = TypeManager.object_getcurrent_void;
3767 // Ok, so they dont return an IEnumerable, we will have to
3768 // find if they support the GetEnumerator pattern.
3771 hm.move_next = FetchMethodMoveNext (return_type);
3772 if (hm.move_next == null)
3775 hm.get_current = FetchMethodGetCurrent (return_type);
3776 if (hm.get_current == null)
3780 hm.element_type = hm.get_current.ReturnType;
3781 hm.enumerator_type = return_type;
3782 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3783 TypeManager.ImplementsInterface (
3784 hm.enumerator_type, TypeManager.idisposable_type);
3790 /// This filter is used to find the GetEnumerator method
3791 /// on which IEnumerator operates
3793 static MemberFilter FilterEnumerator;
3797 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3800 void error1579 (Type t)
3802 Report.Error (1579, loc,
3803 "foreach statement cannot operate on variables of type `" +
3804 t.FullName + "' because that class does not provide a " +
3805 " GetEnumerator method or it is inaccessible");
3808 static bool TryType (Type t, ForeachHelperMethods hm)
3812 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3813 BindingFlags.Public | BindingFlags.NonPublic |
3814 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3815 FilterEnumerator, hm);
3820 hm.get_enumerator = (MethodInfo) mi [0];
3825 // Looks for a usable GetEnumerator in the Type, and if found returns
3826 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3828 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3830 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3832 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3833 if (TryType (tt, hm))
3839 // Now try to find the method in the interfaces
3842 Type [] ifaces = t.GetInterfaces ();
3844 foreach (Type i in ifaces){
3845 if (TryType (i, hm))
3850 // Since TypeBuilder.GetInterfaces only returns the interface
3851 // types for this type, we have to keep looping, but once
3852 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3853 // done, because it returns all the types
3855 if ((t is TypeBuilder))
3865 // FIXME: possible optimization.
3866 // We might be able to avoid creating `empty' if the type is the sam
3868 bool EmitCollectionForeach (EmitContext ec)
3870 ILGenerator ig = ec.ig;
3871 VariableStorage enumerator, disposable;
3873 enumerator = new VariableStorage (ec, hm.enumerator_type);
3874 if (hm.is_disposable)
3875 disposable = new VariableStorage (ec, TypeManager.idisposable_type);
3879 enumerator.EmitThis ();
3881 // Instantiate the enumerator
3883 if (expr.Type.IsValueType){
3884 if (expr is IMemoryLocation){
3885 IMemoryLocation ml = (IMemoryLocation) expr;
3887 ml.AddressOf (ec, AddressOp.Load);
3889 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3890 " does not implement IMemoryLocation");
3891 ig.Emit (OpCodes.Call, hm.get_enumerator);
3894 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3896 enumerator.EmitStore ();
3899 // Protect the code in a try/finalize block, so that
3900 // if the beast implement IDisposable, we get rid of it
3902 if (hm.is_disposable)
3903 ig.BeginExceptionBlock ();
3905 Label end_try = ig.DefineLabel ();
3907 ig.MarkLabel (ec.LoopBegin);
3909 enumerator.EmitCall (hm.move_next);
3911 ig.Emit (OpCodes.Brfalse, end_try);
3915 enumerator.EmitCall (hm.get_current);
3919 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3921 ((IAssignMethod)variable).EmitAssign (ec, conv);
3923 statement.Emit (ec);
3924 ig.Emit (OpCodes.Br, ec.LoopBegin);
3925 ig.MarkLabel (end_try);
3927 // The runtime provides this for us.
3928 // ig.Emit (OpCodes.Leave, end);
3931 // Now the finally block
3933 if (hm.is_disposable) {
3934 Label end_finally = ig.DefineLabel ();
3935 ig.BeginFinallyBlock ();
3937 disposable.EmitThis ();
3938 enumerator.EmitThis ();
3939 enumerator.EmitLoad ();
3940 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3941 disposable.EmitStore ();
3942 disposable.EmitLoad ();
3943 ig.Emit (OpCodes.Brfalse, end_finally);
3944 disposable.EmitThis ();
3945 disposable.EmitLoad ();
3946 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3947 ig.MarkLabel (end_finally);
3949 // The runtime generates this anyways.
3950 // ig.Emit (OpCodes.Endfinally);
3952 ig.EndExceptionBlock ();
3955 ig.MarkLabel (ec.LoopEnd);
3960 // FIXME: possible optimization.
3961 // We might be able to avoid creating `empty' if the type is the sam
3963 bool EmitArrayForeach (EmitContext ec)
3965 int rank = array_type.GetArrayRank ();
3966 ILGenerator ig = ec.ig;
3968 VariableStorage copy = new VariableStorage (ec, array_type);
3971 // Make our copy of the array
3978 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
3982 counter.EmitThis ();
3983 ig.Emit (OpCodes.Ldc_I4_0);
3984 counter.EmitStore ();
3985 test = ig.DefineLabel ();
3986 ig.Emit (OpCodes.Br, test);
3988 loop = ig.DefineLabel ();
3989 ig.MarkLabel (loop);
3996 counter.EmitThis ();
3997 counter.EmitLoad ();
4000 // Load the value, we load the value using the underlying type,
4001 // then we use the variable.EmitAssign to load using the proper cast.
4003 ArrayAccess.EmitLoadOpcode (ig, element_type);
4006 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4008 ((IAssignMethod)variable).EmitAssign (ec, conv);
4010 statement.Emit (ec);
4012 ig.MarkLabel (ec.LoopBegin);
4013 counter.EmitThis ();
4014 counter.EmitThis ();
4015 counter.EmitLoad ();
4016 ig.Emit (OpCodes.Ldc_I4_1);
4017 ig.Emit (OpCodes.Add);
4018 counter.EmitStore ();
4020 ig.MarkLabel (test);
4021 counter.EmitThis ();
4022 counter.EmitLoad ();
4025 ig.Emit (OpCodes.Ldlen);
4026 ig.Emit (OpCodes.Conv_I4);
4027 ig.Emit (OpCodes.Blt, loop);
4029 VariableStorage [] dim_len = new VariableStorage [rank];
4030 VariableStorage [] dim_count = new VariableStorage [rank];
4031 Label [] loop = new Label [rank];
4032 Label [] test = new Label [rank];
4035 for (dim = 0; dim < rank; dim++){
4036 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4037 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4038 test [dim] = ig.DefineLabel ();
4039 loop [dim] = ig.DefineLabel ();
4042 for (dim = 0; dim < rank; dim++){
4043 dim_len [dim].EmitThis ();
4046 IntLiteral.EmitInt (ig, dim);
4047 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4048 dim_len [dim].EmitStore ();
4052 for (dim = 0; dim < rank; dim++){
4053 dim_count [dim].EmitThis ();
4054 ig.Emit (OpCodes.Ldc_I4_0);
4055 dim_count [dim].EmitStore ();
4056 ig.Emit (OpCodes.Br, test [dim]);
4057 ig.MarkLabel (loop [dim]);
4064 for (dim = 0; dim < rank; dim++){
4065 dim_count [dim].EmitThis ();
4066 dim_count [dim].EmitLoad ();
4070 // FIXME: Maybe we can cache the computation of `get'?
4072 Type [] args = new Type [rank];
4075 for (int i = 0; i < rank; i++)
4076 args [i] = TypeManager.int32_type;
4078 ModuleBuilder mb = CodeGen.Module.Builder;
4079 get = mb.GetArrayMethod (
4081 CallingConventions.HasThis| CallingConventions.Standard,
4083 ig.Emit (OpCodes.Call, get);
4086 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4088 ((IAssignMethod)variable).EmitAssign (ec, conv);
4089 statement.Emit (ec);
4090 ig.MarkLabel (ec.LoopBegin);
4091 for (dim = rank - 1; dim >= 0; dim--){
4092 dim_count [dim].EmitThis ();
4093 dim_count [dim].EmitThis ();
4094 dim_count [dim].EmitLoad ();
4095 ig.Emit (OpCodes.Ldc_I4_1);
4096 ig.Emit (OpCodes.Add);
4097 dim_count [dim].EmitStore ();
4099 ig.MarkLabel (test [dim]);
4100 dim_count [dim].EmitThis ();
4101 dim_count [dim].EmitLoad ();
4102 dim_len [dim].EmitThis ();
4103 dim_len [dim].EmitLoad ();
4104 ig.Emit (OpCodes.Blt, loop [dim]);
4107 ig.MarkLabel (ec.LoopEnd);
4112 protected override void DoEmit (EmitContext ec)
4114 ILGenerator ig = ec.ig;
4116 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4117 ec.LoopBegin = ig.DefineLabel ();
4118 ec.LoopEnd = ig.DefineLabel ();
4121 EmitCollectionForeach (ec);
4123 EmitArrayForeach (ec);
4125 ec.LoopBegin = old_begin;
4126 ec.LoopEnd = old_end;