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 ();
653 public Goto (Block parent_block, string label, Location l)
655 block = parent_block;
660 public string Target {
666 protected override void DoEmit (EmitContext ec)
668 Label l = label.LabelTarget (ec);
669 ec.ig.Emit (OpCodes.Br, l);
673 public class LabeledStatement : Statement {
674 public readonly Location Location;
680 FlowBranching.UsageVector vectors;
682 public LabeledStatement (string label_name, Location l)
687 public Label LabelTarget (EmitContext ec)
692 label = ec.ig.DefineLabel ();
698 public bool IsDefined {
704 public bool HasBeenReferenced {
710 public void AddUsageVector (FlowBranching.UsageVector vector)
712 vector = vector.Clone ();
713 vector.Next = vectors;
717 public override bool Resolve (EmitContext ec)
719 ec.CurrentBranching.Label (vectors);
726 protected override void DoEmit (EmitContext ec)
728 if (ig != null && ig != ec.ig) {
729 Report.Error (1632, "Control cannot leave body of anonymous method");
733 ec.ig.MarkLabel (label);
739 /// `goto default' statement
741 public class GotoDefault : Statement {
743 public GotoDefault (Location l)
748 public override bool Resolve (EmitContext ec)
750 ec.CurrentBranching.CurrentUsageVector.Goto ();
754 protected override void DoEmit (EmitContext ec)
756 if (ec.Switch == null){
757 Report.Error (153, loc, "goto default is only valid in a switch statement");
761 if (!ec.Switch.GotDefault){
762 Report.Error (159, loc, "No default target on switch statement");
765 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
770 /// `goto case' statement
772 public class GotoCase : Statement {
776 public GotoCase (Expression e, Location l)
782 public override bool Resolve (EmitContext ec)
784 if (ec.Switch == null){
785 Report.Error (153, loc, "goto case is only valid in a switch statement");
789 expr = expr.Resolve (ec);
793 if (!(expr is Constant)){
794 Report.Error (159, loc, "Target expression for goto case is not constant");
798 object val = Expression.ConvertIntLiteral (
799 (Constant) expr, ec.Switch.SwitchType, loc);
804 sl = (SwitchLabel) ec.Switch.Elements [val];
809 "No such label 'case " + val + "': for the goto case");
813 ec.CurrentBranching.CurrentUsageVector.Goto ();
817 protected override void DoEmit (EmitContext ec)
819 ec.ig.Emit (OpCodes.Br, sl.GetILLabelCode (ec));
823 public class Throw : Statement {
826 public Throw (Expression expr, Location l)
832 public override bool Resolve (EmitContext ec)
834 ec.CurrentBranching.CurrentUsageVector.Throw ();
837 expr = expr.Resolve (ec);
841 ExprClass eclass = expr.eclass;
843 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
844 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
845 expr.Error_UnexpectedKind ("value, variable, property or indexer access ", loc);
851 if ((t != TypeManager.exception_type) &&
852 !t.IsSubclassOf (TypeManager.exception_type) &&
853 !(expr is NullLiteral)) {
855 "The type caught or thrown must be derived " +
856 "from System.Exception");
862 if (ec.CurrentBranching.InFinally (true)) {
863 Error (724, "A throw statement with no argument is only allowed in a catch clause nested inside of the innermost catch clause");
867 if (!ec.CurrentBranching.InCatch ()) {
868 Error (156, "A throw statement with no argument is only allowed in a catch clause");
874 protected override void DoEmit (EmitContext ec)
877 ec.ig.Emit (OpCodes.Rethrow);
881 ec.ig.Emit (OpCodes.Throw);
886 public class Break : Statement {
888 public Break (Location l)
895 public override bool Resolve (EmitContext ec)
897 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
898 Error (139, "No enclosing loop or switch to continue to");
900 } else if (ec.CurrentBranching.InFinally (false)) {
901 Error (157, "Control can not leave the body of the finally block");
903 } else if (ec.CurrentBranching.InTryOrCatch (false))
904 ec.CurrentBranching.AddFinallyVector (
905 ec.CurrentBranching.CurrentUsageVector);
906 else if (ec.CurrentBranching.InLoop ())
907 ec.CurrentBranching.AddBreakVector (
908 ec.CurrentBranching.CurrentUsageVector);
910 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
913 ec.NeedReturnLabel ();
915 ec.CurrentBranching.CurrentUsageVector.Break ();
919 protected override void DoEmit (EmitContext ec)
921 ILGenerator ig = ec.ig;
924 ig.Emit (OpCodes.Leave, ec.LoopEnd);
926 ig.Emit (OpCodes.Br, ec.LoopEnd);
931 public class Continue : Statement {
933 public Continue (Location l)
940 public override bool Resolve (EmitContext ec)
942 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
943 Error (139, "No enclosing loop to continue to");
945 } else if (ec.CurrentBranching.InFinally (false)) {
946 Error (157, "Control can not leave the body of the finally block");
948 } else if (ec.CurrentBranching.InTryOrCatch (false))
949 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
951 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
953 ec.CurrentBranching.CurrentUsageVector.Goto ();
957 protected override void DoEmit (EmitContext ec)
959 Label begin = ec.LoopBegin;
962 ec.ig.Emit (OpCodes.Leave, begin);
964 ec.ig.Emit (OpCodes.Br, begin);
969 // The information about a user-perceived local variable
971 public class LocalInfo {
972 public Expression Type;
975 // Most of the time a variable will be stored in a LocalBuilder
977 // But sometimes, it will be stored in a field (variables that have been
978 // hoisted by iterators or by anonymous methods). The context of the field will
979 // be stored in the EmitContext
982 public LocalBuilder LocalBuilder;
983 public FieldBuilder FieldBuilder;
985 public Type VariableType;
986 public readonly string Name;
987 public readonly Location Location;
988 public readonly Block Block;
990 public VariableInfo VariableInfo;
1003 public LocalInfo (Expression type, string name, Block block, Location l)
1011 public LocalInfo (TypeContainer tc, Block block, Location l)
1013 VariableType = tc.TypeBuilder;
1018 public bool IsThisAssigned (EmitContext ec, Location loc)
1020 if (VariableInfo == null)
1021 throw new Exception ();
1023 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1026 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1029 public bool IsAssigned (EmitContext ec)
1031 if (VariableInfo == null)
1032 throw new Exception ();
1034 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1037 public bool Resolve (EmitContext ec)
1039 if (VariableType == null) {
1040 TypeExpr texpr = Type.ResolveAsTypeTerminal (ec, false);
1044 VariableType = texpr.ResolveType (ec);
1047 if (VariableType == TypeManager.void_type) {
1048 Report.Error (1547, Location,
1049 "Keyword 'void' cannot be used in this context");
1053 if (VariableType.IsAbstract && VariableType.IsSealed) {
1054 Report.Error (723, Location, "Cannot declare variable of static type '{0}'", TypeManager.CSharpName (VariableType));
1057 // TODO: breaks the build
1058 // if (VariableType.IsPointer && !ec.InUnsafe)
1059 // Expression.UnsafeError (Location);
1065 // Whether the variable is Fixed (because its Pinned or its a value type)
1067 public bool IsFixed {
1069 if (((flags & Flags.Pinned) != 0) || TypeManager.IsValueType (VariableType))
1076 public bool IsCaptured {
1078 return (flags & Flags.Captured) != 0;
1082 flags |= Flags.Captured;
1086 public bool AddressTaken {
1088 return (flags & Flags.AddressTaken) != 0;
1092 flags |= Flags.AddressTaken;
1096 public override string ToString ()
1098 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1099 Name, Type, VariableInfo, Location);
1104 return (flags & Flags.Used) != 0;
1107 flags = value ? (flags | Flags.Used) : (unchecked (flags & ~Flags.Used));
1111 public bool ReadOnly {
1113 return (flags & Flags.ReadOnly) != 0;
1116 flags = value ? (flags | Flags.ReadOnly) : (unchecked (flags & ~Flags.ReadOnly));
1121 // Whether the variable is pinned, if Pinned the variable has been
1122 // allocated in a pinned slot with DeclareLocal.
1124 public bool Pinned {
1126 return (flags & Flags.Pinned) != 0;
1129 flags = value ? (flags | Flags.Pinned) : (flags & ~Flags.Pinned);
1133 public bool IsThis {
1135 return (flags & Flags.IsThis) != 0;
1138 flags = value ? (flags | Flags.IsThis) : (flags & ~Flags.IsThis);
1144 /// Block represents a C# block.
1148 /// This class is used in a number of places: either to represent
1149 /// explicit blocks that the programmer places or implicit blocks.
1151 /// Implicit blocks are used as labels or to introduce variable
1154 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1155 /// they contain extra information that is not necessary on normal blocks.
1157 public class Block : Statement {
1158 public Block Parent;
1159 public readonly Location StartLocation;
1160 public Location EndLocation = Location.Null;
1167 VariablesInitialized = 8,
1176 public bool Implicit {
1178 return (flags & Flags.Implicit) != 0;
1182 public bool Unchecked {
1184 return (flags & Flags.Unchecked) != 0;
1187 flags |= Flags.Unchecked;
1191 public bool Unsafe {
1193 return (flags & Flags.Unsafe) != 0;
1196 flags |= Flags.Unsafe;
1200 public bool HasVarargs {
1203 return Parent.HasVarargs;
1205 return (flags & Flags.HasVarargs) != 0;
1208 flags |= Flags.HasVarargs;
1213 // The statements in this block
1215 ArrayList statements;
1219 // An array of Blocks. We keep track of children just
1220 // to generate the local variable declarations.
1222 // Statements and child statements are handled through the
1228 // Labels. (label, block) pairs.
1233 // Keeps track of (name, type) pairs
1235 Hashtable variables;
1238 // Keeps track of constants
1239 Hashtable constants;
1242 // The parameters for the block, this is only needed on the toplevel block really
1243 // TODO: move `parameters' into ToplevelBlock
1244 Parameters parameters;
1247 // If this is a switch section, the enclosing switch block.
1251 protected static int id;
1255 public Block (Block parent)
1256 : this (parent, (Flags) 0, Location.Null, Location.Null)
1259 public Block (Block parent, Flags flags)
1260 : this (parent, flags, Location.Null, Location.Null)
1263 public Block (Block parent, Flags flags, Parameters parameters)
1264 : this (parent, flags, parameters, Location.Null, Location.Null)
1267 public Block (Block parent, Location start, Location end)
1268 : this (parent, (Flags) 0, start, end)
1271 public Block (Block parent, Parameters parameters, Location start, Location end)
1272 : this (parent, (Flags) 0, parameters, start, end)
1275 public Block (Block parent, Flags flags, Location start, Location end)
1276 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1279 public Block (Block parent, Flags flags, Parameters parameters,
1280 Location start, Location end)
1283 parent.AddChild (this);
1285 this.Parent = parent;
1287 this.parameters = parameters;
1288 this.StartLocation = start;
1289 this.EndLocation = end;
1292 statements = new ArrayList ();
1294 if (parent != null && Implicit) {
1295 if (parent.child_variable_names == null)
1296 parent.child_variable_names = new Hashtable();
1297 // share with parent
1298 child_variable_names = parent.child_variable_names;
1303 public Block CreateSwitchBlock (Location start)
1305 Block new_block = new Block (this, start, start);
1306 new_block.switch_block = this;
1316 void AddChild (Block b)
1318 if (children == null)
1319 children = new ArrayList ();
1324 public void SetEndLocation (Location loc)
1330 /// Adds a label to the current block.
1334 /// false if the name already exists in this block. true
1338 public bool AddLabel (string name, LabeledStatement target, Location loc)
1340 if (switch_block != null)
1341 return switch_block.AddLabel (name, target, loc);
1344 while (cur != null) {
1345 if (cur.DoLookupLabel (name) != null) {
1347 140, loc, "The label '{0}' is a duplicate",
1358 while (cur != null) {
1359 if (cur.DoLookupLabel (name) != null) {
1362 "The label '{0}' shadows another label " +
1363 "by the same name in a containing scope.",
1368 if (children != null) {
1369 foreach (Block b in children) {
1370 LabeledStatement s = b.DoLookupLabel (name);
1376 "The label '{0}' shadows another " +
1377 "label by the same name in a " +
1378 "containing scope.",
1389 labels = new Hashtable ();
1391 labels.Add (name, target);
1395 public LabeledStatement LookupLabel (string name)
1397 LabeledStatement s = DoLookupLabel (name);
1401 if (children == null)
1404 foreach (Block child in children) {
1405 if (!child.Implicit)
1408 s = child.LookupLabel (name);
1416 LabeledStatement DoLookupLabel (string name)
1418 if (switch_block != null)
1419 return switch_block.LookupLabel (name);
1422 if (labels.Contains (name))
1423 return ((LabeledStatement) labels [name]);
1428 LocalInfo this_variable = null;
1431 // Returns the "this" instance variable of this block.
1432 // See AddThisVariable() for more information.
1434 public LocalInfo ThisVariable {
1436 for (Block b = this; b != null; b = b.Parent) {
1437 if (b.this_variable != null)
1438 return b.this_variable;
1445 Hashtable child_variable_names;
1448 // Marks a variable with name @name as being used in a child block.
1449 // If a variable name has been used in a child block, it's illegal to
1450 // declare a variable with the same name in the current block.
1452 public void AddChildVariableName (string name)
1454 if (child_variable_names == null)
1455 child_variable_names = new Hashtable ();
1457 child_variable_names [name] = null;
1461 // Checks whether a variable name has already been used in a child block.
1463 public bool IsVariableNameUsedInChildBlock (string name)
1465 if (child_variable_names == null)
1468 return child_variable_names.Contains (name);
1472 // This is used by non-static `struct' constructors which do not have an
1473 // initializer - in this case, the constructor must initialize all of the
1474 // struct's fields. To do this, we add a "this" variable and use the flow
1475 // analysis code to ensure that it's been fully initialized before control
1476 // leaves the constructor.
1478 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1480 if (this_variable != null)
1481 return this_variable;
1483 if (variables == null)
1484 variables = new Hashtable ();
1486 this_variable = new LocalInfo (tc, this, l);
1487 this_variable.Used = true;
1488 this_variable.IsThis = true;
1490 variables.Add ("this", this_variable);
1492 return this_variable;
1495 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1497 if (variables == null)
1498 variables = new Hashtable ();
1500 LocalInfo vi = GetLocalInfo (name);
1502 if (vi.Block != this)
1503 Report.Error (136, l, "A local variable named `" + name + "' " +
1504 "cannot be declared in this scope since it would " +
1505 "give a different meaning to `" + name + "', which " +
1506 "is already used in a `parent or current' scope to " +
1507 "denote something else");
1509 Report.Error (128, l, "A local variable `" + name + "' is already " +
1510 "defined in this scope");
1514 if (IsVariableNameUsedInChildBlock (name)) {
1515 Report.Error (136, l, "A local variable named `" + name + "' " +
1516 "cannot be declared in this scope since it would " +
1517 "give a different meaning to `" + name + "', which " +
1518 "is already used in a `child' scope to denote something " +
1525 Parameter p = pars.GetParameterByName (name, out idx);
1527 Report.Error (136, l, "A local variable named `" + name + "' " +
1528 "cannot be declared in this scope since it would " +
1529 "give a different meaning to `" + name + "', which " +
1530 "is already used in a `parent or current' scope to " +
1531 "denote something else");
1536 vi = new LocalInfo (type, name, this, l);
1538 variables.Add (name, vi);
1540 // Mark 'name' as "used by a child block" in every surrounding block
1542 while (cur != null && cur.Implicit)
1545 for (Block par = cur.Parent; par != null; par = par.Parent)
1546 par.AddChildVariableName (name);
1548 if ((flags & Flags.VariablesInitialized) != 0)
1549 throw new Exception ();
1551 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1555 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1557 if (AddVariable (type, name, pars, l) == null)
1560 if (constants == null)
1561 constants = new Hashtable ();
1563 constants.Add (name, value);
1567 public Hashtable Variables {
1573 public LocalInfo GetLocalInfo (string name)
1575 for (Block b = this; b != null; b = b.Parent) {
1576 if (b.variables != null) {
1577 LocalInfo ret = b.variables [name] as LocalInfo;
1585 public Expression GetVariableType (string name)
1587 LocalInfo vi = GetLocalInfo (name);
1595 public Expression GetConstantExpression (string name)
1597 for (Block b = this; b != null; b = b.Parent) {
1598 if (b.constants != null) {
1599 Expression ret = b.constants [name] as Expression;
1608 /// True if the variable named @name is a constant
1610 public bool IsConstant (string name)
1612 Expression e = null;
1614 e = GetConstantExpression (name);
1620 // Returns a `ParameterReference' for the given name, or null if there
1621 // is no such parameter
1623 public ParameterReference GetParameterReference (string name, Location loc)
1628 Parameters pars = b.parameters;
1634 par = pars.GetParameterByName (name, out idx);
1636 ParameterReference pr;
1638 pr = new ParameterReference (pars, this, idx, name, loc);
1643 } while (b != null);
1648 // Whether the parameter named `name' is local to this block,
1649 // or false, if the parameter belongs to an encompassing block.
1651 public bool IsLocalParameter (string name)
1654 int toplevel_count = 0;
1657 if (this is ToplevelBlock)
1660 Parameters pars = b.parameters;
1662 if (pars.GetParameterByName (name) != null)
1666 if (toplevel_count > 0)
1669 } while (b != null);
1674 // Whether the `name' is a parameter reference
1676 public bool IsParameterReference (string name)
1681 Parameters pars = b.parameters;
1684 if (pars.GetParameterByName (name) != null)
1687 } while (b != null);
1692 /// A list of labels that were not used within this block
1694 public string [] GetUnreferenced ()
1696 // FIXME: Implement me
1700 public void AddStatement (Statement s)
1703 flags |= Flags.BlockUsed;
1708 return (flags & Flags.BlockUsed) != 0;
1714 flags |= Flags.BlockUsed;
1717 public bool HasRet {
1719 return (flags & Flags.HasRet) != 0;
1723 public bool IsDestructor {
1725 return (flags & Flags.IsDestructor) != 0;
1729 public void SetDestructor ()
1731 flags |= Flags.IsDestructor;
1734 VariableMap param_map, local_map;
1736 public VariableMap ParameterMap {
1738 if ((flags & Flags.VariablesInitialized) == 0)
1739 throw new Exception ("Variables have not been initialized yet");
1745 public VariableMap LocalMap {
1747 if ((flags & Flags.VariablesInitialized) == 0)
1748 throw new Exception ("Variables have not been initialized yet");
1755 /// Emits the variable declarations and labels.
1758 /// tc: is our typecontainer (to resolve type references)
1759 /// ig: is the code generator:
1761 public void ResolveMeta (ToplevelBlock toplevel, EmitContext ec, InternalParameters ip)
1763 bool old_unsafe = ec.InUnsafe;
1765 // If some parent block was unsafe, we remain unsafe even if this block
1766 // isn't explicitly marked as such.
1767 ec.InUnsafe |= Unsafe;
1770 // Compute the VariableMap's.
1772 // Unfortunately, we don't know the type when adding variables with
1773 // AddVariable(), so we need to compute this info here.
1777 if (variables != null) {
1778 foreach (LocalInfo li in variables.Values)
1781 locals = new LocalInfo [variables.Count];
1782 variables.Values.CopyTo (locals, 0);
1784 locals = new LocalInfo [0];
1787 local_map = new VariableMap (Parent.LocalMap, locals);
1789 local_map = new VariableMap (locals);
1791 param_map = new VariableMap (ip);
1792 flags |= Flags.VariablesInitialized;
1794 bool old_check_state = ec.ConstantCheckState;
1795 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1798 // Process this block variables
1800 if (variables != null){
1801 foreach (DictionaryEntry de in variables){
1802 string name = (string) de.Key;
1803 LocalInfo vi = (LocalInfo) de.Value;
1805 if (vi.VariableType == null)
1808 Type variable_type = vi.VariableType;
1810 if (variable_type.IsPointer){
1812 // Am not really convinced that this test is required (Microsoft does it)
1813 // but the fact is that you would not be able to use the pointer variable
1816 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1823 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1826 // This is needed to compile on both .NET 1.x and .NET 2.x
1827 // the later introduced `DeclareLocal (Type t, bool pinned)'
1829 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1830 else if (!vi.IsThis)
1831 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1834 if (constants == null)
1837 Expression cv = (Expression) constants [name];
1841 ec.CurrentBlock = this;
1842 Expression e = cv.Resolve (ec);
1846 Constant ce = e as Constant;
1848 Report.Error (133, vi.Location,
1849 "The expression being assigned to `" +
1850 name + "' must be constant (" + e + ")");
1854 if (e.Type != variable_type){
1855 e = Const.ChangeType (vi.Location, ce, variable_type);
1860 constants.Remove (name);
1861 constants.Add (name, e);
1864 ec.ConstantCheckState = old_check_state;
1867 // Now, handle the children
1869 if (children != null){
1870 foreach (Block b in children)
1871 b.ResolveMeta (toplevel, ec, ip);
1873 ec.InUnsafe = old_unsafe;
1877 // Emits the local variable declarations for a block
1879 public void EmitMeta (EmitContext ec)
1881 ILGenerator ig = ec.ig;
1883 if (variables != null){
1884 bool have_captured_vars = ec.HaveCapturedVariables ();
1885 bool remap_locals = ec.RemapToProxy;
1887 foreach (DictionaryEntry de in variables){
1888 LocalInfo vi = (LocalInfo) de.Value;
1890 if (have_captured_vars && ec.IsCaptured (vi))
1894 vi.FieldBuilder = ec.MapVariable (vi.Name, vi.VariableType);
1898 // This is needed to compile on both .NET 1.x and .NET 2.x
1899 // the later introduced `DeclareLocal (Type t, bool pinned)'
1901 vi.LocalBuilder = TypeManager.DeclareLocalPinned (ig, vi.VariableType);
1902 else if (!vi.IsThis)
1903 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1908 if (children != null){
1909 foreach (Block b in children)
1914 void UsageWarning (FlowBranching.UsageVector vector)
1918 if ((variables != null) && (RootContext.WarningLevel >= 3)) {
1919 foreach (DictionaryEntry de in variables){
1920 LocalInfo vi = (LocalInfo) de.Value;
1925 name = (string) de.Key;
1927 if (vector.IsAssigned (vi.VariableInfo)){
1928 Report.Warning (219, vi.Location, "The variable '{0}' is assigned but its value is never used", name);
1930 Report.Warning (168, vi.Location, "The variable '{0}' is declared but never used", name);
1936 bool unreachable_shown;
1938 public override bool Resolve (EmitContext ec)
1940 Block prev_block = ec.CurrentBlock;
1943 int errors = Report.Errors;
1945 ec.CurrentBlock = this;
1946 ec.StartFlowBranching (this);
1948 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1950 bool unreachable = false;
1952 int statement_count = statements.Count;
1953 for (int ix = 0; ix < statement_count; ix++){
1954 Statement s = (Statement) statements [ix];
1956 if (unreachable && !(s is LabeledStatement)) {
1957 if (s == EmptyStatement.Value)
1958 s.loc = EndLocation;
1960 if (!s.ResolveUnreachable (ec, !unreachable_shown))
1963 if (s != EmptyStatement.Value)
1964 unreachable_shown = true;
1966 s.loc = Location.Null;
1968 statements [ix] = EmptyStatement.Value;
1972 if (s.Resolve (ec) == false) {
1974 statements [ix] = EmptyStatement.Value;
1978 num_statements = ix + 1;
1980 if (s is LabeledStatement)
1981 unreachable = false;
1983 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1986 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1987 ec.CurrentBranching, statement_count, num_statements);
1990 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1992 ec.CurrentBlock = prev_block;
1994 // If we're a non-static `struct' constructor which doesn't have an
1995 // initializer, then we must initialize all of the struct's fields.
1996 if ((this_variable != null) &&
1997 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1998 !this_variable.IsThisAssigned (ec, loc))
2001 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
2002 foreach (LabeledStatement label in labels.Values)
2003 if (!label.HasBeenReferenced)
2004 Report.Warning (164, label.Location,
2005 "This label has not been referenced");
2008 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
2010 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
2011 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
2012 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
2013 flags |= Flags.HasRet;
2015 if (ok && (errors == Report.Errors)) {
2016 if (RootContext.WarningLevel >= 3)
2017 UsageWarning (vector);
2023 public override bool ResolveUnreachable (EmitContext ec, bool warn)
2025 unreachable_shown = true;
2026 return base.ResolveUnreachable (ec, warn);
2029 protected override void DoEmit (EmitContext ec)
2031 for (int ix = 0; ix < num_statements; ix++){
2032 Statement s = (Statement) statements [ix];
2034 // Check whether we are the last statement in a
2037 if ((Parent == null) && (ix+1 == num_statements))
2038 ec.IsLastStatement = true;
2040 ec.IsLastStatement = false;
2046 public override void Emit (EmitContext ec)
2048 Block prev_block = ec.CurrentBlock;
2050 ec.CurrentBlock = this;
2052 bool emit_debug_info = (CodeGen.SymbolWriter != null);
2053 bool is_lexical_block = !Implicit && (Parent != null);
2055 if (emit_debug_info) {
2056 if (is_lexical_block)
2057 ec.ig.BeginScope ();
2059 if (variables != null) {
2060 foreach (DictionaryEntry de in variables) {
2061 string name = (string) de.Key;
2062 LocalInfo vi = (LocalInfo) de.Value;
2064 if (vi.LocalBuilder == null)
2067 ec.DefineLocalVariable (name, vi.LocalBuilder);
2072 ec.Mark (StartLocation, true);
2074 ec.Mark (EndLocation, true);
2076 if (emit_debug_info && is_lexical_block)
2079 ec.CurrentBlock = prev_block;
2082 public ToplevelBlock Toplevel {
2085 while (b.Parent != null){
2086 if ((b.flags & Flags.IsToplevel) != 0)
2091 return (ToplevelBlock) b;
2096 // Returns true if we ar ea child of `b'.
2098 public bool IsChildOf (Block b)
2100 Block current = this;
2103 if (current.Parent == b)
2105 current = current.Parent;
2106 } while (current != null);
2112 // A toplevel block contains extra information, the split is done
2113 // only to separate information that would otherwise bloat the more
2114 // lightweight Block.
2116 // In particular, this was introduced when the support for Anonymous
2117 // Methods was implemented.
2119 public class ToplevelBlock : Block {
2121 // Pointer to the host of this anonymous method, or null
2122 // if we are the topmost block
2124 public ToplevelBlock Container;
2125 CaptureContext capture_context;
2127 Hashtable capture_contexts;
2132 public void RegisterCaptureContext (CaptureContext cc)
2134 if (capture_contexts == null)
2135 capture_contexts = new Hashtable ();
2136 capture_contexts [cc] = cc;
2139 public void CompleteContexts ()
2141 if (capture_contexts == null)
2144 foreach (CaptureContext cc in capture_contexts.Keys){
2149 public CaptureContext ToplevelBlockCaptureContext {
2151 return capture_context;
2156 // Parent is only used by anonymous blocks to link back to their
2159 public ToplevelBlock (ToplevelBlock container, Parameters parameters, Location start) :
2160 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2162 Container = container;
2165 public ToplevelBlock (Parameters parameters, Location start) :
2166 base (null, Flags.IsToplevel, parameters, start, Location.Null)
2170 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
2171 base (null, flags | Flags.IsToplevel, parameters, start, Location.Null)
2175 public ToplevelBlock (Location loc) : base (null, Flags.IsToplevel, loc, loc)
2179 public void SetHaveAnonymousMethods (Location loc, AnonymousMethod host)
2181 if (capture_context == null)
2182 capture_context = new CaptureContext (this, loc, host);
2185 public CaptureContext CaptureContext {
2187 return capture_context;
2192 public class SwitchLabel {
2195 public Location loc;
2199 Label il_label_code;
2200 bool il_label_code_set;
2203 // if expr == null, then it is the default case.
2205 public SwitchLabel (Expression expr, Location l)
2211 public Expression Label {
2217 public object Converted {
2223 public Label GetILLabel (EmitContext ec)
2226 il_label = ec.ig.DefineLabel ();
2227 il_label_set = true;
2232 public Label GetILLabelCode (EmitContext ec)
2234 if (!il_label_code_set){
2235 il_label_code = ec.ig.DefineLabel ();
2236 il_label_code_set = true;
2238 return il_label_code;
2242 // Resolves the expression, reduces it to a literal if possible
2243 // and then converts it to the requested type.
2245 public bool ResolveAndReduce (EmitContext ec, Type required_type)
2250 Expression e = label.Resolve (ec);
2255 if (!(e is Constant)){
2256 Report.Error (150, loc, "A constant value is expected, got: " + e);
2260 if (e is StringConstant || e is NullLiteral){
2261 if (required_type == TypeManager.string_type){
2267 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
2268 if (converted == null)
2275 public class SwitchSection {
2276 // An array of SwitchLabels.
2277 public readonly ArrayList Labels;
2278 public readonly Block Block;
2280 public SwitchSection (ArrayList labels, Block block)
2287 public class Switch : Statement {
2288 public readonly ArrayList Sections;
2289 public Expression Expr;
2292 /// Maps constants whose type type SwitchType to their SwitchLabels.
2294 public Hashtable Elements;
2297 /// The governing switch type
2299 public Type SwitchType;
2305 Label default_target;
2306 Expression new_expr;
2308 SwitchSection constant_section;
2311 // The types allowed to be implicitly cast from
2312 // on the governing type
2314 static Type [] allowed_types;
2316 public Switch (Expression e, ArrayList sects, Location l)
2323 public bool GotDefault {
2329 public Label DefaultTarget {
2331 return default_target;
2336 // Determines the governing type for a switch. The returned
2337 // expression might be the expression from the switch, or an
2338 // expression that includes any potential conversions to the
2339 // integral types or to string.
2341 Expression SwitchGoverningType (EmitContext ec, Type t)
2343 if (t == TypeManager.int32_type ||
2344 t == TypeManager.uint32_type ||
2345 t == TypeManager.char_type ||
2346 t == TypeManager.byte_type ||
2347 t == TypeManager.sbyte_type ||
2348 t == TypeManager.ushort_type ||
2349 t == TypeManager.short_type ||
2350 t == TypeManager.uint64_type ||
2351 t == TypeManager.int64_type ||
2352 t == TypeManager.string_type ||
2353 t == TypeManager.bool_type ||
2354 t.IsSubclassOf (TypeManager.enum_type))
2357 if (allowed_types == null){
2358 allowed_types = new Type [] {
2359 TypeManager.int32_type,
2360 TypeManager.uint32_type,
2361 TypeManager.sbyte_type,
2362 TypeManager.byte_type,
2363 TypeManager.short_type,
2364 TypeManager.ushort_type,
2365 TypeManager.int64_type,
2366 TypeManager.uint64_type,
2367 TypeManager.char_type,
2368 TypeManager.bool_type,
2369 TypeManager.string_type
2374 // Try to find a *user* defined implicit conversion.
2376 // If there is no implicit conversion, or if there are multiple
2377 // conversions, we have to report an error
2379 Expression converted = null;
2380 foreach (Type tt in allowed_types){
2383 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2388 // Ignore over-worked ImplicitUserConversions that do
2389 // an implicit conversion in addition to the user conversion.
2392 UserCast ue = e as UserCast;
2394 if (ue.Source != Expr)
2398 if (converted != null){
2399 Report.ExtraInformation (
2401 String.Format ("reason: more than one conversion to an integral type exist for type {0}",
2402 TypeManager.CSharpName (Expr.Type)));
2411 static string Error152 {
2413 return "The label '{0}:' already occurs in this switch statement";
2418 // Performs the basic sanity checks on the switch statement
2419 // (looks for duplicate keys and non-constant expressions).
2421 // It also returns a hashtable with the keys that we will later
2422 // use to compute the switch tables
2424 bool CheckSwitch (EmitContext ec)
2428 Elements = new Hashtable ();
2430 got_default = false;
2432 if (TypeManager.IsEnumType (SwitchType)){
2433 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2435 compare_type = SwitchType;
2437 foreach (SwitchSection ss in Sections){
2438 foreach (SwitchLabel sl in ss.Labels){
2439 if (!sl.ResolveAndReduce (ec, SwitchType)){
2444 if (sl.Label == null){
2446 Report.Error (152, sl.loc, Error152, "default");
2453 object key = sl.Converted;
2455 if (key is Constant)
2456 key = ((Constant) key).GetValue ();
2459 key = NullLiteral.Null;
2461 string lname = null;
2462 if (compare_type == TypeManager.uint64_type){
2463 ulong v = (ulong) key;
2465 if (Elements.Contains (v))
2466 lname = v.ToString ();
2468 Elements.Add (v, sl);
2469 } else if (compare_type == TypeManager.int64_type){
2470 long v = (long) key;
2472 if (Elements.Contains (v))
2473 lname = v.ToString ();
2475 Elements.Add (v, sl);
2476 } else if (compare_type == TypeManager.uint32_type){
2477 uint v = (uint) key;
2479 if (Elements.Contains (v))
2480 lname = v.ToString ();
2482 Elements.Add (v, sl);
2483 } else if (compare_type == TypeManager.char_type){
2484 char v = (char) key;
2486 if (Elements.Contains (v))
2487 lname = v.ToString ();
2489 Elements.Add (v, sl);
2490 } else if (compare_type == TypeManager.byte_type){
2491 byte v = (byte) key;
2493 if (Elements.Contains (v))
2494 lname = v.ToString ();
2496 Elements.Add (v, sl);
2497 } else if (compare_type == TypeManager.sbyte_type){
2498 sbyte v = (sbyte) key;
2500 if (Elements.Contains (v))
2501 lname = v.ToString ();
2503 Elements.Add (v, sl);
2504 } else if (compare_type == TypeManager.short_type){
2505 short v = (short) key;
2507 if (Elements.Contains (v))
2508 lname = v.ToString ();
2510 Elements.Add (v, sl);
2511 } else if (compare_type == TypeManager.ushort_type){
2512 ushort v = (ushort) key;
2514 if (Elements.Contains (v))
2515 lname = v.ToString ();
2517 Elements.Add (v, sl);
2518 } else if (compare_type == TypeManager.string_type){
2519 if (key is NullLiteral){
2520 if (Elements.Contains (NullLiteral.Null))
2523 Elements.Add (NullLiteral.Null, null);
2525 string s = (string) key;
2527 if (Elements.Contains (s))
2530 Elements.Add (s, sl);
2532 } else if (compare_type == TypeManager.int32_type) {
2535 if (Elements.Contains (v))
2536 lname = v.ToString ();
2538 Elements.Add (v, sl);
2539 } else if (compare_type == TypeManager.bool_type) {
2540 bool v = (bool) key;
2542 if (Elements.Contains (v))
2543 lname = v.ToString ();
2545 Elements.Add (v, sl);
2549 throw new Exception ("Unknown switch type!" +
2550 SwitchType + " " + compare_type);
2553 if (lname != null) {
2554 Report.Error (152, sl.loc, Error152, "case " + lname);
2565 void EmitObjectInteger (ILGenerator ig, object k)
2568 IntConstant.EmitInt (ig, (int) k);
2569 else if (k is Constant) {
2570 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2573 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2576 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2578 IntConstant.EmitInt (ig, (int) (long) k);
2579 ig.Emit (OpCodes.Conv_I8);
2582 LongConstant.EmitLong (ig, (long) k);
2584 else if (k is ulong)
2586 if ((ulong) k < (1L<<32))
2588 IntConstant.EmitInt (ig, (int) (long) k);
2589 ig.Emit (OpCodes.Conv_U8);
2593 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2597 IntConstant.EmitInt (ig, (int) ((char) k));
2598 else if (k is sbyte)
2599 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2601 IntConstant.EmitInt (ig, (int) ((byte) k));
2602 else if (k is short)
2603 IntConstant.EmitInt (ig, (int) ((short) k));
2604 else if (k is ushort)
2605 IntConstant.EmitInt (ig, (int) ((ushort) k));
2607 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2609 throw new Exception ("Unhandled case");
2612 // structure used to hold blocks of keys while calculating table switch
2613 class KeyBlock : IComparable
2615 public KeyBlock (long _nFirst)
2617 nFirst = nLast = _nFirst;
2621 public ArrayList rgKeys = null;
2622 // how many items are in the bucket
2623 public int Size = 1;
2626 get { return (int) (nLast - nFirst + 1); }
2628 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2630 return kbLast.nLast - kbFirst.nFirst + 1;
2632 public int CompareTo (object obj)
2634 KeyBlock kb = (KeyBlock) obj;
2635 int nLength = Length;
2636 int nLengthOther = kb.Length;
2637 if (nLengthOther == nLength)
2638 return (int) (kb.nFirst - nFirst);
2639 return nLength - nLengthOther;
2644 /// This method emits code for a lookup-based switch statement (non-string)
2645 /// Basically it groups the cases into blocks that are at least half full,
2646 /// and then spits out individual lookup opcodes for each block.
2647 /// It emits the longest blocks first, and short blocks are just
2648 /// handled with direct compares.
2650 /// <param name="ec"></param>
2651 /// <param name="val"></param>
2652 /// <returns></returns>
2653 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2655 int cElements = Elements.Count;
2656 object [] rgKeys = new object [cElements];
2657 Elements.Keys.CopyTo (rgKeys, 0);
2658 Array.Sort (rgKeys);
2660 // initialize the block list with one element per key
2661 ArrayList rgKeyBlocks = new ArrayList ();
2662 foreach (object key in rgKeys)
2663 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2666 // iteratively merge the blocks while they are at least half full
2667 // there's probably a really cool way to do this with a tree...
2668 while (rgKeyBlocks.Count > 1)
2670 ArrayList rgKeyBlocksNew = new ArrayList ();
2671 kbCurr = (KeyBlock) rgKeyBlocks [0];
2672 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2674 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2675 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2678 kbCurr.nLast = kb.nLast;
2679 kbCurr.Size += kb.Size;
2683 // start a new block
2684 rgKeyBlocksNew.Add (kbCurr);
2688 rgKeyBlocksNew.Add (kbCurr);
2689 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2691 rgKeyBlocks = rgKeyBlocksNew;
2694 // initialize the key lists
2695 foreach (KeyBlock kb in rgKeyBlocks)
2696 kb.rgKeys = new ArrayList ();
2698 // fill the key lists
2700 if (rgKeyBlocks.Count > 0) {
2701 kbCurr = (KeyBlock) rgKeyBlocks [0];
2702 foreach (object key in rgKeys)
2704 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2705 System.Convert.ToInt64 (key) > kbCurr.nLast;
2707 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2708 kbCurr.rgKeys.Add (key);
2712 // sort the blocks so we can tackle the largest ones first
2713 rgKeyBlocks.Sort ();
2715 // okay now we can start...
2716 ILGenerator ig = ec.ig;
2717 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2718 Label lblDefault = ig.DefineLabel ();
2720 Type typeKeys = null;
2721 if (rgKeys.Length > 0)
2722 typeKeys = rgKeys [0].GetType (); // used for conversions
2726 if (TypeManager.IsEnumType (SwitchType))
2727 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2729 compare_type = SwitchType;
2731 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2733 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2734 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2737 foreach (object key in kb.rgKeys)
2739 ig.Emit (OpCodes.Ldloc, val);
2740 EmitObjectInteger (ig, key);
2741 SwitchLabel sl = (SwitchLabel) Elements [key];
2742 ig.Emit (OpCodes.Beq, sl.GetILLabel (ec));
2747 // TODO: if all the keys in the block are the same and there are
2748 // no gaps/defaults then just use a range-check.
2749 if (compare_type == TypeManager.int64_type ||
2750 compare_type == TypeManager.uint64_type)
2752 // TODO: optimize constant/I4 cases
2754 // check block range (could be > 2^31)
2755 ig.Emit (OpCodes.Ldloc, val);
2756 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2757 ig.Emit (OpCodes.Blt, lblDefault);
2758 ig.Emit (OpCodes.Ldloc, val);
2759 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2760 ig.Emit (OpCodes.Bgt, lblDefault);
2763 ig.Emit (OpCodes.Ldloc, val);
2766 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2767 ig.Emit (OpCodes.Sub);
2769 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2774 ig.Emit (OpCodes.Ldloc, val);
2775 int nFirst = (int) kb.nFirst;
2778 IntConstant.EmitInt (ig, nFirst);
2779 ig.Emit (OpCodes.Sub);
2781 else if (nFirst < 0)
2783 IntConstant.EmitInt (ig, -nFirst);
2784 ig.Emit (OpCodes.Add);
2788 // first, build the list of labels for the switch
2790 int cJumps = kb.Length;
2791 Label [] rgLabels = new Label [cJumps];
2792 for (int iJump = 0; iJump < cJumps; iJump++)
2794 object key = kb.rgKeys [iKey];
2795 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2797 SwitchLabel sl = (SwitchLabel) Elements [key];
2798 rgLabels [iJump] = sl.GetILLabel (ec);
2802 rgLabels [iJump] = lblDefault;
2804 // emit the switch opcode
2805 ig.Emit (OpCodes.Switch, rgLabels);
2808 // mark the default for this block
2810 ig.MarkLabel (lblDefault);
2813 // TODO: find the default case and emit it here,
2814 // to prevent having to do the following jump.
2815 // make sure to mark other labels in the default section
2817 // the last default just goes to the end
2818 ig.Emit (OpCodes.Br, lblDefault);
2820 // now emit the code for the sections
2821 bool fFoundDefault = false;
2822 foreach (SwitchSection ss in Sections)
2824 foreach (SwitchLabel sl in ss.Labels)
2826 ig.MarkLabel (sl.GetILLabel (ec));
2827 ig.MarkLabel (sl.GetILLabelCode (ec));
2828 if (sl.Label == null)
2830 ig.MarkLabel (lblDefault);
2831 fFoundDefault = true;
2835 //ig.Emit (OpCodes.Br, lblEnd);
2838 if (!fFoundDefault) {
2839 ig.MarkLabel (lblDefault);
2841 ig.MarkLabel (lblEnd);
2844 // This simple emit switch works, but does not take advantage of the
2846 // TODO: remove non-string logic from here
2847 // TODO: binary search strings?
2849 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2851 ILGenerator ig = ec.ig;
2852 Label end_of_switch = ig.DefineLabel ();
2853 Label next_test = ig.DefineLabel ();
2854 Label null_target = ig.DefineLabel ();
2855 bool default_found = false;
2856 bool first_test = true;
2857 bool pending_goto_end = false;
2859 bool default_at_end = false;
2861 ig.Emit (OpCodes.Ldloc, val);
2863 if (Elements.Contains (NullLiteral.Null)){
2864 ig.Emit (OpCodes.Brfalse, null_target);
2866 ig.Emit (OpCodes.Brfalse, default_target);
2868 ig.Emit (OpCodes.Ldloc, val);
2869 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2870 ig.Emit (OpCodes.Stloc, val);
2872 int section_count = Sections.Count;
2873 for (int section = 0; section < section_count; section++){
2874 SwitchSection ss = (SwitchSection) Sections [section];
2875 Label sec_begin = ig.DefineLabel ();
2877 if (pending_goto_end)
2878 ig.Emit (OpCodes.Br, end_of_switch);
2880 int label_count = ss.Labels.Count;
2881 bool mark_default = false;
2883 for (int label = 0; label < label_count; label++){
2884 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2885 ig.MarkLabel (sl.GetILLabel (ec));
2888 ig.MarkLabel (next_test);
2889 next_test = ig.DefineLabel ();
2892 // If we are the default target
2894 if (sl.Label == null){
2895 if (label+1 == label_count)
2896 default_at_end = true;
2897 mark_default = true;
2898 default_found = true;
2900 object lit = sl.Converted;
2902 if (lit is NullLiteral){
2904 if (label_count == 1)
2905 ig.Emit (OpCodes.Br, next_test);
2909 StringConstant str = (StringConstant) lit;
2911 ig.Emit (OpCodes.Ldloc, val);
2912 ig.Emit (OpCodes.Ldstr, str.Value);
2913 if (label_count == 1)
2914 ig.Emit (OpCodes.Bne_Un, next_test);
2916 if (label+1 == label_count)
2917 ig.Emit (OpCodes.Bne_Un, next_test);
2919 ig.Emit (OpCodes.Beq, sec_begin);
2924 ig.MarkLabel (null_target);
2925 ig.MarkLabel (sec_begin);
2926 foreach (SwitchLabel sl in ss.Labels)
2927 ig.MarkLabel (sl.GetILLabelCode (ec));
2930 ig.MarkLabel (default_target);
2932 pending_goto_end = !ss.Block.HasRet;
2935 ig.MarkLabel (next_test);
2937 if (!default_at_end)
2938 ig.Emit (OpCodes.Br, default_target);
2940 ig.MarkLabel (default_target);
2941 ig.MarkLabel (end_of_switch);
2944 SwitchSection FindSection (SwitchLabel label)
2946 foreach (SwitchSection ss in Sections){
2947 foreach (SwitchLabel sl in ss.Labels){
2956 bool ResolveConstantSwitch (EmitContext ec)
2958 object key = ((Constant) new_expr).GetValue ();
2959 SwitchLabel label = (SwitchLabel) Elements [key];
2964 constant_section = FindSection (label);
2965 if (constant_section == null)
2968 if (constant_section.Block.Resolve (ec) != true)
2974 public override bool Resolve (EmitContext ec)
2976 Expr = Expr.Resolve (ec);
2980 new_expr = SwitchGoverningType (ec, Expr.Type);
2981 if (new_expr == null){
2982 Report.Error (151, loc, "An integer type or string was expected for switch");
2987 SwitchType = new_expr.Type;
2989 if (!CheckSwitch (ec))
2992 Switch old_switch = ec.Switch;
2994 ec.Switch.SwitchType = SwitchType;
2996 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2997 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2999 is_constant = new_expr is Constant;
3001 object key = ((Constant) new_expr).GetValue ();
3002 SwitchLabel label = (SwitchLabel) Elements [key];
3004 constant_section = FindSection (label);
3008 foreach (SwitchSection ss in Sections){
3010 ec.CurrentBranching.CreateSibling (
3011 null, FlowBranching.SiblingType.SwitchSection);
3015 if (is_constant && (ss != constant_section)) {
3016 // If we're a constant switch, we're only emitting
3017 // one single section - mark all the others as
3019 ec.CurrentBranching.CurrentUsageVector.Goto ();
3020 if (!ss.Block.ResolveUnreachable (ec, true))
3023 if (!ss.Block.Resolve (ec))
3029 ec.CurrentBranching.CreateSibling (
3030 null, FlowBranching.SiblingType.SwitchSection);
3032 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3033 ec.Switch = old_switch;
3035 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
3041 protected override void DoEmit (EmitContext ec)
3043 ILGenerator ig = ec.ig;
3045 // Store variable for comparission purposes
3048 value = ig.DeclareLocal (SwitchType);
3050 ig.Emit (OpCodes.Stloc, value);
3054 default_target = ig.DefineLabel ();
3057 // Setup the codegen context
3059 Label old_end = ec.LoopEnd;
3060 Switch old_switch = ec.Switch;
3062 ec.LoopEnd = ig.DefineLabel ();
3067 if (constant_section != null)
3068 constant_section.Block.Emit (ec);
3069 } else if (SwitchType == TypeManager.string_type)
3070 SimpleSwitchEmit (ec, value);
3072 TableSwitchEmit (ec, value);
3074 // Restore context state.
3075 ig.MarkLabel (ec.LoopEnd);
3078 // Restore the previous context
3080 ec.LoopEnd = old_end;
3081 ec.Switch = old_switch;
3085 public abstract class ExceptionStatement : Statement
3087 public abstract void EmitFinally (EmitContext ec);
3089 protected bool emit_finally = true;
3090 ArrayList parent_vectors;
3092 protected void DoEmitFinally (EmitContext ec)
3095 ec.ig.BeginFinallyBlock ();
3097 ec.CurrentIterator.MarkFinally (ec, parent_vectors);
3101 protected void ResolveFinally (FlowBranchingException branching)
3103 emit_finally = branching.EmitFinally;
3105 branching.Parent.StealFinallyClauses (ref parent_vectors);
3109 public class Lock : ExceptionStatement {
3111 Statement Statement;
3114 public Lock (Expression expr, Statement stmt, Location l)
3121 public override bool Resolve (EmitContext ec)
3123 expr = expr.Resolve (ec);
3127 if (expr.Type.IsValueType){
3128 Error (185, "lock statement requires the expression to be " +
3129 " a reference type (type is: `{0}'",
3130 TypeManager.CSharpName (expr.Type));
3134 FlowBranchingException branching = ec.StartFlowBranching (this);
3135 bool ok = Statement.Resolve (ec);
3137 ec.KillFlowBranching ();
3141 ResolveFinally (branching);
3143 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3144 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3145 // Unfortunately, System.Reflection.Emit automatically emits
3146 // a leave to the end of the finally block.
3147 // This is a problem if `returns' is true since we may jump
3148 // to a point after the end of the method.
3149 // As a workaround, emit an explicit ret here.
3150 ec.NeedReturnLabel ();
3156 protected override void DoEmit (EmitContext ec)
3158 Type type = expr.Type;
3160 ILGenerator ig = ec.ig;
3161 temp = ig.DeclareLocal (type);
3164 ig.Emit (OpCodes.Dup);
3165 ig.Emit (OpCodes.Stloc, temp);
3166 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
3170 ig.BeginExceptionBlock ();
3171 Statement.Emit (ec);
3176 ig.EndExceptionBlock ();
3179 public override void EmitFinally (EmitContext ec)
3181 ILGenerator ig = ec.ig;
3182 ig.Emit (OpCodes.Ldloc, temp);
3183 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
3187 public class Unchecked : Statement {
3188 public readonly Block Block;
3190 public Unchecked (Block b)
3196 public override bool Resolve (EmitContext ec)
3198 bool previous_state = ec.CheckState;
3199 bool previous_state_const = ec.ConstantCheckState;
3201 ec.CheckState = false;
3202 ec.ConstantCheckState = false;
3203 bool ret = Block.Resolve (ec);
3204 ec.CheckState = previous_state;
3205 ec.ConstantCheckState = previous_state_const;
3210 protected override void DoEmit (EmitContext ec)
3212 bool previous_state = ec.CheckState;
3213 bool previous_state_const = ec.ConstantCheckState;
3215 ec.CheckState = false;
3216 ec.ConstantCheckState = false;
3218 ec.CheckState = previous_state;
3219 ec.ConstantCheckState = previous_state_const;
3223 public class Checked : Statement {
3224 public readonly Block Block;
3226 public Checked (Block b)
3229 b.Unchecked = false;
3232 public override bool Resolve (EmitContext ec)
3234 bool previous_state = ec.CheckState;
3235 bool previous_state_const = ec.ConstantCheckState;
3237 ec.CheckState = true;
3238 ec.ConstantCheckState = true;
3239 bool ret = Block.Resolve (ec);
3240 ec.CheckState = previous_state;
3241 ec.ConstantCheckState = previous_state_const;
3246 protected override void DoEmit (EmitContext ec)
3248 bool previous_state = ec.CheckState;
3249 bool previous_state_const = ec.ConstantCheckState;
3251 ec.CheckState = true;
3252 ec.ConstantCheckState = true;
3254 ec.CheckState = previous_state;
3255 ec.ConstantCheckState = previous_state_const;
3259 public class Unsafe : Statement {
3260 public readonly Block Block;
3262 public Unsafe (Block b)
3265 Block.Unsafe = true;
3268 public override bool Resolve (EmitContext ec)
3270 bool previous_state = ec.InUnsafe;
3274 val = Block.Resolve (ec);
3275 ec.InUnsafe = previous_state;
3280 protected override void DoEmit (EmitContext ec)
3282 bool previous_state = ec.InUnsafe;
3286 ec.InUnsafe = previous_state;
3293 public class Fixed : Statement {
3295 ArrayList declarators;
3296 Statement statement;
3302 public bool is_object;
3303 public LocalInfo vi;
3304 public Expression expr;
3305 public Expression converted;
3308 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
3311 declarators = decls;
3316 public override bool Resolve (EmitContext ec)
3319 Expression.UnsafeError (loc);
3323 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
3327 expr_type = texpr.ResolveType (ec);
3329 CheckObsolete (expr_type);
3331 if (ec.RemapToProxy){
3332 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
3336 data = new FixedData [declarators.Count];
3338 if (!expr_type.IsPointer){
3339 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
3344 foreach (Pair p in declarators){
3345 LocalInfo vi = (LocalInfo) p.First;
3346 Expression e = (Expression) p.Second;
3348 vi.VariableInfo.SetAssigned (ec);
3352 // The rules for the possible declarators are pretty wise,
3353 // but the production on the grammar is more concise.
3355 // So we have to enforce these rules here.
3357 // We do not resolve before doing the case 1 test,
3358 // because the grammar is explicit in that the token &
3359 // is present, so we need to test for this particular case.
3363 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
3368 // Case 1: & object.
3370 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
3371 Expression child = ((Unary) e).Expr;
3373 if (child is ParameterReference || child is LocalVariableReference){
3376 "No need to use fixed statement for parameters or " +
3377 "local variable declarations (address is already " +
3382 ec.InFixedInitializer = true;
3384 ec.InFixedInitializer = false;
3388 child = ((Unary) e).Expr;
3390 if (!TypeManager.VerifyUnManaged (child.Type, loc))
3393 data [i].is_object = true;
3395 data [i].converted = null;
3402 ec.InFixedInitializer = true;
3404 ec.InFixedInitializer = false;
3411 if (e.Type.IsArray){
3412 Type array_type = TypeManager.GetElementType (e.Type);
3415 // Provided that array_type is unmanaged,
3417 if (!TypeManager.VerifyUnManaged (array_type, loc))
3421 // and T* is implicitly convertible to the
3422 // pointer type given in the fixed statement.
3424 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3426 Expression converted = Convert.ImplicitConversionRequired (
3427 ec, array_ptr, vi.VariableType, loc);
3428 if (converted == null)
3431 data [i].is_object = false;
3433 data [i].converted = converted;
3443 if (e.Type == TypeManager.string_type){
3444 data [i].is_object = false;
3446 data [i].converted = null;
3453 // For other cases, flag a `this is already fixed expression'
3455 if (e is LocalVariableReference || e is ParameterReference ||
3456 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3458 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3462 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3466 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3468 if (!statement.Resolve (ec)) {
3469 ec.KillFlowBranching ();
3473 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3474 has_ret = reachability.IsUnreachable;
3479 protected override void DoEmit (EmitContext ec)
3481 ILGenerator ig = ec.ig;
3483 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3485 for (int i = 0; i < data.Length; i++) {
3486 LocalInfo vi = data [i].vi;
3489 // Case 1: & object.
3491 if (data [i].is_object) {
3493 // Store pointer in pinned location
3495 data [i].expr.Emit (ec);
3496 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3497 clear_list [i] = vi.LocalBuilder;
3504 if (data [i].expr.Type.IsArray){
3506 // Store pointer in pinned location
3508 data [i].converted.Emit (ec);
3510 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3511 clear_list [i] = vi.LocalBuilder;
3518 if (data [i].expr.Type == TypeManager.string_type){
3519 LocalBuilder pinned_string = TypeManager.DeclareLocalPinned (ig, TypeManager.string_type);
3520 clear_list [i] = pinned_string;
3522 data [i].expr.Emit (ec);
3523 ig.Emit (OpCodes.Stloc, pinned_string);
3525 Expression sptr = new StringPtr (pinned_string, loc);
3526 Expression converted = Convert.ImplicitConversionRequired (
3527 ec, sptr, vi.VariableType, loc);
3529 if (converted == null)
3532 converted.Emit (ec);
3533 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3537 statement.Emit (ec);
3543 // Clear the pinned variable
3545 for (int i = 0; i < data.Length; i++) {
3546 if (data [i].is_object || data [i].expr.Type.IsArray) {
3547 ig.Emit (OpCodes.Ldc_I4_0);
3548 ig.Emit (OpCodes.Conv_U);
3549 ig.Emit (OpCodes.Stloc, clear_list [i]);
3550 } else if (data [i].expr.Type == TypeManager.string_type){
3551 ig.Emit (OpCodes.Ldnull);
3552 ig.Emit (OpCodes.Stloc, clear_list [i]);
3558 public class Catch: Statement {
3559 public readonly string Name;
3560 public readonly Block Block;
3562 Expression type_expr;
3565 public Catch (Expression type, string name, Block block, Location l)
3573 public Type CatchType {
3579 public bool IsGeneral {
3581 return type_expr == null;
3585 protected override void DoEmit(EmitContext ec)
3589 public override bool Resolve (EmitContext ec)
3591 if (type_expr != null) {
3592 TypeExpr te = type_expr.ResolveAsTypeTerminal (ec, false);
3596 type = te.ResolveType (ec);
3598 CheckObsolete (type);
3600 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3601 Error (155, "The type caught or thrown must be derived from System.Exception");
3607 return Block.Resolve (ec);
3611 public class Try : ExceptionStatement {
3612 public readonly Block Fini, Block;
3613 public readonly ArrayList Specific;
3614 public readonly Catch General;
3616 bool need_exc_block;
3619 // specific, general and fini might all be null.
3621 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3623 if (specific == null && general == null){
3624 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3628 this.Specific = specific;
3629 this.General = general;
3634 public override bool Resolve (EmitContext ec)
3638 FlowBranchingException branching = ec.StartFlowBranching (this);
3640 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3642 if (!Block.Resolve (ec))
3645 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3647 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3649 Type[] prevCatches = new Type [Specific.Count];
3651 foreach (Catch c in Specific){
3652 ec.CurrentBranching.CreateSibling (
3653 c.Block, FlowBranching.SiblingType.Catch);
3655 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3657 if (c.Name != null) {
3658 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3660 throw new Exception ();
3662 vi.VariableInfo = null;
3665 if (!c.Resolve (ec))
3668 Type resolvedType = c.CatchType;
3669 for (int ii = 0; ii < last_index; ++ii) {
3670 if (resolvedType == prevCatches [ii] || resolvedType.IsSubclassOf (prevCatches [ii])) {
3671 Report.Error (160, c.loc, "A previous catch clause already catches all exceptions of this or a super type '{0}'", prevCatches [ii].FullName);
3676 prevCatches [last_index++] = resolvedType;
3677 need_exc_block = true;
3680 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3682 if (General != null){
3683 ec.CurrentBranching.CreateSibling (
3684 General.Block, FlowBranching.SiblingType.Catch);
3686 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3688 if (!General.Resolve (ec))
3691 need_exc_block = true;
3694 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3698 ec.CurrentBranching.CreateSibling (
3699 Fini, FlowBranching.SiblingType.Finally);
3701 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3703 if (!Fini.Resolve (ec))
3707 ResolveFinally (branching);
3708 need_exc_block |= emit_finally;
3710 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3712 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3714 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3716 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3717 // Unfortunately, System.Reflection.Emit automatically emits
3718 // a leave to the end of the finally block. This is a problem
3719 // if `returns' is true since we may jump to a point after the
3720 // end of the method.
3721 // As a workaround, emit an explicit ret here.
3722 ec.NeedReturnLabel ();
3728 protected override void DoEmit (EmitContext ec)
3730 ILGenerator ig = ec.ig;
3733 ig.BeginExceptionBlock ();
3736 foreach (Catch c in Specific){
3739 ig.BeginCatchBlock (c.CatchType);
3741 if (c.Name != null){
3742 vi = c.Block.GetLocalInfo (c.Name);
3744 throw new Exception ("Variable does not exist in this block");
3746 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3748 ig.Emit (OpCodes.Pop);
3753 if (General != null){
3754 ig.BeginCatchBlock (TypeManager.object_type);
3755 ig.Emit (OpCodes.Pop);
3756 General.Block.Emit (ec);
3761 ig.EndExceptionBlock ();
3764 public override void EmitFinally (EmitContext ec)
3772 public class Using : ExceptionStatement {
3773 object expression_or_block;
3774 Statement Statement;
3779 Expression [] resolved_vars;
3780 Expression [] converted_vars;
3781 ExpressionStatement [] assign;
3782 LocalBuilder local_copy;
3784 public Using (object expression_or_block, Statement stmt, Location l)
3786 this.expression_or_block = expression_or_block;
3792 // Resolves for the case of using using a local variable declaration.
3794 bool ResolveLocalVariableDecls (EmitContext ec)
3798 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
3802 expr_type = texpr.ResolveType (ec);
3805 // The type must be an IDisposable or an implicit conversion
3808 converted_vars = new Expression [var_list.Count];
3809 resolved_vars = new Expression [var_list.Count];
3810 assign = new ExpressionStatement [var_list.Count];
3812 bool need_conv = !TypeManager.ImplementsInterface (
3813 expr_type, TypeManager.idisposable_type);
3815 foreach (DictionaryEntry e in var_list){
3816 Expression var = (Expression) e.Key;
3818 var = var.ResolveLValue (ec, new EmptyExpression ());
3822 resolved_vars [i] = var;
3829 converted_vars [i] = Convert.ImplicitConversionRequired (
3830 ec, var, TypeManager.idisposable_type, loc);
3832 if (converted_vars [i] == null)
3839 foreach (DictionaryEntry e in var_list){
3840 Expression var = resolved_vars [i];
3841 Expression new_expr = (Expression) e.Value;
3844 a = new Assign (var, new_expr, loc);
3850 converted_vars [i] = var;
3851 assign [i] = (ExpressionStatement) a;
3858 bool ResolveExpression (EmitContext ec)
3860 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3861 conv = Convert.ImplicitConversionRequired (
3862 ec, expr, TypeManager.idisposable_type, loc);
3872 // Emits the code for the case of using using a local variable declaration.
3874 void EmitLocalVariableDecls (EmitContext ec)
3876 ILGenerator ig = ec.ig;
3879 for (i = 0; i < assign.Length; i++) {
3880 assign [i].EmitStatement (ec);
3883 ig.BeginExceptionBlock ();
3885 Statement.Emit (ec);
3886 var_list.Reverse ();
3891 void EmitLocalVariableDeclFinally (EmitContext ec)
3893 ILGenerator ig = ec.ig;
3895 int i = assign.Length;
3896 for (int ii = 0; ii < var_list.Count; ++ii){
3897 Expression var = resolved_vars [--i];
3898 Label skip = ig.DefineLabel ();
3900 if (!var.Type.IsValueType) {
3902 ig.Emit (OpCodes.Brfalse, skip);
3903 converted_vars [i].Emit (ec);
3904 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3906 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3908 if (!(ml is MethodGroupExpr)) {
3910 ig.Emit (OpCodes.Box, var.Type);
3911 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3913 MethodInfo mi = null;
3915 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3916 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3923 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3927 IMemoryLocation mloc = (IMemoryLocation) var;
3929 mloc.AddressOf (ec, AddressOp.Load);
3930 ig.Emit (OpCodes.Call, mi);
3934 ig.MarkLabel (skip);
3937 ig.EndExceptionBlock ();
3939 ig.BeginFinallyBlock ();
3944 void EmitExpression (EmitContext ec)
3947 // Make a copy of the expression and operate on that.
3949 ILGenerator ig = ec.ig;
3950 local_copy = ig.DeclareLocal (expr_type);
3955 ig.Emit (OpCodes.Stloc, local_copy);
3958 ig.BeginExceptionBlock ();
3960 Statement.Emit (ec);
3964 ig.EndExceptionBlock ();
3967 void EmitExpressionFinally (EmitContext ec)
3969 ILGenerator ig = ec.ig;
3970 if (!local_copy.LocalType.IsValueType) {
3971 Label skip = ig.DefineLabel ();
3972 ig.Emit (OpCodes.Ldloc, local_copy);
3973 ig.Emit (OpCodes.Brfalse, skip);
3974 ig.Emit (OpCodes.Ldloc, local_copy);
3975 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3976 ig.MarkLabel (skip);
3978 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, local_copy.LocalType, "Dispose", Mono.CSharp.Location.Null);
3980 if (!(ml is MethodGroupExpr)) {
3981 ig.Emit (OpCodes.Ldloc, local_copy);
3982 ig.Emit (OpCodes.Box, local_copy.LocalType);
3983 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3985 MethodInfo mi = null;
3987 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3988 if (TypeManager.GetArgumentTypes (mk).Length == 0) {
3995 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3999 ig.Emit (OpCodes.Ldloca, local_copy);
4000 ig.Emit (OpCodes.Call, mi);
4005 public override bool Resolve (EmitContext ec)
4007 if (expression_or_block is DictionaryEntry){
4008 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
4009 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
4011 if (!ResolveLocalVariableDecls (ec))
4014 } else if (expression_or_block is Expression){
4015 expr = (Expression) expression_or_block;
4017 expr = expr.Resolve (ec);
4021 expr_type = expr.Type;
4023 if (!ResolveExpression (ec))
4027 FlowBranchingException branching = ec.StartFlowBranching (this);
4029 bool ok = Statement.Resolve (ec);
4032 ec.KillFlowBranching ();
4036 ResolveFinally (branching);
4037 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
4039 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
4040 // Unfortunately, System.Reflection.Emit automatically emits a leave
4041 // to the end of the finally block. This is a problem if `returns'
4042 // is true since we may jump to a point after the end of the method.
4043 // As a workaround, emit an explicit ret here.
4044 ec.NeedReturnLabel ();
4050 protected override void DoEmit (EmitContext ec)
4052 if (expression_or_block is DictionaryEntry)
4053 EmitLocalVariableDecls (ec);
4054 else if (expression_or_block is Expression)
4055 EmitExpression (ec);
4058 public override void EmitFinally (EmitContext ec)
4060 if (expression_or_block is DictionaryEntry)
4061 EmitLocalVariableDeclFinally (ec);
4062 else if (expression_or_block is Expression)
4063 EmitExpressionFinally (ec);
4068 /// Implementation of the foreach C# statement
4070 public class Foreach : ExceptionStatement {
4072 Expression variable;
4074 Statement statement;
4075 ForeachHelperMethods hm;
4076 Expression empty, conv;
4077 Type array_type, element_type;
4079 VariableStorage enumerator;
4081 public Foreach (Expression type, LocalVariableReference var, Expression expr,
4082 Statement stmt, Location l)
4085 this.variable = var;
4091 public override bool Resolve (EmitContext ec)
4093 expr = expr.Resolve (ec);
4097 if (expr is NullLiteral) {
4098 Report.Error (186, expr.Location, "Use of null is not valid in this context");
4102 TypeExpr texpr = type.ResolveAsTypeTerminal (ec, false);
4106 var_type = texpr.ResolveType (ec);
4109 // We need an instance variable. Not sure this is the best
4110 // way of doing this.
4112 // FIXME: When we implement propertyaccess, will those turn
4113 // out to return values in ExprClass? I think they should.
4115 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
4116 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
4117 error1579 (expr.Type);
4121 if (expr.Type.IsArray) {
4122 array_type = expr.Type;
4123 element_type = TypeManager.GetElementType (array_type);
4125 empty = new EmptyExpression (element_type);
4127 hm = ProbeCollectionType (ec, expr.Type);
4129 error1579 (expr.Type);
4133 // When ProbeCollection reported error
4134 if (hm.move_next == null)
4137 array_type = expr.Type;
4138 element_type = hm.element_type;
4140 empty = new EmptyExpression (hm.element_type);
4145 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
4146 ec.CurrentBranching.CreateSibling ();
4150 // FIXME: maybe we can apply the same trick we do in the
4151 // array handling to avoid creating empty and conv in some cases.
4153 // Although it is not as important in this case, as the type
4154 // will not likely be object (what the enumerator will return).
4156 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
4160 variable = variable.ResolveLValue (ec, empty);
4161 if (variable == null)
4164 bool disposable = (hm != null) && hm.is_disposable;
4165 FlowBranchingException branching = null;
4167 branching = ec.StartFlowBranching (this);
4169 if (!statement.Resolve (ec))
4173 ResolveFinally (branching);
4174 ec.EndFlowBranching ();
4176 emit_finally = true;
4178 ec.EndFlowBranching ();
4184 // Retrieves a `public bool MoveNext ()' method from the Type `t'
4186 static MethodInfo FetchMethodMoveNext (Type t)
4188 MemberList move_next_list;
4190 move_next_list = TypeContainer.FindMembers (
4191 t, MemberTypes.Method,
4192 BindingFlags.Public | BindingFlags.Instance,
4193 Type.FilterName, "MoveNext");
4194 if (move_next_list.Count == 0)
4197 foreach (MemberInfo m in move_next_list){
4198 MethodInfo mi = (MethodInfo) m;
4201 args = TypeManager.GetArgumentTypes (mi);
4202 if (args != null && args.Length == 0){
4203 if (mi.ReturnType == TypeManager.bool_type)
4211 // Retrieves a `public T get_Current ()' method from the Type `t'
4213 static MethodInfo FetchMethodGetCurrent (Type t)
4215 MemberList get_current_list;
4217 get_current_list = TypeContainer.FindMembers (
4218 t, MemberTypes.Method,
4219 BindingFlags.Public | BindingFlags.Instance,
4220 Type.FilterName, "get_Current");
4221 if (get_current_list.Count == 0)
4224 foreach (MemberInfo m in get_current_list){
4225 MethodInfo mi = (MethodInfo) m;
4228 args = TypeManager.GetArgumentTypes (mi);
4229 if (args != null && args.Length == 0)
4236 // Retrieves a `public void Dispose ()' method from the Type `t'
4238 static MethodInfo FetchMethodDispose (Type t)
4240 MemberList dispose_list;
4242 dispose_list = TypeContainer.FindMembers (
4243 t, MemberTypes.Method,
4244 BindingFlags.Public | BindingFlags.Instance,
4245 Type.FilterName, "Dispose");
4246 if (dispose_list.Count == 0)
4249 foreach (MemberInfo m in dispose_list){
4250 MethodInfo mi = (MethodInfo) m;
4253 args = TypeManager.GetArgumentTypes (mi);
4254 if (args != null && args.Length == 0){
4255 if (mi.ReturnType == TypeManager.void_type)
4263 // This struct records the helper methods used by the Foreach construct
4265 class ForeachHelperMethods {
4266 public EmitContext ec;
4267 public MethodInfo get_enumerator;
4268 public MethodInfo move_next;
4269 public MethodInfo get_current;
4270 public Type element_type;
4271 public Type enumerator_type;
4272 public bool is_disposable;
4273 public readonly Location Location;
4275 public ForeachHelperMethods (EmitContext ec, Location loc)
4278 this.Location = loc;
4279 this.element_type = TypeManager.object_type;
4280 this.enumerator_type = TypeManager.ienumerator_type;
4281 this.is_disposable = true;
4285 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
4290 if (!(m is MethodInfo))
4293 if (m.Name != "GetEnumerator")
4296 MethodInfo mi = (MethodInfo) m;
4297 Type [] args = TypeManager.GetArgumentTypes (mi);
4299 if (args.Length != 0)
4302 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
4304 // Check whether GetEnumerator is public
4305 if ((mi.Attributes & MethodAttributes.Public) != MethodAttributes.Public)
4308 if ((mi.ReturnType == TypeManager.ienumerator_type) && (mi.DeclaringType == TypeManager.string_type))
4310 // Apply the same optimization as MS: skip the GetEnumerator
4311 // returning an IEnumerator, and use the one returning a
4312 // CharEnumerator instead. This allows us to avoid the
4313 // try-finally block and the boxing.
4318 // Ok, we can access it, now make sure that we can do something
4319 // with this `GetEnumerator'
4322 Type return_type = mi.ReturnType;
4323 if (mi.ReturnType == TypeManager.ienumerator_type ||
4324 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
4325 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
4328 // If it is not an interface, lets try to find the methods ourselves.
4329 // For example, if we have:
4330 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
4331 // We can avoid the iface call. This is a runtime perf boost.
4332 // even bigger if we have a ValueType, because we avoid the cost
4335 // We have to make sure that both methods exist for us to take
4336 // this path. If one of the methods does not exist, we will just
4337 // use the interface. Sadly, this complex if statement is the only
4338 // way I could do this without a goto
4341 if (return_type.IsInterface ||
4342 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
4343 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
4345 hm.move_next = TypeManager.bool_movenext_void;
4346 hm.get_current = TypeManager.object_getcurrent_void;
4352 if (return_type.IsPointer || return_type.IsArray) {
4353 Report.SymbolRelatedToPreviousError (mi);
4354 Type t = return_type.GetElementType ();
4355 Report.SymbolRelatedToPreviousError (t);
4356 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",
4357 TypeManager.CSharpName (return_type), TypeManager.GetFullNameSignature (m));
4358 hm.get_enumerator = mi;
4363 // Ok, so they dont return an IEnumerable, we will have to
4364 // find if they support the GetEnumerator pattern.
4367 hm.move_next = FetchMethodMoveNext (return_type);
4368 if (hm.move_next == null)
4371 hm.get_current = FetchMethodGetCurrent (return_type);
4372 if (hm.get_current == null)
4376 hm.element_type = hm.get_current.ReturnType;
4377 hm.enumerator_type = return_type;
4378 hm.is_disposable = !hm.enumerator_type.IsSealed ||
4379 TypeManager.ImplementsInterface (
4380 hm.enumerator_type, TypeManager.idisposable_type);
4386 /// This filter is used to find the GetEnumerator method
4387 /// on which IEnumerator operates
4389 static MemberFilter FilterEnumerator;
4393 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
4396 void error1579 (Type t)
4398 Report.Error (1579, loc,
4399 "foreach statement cannot operate on variables of type `" +
4400 t.FullName + "' because that class does not provide a " +
4401 " GetEnumerator method or it is inaccessible");
4404 static bool TryType (Type t, ForeachHelperMethods hm)
4408 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
4409 BindingFlags.Public | BindingFlags.NonPublic |
4410 BindingFlags.Instance | BindingFlags.DeclaredOnly,
4411 FilterEnumerator, hm);
4416 hm.get_enumerator = (MethodInfo) mi [0];
4421 // Looks for a usable GetEnumerator in the Type, and if found returns
4422 // the three methods that participate: GetEnumerator, MoveNext and get_Current
4424 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
4426 ForeachHelperMethods hm = new ForeachHelperMethods (ec, loc);
4428 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
4429 if (TryType (tt, hm))
4435 // Now try to find the method in the interfaces
4438 Type [] ifaces = t.GetInterfaces ();
4440 foreach (Type i in ifaces){
4441 if (TryType (i, hm))
4446 // Since TypeBuilder.GetInterfaces only returns the interface
4447 // types for this type, we have to keep looping, but once
4448 // we hit a non-TypeBuilder (ie, a Type), then we know we are
4449 // done, because it returns all the types
4451 if ((t is TypeBuilder))
4461 // FIXME: possible optimization.
4462 // We might be able to avoid creating `empty' if the type is the sam
4464 bool EmitCollectionForeach (EmitContext ec)
4466 ILGenerator ig = ec.ig;
4468 enumerator = new VariableStorage (ec, hm.enumerator_type);
4469 enumerator.EmitThis (ig);
4471 // Instantiate the enumerator
4473 if (expr.Type.IsValueType) {
4474 IMemoryLocation ml = expr as IMemoryLocation;
4475 // Load the address of the value type.
4477 // This happens if, for example, you have a property
4478 // returning a struct which is IEnumerable
4479 LocalBuilder t = ec.GetTemporaryLocal (expr.Type);
4481 ig.Emit (OpCodes.Stloc, t);
4482 ig.Emit (OpCodes.Ldloca, t);
4483 ec.FreeTemporaryLocal (t, expr.Type);
4485 ml.AddressOf (ec, AddressOp.Load);
4489 if (hm.get_enumerator.DeclaringType.IsValueType) {
4490 // the method is declared on the value type
4491 ig.Emit (OpCodes.Call, hm.get_enumerator);
4493 // it is an interface method, so we must box
4494 ig.Emit (OpCodes.Box, expr.Type);
4495 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4499 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
4501 enumerator.EmitStore (ig);
4504 // Protect the code in a try/finalize block, so that
4505 // if the beast implement IDisposable, we get rid of it
4507 if (hm.is_disposable && emit_finally)
4508 ig.BeginExceptionBlock ();
4510 Label end_try = ig.DefineLabel ();
4512 ig.MarkLabel (ec.LoopBegin);
4514 enumerator.EmitCall (ig, hm.move_next);
4516 ig.Emit (OpCodes.Brfalse, end_try);
4519 ig.Emit (OpCodes.Ldarg_0);
4521 enumerator.EmitCall (ig, hm.get_current);
4525 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4527 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4529 statement.Emit (ec);
4530 ig.Emit (OpCodes.Br, ec.LoopBegin);
4531 ig.MarkLabel (end_try);
4534 // Now the finally block
4536 if (hm.is_disposable) {
4539 ig.EndExceptionBlock ();
4542 ig.MarkLabel (ec.LoopEnd);
4546 public override void EmitFinally (EmitContext ec)
4548 ILGenerator ig = ec.ig;
4550 if (hm.enumerator_type.IsValueType) {
4551 enumerator.EmitThis (ig);
4553 MethodInfo mi = FetchMethodDispose (hm.enumerator_type);
4555 enumerator.EmitLoadAddress (ig);
4556 ig.Emit (OpCodes.Call, mi);
4558 enumerator.EmitLoad (ig);
4559 ig.Emit (OpCodes.Box, hm.enumerator_type);
4560 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4563 Label call_dispose = ig.DefineLabel ();
4565 enumerator.EmitThis (ig);
4566 enumerator.EmitLoad (ig);
4567 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4568 ig.Emit (OpCodes.Dup);
4569 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4570 ig.Emit (OpCodes.Pop);
4572 Label end_finally = ig.DefineLabel ();
4573 ig.Emit (OpCodes.Br, end_finally);
4575 ig.MarkLabel (call_dispose);
4576 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4577 ig.MarkLabel (end_finally);
4580 ig.Emit (OpCodes.Endfinally);
4585 // FIXME: possible optimization.
4586 // We might be able to avoid creating `empty' if the type is the sam
4588 bool EmitArrayForeach (EmitContext ec)
4590 int rank = array_type.GetArrayRank ();
4591 ILGenerator ig = ec.ig;
4593 VariableStorage copy = new VariableStorage (ec, array_type);
4596 // Make our copy of the array
4600 copy.EmitStore (ig);
4603 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4607 counter.EmitThis (ig);
4608 ig.Emit (OpCodes.Ldc_I4_0);
4609 counter.EmitStore (ig);
4610 test = ig.DefineLabel ();
4611 ig.Emit (OpCodes.Br, test);
4613 loop = ig.DefineLabel ();
4614 ig.MarkLabel (loop);
4617 ig.Emit (OpCodes.Ldarg_0);
4621 counter.EmitThis (ig);
4622 counter.EmitLoad (ig);
4625 // Load the value, we load the value using the underlying type,
4626 // then we use the variable.EmitAssign to load using the proper cast.
4628 ArrayAccess.EmitLoadOpcode (ig, element_type);
4631 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4633 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4635 statement.Emit (ec);
4637 ig.MarkLabel (ec.LoopBegin);
4638 counter.EmitThis (ig);
4639 counter.EmitThis (ig);
4640 counter.EmitLoad (ig);
4641 ig.Emit (OpCodes.Ldc_I4_1);
4642 ig.Emit (OpCodes.Add);
4643 counter.EmitStore (ig);
4645 ig.MarkLabel (test);
4646 counter.EmitThis (ig);
4647 counter.EmitLoad (ig);
4650 ig.Emit (OpCodes.Ldlen);
4651 ig.Emit (OpCodes.Conv_I4);
4652 ig.Emit (OpCodes.Blt, loop);
4654 VariableStorage [] dim_len = new VariableStorage [rank];
4655 VariableStorage [] dim_count = new VariableStorage [rank];
4656 Label [] loop = new Label [rank];
4657 Label [] test = new Label [rank];
4660 for (dim = 0; dim < rank; dim++){
4661 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4662 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4663 test [dim] = ig.DefineLabel ();
4664 loop [dim] = ig.DefineLabel ();
4667 for (dim = 0; dim < rank; dim++){
4668 dim_len [dim].EmitThis (ig);
4671 IntLiteral.EmitInt (ig, dim);
4672 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4673 dim_len [dim].EmitStore (ig);
4677 for (dim = 0; dim < rank; dim++){
4678 dim_count [dim].EmitThis (ig);
4679 ig.Emit (OpCodes.Ldc_I4_0);
4680 dim_count [dim].EmitStore (ig);
4681 ig.Emit (OpCodes.Br, test [dim]);
4682 ig.MarkLabel (loop [dim]);
4686 ig.Emit (OpCodes.Ldarg_0);
4690 for (dim = 0; dim < rank; dim++){
4691 dim_count [dim].EmitThis (ig);
4692 dim_count [dim].EmitLoad (ig);
4696 // FIXME: Maybe we can cache the computation of `get'?
4698 Type [] args = new Type [rank];
4701 for (int i = 0; i < rank; i++)
4702 args [i] = TypeManager.int32_type;
4704 ModuleBuilder mb = CodeGen.Module.Builder;
4705 get = mb.GetArrayMethod (
4707 CallingConventions.HasThis| CallingConventions.Standard,
4709 ig.Emit (OpCodes.Call, get);
4712 ig.Emit (OpCodes.Stfld, ((LocalVariableReference) variable).local_info.FieldBuilder);
4714 ((IAssignMethod)variable).EmitAssign (ec, conv, false, false);
4715 statement.Emit (ec);
4716 ig.MarkLabel (ec.LoopBegin);
4717 for (dim = rank - 1; dim >= 0; dim--){
4718 dim_count [dim].EmitThis (ig);
4719 dim_count [dim].EmitThis (ig);
4720 dim_count [dim].EmitLoad (ig);
4721 ig.Emit (OpCodes.Ldc_I4_1);
4722 ig.Emit (OpCodes.Add);
4723 dim_count [dim].EmitStore (ig);
4725 ig.MarkLabel (test [dim]);
4726 dim_count [dim].EmitThis (ig);
4727 dim_count [dim].EmitLoad (ig);
4728 dim_len [dim].EmitThis (ig);
4729 dim_len [dim].EmitLoad (ig);
4730 ig.Emit (OpCodes.Blt, loop [dim]);
4733 ig.MarkLabel (ec.LoopEnd);
4738 protected override void DoEmit (EmitContext ec)
4740 ILGenerator ig = ec.ig;
4742 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4743 ec.LoopBegin = ig.DefineLabel ();
4744 ec.LoopEnd = ig.DefineLabel ();
4747 EmitCollectionForeach (ec);
4749 EmitArrayForeach (ec);
4751 ec.LoopBegin = old_begin;
4752 ec.LoopEnd = old_end;