2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@ximian.com)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
9 // (C) 2003, 2004 Novell, Inc.
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Diagnostics;
18 namespace Mono.CSharp {
20 using System.Collections;
22 public abstract class Statement {
26 /// Resolves the statement, true means that all sub-statements
29 public virtual bool Resolve (EmitContext ec)
35 /// We already know that the statement is unreachable, but we still
36 /// need to resolve it to catch errors.
38 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
41 // This conflicts with csc's way of doing this, but IMHO it's
42 // the right thing to do.
44 // If something is unreachable, we still check whether it's
45 // correct. This means that you cannot use unassigned variables
46 // in unreachable code, for instance.
49 if (warn && (RootContext.WarningLevel >= 2))
50 Report.Warning (162, loc, "Unreachable code detected");
52 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
53 bool ok = Resolve (ec);
54 ec.KillFlowBranching ();
59 protected void CheckObsolete (Type type)
61 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
62 if (obsolete_attr == null)
65 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
69 /// Return value indicates whether all code paths emitted return.
71 protected abstract void DoEmit (EmitContext ec);
74 /// Utility wrapper routine for Error, just to beautify the code
76 public void Error (int error, string format, params object[] args)
78 Error (error, String.Format (format, args));
81 public void Error (int error, string s)
83 if (!Location.IsNull (loc))
84 Report.Error (error, loc, s);
86 Report.Error (error, s);
90 /// Return value indicates whether all code paths emitted return.
92 public virtual void Emit (EmitContext ec)
99 public sealed class EmptyStatement : Statement {
101 private EmptyStatement () {}
103 public static readonly EmptyStatement Value = new EmptyStatement ();
105 public override bool Resolve (EmitContext ec)
110 protected override void DoEmit (EmitContext ec)
115 public class If : Statement {
117 public Statement TrueStatement;
118 public Statement FalseStatement;
122 public If (Expression expr, Statement trueStatement, Location l)
125 TrueStatement = trueStatement;
129 public If (Expression expr,
130 Statement trueStatement,
131 Statement falseStatement,
135 TrueStatement = trueStatement;
136 FalseStatement = falseStatement;
140 public override bool Resolve (EmitContext ec)
142 Report.Debug (1, "START IF BLOCK", loc);
144 expr = Expression.ResolveBoolean (ec, expr, loc);
149 Assign ass = expr as Assign;
150 if (ass != null && ass.Source is Constant) {
151 Report.Warning (665, 3, loc, "Assignment in conditional expression is always constant; did you mean to use == instead of = ?");
155 // Dead code elimination
157 if (expr is BoolConstant){
158 bool take = ((BoolConstant) expr).Value;
161 if (!TrueStatement.Resolve (ec))
164 if ((FalseStatement != null) &&
165 !FalseStatement.ResolveUnreachable (ec, true))
167 FalseStatement = null;
169 if (!TrueStatement.ResolveUnreachable (ec, true))
171 TrueStatement = null;
173 if ((FalseStatement != null) &&
174 !FalseStatement.Resolve (ec))
181 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
183 bool ok = TrueStatement.Resolve (ec);
185 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
187 ec.CurrentBranching.CreateSibling ();
189 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
192 ec.EndFlowBranching ();
194 Report.Debug (1, "END IF BLOCK", loc);
199 protected override void DoEmit (EmitContext ec)
201 ILGenerator ig = ec.ig;
202 Label false_target = ig.DefineLabel ();
206 // If we're a boolean expression, Resolve() already
207 // eliminated dead code for us.
209 if (expr is BoolConstant){
210 bool take = ((BoolConstant) expr).Value;
213 TrueStatement.Emit (ec);
214 else if (FalseStatement != null)
215 FalseStatement.Emit (ec);
220 expr.EmitBranchable (ec, false_target, false);
222 TrueStatement.Emit (ec);
224 if (FalseStatement != null){
225 bool branch_emitted = false;
227 end = ig.DefineLabel ();
229 ig.Emit (OpCodes.Br, end);
230 branch_emitted = true;
233 ig.MarkLabel (false_target);
234 FalseStatement.Emit (ec);
239 ig.MarkLabel (false_target);
244 public class Do : Statement {
245 public Expression expr;
246 public readonly Statement EmbeddedStatement;
249 public Do (Statement statement, Expression boolExpr, Location l)
252 EmbeddedStatement = statement;
256 public override bool Resolve (EmitContext ec)
260 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
262 if (!EmbeddedStatement.Resolve (ec))
265 expr = Expression.ResolveBoolean (ec, expr, loc);
268 else if (expr is BoolConstant){
269 bool res = ((BoolConstant) expr).Value;
275 ec.CurrentBranching.Infinite = infinite;
276 ec.EndFlowBranching ();
281 protected override void DoEmit (EmitContext ec)
283 ILGenerator ig = ec.ig;
284 Label loop = ig.DefineLabel ();
285 Label old_begin = ec.LoopBegin;
286 Label old_end = ec.LoopEnd;
288 ec.LoopBegin = ig.DefineLabel ();
289 ec.LoopEnd = ig.DefineLabel ();
292 EmbeddedStatement.Emit (ec);
293 ig.MarkLabel (ec.LoopBegin);
296 // Dead code elimination
298 if (expr is BoolConstant){
299 bool res = ((BoolConstant) expr).Value;
302 ec.ig.Emit (OpCodes.Br, loop);
304 expr.EmitBranchable (ec, loop, true);
306 ig.MarkLabel (ec.LoopEnd);
308 ec.LoopBegin = old_begin;
309 ec.LoopEnd = old_end;
313 public class While : Statement {
314 public Expression expr;
315 public readonly Statement Statement;
316 bool infinite, empty;
318 public While (Expression boolExpr, Statement statement, Location l)
320 this.expr = boolExpr;
321 Statement = statement;
325 public override bool Resolve (EmitContext ec)
329 expr = Expression.ResolveBoolean (ec, expr, loc);
334 // Inform whether we are infinite or not
336 if (expr is BoolConstant){
337 BoolConstant bc = (BoolConstant) expr;
339 if (bc.Value == false){
340 if (!Statement.ResolveUnreachable (ec, true))
348 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
350 if (!Statement.Resolve (ec))
353 ec.CurrentBranching.Infinite = infinite;
354 ec.EndFlowBranching ();
359 protected override void DoEmit (EmitContext ec)
364 ILGenerator ig = ec.ig;
365 Label old_begin = ec.LoopBegin;
366 Label old_end = ec.LoopEnd;
368 ec.LoopBegin = ig.DefineLabel ();
369 ec.LoopEnd = ig.DefineLabel ();
372 // Inform whether we are infinite or not
374 if (expr is BoolConstant){
375 ig.MarkLabel (ec.LoopBegin);
377 ig.Emit (OpCodes.Br, ec.LoopBegin);
380 // Inform that we are infinite (ie, `we return'), only
381 // if we do not `break' inside the code.
383 ig.MarkLabel (ec.LoopEnd);
385 Label while_loop = ig.DefineLabel ();
387 ig.Emit (OpCodes.Br, ec.LoopBegin);
388 ig.MarkLabel (while_loop);
392 ig.MarkLabel (ec.LoopBegin);
394 expr.EmitBranchable (ec, while_loop, true);
396 ig.MarkLabel (ec.LoopEnd);
399 ec.LoopBegin = old_begin;
400 ec.LoopEnd = old_end;
404 public class For : Statement {
406 readonly Statement InitStatement;
407 readonly Statement Increment;
408 readonly Statement Statement;
409 bool infinite, empty;
411 public For (Statement initStatement,
417 InitStatement = initStatement;
419 Increment = increment;
420 Statement = statement;
424 public override bool Resolve (EmitContext ec)
428 if (InitStatement != null){
429 if (!InitStatement.Resolve (ec))
434 Test = Expression.ResolveBoolean (ec, Test, loc);
437 else if (Test is BoolConstant){
438 BoolConstant bc = (BoolConstant) Test;
440 if (bc.Value == false){
441 if (!Statement.ResolveUnreachable (ec, true))
443 if ((Increment != null) &&
444 !Increment.ResolveUnreachable (ec, false))
454 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
456 ec.CurrentBranching.CreateSibling ();
458 if (!Statement.Resolve (ec))
461 if (Increment != null){
462 if (!Increment.Resolve (ec))
466 ec.CurrentBranching.Infinite = infinite;
467 ec.EndFlowBranching ();
472 protected override void DoEmit (EmitContext ec)
477 ILGenerator ig = ec.ig;
478 Label old_begin = ec.LoopBegin;
479 Label old_end = ec.LoopEnd;
480 Label loop = ig.DefineLabel ();
481 Label test = ig.DefineLabel ();
483 if (InitStatement != null && InitStatement != EmptyStatement.Value)
484 InitStatement.Emit (ec);
486 ec.LoopBegin = ig.DefineLabel ();
487 ec.LoopEnd = ig.DefineLabel ();
489 ig.Emit (OpCodes.Br, test);
493 ig.MarkLabel (ec.LoopBegin);
494 if (Increment != EmptyStatement.Value)
499 // If test is null, there is no test, and we are just
504 // The Resolve code already catches the case for
505 // Test == BoolConstant (false) so we know that
508 if (Test is BoolConstant)
509 ig.Emit (OpCodes.Br, loop);
511 Test.EmitBranchable (ec, loop, true);
514 ig.Emit (OpCodes.Br, loop);
515 ig.MarkLabel (ec.LoopEnd);
517 ec.LoopBegin = old_begin;
518 ec.LoopEnd = old_end;
522 public class StatementExpression : Statement {
523 ExpressionStatement expr;
525 public StatementExpression (ExpressionStatement expr, Location l)
531 public override bool Resolve (EmitContext ec)
533 expr = expr.ResolveStatement (ec);
537 protected override void DoEmit (EmitContext ec)
539 expr.EmitStatement (ec);
542 public override string ToString ()
544 return "StatementExpression (" + expr + ")";
549 /// Implements the return statement
551 public class Return : Statement {
552 public Expression Expr;
554 public Return (Expression expr, Location l)
562 public override bool Resolve (EmitContext ec)
564 if (ec.ReturnType == null){
566 if (ec.CurrentAnonymousMethod != null){
567 Report.Error (1662, loc, String.Format (
568 "Anonymous method could not be converted to delegate " +
569 "since the return value does not match the delegate value"));
571 Error (127, "Return with a value not allowed here");
576 Error (126, "An object of type `{0}' is expected " +
577 "for the return statement",
578 TypeManager.CSharpName (ec.ReturnType));
582 Expr = Expr.Resolve (ec);
586 if (Expr.Type != ec.ReturnType) {
587 Expr = Convert.ImplicitConversionRequired (
588 ec, Expr, ec.ReturnType, loc);
595 Error (-206, "Return statement not allowed inside iterators");
599 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
601 if (ec.CurrentBranching.InTryOrCatch (true)) {
602 ec.CurrentBranching.AddFinallyVector (vector);
604 } else if (ec.CurrentBranching.InFinally (true)) {
605 Error (157, "Control can not leave the body of the finally block");
608 vector.CheckOutParameters (ec.CurrentBranching);
611 ec.NeedReturnLabel ();
613 ec.CurrentBranching.CurrentUsageVector.Return ();
617 protected override void DoEmit (EmitContext ec)
623 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
627 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
629 ec.ig.Emit (OpCodes.Ret);
633 public class Goto : Statement {
636 LabeledStatement label;
638 public override bool Resolve (EmitContext ec)
640 label = ec.CurrentBranching.LookupLabel (target, loc);
644 // If this is a forward goto.
645 if (!label.IsDefined)
646 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
648 ec.CurrentBranching.CurrentUsageVector.Goto ();
649 label.AddReference ();
654 public Goto (Block parent_block, string label, Location l)
656 block = parent_block;
661 public string Target {
667 protected override void DoEmit (EmitContext ec)
669 Label l = label.LabelTarget (ec);
670 ec.ig.Emit (OpCodes.Br, l);
674 public class LabeledStatement : Statement {
675 public readonly Location Location;
681 FlowBranching.UsageVector vectors;
683 public LabeledStatement (string label_name, Location l)
688 public Label LabelTarget (EmitContext ec)
693 label = ec.ig.DefineLabel ();
699 public bool IsDefined {
705 public bool HasBeenReferenced {
711 public void AddUsageVector (FlowBranching.UsageVector vector)
713 vector = vector.Clone ();
714 vector.Next = vectors;
718 public override bool Resolve (EmitContext ec)
720 ec.CurrentBranching.Label (vectors);
725 protected override void DoEmit (EmitContext ec)
727 if (ig != null && ig != ec.ig) {
728 Report.Error (1632, "Control cannot leave body of anonymous method");
732 ec.ig.MarkLabel (label);
735 public void AddReference ()
743 /// `goto default' statement
745 public class GotoDefault : Statement {
747 public GotoDefault (Location l)
752 public override bool Resolve (EmitContext ec)
754 ec.CurrentBranching.CurrentUsageVector.Goto ();
758 protected override void DoEmit (EmitContext ec)
760 if (ec.Switch == null){
761 Report.Error (153, loc, "goto default is only valid in a switch statement");
765 if (!ec.Switch.GotDefault){
766 Report.Error (159, loc, "No default target on switch statement");
769 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
774 /// `goto case' statement
776 public class GotoCase : Statement {
780 public GotoCase (Expression e, Location l)
786 public override bool Resolve (EmitContext ec)
788 if (ec.Switch == null){
789 Report.Error (153, loc, "goto case is only valid in a switch statement");
793 expr = expr.Resolve (ec);
797 if (!(expr is Constant)){
798 Report.Error (159, loc, "Target expression for goto case is not constant");
802 object val = Expression.ConvertIntLiteral (
803 (Constant) expr, ec.Switch.SwitchType, loc);
808 sl = (SwitchLabel) ec.Switch.Elements [val];
813 "No such label 'case " + val + "': for the goto case");
817 ec.CurrentBranching.CurrentUsageVector.Goto ();
821 protected override void DoEmit (EmitContext ec)
823 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
827 public class Throw : Statement {
830 public Throw (Expression expr, Location l)
836 public override bool Resolve (EmitContext ec)
838 ec.CurrentBranching.CurrentUsageVector.Throw ();
841 expr = expr.Resolve (ec);
845 ExprClass eclass = expr.eclass;
847 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
848 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
849 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
855 if ((t != TypeManager.exception_type) &&
856 !t.IsSubclassOf (TypeManager.exception_type) &&
857 !(expr is NullLiteral)) {
859 "The type caught or thrown must be derived " +
860 "from System.Exception");
866 if (ec.CurrentBranching.InFinally (true)) {
867 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
871 if (!ec.CurrentBranching.InCatch ()) {
872 Error (156, "A throw statement with no argument is only allowed in a catch clause");
878 protected override void DoEmit (EmitContext ec)
881 ec.ig.Emit (OpCodes.Rethrow);
885 ec.ig.Emit (OpCodes.Throw);
890 public class Break : Statement {
892 public Break (Location l)
899 public override bool Resolve (EmitContext ec)
901 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
902 Error (139, "No enclosing loop or switch to continue to");
904 } else if (ec.CurrentBranching.InFinally (false)) {
905 Error (157, "Control can not leave the body of the finally block");
907 } else if (ec.CurrentBranching.InTryOrCatch (false))
908 ec.CurrentBranching.AddFinallyVector (
909 ec.CurrentBranching.CurrentUsageVector);
910 else if (ec.CurrentBranching.InLoop ())
911 ec.CurrentBranching.AddBreakVector (
912 ec.CurrentBranching.CurrentUsageVector);
914 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
917 ec.NeedReturnLabel ();
919 ec.CurrentBranching.CurrentUsageVector.Break ();
923 protected override void DoEmit (EmitContext ec)
925 ILGenerator ig = ec.ig;
928 ig.Emit (OpCodes.Leave, ec.LoopEnd);
930 ig.Emit (OpCodes.Br, ec.LoopEnd);
935 public class Continue : Statement {
937 public Continue (Location l)
944 public override bool Resolve (EmitContext ec)
946 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
947 Error (139, "No enclosing loop to continue to");
949 } else if (ec.CurrentBranching.InFinally (false)) {
950 Error (157, "Control can not leave the body of the finally block");
952 } else if (ec.CurrentBranching.InTryOrCatch (false))
953 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
955 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
957 ec.CurrentBranching.CurrentUsageVector.Goto ();
961 protected override void DoEmit (EmitContext ec)
963 Label begin = ec.LoopBegin;
966 ec.ig.Emit (OpCodes.Leave, begin);
968 ec.ig.Emit (OpCodes.Br, begin);
973 // The information about a user-perceived local variable
975 public class LocalInfo {
976 public Expression Type;
979 // Most of the time a variable will be stored in a LocalBuilder
981 // But sometimes, it will be stored in a field (variables that have been
982 // hoisted by iterators or by anonymous methods). The context of the field will
983 // be stored in the EmitContext
986 public LocalBuilder LocalBuilder;
987 public FieldBuilder FieldBuilder;
989 public Type VariableType;
990 public readonly string Name;
991 public readonly Location Location;
992 public readonly Block Block;
994 public VariableInfo VariableInfo;
1007 public LocalInfo (Expression type, string name, Block block, Location l)
1015 public LocalInfo (TypeContainer tc, Block block, Location l)
1017 VariableType = tc.TypeBuilder;
1022 public bool IsThisAssigned (EmitContext ec, Location loc)
1024 if (VariableInfo == null)
1025 throw new Exception ();
1027 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1030 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1033 public bool IsAssigned (EmitContext ec)
1035 if (VariableInfo == null)
1036 throw new Exception ();
1038 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1041 public bool Resolve (EmitContext ec)
1043 if (VariableType == null) {
1044 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1048 VariableType = texpr.ResolveType (ec);
1051 if (VariableType == TypeManager.void_type) {
1052 Report.Error (1547, Location,
1053 "Keyword 'void' cannot be used in this context");
1057 if (VariableType.IsAbstract && VariableType.IsSealed) {
1058 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1061 // TODO: breaks the build
1062 // if (VariableType.IsPointer && !ec.InUnsafe)
1063 // Expression.UnsafeError (Location);
1069 // Whether the variable is Fixed (because its Pinned or its a value type)
1071 public bool IsFixed {
1073 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1080 public bool IsCaptured {
1082 return (flags & Flags.Captured) != 0;
1086 flags |= Flags.Captured;
1090 public bool AddressTaken {
1092 return (flags & Flags.AddressTaken) != 0;
1096 flags |= Flags.AddressTaken;
1100 public override string ToString ()
1102 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1103 Name, Type, VariableInfo, Location);
1108 return (flags & Flags.Used) != 0;
1111 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1115 public bool ReadOnly {
1117 return (flags & Flags.ReadOnly) != 0;
1120 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1125 // Whether the variable is pinned, if Pinned the variable has been
1126 // allocated in a pinned slot with DeclareLocal.
1128 public bool Pinned {
1130 return (flags & Flags.Pinned) != 0;
1133 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1137 public bool IsThis {
1139 return (flags & Flags.IsThis) != 0;
1142 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1148 /// Block represents a C# block.
1152 /// This class is used in a number of places: either to represent
1153 /// explicit blocks that the programmer places or implicit blocks.
1155 /// Implicit blocks are used as labels or to introduce variable
1158 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1159 /// they contain extra information that is not necessary on normal blocks.
1161 public class Block : Statement {
1162 public Block Parent;
1163 public readonly Location StartLocation;
1164 public Location EndLocation = Location.Null;
1171 VariablesInitialized = 8,
1180 public bool Implicit {
1182 return (flags & Flags.Implicit) != 0;
1186 public bool Unchecked {
1188 return (flags & Flags.Unchecked) != 0;
1191 flags |= Flags.Unchecked;
1195 public bool Unsafe {
1197 return (flags & Flags.Unsafe) != 0;
1200 flags |= Flags.Unsafe;
1204 public bool HasVarargs {
1207 return Parent.HasVarargs;
1209 return (flags & Flags.HasVarargs) != 0;
1212 flags |= Flags.HasVarargs;
1217 // The statements in this block
1219 ArrayList statements;
1223 // An array of Blocks. We keep track of children just
1224 // to generate the local variable declarations.
1226 // Statements and child statements are handled through the
1232 // Labels. (label, block) pairs.
1237 // Keeps track of (name, type) pairs
1239 Hashtable variables;
1242 // Keeps track of constants
1243 Hashtable constants;
1246 // The parameters for the block, this is only needed on the toplevel block really
1247 // TODO: move `parameters' into ToplevelBlock
1248 Parameters parameters;
1251 // If this is a switch section, the enclosing switch block.
1255 protected static int id;
1259 public Block (Block parent)
1260 : this (parent, (Flags) 0, Location.Null, Location.Null)
1263 public Block (Block parent, Flags flags)
1264 : this (parent, flags, Location.Null, Location.Null)
1267 public Block (Block parent, Flags flags, Parameters parameters)
1268 : this (parent, flags, parameters, Location.Null, Location.Null)
1271 public Block (Block parent, Location start, Location end)
1272 : this (parent, (Flags) 0, start, end)
1275 public Block (Block parent, Parameters parameters, Location start, Location end)
1276 : this (parent, (Flags) 0, parameters, start, end)
1279 public Block (Block parent, Flags flags, Location start, Location end)
1280 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1283 public Block (Block parent, Flags flags, Parameters parameters,
1284 Location start, Location end)
1287 parent.AddChild (this);
1289 this.Parent = parent;
1291 this.parameters = parameters;
1292 this.StartLocation = start;
1293 this.EndLocation = end;
1296 statements = new ArrayList ();
1298 if (parent != null && Implicit) {
1299 if (parent.child_variable_names == null)
1300 parent.child_variable_names = new Hashtable();
1301 // share with parent
1302 child_variable_names = parent.child_variable_names;
1307 public Block CreateSwitchBlock (Location start)
1309 Block new_block = new Block (this, start, start);
1310 new_block.switch_block = this;
1320 void AddChild (Block b)
1322 if (children == null)
1323 children = new ArrayList ();
1328 public void SetEndLocation (Location loc)
1334 /// Adds a label to the current block.
1338 /// false if the name already exists in this block. true
1342 public bool AddLabel (string name, LabeledStatement target, Location loc)
1344 if (switch_block != null)
1345 return switch_block.AddLabel (name, target, loc);
1348 while (cur != null) {
1349 if (cur.DoLookupLabel (name) != null) {
1351 140, loc, "The label '{0}' is a duplicate",
1362 while (cur != null) {
1363 if (cur.DoLookupLabel (name) != null) {
1366 "The label '{0}' shadows another label " +
1367 "by the same name in a containing scope.",
1372 if (children != null) {
1373 foreach (Block b in children) {
1374 LabeledStatement s = b.DoLookupLabel (name);
1380 "The label '{0}' shadows another " +
1381 "label by the same name in a " +
1382 "containing scope.",
1393 labels = new Hashtable ();
1395 labels.Add (name, target);
1399 public LabeledStatement LookupLabel (string name)
1401 LabeledStatement s = DoLookupLabel (name);
1405 if (children == null)
1408 foreach (Block child in children) {
1409 if (!child.Implicit)
1412 s = child.LookupLabel (name);
1420 LabeledStatement DoLookupLabel (string name)
1422 if (switch_block != null)
1423 return switch_block.LookupLabel (name);
1426 if (labels.Contains (name))
1427 return ((LabeledStatement) labels [name]);
1432 LocalInfo this_variable = null;
1435 // Returns the "this" instance variable of this block.
1436 // See AddThisVariable() for more information.
1438 public LocalInfo ThisVariable {
1440 for (Block b = this; b != null; b = b.Parent) {
1441 if (b.this_variable != null)
1442 return b.this_variable;
1449 Hashtable child_variable_names;
1452 // Marks a variable with name @name as being used in a child block.
1453 // If a variable name has been used in a child block, it's illegal to
1454 // declare a variable with the same name in the current block.
1456 public void AddChildVariableName (string name)
1458 if (child_variable_names == null)
1459 child_variable_names = new Hashtable ();
1461 child_variable_names [name] = null;
1465 // Checks whether a variable name has already been used in a child block.
1467 public bool IsVariableNameUsedInChildBlock (string name)
1469 if (child_variable_names == null)
1472 return child_variable_names.Contains (name);
1476 // This is used by non-static `struct' constructors which do not have an
1477 // initializer - in this case, the constructor must initialize all of the
1478 // struct's fields. To do this, we add a "this" variable and use the flow
1479 // analysis code to ensure that it's been fully initialized before control
1480 // leaves the constructor.
1482 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1484 if (this_variable != null)
1485 return this_variable;
1487 if (variables == null)
1488 variables = new Hashtable ();
1490 this_variable = new LocalInfo (tc, this, l);
1491 this_variable.Used = true;
1492 this_variable.IsThis = true;
1494 variables.Add ("this", this_variable);
1496 return this_variable;
1499 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1501 if (variables == null)
1502 variables = new Hashtable ();
1504 LocalInfo vi = GetLocalInfo (name);
1506 if (vi.Block != this)
1507 Report.Error (136, l, "A local variable named `" + name + "' " +
1508 "cannot be declared in this scope since it would " +
1509 "give a different meaning to `" + name + "', which " +
1510 "is already used in a `parent or current' scope to " +
1511 "denote something else");
1513 Report.Error (128, l, "A local variable `" + name + "' is already " +
1514 "defined in this scope");
1518 if (IsVariableNameUsedInChildBlock (name)) {
1519 Report.Error (136, l, "A local variable named `" + name + "' " +
1520 "cannot be declared in this scope since it would " +
1521 "give a different meaning to `" + name + "', which " +
1522 "is already used in a `child' scope to denote something " +
1529 Parameter p = pars.GetParameterByName (name, out idx);
1531 Report.Error (136, l, "A local variable named `" + name + "' " +
1532 "cannot be declared in this scope since it would " +
1533 "give a different meaning to `" + name + "', which " +
1534 "is already used in a `parent or current' scope to " +
1535 "denote something else");
1540 vi = new LocalInfo (type, name, this, l);
1542 variables.Add (name, vi);
1544 // Mark 'name' as "used by a child block" in every surrounding block
1546 while (cur != null && cur.Implicit)
1549 for (Block par = cur.Parent; par != null; par = par.Parent)
1550 par.AddChildVariableName (name);
1552 if ((flags & Flags.VariablesInitialized) != 0)
1553 throw new Exception ();
1555 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1559 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1561 if (AddVariable (type, name, pars, l) == null)
1564 if (constants == null)
1565 constants = new Hashtable ();
1567 constants.Add (name, value);
1571 public Hashtable Variables {
1577 public LocalInfo GetLocalInfo (string name)
1579 for (Block b = this; b != null; b = b.Parent) {
1580 if (b.variables != null) {
1581 LocalInfo ret = b.variables [name] as LocalInfo;
1589 public Expression GetVariableType (string name)
1591 LocalInfo vi = GetLocalInfo (name);
1599 public Expression GetConstantExpression (string name)
1601 for (Block b = this; b != null; b = b.Parent) {
1602 if (b.constants != null) {
1603 Expression ret = b.constants [name] as Expression;
1612 /// True if the variable named @name is a constant
1614 public bool IsConstant (string name)
1616 Expression e = null;
1618 e = GetConstantExpression (name);
1624 // Returns a `ParameterReference' for the given name, or null if there
1625 // is no such parameter
1627 public ParameterReference GetParameterReference (string name, Location loc)
1632 Parameters pars = b.parameters;
1638 par = pars.GetParameterByName (name, out idx);
1640 ParameterReference pr;
1642 pr = new ParameterReference (pars, this, idx, name, loc);
1647 } while (b != null);
1652 // Whether the parameter named `name' is local to this block,
1653 // or false, if the parameter belongs to an encompassing block.
1655 public bool IsLocalParameter (string name)
1658 int toplevel_count = 0;
1661 if (this is ToplevelBlock)
1664 Parameters pars = b.parameters;
1666 if (pars.GetParameterByName (name) != null)
1670 if (toplevel_count > 0)
1673 } while (b != null);
1678 // Whether the `name' is a parameter reference
1680 public bool IsParameterReference (string name)
1685 Parameters pars = b.parameters;
1688 if (pars.GetParameterByName (name) != null)
1691 } while (b != null);
1696 /// A list of labels that were not used within this block
1698 public string [] GetUnreferenced ()
1700 // FIXME: Implement me
1704 public void AddStatement (Statement s)
1707 flags |= Flags.BlockUsed;
1712 return (flags & Flags.BlockUsed) != 0;
1718 flags |= Flags.BlockUsed;
1721 public bool HasRet {
1723 return (flags & Flags.HasRet) != 0;
1727 public bool IsDestructor {
1729 return (flags & Flags.IsDestructor) != 0;
1733 public void SetDestructor ()
1735 flags |= Flags.IsDestructor;
1738 VariableMap param_map, local_map;
1740 public VariableMap ParameterMap {
1742 if ((flags & Flags.VariablesInitialized) == 0)
1743 throw new Exception ("Variables have not been initialized yet");
1749 public VariableMap LocalMap {
1751 if ((flags & Flags.VariablesInitialized) == 0)
1752 throw new Exception ("Variables have not been initialized yet");
1759 /// Emits the variable declarations and labels.
1762 /// tc: is our typecontainer (to resolve type references)
1763 /// ig: is the code generator:
1765 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1767 bool old_unsafe = ec.InUnsafe;
1769 // If some parent block was unsafe, we remain unsafe even if this block
1770 // isn't explicitly marked as such.
1771 ec.InUnsafe |= Unsafe;
1774 // Compute the VariableMap's.
1776 // Unfortunately, we don't know the type when adding variables with
1777 // AddVariable(), so we need to compute this info here.
1781 if (variables != null) {
1782 foreach (LocalInfo li in variables.Values)
1785 locals = new LocalInfo [variables.Count];
1786 variables.Values.CopyTo (locals, 0);
1788 locals = new LocalInfo [0];
1791 local_map = new VariableMap (Parent.LocalMap, locals);
1793 local_map = new VariableMap (locals);
1795 param_map = new VariableMap (ip);
1796 flags |= Flags.VariablesInitialized;
1798 bool old_check_state = ec.ConstantCheckState;
1799 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1802 // Process this block variables
1804 if (variables != null){
1805 foreach (DictionaryEntry de in variables){
1806 string name = (string) de.Key;
1807 LocalInfo vi = (LocalInfo) de.Value;
1809 if (vi.VariableType == null)
1812 Type variable_type = vi.VariableType;
1814 if (variable_type.IsPointer){
1816 // Am not really convinced that this test is required (Microsoft does it)
1817 // but the fact is that you would not be able to use the pointer variable
1820 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1827 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1830 // This is needed to compile on both .NET 1.x and .NET 2.x
1831 // the later introduced `DeclareLocal (Type t, bool pinned)'
1833 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1834 else if (!vi.IsThis)
1835 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1838 if (constants == null)
1841 Expression cv = (Expression) constants [name];
1845 ec.CurrentBlock = this;
1846 Expression e = cv.Resolve (ec);
1850 Constant ce = e as Constant;
1852 Report.Error (133, vi.Location,
1853 "The expression being assigned to `" +
1854 name + "' must be constant (" + e + ")");
1858 if (e.Type != variable_type){
1859 e = Const.ChangeType (vi.Location, ce, variable_type);
1864 constants.Remove (name);
1865 constants.Add (name, e);
1868 ec.ConstantCheckState = old_check_state;
1871 // Now, handle the children
1873 if (children != null){
1874 foreach (Block b in children)
1875 b.ResolveMeta (toplevel, ec, ip);
1877 ec.InUnsafe = old_unsafe;
1881 // Emits the local variable declarations for a block
1883 public void EmitMeta (EmitContext ec)
1885 ILGenerator ig = ec.ig;
1887 if (variables != null){
1888 bool have_captured_vars = ec.HaveCapturedVariables ();
1889 bool remap_locals = ec.RemapToProxy;
1891 foreach (DictionaryEntry de in variables){
1892 LocalInfo vi = (LocalInfo) de.Value;
1894 if (have_captured_vars && ec.IsCaptured (vi))
1898 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1902 // This is needed to compile on both .NET 1.x and .NET 2.x
1903 // the later introduced `DeclareLocal (Type t, bool pinned)'
1905 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1906 else if (!vi.IsThis)
1907 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1912 if (children != null){
1913 foreach (Block b in children)
1918 void UsageWarning (FlowBranching.UsageVector vector)
1922 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1923 foreach (DictionaryEntry de in variables){
1924 LocalInfo vi = (LocalInfo) de.Value;
1929 name = (string) de.Key;
1931 if (vector.IsAssigned (vi.VariableInfo)){
1932 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1934 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1940 bool unreachable_shown;
1942 public override bool Resolve (EmitContext ec)
1944 Block prev_block = ec.CurrentBlock;
1947 int errors = Report.Errors;
1949 ec.CurrentBlock = this;
1950 ec.StartFlowBranching (this);
1952 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1954 bool unreachable = unreachable_shown;
1956 int statement_count = statements.Count;
1957 for (int ix = 0; ix < statement_count; ix++){
1958 Statement s = (Statement) statements [ix];
1960 if (unreachable && !(s is LabeledStatement)) {
1961 if (s == EmptyStatement.Value)
1962 s.loc = EndLocation;
1964 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1967 if (s != EmptyStatement.Value)
1968 unreachable_shown = true;
1970 s.loc = Location.Null;
1972 if (ok && !(s is Block)) {
1973 statements [ix] = EmptyStatement.Value;
1978 if (s.Resolve (ec) == false) {
1980 statements [ix] = EmptyStatement.Value;
1984 num_statements = ix + 1;
1986 if (s is LabeledStatement)
1987 unreachable = false;
1989 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1992 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1993 ec.CurrentBranching, statement_count, num_statements);
1996 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1998 ec.CurrentBlock = prev_block;
2000 // If we're a non-static `struct' constructor which doesn't have an
2001 // initializer, then we must initialize all of the struct's fields.
2002 if ((this_variable != null) &&
2003 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
2004 !this_variable.IsThisAssigned (ec, loc))
2007 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2008 foreach (LabeledStatement label in labels.Values)
2009 if (!label.HasBeenReferenced)
2010 Report.Warning (164, label.Location,
2011 "This label has not been referenced");
2014 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2016 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2017 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2018 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2019 flags |= Flags.HasRet;
2021 if (ok && (errors == Report.Errors)) {
2022 if (RootContext.WarningLevel >= 3)
2023 UsageWarning (vector);
2029 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2031 unreachable_shown = true;
2033 if (warn && (RootContext.WarningLevel >= 2))
2034 Report.Warning (162, loc, "Unreachable code detected");
2037 return Resolve (ec);
2039 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
2040 bool ok = Resolve (ec);
2041 ec.KillFlowBranching ();
2046 protected override void DoEmit (EmitContext ec)
2048 for (int ix = 0; ix < num_statements; ix++){
2049 Statement s = (Statement) statements [ix];
2051 // Check whether we are the last statement in a
2054 if (((Parent == null) || Implicit) && (ix+1 == num_statements) && !(s is Block))
2055 ec.IsLastStatement = true;
2057 ec.IsLastStatement = false;
2063 public override void Emit (EmitContext ec)
2065 Block prev_block = ec.CurrentBlock;
2067 ec.CurrentBlock = this;
2069 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2070 bool is_lexical_block = !Implicit && (Parent != null);
2072 if (emit_debug_info) {
2073 if (is_lexical_block)
2074 ec.ig.BeginScope ();
2076 if (variables != null) {
2077 foreach (DictionaryEntry de in variables) {
2078 string name = (string) de.Key;
2079 LocalInfo vi = (LocalInfo) de.Value;
2081 if (vi.LocalBuilder == null)
2084 ec.DefineLocalVariable (name, vi.LocalBuilder);
2089 ec.Mark (StartLocation, true);
2091 ec.Mark (EndLocation, true);
2093 if (emit_debug_info && is_lexical_block)
2096 ec.CurrentBlock = prev_block;
2099 public ToplevelBlock Toplevel {
2102 while (b.Parent != null){
2103 if ((b.flags & Flags.IsToplevel) != 0)
2108 return (ToplevelBlock) b;
2113 // Returns true if we ar ea child of `b'.
2115 public bool IsChildOf (Block b)
2117 Block current = this;
2120 if (current.Parent == b)
2122 current = current.Parent;
2123 } while (current != null);
2129 // A toplevel block contains extra information, the split is done
2130 // only to separate information that would otherwise bloat the more
2131 // lightweight Block.
2133 // In particular, this was introduced when the support for Anonymous
2134 // Methods was implemented.
2136 public class ToplevelBlock : Block {
2138 // Pointer to the host of this anonymous method, or null
2139 // if we are the topmost block
2141 public ToplevelBlock Container;
2142 CaptureContext capture_context;
2144 Hashtable capture_contexts;
2149 public void RegisterCaptureContext (CaptureContext cc)
2151 if (capture_contexts == null)
2152 capture_contexts = new Hashtable ();
2153 capture_contexts [cc] = cc;
2156 public void CompleteContexts ()
2158 if (capture_contexts == null)
2161 foreach (CaptureContext cc in capture_contexts.Keys){
2166 public CaptureContext ToplevelBlockCaptureContext {
2168 return capture_context;
2173 // Parent is only used by anonymous blocks to link back to their
2176 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2177 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2179 Container = container;
2182 public ToplevelBlock (Parameters parameters, Location start) :
2183 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2187 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2188 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2192 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2196 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2198 if (capture_context == null)
2199 capture_context = new CaptureContext (this, loc, host);
2202 public CaptureContext CaptureContext {
2204 return capture_context;
2209 public class SwitchLabel {
2212 public Location loc;
2216 Label il_label_code;
2217 bool il_label_code_set;
2220 // if expr == null, then it is the default case.
2222 public SwitchLabel (Expression expr, Location l)
2228 public Expression Label {
2234 public object Converted {
2240 public Label GetILLabel (EmitContext ec)
2243 il_label = ec.ig.DefineLabel ();
2244 il_label_set = true;
2249 public Label GetILLabelCode (EmitContext ec)
2251 if (!il_label_code_set){
2252 il_label_code = ec.ig.DefineLabel ();
2253 il_label_code_set = true;
2255 return il_label_code;
2259 // Resolves the expression, reduces it to a literal if possible
2260 // and then converts it to the requested type.
2262 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2267 Expression e = label.Resolve (ec);
2272 if (!(e is Constant)){
2273 Report.Error (150, loc, "A constant value is expected, got: " + e);
2277 if (e is StringConstant || e is NullLiteral){
2278 if (required_type == TypeManager.string_type){
2284 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2285 if (converted == null)
2292 public class SwitchSection {
2293 // An array of SwitchLabels.
2294 public readonly ArrayList Labels;
2295 public readonly Block Block;
2297 public SwitchSection (ArrayList labels, Block block)
2304 public class Switch : Statement {
2305 public readonly ArrayList Sections;
2306 public Expression Expr;
2309 /// Maps constants whose type type SwitchType to their SwitchLabels.
2311 public Hashtable Elements;
2314 /// The governing switch type
2316 public Type SwitchType;
2322 Label default_target;
2323 Expression new_expr;
2325 SwitchSection constant_section;
2328 // The types allowed to be implicitly cast from
2329 // on the governing type
2331 static Type [] allowed_types;
2333 public Switch (Expression e, ArrayList sects, Location l)
2340 public bool GotDefault {
2346 public Label DefaultTarget {
2348 return default_target;
2353 // Determines the governing type for a switch. The returned
2354 // expression might be the expression from the switch, or an
2355 // expression that includes any potential conversions to the
2356 // integral types or to string.
2358 Expression SwitchGoverningType (EmitContext ec, Type t)
2360 if (t == TypeManager.int32_type ||
2361 t == TypeManager.uint32_type ||
2362 t == TypeManager.char_type ||
2363 t == TypeManager.byte_type ||
2364 t == TypeManager.sbyte_type ||
2365 t == TypeManager.ushort_type ||
2366 t == TypeManager.short_type ||
2367 t == TypeManager.uint64_type ||
2368 t == TypeManager.int64_type ||
2369 t == TypeManager.string_type ||
2370 t == TypeManager.bool_type ||
2371 t.IsSubclassOf (TypeManager.enum_type))
2374 if (allowed_types == null){
2375 allowed_types = new Type [] {
2376 TypeManager.int32_type,
2377 TypeManager.uint32_type,
2378 TypeManager.sbyte_type,
2379 TypeManager.byte_type,
2380 TypeManager.short_type,
2381 TypeManager.ushort_type,
2382 TypeManager.int64_type,
2383 TypeManager.uint64_type,
2384 TypeManager.char_type,
2385 TypeManager.bool_type,
2386 TypeManager.string_type
2391 // Try to find a *user* defined implicit conversion.
2393 // If there is no implicit conversion, or if there are multiple
2394 // conversions, we have to report an error
2396 Expression converted = null;
2397 foreach (Type tt in allowed_types){
2400 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2405 // Ignore over-worked ImplicitUserConversions that do
2406 // an implicit conversion in addition to the user conversion.
2409 UserCast ue = e as UserCast;
2411 if (ue.Source != Expr)
2415 if (converted != null){
2416 Report.ExtraInformation (
2418 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2419 TypeManager.CSharpName (Expr.Type)));
2428 static string Error152 {
2430 return "The label '{0}:' already occurs in this switch statement";
2435 // Performs the basic sanity checks on the switch statement
2436 // (looks for duplicate keys and non-constant expressions).
2438 // It also returns a hashtable with the keys that we will later
2439 // use to compute the switch tables
2441 bool CheckSwitch (EmitContext ec)
2445 Elements = new Hashtable ();
2447 got_default = false;
2449 if (TypeManager.IsEnumType (SwitchType)){
2450 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2452 compare_type = SwitchType;
2454 foreach (SwitchSection ss in Sections){
2455 foreach (SwitchLabel sl in ss.Labels){
2456 if (!sl.ResolveAndReduce (ec, SwitchType)){
2461 if (sl.Label == null){
2463 Report.Error (152, sl.loc, Error152, "default");
2470 object key = sl.Converted;
2472 if (key is Constant)
2473 key = ((Constant) key).GetValue ();
2476 key = NullLiteral.Null;
2478 string lname = null;
2479 if (compare_type == TypeManager.uint64_type){
2480 ulong v = (ulong) key;
2482 if (Elements.Contains (v))
2483 lname = v.ToString ();
2485 Elements.Add (v, sl);
2486 } else if (compare_type == TypeManager.int64_type){
2487 long v = (long) key;
2489 if (Elements.Contains (v))
2490 lname = v.ToString ();
2492 Elements.Add (v, sl);
2493 } else if (compare_type == TypeManager.uint32_type){
2494 uint v = (uint) key;
2496 if (Elements.Contains (v))
2497 lname = v.ToString ();
2499 Elements.Add (v, sl);
2500 } else if (compare_type == TypeManager.char_type){
2501 char v = (char) key;
2503 if (Elements.Contains (v))
2504 lname = v.ToString ();
2506 Elements.Add (v, sl);
2507 } else if (compare_type == TypeManager.byte_type){
2508 byte v = (byte) key;
2510 if (Elements.Contains (v))
2511 lname = v.ToString ();
2513 Elements.Add (v, sl);
2514 } else if (compare_type == TypeManager.sbyte_type){
2515 sbyte v = (sbyte) key;
2517 if (Elements.Contains (v))
2518 lname = v.ToString ();
2520 Elements.Add (v, sl);
2521 } else if (compare_type == TypeManager.short_type){
2522 short v = (short) key;
2524 if (Elements.Contains (v))
2525 lname = v.ToString ();
2527 Elements.Add (v, sl);
2528 } else if (compare_type == TypeManager.ushort_type){
2529 ushort v = (ushort) key;
2531 if (Elements.Contains (v))
2532 lname = v.ToString ();
2534 Elements.Add (v, sl);
2535 } else if (compare_type == TypeManager.string_type){
2536 if (key is NullLiteral){
2537 if (Elements.Contains (NullLiteral.Null))
2540 Elements.Add (NullLiteral.Null, null);
2542 string s = (string) key;
2544 if (Elements.Contains (s))
2547 Elements.Add (s, sl);
2549 } else if (compare_type == TypeManager.int32_type) {
2552 if (Elements.Contains (v))
2553 lname = v.ToString ();
2555 Elements.Add (v, sl);
2556 } else if (compare_type == TypeManager.bool_type) {
2557 bool v = (bool) key;
2559 if (Elements.Contains (v))
2560 lname = v.ToString ();
2562 Elements.Add (v, sl);
2566 throw new Exception ("Unknown switch type!" +
2567 SwitchType + " " + compare_type);
2570 if (lname != null) {
2571 Report.Error (152, sl.loc, Error152, "case " + lname);
2582 void EmitObjectInteger (ILGenerator ig, object k)
2585 IntConstant.EmitInt (ig, (int) k);
2586 else if (k is Constant) {
2587 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2590 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2593 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2595 IntConstant.EmitInt (ig, (int) (long) k);
2596 ig.Emit (OpCodes.Conv_I8);
2599 LongConstant.EmitLong (ig, (long) k);
2601 else if (k is ulong)
2603 if ((ulong) k < (1L<<32))
2605 IntConstant.EmitInt (ig, (int) (long) k);
2606 ig.Emit (OpCodes.Conv_U8);
2610 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2614 IntConstant.EmitInt (ig, (int) ((char) k));
2615 else if (k is sbyte)
2616 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2618 IntConstant.EmitInt (ig, (int) ((byte) k));
2619 else if (k is short)
2620 IntConstant.EmitInt (ig, (int) ((short) k));
2621 else if (k is ushort)
2622 IntConstant.EmitInt (ig, (int) ((ushort) k));
2624 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2626 throw new Exception ("Unhandled case");
2629 // structure used to hold blocks of keys while calculating table switch
2630 class KeyBlock : IComparable
2632 public KeyBlock (long _nFirst)
2634 nFirst = nLast = _nFirst;
2638 public ArrayList rgKeys = null;
2639 // how many items are in the bucket
2640 public int Size = 1;
2643 get { return (int) (nLast - nFirst + 1); }
2645 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2647 return kbLast.nLast - kbFirst.nFirst + 1;
2649 public int CompareTo (object obj)
2651 KeyBlock kb = (KeyBlock) obj;
2652 int nLength = Length;
2653 int nLengthOther = kb.Length;
2654 if (nLengthOther == nLength)
2655 return (int) (kb.nFirst - nFirst);
2656 return nLength - nLengthOther;
2661 /// This method emits code for a lookup-based switch statement (non-string)
2662 /// Basically it groups the cases into blocks that are at least half full,
2663 /// and then spits out individual lookup opcodes for each block.
2664 /// It emits the longest blocks first, and short blocks are just
2665 /// handled with direct compares.
2667 /// <param name="ec"></param>
2668 /// <param name="val"></param>
2669 /// <returns></returns>
2670 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2672 int cElements = Elements.Count;
2673 object [] rgKeys = new object [cElements];
2674 Elements.Keys.CopyTo (rgKeys, 0);
2675 Array.Sort (rgKeys);
2677 // initialize the block list with one element per key
2678 ArrayList rgKeyBlocks = new ArrayList ();
2679 foreach (object key in rgKeys)
2680 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2683 // iteratively merge the blocks while they are at least half full
2684 // there's probably a really cool way to do this with a tree...
2685 while (rgKeyBlocks.Count > 1)
2687 ArrayList rgKeyBlocksNew = new ArrayList ();
2688 kbCurr = (KeyBlock) rgKeyBlocks [0];
2689 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2691 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2692 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2695 kbCurr.nLast = kb.nLast;
2696 kbCurr.Size += kb.Size;
2700 // start a new block
2701 rgKeyBlocksNew.Add (kbCurr);
2705 rgKeyBlocksNew.Add (kbCurr);
2706 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2708 rgKeyBlocks = rgKeyBlocksNew;
2711 // initialize the key lists
2712 foreach (KeyBlock kb in rgKeyBlocks)
2713 kb.rgKeys = new ArrayList ();
2715 // fill the key lists
2717 if (rgKeyBlocks.Count > 0) {
2718 kbCurr = (KeyBlock) rgKeyBlocks [0];
2719 foreach (object key in rgKeys)
2721 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2722 System.Convert.ToInt64 (key) > kbCurr.nLast;
2724 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2725 kbCurr.rgKeys.Add (key);
2729 // sort the blocks so we can tackle the largest ones first
2730 rgKeyBlocks.Sort ();
2732 // okay now we can start...
2733 ILGenerator ig = ec.ig;
2734 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2735 Label lblDefault = ig.DefineLabel ();
2737 Type typeKeys = null;
2738 if (rgKeys.Length > 0)
2739 typeKeys = rgKeys [0].GetType (); // used for conversions
2743 if (TypeManager.IsEnumType (SwitchType))
2744 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2746 compare_type = SwitchType;
2748 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2750 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2751 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2754 foreach (object key in kb.rgKeys)
2756 ig.Emit (OpCodes.Ldloc, val);
2757 EmitObjectInteger (ig, key);
2758 SwitchLabel sl = (SwitchLabel) Elements [key];
2759 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2764 // TODO: if all the keys in the block are the same and there are
2765 // no gaps/defaults then just use a range-check.
2766 if (compare_type == TypeManager.int64_type ||
2767 compare_type == TypeManager.uint64_type)
2769 // TODO: optimize constant/I4 cases
2771 // check block range (could be > 2^31)
2772 ig.Emit (OpCodes.Ldloc, val);
2773 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2774 ig.Emit (OpCodes.Blt, lblDefault);
2775 ig.Emit (OpCodes.Ldloc, val);
2776 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2777 ig.Emit (OpCodes.Bgt, lblDefault);
2780 ig.Emit (OpCodes.Ldloc, val);
2783 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2784 ig.Emit (OpCodes.Sub);
2786 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2791 ig.Emit (OpCodes.Ldloc, val);
2792 int nFirst = (int) kb.nFirst;
2795 IntConstant.EmitInt (ig, nFirst);
2796 ig.Emit (OpCodes.Sub);
2798 else if (nFirst < 0)
2800 IntConstant.EmitInt (ig, -nFirst);
2801 ig.Emit (OpCodes.Add);
2805 // first, build the list of labels for the switch
2807 int cJumps = kb.Length;
2808 Label [] rgLabels = new Label [cJumps];
2809 for (int iJump = 0; iJump < cJumps; iJump++)
2811 object key = kb.rgKeys [iKey];
2812 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2814 SwitchLabel sl = (SwitchLabel) Elements [key];
2815 rgLabels [iJump] = sl.GetILLabel (ec);
2819 rgLabels [iJump] = lblDefault;
2821 // emit the switch opcode
2822 ig.Emit (OpCodes.Switch, rgLabels);
2825 // mark the default for this block
2827 ig.MarkLabel (lblDefault);
2830 // TODO: find the default case and emit it here,
2831 // to prevent having to do the following jump.
2832 // make sure to mark other labels in the default section
2834 // the last default just goes to the end
2835 ig.Emit (OpCodes.Br, lblDefault);
2837 // now emit the code for the sections
2838 bool fFoundDefault = false;
2839 foreach (SwitchSection ss in Sections)
2841 foreach (SwitchLabel sl in ss.Labels)
2843 ig.MarkLabel (sl.GetILLabel (ec));
2844 ig.MarkLabel (sl.GetILLabelCode (ec));
2845 if (sl.Label == null)
2847 ig.MarkLabel (lblDefault);
2848 fFoundDefault = true;
2852 //ig.Emit (OpCodes.Br, lblEnd);
2855 if (!fFoundDefault) {
2856 ig.MarkLabel (lblDefault);
2858 ig.MarkLabel (lblEnd);
2861 // This simple emit switch works, but does not take advantage of the
2863 // TODO: remove non-string logic from here
2864 // TODO: binary search strings?
2866 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2868 ILGenerator ig = ec.ig;
2869 Label end_of_switch = ig.DefineLabel ();
2870 Label next_test = ig.DefineLabel ();
2871 Label null_target = ig.DefineLabel ();
2872 bool default_found = false;
2873 bool first_test = true;
2874 bool pending_goto_end = false;
2876 bool default_at_end = false;
2878 ig.Emit (OpCodes.Ldloc, val);
2880 if (Elements.Contains (NullLiteral.Null)){
2881 ig.Emit (OpCodes.Brfalse, null_target);
2883 ig.Emit (OpCodes.Brfalse, default_target);
2885 ig.Emit (OpCodes.Ldloc, val);
2886 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2887 ig.Emit (OpCodes.Stloc, val);
2889 int section_count = Sections.Count;
2890 for (int section = 0; section < section_count; section++){
2891 SwitchSection ss = (SwitchSection) Sections [section];
2892 Label sec_begin = ig.DefineLabel ();
2894 if (pending_goto_end)
2895 ig.Emit (OpCodes.Br, end_of_switch);
2897 int label_count = ss.Labels.Count;
2898 bool mark_default = false;
2900 for (int label = 0; label < label_count; label++){
2901 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2902 ig.MarkLabel (sl.GetILLabel (ec));
2905 ig.MarkLabel (next_test);
2906 next_test = ig.DefineLabel ();
2909 // If we are the default target
2911 if (sl.Label == null){
2912 if (label+1 == label_count)
2913 default_at_end = true;
2914 mark_default = true;
2915 default_found = true;
2917 object lit = sl.Converted;
2919 if (lit is NullLiteral){
2921 if (label_count == 1)
2922 ig.Emit (OpCodes.Br, next_test);
2926 StringConstant str = (StringConstant) lit;
2928 ig.Emit (OpCodes.Ldloc, val);
2929 ig.Emit (OpCodes.Ldstr, str.Value);
2930 if (label_count == 1)
2931 ig.Emit (OpCodes.Bne_Un, next_test);
2933 if (label+1 == label_count)
2934 ig.Emit (OpCodes.Bne_Un, next_test);
2936 ig.Emit (OpCodes.Beq, sec_begin);
2941 ig.MarkLabel (null_target);
2942 ig.MarkLabel (sec_begin);
2943 foreach (SwitchLabel sl in ss.Labels)
2944 ig.MarkLabel (sl.GetILLabelCode (ec));
2947 ig.MarkLabel (default_target);
2949 pending_goto_end = !ss.Block.HasRet;
2952 ig.MarkLabel (next_test);
2954 if (!default_at_end)
2955 ig.Emit (OpCodes.Br, default_target);
2957 ig.MarkLabel (default_target);
2958 ig.MarkLabel (end_of_switch);
2961 SwitchSection FindSection (SwitchLabel label)
2963 foreach (SwitchSection ss in Sections){
2964 foreach (SwitchLabel sl in ss.Labels){
2973 bool ResolveConstantSwitch (EmitContext ec)
2975 object key = ((Constant) new_expr).GetValue ();
2976 SwitchLabel label = (SwitchLabel) Elements [key];
2981 constant_section = FindSection (label);
2982 if (constant_section == null)
2985 if (constant_section.Block.Resolve (ec) != true)
2991 public override bool Resolve (EmitContext ec)
2993 Expr = Expr.Resolve (ec);
2997 new_expr = SwitchGoverningType (ec, Expr.Type);
2998 if (new_expr == null){
2999 Report.Error (151, loc, "An integer type or string was expected for switch");
3004 SwitchType = new_expr.Type;
3006 if (!CheckSwitch (ec))
3009 Switch old_switch = ec.Switch;
3011 ec.Switch.SwitchType = SwitchType;
3013 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
3014 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
3016 is_constant = new_expr is Constant;
3018 object key = ((Constant) new_expr).GetValue ();
3019 SwitchLabel label = (SwitchLabel) Elements [key];
3021 constant_section = FindSection (label);
3025 foreach (SwitchSection ss in Sections){
3027 ec.CurrentBranching.CreateSibling (
3028 null, FlowBranching.SiblingType.SwitchSection);
3032 if (is_constant && (ss != constant_section)) {
3033 // If we're a constant switch, we're only emitting
3034 // one single section - mark all the others as
3036 ec.CurrentBranching.CurrentUsageVector.Goto ();
3037 if (!ss.Block.ResolveUnreachable (ec, true))
3040 if (!ss.Block.Resolve (ec))
3046 ec.CurrentBranching.CreateSibling (
3047 null, FlowBranching.SiblingType.SwitchSection);
3049 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3050 ec.Switch = old_switch;
3052 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3058 protected override void DoEmit (EmitContext ec)
3060 ILGenerator ig = ec.ig;
3062 // Store variable for comparission purposes
3065 value = ig.DeclareLocal (SwitchType);
3067 ig.Emit (OpCodes.Stloc, value);
3071 default_target = ig.DefineLabel ();
3074 // Setup the codegen context
3076 Label old_end = ec.LoopEnd;
3077 Switch old_switch = ec.Switch;
3079 ec.LoopEnd = ig.DefineLabel ();
3084 if (constant_section != null)
3085 constant_section.Block.Emit (ec);
3086 } else if (SwitchType == TypeManager.string_type)
3087 SimpleSwitchEmit (ec, value);
3089 TableSwitchEmit (ec, value);
3091 // Restore context state.
3092 ig.MarkLabel (ec.LoopEnd);
3095 // Restore the previous context
3097 ec.LoopEnd = old_end;
3098 ec.Switch = old_switch;
3102 public abstract class ExceptionStatement : Statement
3104 public abstract void EmitFinally (EmitContext ec);
3106 protected bool emit_finally = true;
3107 ArrayList parent_vectors;
3109 protected void DoEmitFinally (EmitContext ec)
3112 ec.ig.BeginFinallyBlock ();
3114 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3118 protected void ResolveFinally (FlowBranchingException branching)
3120 emit_finally = branching.EmitFinally;
3122 branching.Parent.StealFinallyClauses (ref parent_vectors);
3126 public class Lock : ExceptionStatement {
3128 Statement Statement;
3131 public Lock (Expression expr, Statement stmt, Location l)
3138 public override bool Resolve (EmitContext ec)
3140 expr = expr.Resolve (ec);
3144 if (expr.Type.IsValueType){
3145 Error (185, "lock statement requires the expression to be " +
3146 " a reference type (type is: `{0}'",
3147 TypeManager.CSharpName (expr.Type));
3151 FlowBranchingException branching = ec.StartFlowBranching (this);
3152 bool ok = Statement.Resolve (ec);
3154 ec.KillFlowBranching ();
3158 ResolveFinally (branching);
3160 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3161 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3162 // Unfortunately, System.Reflection.Emit automatically emits
3163 // a leave to the end of the finally block.
3164 // This is a problem if `returns' is true since we may jump
3165 // to a point after the end of the method.
3166 // As a workaround, emit an explicit ret here.
3167 ec.NeedReturnLabel ();
3173 protected override void DoEmit (EmitContext ec)
3175 Type type = expr.Type;
3177 ILGenerator ig = ec.ig;
3178 temp = ig.DeclareLocal (type);
3181 ig.Emit (OpCodes.Dup);
3182 ig.Emit (OpCodes.Stloc, temp);
3183 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3187 ig.BeginExceptionBlock ();
3188 Statement.Emit (ec);
3193 ig.EndExceptionBlock ();
3196 public override void EmitFinally (EmitContext ec)
3198 ILGenerator ig = ec.ig;
3199 ig.Emit (OpCodes.Ldloc, temp);
3200 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3204 public class Unchecked : Statement {
3205 public readonly Block Block;
3207 public Unchecked (Block b)
3213 public override bool Resolve (EmitContext ec)
3215 bool previous_state = ec.CheckState;
3216 bool previous_state_const = ec.ConstantCheckState;
3218 ec.CheckState = false;
3219 ec.ConstantCheckState = false;
3220 bool ret = Block.Resolve (ec);
3221 ec.CheckState = previous_state;
3222 ec.ConstantCheckState = previous_state_const;
3227 protected override void DoEmit (EmitContext ec)
3229 bool previous_state = ec.CheckState;
3230 bool previous_state_const = ec.ConstantCheckState;
3232 ec.CheckState = false;
3233 ec.ConstantCheckState = false;
3235 ec.CheckState = previous_state;
3236 ec.ConstantCheckState = previous_state_const;
3240 public class Checked : Statement {
3241 public readonly Block Block;
3243 public Checked (Block b)
3246 b.Unchecked = false;
3249 public override bool Resolve (EmitContext ec)
3251 bool previous_state = ec.CheckState;
3252 bool previous_state_const = ec.ConstantCheckState;
3254 ec.CheckState = true;
3255 ec.ConstantCheckState = true;
3256 bool ret = Block.Resolve (ec);
3257 ec.CheckState = previous_state;
3258 ec.ConstantCheckState = previous_state_const;
3263 protected override void DoEmit (EmitContext ec)
3265 bool previous_state = ec.CheckState;
3266 bool previous_state_const = ec.ConstantCheckState;
3268 ec.CheckState = true;
3269 ec.ConstantCheckState = true;
3271 ec.CheckState = previous_state;
3272 ec.ConstantCheckState = previous_state_const;
3276 public class Unsafe : Statement {
3277 public readonly Block Block;
3279 public Unsafe (Block b)
3282 Block.Unsafe = true;
3285 public override bool Resolve (EmitContext ec)
3287 bool previous_state = ec.InUnsafe;
3291 val = Block.Resolve (ec);
3292 ec.InUnsafe = previous_state;
3297 protected override void DoEmit (EmitContext ec)
3299 bool previous_state = ec.InUnsafe;
3303 ec.InUnsafe = previous_state;
3310 public class Fixed : Statement {
3312 ArrayList declarators;
3313 Statement statement;
3318 abstract class Emitter
3320 protected LocalInfo vi;
3321 protected Expression converted;
3323 protected Emitter (Expression expr, LocalInfo li)
3329 public abstract void Emit (EmitContext ec);
3330 public abstract void EmitExit (ILGenerator ig);
3333 class ExpressionEmitter: Emitter {
3334 public ExpressionEmitter (Expression converted, LocalInfo li) :
3335 base (converted, li)
3339 public override void Emit (EmitContext ec) {
3341 // Store pointer in pinned location
3343 converted.Emit (ec);
3344 ec.ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3347 public override void EmitExit (ILGenerator ig)
3349 ig.Emit (OpCodes.Ldc_I4_0);
3350 ig.Emit (OpCodes.Conv_U);
3351 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3355 class StringEmitter: Emitter {
3356 LocalBuilder pinned_string;
3359 public StringEmitter (Expression expr, LocalInfo li, Location loc):
3365 public override void Emit (EmitContext ec)
3367 ILGenerator ig = ec.ig;
3368 pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3370 converted.Emit (ec);
3371 ig.Emit (OpCodes.Stloc, pinned_string);
3373 Expression sptr = new StringPtr (pinned_string, loc);
3374 converted = Convert.ImplicitConversionRequired (
3375 ec, sptr, vi.VariableType, loc);
3377 if (converted == null)
3380 converted.Emit (ec);
3381 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3384 public override void EmitExit(ILGenerator ig)
3386 ig.Emit (OpCodes.Ldnull);
3387 ig.Emit (OpCodes.Stloc, pinned_string);
3391 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3394 declarators = decls;
3399 public override bool Resolve (EmitContext ec)
3402 Expression.UnsafeError (loc);
3406 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3410 expr_type = texpr.ResolveType (ec);
3412 CheckObsolete (expr_type);
3414 if (ec.RemapToProxy){
3415 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3419 data = new Emitter [declarators.Count];
3421 if (!expr_type.IsPointer){
3422 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3427 foreach (Pair p in declarators){
3428 LocalInfo vi = (LocalInfo) p.First;
3429 Expression e = (Expression) p.Second;
3431 vi.VariableInfo.SetAssigned (ec);
3435 // The rules for the possible declarators are pretty wise,
3436 // but the production on the grammar is more concise.
3438 // So we have to enforce these rules here.
3440 // We do not resolve before doing the case 1 test,
3441 // because the grammar is explicit in that the token &
3442 // is present, so we need to test for this particular case.
3446 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3451 // Case 1: & object.
3453 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3454 Expression child = ((Unary) e).Expr;
3456 if (child is ParameterReference || child is LocalVariableReference){
3459 "No need to use fixed statement for parameters or " +
3460 "local variable declarations (address is already " +
3465 ec.InFixedInitializer = true;
3467 ec.InFixedInitializer = false;
3471 child = ((Unary) e).Expr;
3473 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3476 data [i] = new ExpressionEmitter (e, vi);
3482 ec.InFixedInitializer = true;
3484 ec.InFixedInitializer = false;
3491 if (e.Type.IsArray){
3492 Type array_type = TypeManager.GetElementType (e.Type);
3495 // Provided that array_type is unmanaged,
3497 if (!TypeManager.VerifyUnManaged (array_type, loc))
3501 // and T* is implicitly convertible to the
3502 // pointer type given in the fixed statement.
3504 ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
3506 Expression converted = Convert.ImplicitConversionRequired (
3507 ec, array_ptr, vi.VariableType, loc);
3508 if (converted == null)
3511 data [i] = new ExpressionEmitter (converted, vi);
3520 if (e.Type == TypeManager.string_type){
3521 data [i] = new StringEmitter (e, vi, loc);
3526 // Case 4: fixed buffer
3527 FieldExpr fe = e as FieldExpr;
3529 IFixedBuffer ff = AttributeTester.GetFixedBuffer (fe.FieldInfo);
3531 Expression fixed_buffer_ptr = new FixedBufferPtr (fe, ff.ElementType, loc);
3533 Expression converted = Convert.ImplicitConversionRequired (
3534 ec, fixed_buffer_ptr, vi.VariableType, loc);
3535 if (converted == null)
3538 data [i] = new ExpressionEmitter (converted, vi);
3546 // For other cases, flag a `this is already fixed expression'
3548 if (e is LocalVariableReference || e is ParameterReference ||
3549 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3551 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3555 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3559 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3561 if (!statement.Resolve (ec)) {
3562 ec.KillFlowBranching ();
3566 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3567 has_ret = reachability.IsUnreachable;
3572 protected override void DoEmit (EmitContext ec)
3574 for (int i = 0; i < data.Length; i++) {
3578 statement.Emit (ec);
3583 ILGenerator ig = ec.ig;
3586 // Clear the pinned variable
3588 for (int i = 0; i < data.Length; i++) {
3589 data [i].EmitExit (ig);
3594 public class Catch: Statement {
3595 public readonly string Name;
3596 public readonly Block Block;
3598 Expression type_expr;
3601 public Catch (Expression type, string name, Block block, Location l)
3609 public Type CatchType {
3615 public bool IsGeneral {
3617 return type_expr == null;
3621 protected override void DoEmit(EmitContext ec)
3625 public override bool Resolve (EmitContext ec)
3627 if (type_expr != null) {
3628 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3632 type = te.ResolveType (ec);
3634 CheckObsolete (type);
3636 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3637 Error (155, "The type caught or thrown must be derived from System.Exception");
3643 return Block.Resolve (ec);
3647 public class Try : ExceptionStatement {
3648 public readonly Block Fini, Block;
3649 public readonly ArrayList Specific;
3650 public readonly Catch General;
3652 bool need_exc_block;
3655 // specific, general and fini might all be null.
3657 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3659 if (specific == null && general == null){
3660 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3664 this.Specific = specific;
3665 this.General = general;
3670 public override bool Resolve (EmitContext ec)
3674 FlowBranchingException branching = ec.StartFlowBranching (this);
3676 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3678 if (!Block.Resolve (ec))
3681 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3683 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3685 Type[] prevCatches = new Type [Specific.Count];
3687 foreach (Catch c in Specific){
3688 ec.CurrentBranching.CreateSibling (
3689 c.Block, FlowBranching.SiblingType.Catch);
3691 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3693 if (c.Name != null) {
3694 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3696 throw new Exception ();
3698 vi.VariableInfo = null;
3701 if (!c.Resolve (ec))
3704 Type resolvedType = c.CatchType;
3705 for (int ii = 0; ii < last_index; ++ii) {
3706 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3707 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3712 prevCatches [last_index++] = resolvedType;
3713 need_exc_block = true;
3716 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3718 if (General != null){
3719 ec.CurrentBranching.CreateSibling (
3720 General.Block, FlowBranching.SiblingType.Catch);
3722 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3724 if (!General.Resolve (ec))
3727 need_exc_block = true;
3730 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3734 ec.CurrentBranching.CreateSibling (
3735 Fini, FlowBranching.SiblingType.Finally);
3737 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3739 if (!Fini.Resolve (ec))
3743 ResolveFinally (branching);
3744 need_exc_block |= emit_finally;
3746 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3748 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3750 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3752 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3753 // Unfortunately, System.Reflection.Emit automatically emits
3754 // a leave to the end of the finally block. This is a problem
3755 // if `returns' is true since we may jump to a point after the
3756 // end of the method.
3757 // As a workaround, emit an explicit ret here.
3758 ec.NeedReturnLabel ();
3764 protected override void DoEmit (EmitContext ec)
3766 ILGenerator ig = ec.ig;
3769 ig.BeginExceptionBlock ();
3772 foreach (Catch c in Specific){
3775 ig.BeginCatchBlock (c.CatchType);
3777 if (c.Name != null){
3778 vi = c.Block.GetLocalInfo (c.Name);
3780 throw new Exception ("Variable does not exist in this block");
3782 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3784 ig.Emit (OpCodes.Pop);
3789 if (General != null){
3790 ig.BeginCatchBlock (TypeManager.object_type);
3791 ig.Emit (OpCodes.Pop);
3792 General.Block.Emit (ec);
3797 ig.EndExceptionBlock ();
3800 public override void EmitFinally (EmitContext ec)
3808 public class Using : ExceptionStatement {
3809 object expression_or_block;
3810 Statement Statement;
3815 Expression [] resolved_vars;
3816 Expression [] converted_vars;
3817 ExpressionStatement [] assign;
3818 LocalBuilder local_copy;
3820 public Using (object expression_or_block, Statement stmt, Location l)
3822 this.expression_or_block = expression_or_block;
3828 // Resolves for the case of using using a local variable declaration.
3830 bool ResolveLocalVariableDecls (EmitContext ec)
3834 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3838 expr_type = texpr.ResolveType (ec);
3841 // The type must be an IDisposable or an implicit conversion
3844 converted_vars = new Expression [var_list.Count];
3845 resolved_vars = new Expression [var_list.Count];
3846 assign = new ExpressionStatement [var_list.Count];
3848 bool need_conv = !TypeManager.ImplementsInterface (
3849 expr_type, TypeManager.idisposable_type);
3851 foreach (DictionaryEntry e in var_list){
3852 Expression var = (Expression) e.Key;
3854 var = var.ResolveLValue (ec, new EmptyExpression ());
3858 resolved_vars [i] = var;
3865 converted_vars [i] = Convert.ImplicitConversionRequired (
3866 ec, var, TypeManager.idisposable_type, loc);
3868 if (converted_vars [i] == null)
3875 foreach (DictionaryEntry e in var_list){
3876 Expression var = resolved_vars [i];
3877 Expression new_expr = (Expression) e.Value;
3880 a = new Assign (var, new_expr, loc);
3886 converted_vars [i] = var;
3887 assign [i] = (ExpressionStatement) a;
3894 bool ResolveExpression (EmitContext ec)
3896 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3897 conv = Convert.ImplicitConversionRequired (
3898 ec, expr, TypeManager.idisposable_type, loc);
3908 // Emits the code for the case of using using a local variable declaration.
3910 void EmitLocalVariableDecls (EmitContext ec)
3912 ILGenerator ig = ec.ig;
3915 for (i = 0; i < assign.Length; i++) {
3916 assign [i].EmitStatement (ec);
3919 ig.BeginExceptionBlock ();
3921 Statement.Emit (ec);
3922 var_list.Reverse ();
3927 void EmitLocalVariableDeclFinally (EmitContext ec)
3929 ILGenerator ig = ec.ig;
3931 int i = assign.Length;
3932 for (int ii = 0; ii < var_list.Count; ++ii){
3933 Expression var = resolved_vars [--i];
3934 Label skip = ig.DefineLabel ();
3936 if (!var.Type.IsValueType) {
3938 ig.Emit (OpCodes.Brfalse, skip);
3939 converted_vars [i].Emit (ec);
3940 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3942 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3944 if (!(ml is MethodGroupExpr)) {
3946 ig.Emit (OpCodes.Box, var.Type);
3947 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3949 MethodInfo mi = null;
3951 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3952 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3959 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3963 IMemoryLocation mloc = (IMemoryLocation) var;
3965 mloc.AddressOf (ec, AddressOp.Load);
3966 ig.Emit (OpCodes.Call, mi);
3970 ig.MarkLabel (skip);
3973 ig.EndExceptionBlock ();
3975 ig.BeginFinallyBlock ();
3980 void EmitExpression (EmitContext ec)
3983 // Make a copy of the expression and operate on that.
3985 ILGenerator ig = ec.ig;
3986 local_copy = ig.DeclareLocal (expr_type);
3991 ig.Emit (OpCodes.Stloc, local_copy);
3994 ig.BeginExceptionBlock ();
3996 Statement.Emit (ec);
4000 ig.EndExceptionBlock ();
4003 void EmitExpressionFinally (EmitContext ec)
4005 ILGenerator ig = ec.ig;
4006 if (!local_copy.LocalType.IsValueType) {
4007 Label skip = ig.DefineLabel ();
4008 ig.Emit (OpCodes.Ldloc, local_copy);
4009 ig.Emit (OpCodes.Brfalse, skip);
4010 ig.Emit (OpCodes.Ldloc, local_copy);
4011 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4012 ig.MarkLabel (skip);
4014 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
4016 if (!(ml is MethodGroupExpr)) {
4017 ig.Emit (OpCodes.Ldloc, local_copy);
4018 ig.Emit (OpCodes.Box, local_copy.LocalType);
4019 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4021 MethodInfo mi = null;
4023 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
4024 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
4031 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
4035 ig.Emit (OpCodes.Ldloca, local_copy);
4036 ig.Emit (OpCodes.Call, mi);
4041 public override bool Resolve (EmitContext ec)
4043 if (expression_or_block is DictionaryEntry){
4044 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4045 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4047 if (!ResolveLocalVariableDecls (ec))
4050 } else if (expression_or_block is Expression){
4051 expr = (Expression) expression_or_block;
4053 expr = expr.Resolve (ec);
4057 expr_type = expr.Type;
4059 if (!ResolveExpression (ec))
4063 FlowBranchingException branching = ec.StartFlowBranching (this);
4065 bool ok = Statement.Resolve (ec);
4068 ec.KillFlowBranching ();
4072 ResolveFinally (branching);
4073 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4075 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4076 // Unfortunately, System.Reflection.Emit automatically emits a leave
4077 // to the end of the finally block. This is a problem if `returns'
4078 // is true since we may jump to a point after the end of the method.
4079 // As a workaround, emit an explicit ret here.
4080 ec.NeedReturnLabel ();
4086 protected override void DoEmit (EmitContext ec)
4088 if (expression_or_block is DictionaryEntry)
4089 EmitLocalVariableDecls (ec);
4090 else if (expression_or_block is Expression)
4091 EmitExpression (ec);
4094 public override void EmitFinally (EmitContext ec)
4096 if (expression_or_block is DictionaryEntry)
4097 EmitLocalVariableDeclFinally (ec);
4098 else if (expression_or_block is Expression)
4099 EmitExpressionFinally (ec);
4104 /// Implementation of the foreach C# statement
4106 public class Foreach : ExceptionStatement {
4108 Expression variable;
4110 Statement statement;
4111 ForeachHelperMethods hm;
4112 Expression empty, conv;
4113 Type array_type, element_type;
4115 VariableStorage enumerator;
4117 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4118 Statement stmt, Location l)
4121 this.variable = var;
4127 public override bool Resolve (EmitContext ec)
4129 expr = expr.Resolve (ec);
4133 if (expr is NullLiteral) {
4134 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4138 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4142 var_type = texpr.ResolveType (ec);
4145 // We need an instance variable. Not sure this is the best
4146 // way of doing this.
4148 // FIXME: When we implement propertyaccess, will those turn
4149 // out to return values in ExprClass? I think they should.
4151 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4152 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4153 error1579 (expr.Type);
4157 if (expr.Type.IsArray) {
4158 array_type = expr.Type;
4159 element_type = TypeManager.GetElementType (array_type);
4161 empty = new EmptyExpression (element_type);
4163 hm = ProbeCollectionType (ec, expr.Type);
4165 error1579 (expr.Type);
4169 // When ProbeCollection reported error
4170 if (hm.move_next == null)
4173 array_type = expr.Type;
4174 element_type = hm.element_type;
4176 empty = new EmptyExpression (hm.element_type);
4181 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4182 ec.CurrentBranching.CreateSibling ();
4186 // FIXME: maybe we can apply the same trick we do in the
4187 // array handling to avoid creating empty and conv in some cases.
4189 // Although it is not as important in this case, as the type
4190 // will not likely be object (what the enumerator will return).
4192 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4196 variable = variable.ResolveLValue (ec, empty);
4197 if (variable == null)
4200 bool disposable = (hm != null) && hm.is_disposable;
4201 FlowBranchingException branching = null;
4203 branching = ec.StartFlowBranching (this);
4205 if (!statement.Resolve (ec))
4209 ResolveFinally (branching);
4210 ec.EndFlowBranching ();
4212 emit_finally = true;
4214 ec.EndFlowBranching ();
4220 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4222 static MethodInfo FetchMethodMoveNext (Type t)
4224 MemberList move_next_list;
4226 move_next_list = TypeContainer.FindMembers (
4227 t, MemberTypes.Method,
4228 BindingFlags.Public | BindingFlags.Instance,
4229 Type.FilterName, "MoveNext");
4230 if (move_next_list.Count == 0)
4233 foreach (MemberInfo m in move_next_list){
4234 MethodInfo mi = (MethodInfo) m;
4237 args = TypeManager.GetArgumentTypes (mi);
4238 if (args != null && args.Length == 0){
4239 if (mi.ReturnType == TypeManager.bool_type)
4247 // Retrieves a `public T get_Current ()' method from the Type `t'
4249 static MethodInfo FetchMethodGetCurrent (Type t)
4251 MemberList get_current_list;
4253 get_current_list = TypeContainer.FindMembers (
4254 t, MemberTypes.Method,
4255 BindingFlags.Public | BindingFlags.Instance,
4256 Type.FilterName, "get_Current");
4257 if (get_current_list.Count == 0)
4260 foreach (MemberInfo m in get_current_list){
4261 MethodInfo mi = (MethodInfo) m;
4264 args = TypeManager.GetArgumentTypes (mi);
4265 if (args != null && args.Length == 0)
4272 // Retrieves a `public void Dispose ()' method from the Type `t'
4274 static MethodInfo FetchMethodDispose (Type t)
4276 MemberList dispose_list;
4278 dispose_list = TypeContainer.FindMembers (
4279 t, MemberTypes.Method,
4280 BindingFlags.Public | BindingFlags.Instance,
4281 Type.FilterName, "Dispose");
4282 if (dispose_list.Count == 0)
4285 foreach (MemberInfo m in dispose_list){
4286 MethodInfo mi = (MethodInfo) m;
4289 args = TypeManager.GetArgumentTypes (mi);
4290 if (args != null && args.Length == 0){
4291 if (mi.ReturnType == TypeManager.void_type)
4299 // This struct records the helper methods used by the Foreach construct
4301 class ForeachHelperMethods {
4302 public EmitContext ec;
4303 public MethodInfo get_enumerator;
4304 public MethodInfo move_next;
4305 public MethodInfo get_current;
4306 public Type element_type;
4307 public Type enumerator_type;
4308 public bool is_disposable;
4309 public readonly Location Location;
4311 public ForeachHelperMethods (EmitContext ec, Location loc)
4314 this.Location = loc;
4315 this.element_type = TypeManager.object_type;
4316 this.enumerator_type = TypeManager.ienumerator_type;
4317 this.is_disposable = true;
4321 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4326 if (!(m is MethodInfo))
4329 if (m.Name != "GetEnumerator")
4332 MethodInfo mi = (MethodInfo) m;
4333 Type [] args = TypeManager.GetArgumentTypes (mi);
4335 if (args.Length != 0)
4338 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4340 // Check whether GetEnumerator is public
4341 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4344 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4346 // Apply the same optimization as MS: skip the GetEnumerator
4347 // returning an IEnumerator, and use the one returning a
4348 // CharEnumerator instead. This allows us to avoid the
4349 // try-finally block and the boxing.
4354 // Ok, we can access it, now make sure that we can do something
4355 // with this `GetEnumerator'
4358 Type return_type = mi.ReturnType;
4359 if (mi.ReturnType == TypeManager.ienumerator_type ||
4360 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4361 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4364 // If it is not an interface, lets try to find the methods ourselves.
4365 // For example, if we have:
4366 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4367 // We can avoid the iface call. This is a runtime perf boost.
4368 // even bigger if we have a ValueType, because we avoid the cost
4371 // We have to make sure that both methods exist for us to take
4372 // this path. If one of the methods does not exist, we will just
4373 // use the interface. Sadly, this complex if statement is the only
4374 // way I could do this without a goto
4377 if (return_type.IsInterface ||
4378 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4379 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4381 hm.move_next = TypeManager.bool_movenext_void;
4382 hm.get_current = TypeManager.object_getcurrent_void;
4388 if (return_type.IsPointer || return_type.IsArray) {
4389 Report.SymbolRelatedToPreviousError (mi);
4390 Type t = return_type.GetElementType ();
4391 Report.SymbolRelatedToPreviousError (t);
4392 Report.Error (202, hm.Location, "foreach requires that the return type '{0}' of '{1}' must have a suitable public MoveNext method and public Current property",
4393 TypeManager.CSharpName (return_type), TypeManager.GetFullNameSignature (m));
4394 hm.get_enumerator = mi;
4399 // Ok, so they dont return an IEnumerable, we will have to
4400 // find if they support the GetEnumerator pattern.
4403 hm.move_next = FetchMethodMoveNext (return_type);
4404 if (hm.move_next == null)
4407 hm.get_current = FetchMethodGetCurrent (return_type);
4408 if (hm.get_current == null)
4412 hm.element_type = hm.get_current.ReturnType;
4413 hm.enumerator_type = return_type;
4414 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4415 TypeManager.ImplementsInterface (
4416 hm.enumerator_type, TypeManager.idisposable_type);
4422 /// This filter is used to find the GetEnumerator method
4423 /// on which IEnumerator operates
4425 static MemberFilter FilterEnumerator;
4429 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4432 void error1579 (Type t)
4434 Report.Error (1579, loc,
4435 "foreach statement cannot operate on variables of type `" +
4436 t.FullName + "' because that class does not provide a " +
4437 " GetEnumerator method or it is inaccessible");
4440 static bool TryType (Type t, ForeachHelperMethods hm)
4444 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4445 BindingFlags.Public | BindingFlags.NonPublic |
4446 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4447 FilterEnumerator, hm);
4452 hm.get_enumerator = (MethodInfo) mi [0];
4457 // Looks for a usable GetEnumerator in the Type, and if found returns
4458 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4460 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4462 ForeachHelperMethods hm = new ForeachHelperMethods (ec, loc);
4464 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4465 if (TryType (tt, hm))
4471 // Now try to find the method in the interfaces
4474 Type [] ifaces = t.GetInterfaces ();
4476 foreach (Type i in ifaces){
4477 if (TryType (i, hm))
4482 // Since TypeBuilder.GetInterfaces only returns the interface
4483 // types for this type, we have to keep looping, but once
4484 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4485 // done, because it returns all the types
4487 if ((t is TypeBuilder))
4497 // FIXME: possible optimization.
4498 // We might be able to avoid creating `empty' if the type is the sam
4500 bool EmitCollectionForeach (EmitContext ec)
4502 ILGenerator ig = ec.ig;
4504 enumerator = new VariableStorage (ec, hm.enumerator_type);
4505 enumerator.EmitThis (ig);
4507 // Instantiate the enumerator
4509 if (expr.Type.IsValueType) {
4510 IMemoryLocation ml = expr as IMemoryLocation;
4511 // Load the address of the value type.
4513 // This happens if, for example, you have a property
4514 // returning a struct which is IEnumerable
4515 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4517 ig.Emit (OpCodes.Stloc, t);
4518 ig.Emit (OpCodes.Ldloca, t);
4519 ec.FreeTemporaryLocal (t, expr.Type);
4521 ml.AddressOf (ec, AddressOp.Load);
4525 if (hm.get_enumerator.DeclaringType.IsValueType) {
4526 // the method is declared on the value type
4527 ig.Emit (OpCodes.Call, hm.get_enumerator);
4529 // it is an interface method, so we must box
4530 ig.Emit (OpCodes.Box, expr.Type);
4531 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4535 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4537 enumerator.EmitStore (ig);
4540 // Protect the code in a try/finalize block, so that
4541 // if the beast implement IDisposable, we get rid of it
4543 if (hm.is_disposable && emit_finally)
4544 ig.BeginExceptionBlock ();
4546 Label end_try = ig.DefineLabel ();
4548 ig.MarkLabel (ec.LoopBegin);
4550 enumerator.EmitCall (ig, hm.move_next);
4552 ig.Emit (OpCodes.Brfalse, end_try);
4555 ig.Emit (OpCodes.Ldarg_0);
4557 enumerator.EmitCall (ig, hm.get_current);
4561 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4563 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4565 statement.Emit (ec);
4566 ig.Emit (OpCodes.Br, ec.LoopBegin);
4567 ig.MarkLabel (end_try);
4570 // Now the finally block
4572 if (hm.is_disposable) {
4575 ig.EndExceptionBlock ();
4578 ig.MarkLabel (ec.LoopEnd);
4582 public override void EmitFinally (EmitContext ec)
4584 ILGenerator ig = ec.ig;
4586 if (hm.enumerator_type.IsValueType) {
4587 enumerator.EmitThis (ig);
4589 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4591 enumerator.EmitLoadAddress (ig);
4592 ig.Emit (OpCodes.Call, mi);
4594 enumerator.EmitLoad (ig);
4595 ig.Emit (OpCodes.Box, hm.enumerator_type);
4596 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4599 Label call_dispose = ig.DefineLabel ();
4601 enumerator.EmitThis (ig);
4602 enumerator.EmitLoad (ig);
4603 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4604 ig.Emit (OpCodes.Dup);
4605 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4606 ig.Emit (OpCodes.Pop);
4608 Label end_finally = ig.DefineLabel ();
4609 ig.Emit (OpCodes.Br, end_finally);
4611 ig.MarkLabel (call_dispose);
4612 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4613 ig.MarkLabel (end_finally);
4616 ig.Emit (OpCodes.Endfinally);
4621 // FIXME: possible optimization.
4622 // We might be able to avoid creating `empty' if the type is the sam
4624 bool EmitArrayForeach (EmitContext ec)
4626 int rank = array_type.GetArrayRank ();
4627 ILGenerator ig = ec.ig;
4629 VariableStorage copy = new VariableStorage (ec, array_type);
4632 // Make our copy of the array
4636 copy.EmitStore (ig);
4639 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4643 counter.EmitThis (ig);
4644 ig.Emit (OpCodes.Ldc_I4_0);
4645 counter.EmitStore (ig);
4646 test = ig.DefineLabel ();
4647 ig.Emit (OpCodes.Br, test);
4649 loop = ig.DefineLabel ();
4650 ig.MarkLabel (loop);
4653 ig.Emit (OpCodes.Ldarg_0);
4657 counter.EmitThis (ig);
4658 counter.EmitLoad (ig);
4661 // Load the value, we load the value using the underlying type,
4662 // then we use the variable.EmitAssign to load using the proper cast.
4664 ArrayAccess.EmitLoadOpcode (ig, element_type);
4667 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4669 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4671 statement.Emit (ec);
4673 ig.MarkLabel (ec.LoopBegin);
4674 counter.EmitThis (ig);
4675 counter.EmitThis (ig);
4676 counter.EmitLoad (ig);
4677 ig.Emit (OpCodes.Ldc_I4_1);
4678 ig.Emit (OpCodes.Add);
4679 counter.EmitStore (ig);
4681 ig.MarkLabel (test);
4682 counter.EmitThis (ig);
4683 counter.EmitLoad (ig);
4686 ig.Emit (OpCodes.Ldlen);
4687 ig.Emit (OpCodes.Conv_I4);
4688 ig.Emit (OpCodes.Blt, loop);
4690 VariableStorage [] dim_len = new VariableStorage [rank];
4691 VariableStorage [] dim_count = new VariableStorage [rank];
4692 Label [] loop = new Label [rank];
4693 Label [] test = new Label [rank];
4696 for (dim = 0; dim < rank; dim++){
4697 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4698 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4699 test [dim] = ig.DefineLabel ();
4700 loop [dim] = ig.DefineLabel ();
4703 for (dim = 0; dim < rank; dim++){
4704 dim_len [dim].EmitThis (ig);
4707 IntLiteral.EmitInt (ig, dim);
4708 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4709 dim_len [dim].EmitStore (ig);
4713 for (dim = 0; dim < rank; dim++){
4714 dim_count [dim].EmitThis (ig);
4715 ig.Emit (OpCodes.Ldc_I4_0);
4716 dim_count [dim].EmitStore (ig);
4717 ig.Emit (OpCodes.Br, test [dim]);
4718 ig.MarkLabel (loop [dim]);
4722 ig.Emit (OpCodes.Ldarg_0);
4726 for (dim = 0; dim < rank; dim++){
4727 dim_count [dim].EmitThis (ig);
4728 dim_count [dim].EmitLoad (ig);
4732 // FIXME: Maybe we can cache the computation of `get'?
4734 Type [] args = new Type [rank];
4737 for (int i = 0; i < rank; i++)
4738 args [i] = TypeManager.int32_type;
4740 ModuleBuilder mb = CodeGen.Module.Builder;
4741 get = mb.GetArrayMethod (
4743 CallingConventions.HasThis| CallingConventions.Standard,
4745 ig.Emit (OpCodes.Call, get);
4748 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4750 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4751 statement.Emit (ec);
4752 ig.MarkLabel (ec.LoopBegin);
4753 for (dim = rank - 1; dim >= 0; dim--){
4754 dim_count [dim].EmitThis (ig);
4755 dim_count [dim].EmitThis (ig);
4756 dim_count [dim].EmitLoad (ig);
4757 ig.Emit (OpCodes.Ldc_I4_1);
4758 ig.Emit (OpCodes.Add);
4759 dim_count [dim].EmitStore (ig);
4761 ig.MarkLabel (test [dim]);
4762 dim_count [dim].EmitThis (ig);
4763 dim_count [dim].EmitLoad (ig);
4764 dim_len [dim].EmitThis (ig);
4765 dim_len [dim].EmitLoad (ig);
4766 ig.Emit (OpCodes.Blt, loop [dim]);
4769 ig.MarkLabel (ec.LoopEnd);
4774 protected override void DoEmit (EmitContext ec)
4776 ILGenerator ig = ec.ig;
4778 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4779 ec.LoopBegin = ig.DefineLabel ();
4780 ec.LoopEnd = ig.DefineLabel ();
4783 EmitCollectionForeach (ec);
4785 EmitArrayForeach (ec);
4787 ec.LoopBegin = old_begin;
4788 ec.LoopEnd = old_end;