2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 using System.Collections;
21 public abstract class Statement {
25 /// Resolves the statement, true means that all sub-statements
28 public virtual bool Resolve (EmitContext ec)
34 /// We already know that the statement is unreachable, but we still
35 /// need to resolve it to catch errors.
37 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
40 // This conflicts with csc's way of doing this, but IMHO it's
41 // the right thing to do.
43 // If something is unreachable, we still check whether it's
44 // correct. This means that you cannot use unassigned variables
45 // in unreachable code, for instance.
48 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
49 bool ok = Resolve (ec);
50 ec.KillFlowBranching ();
56 Report.Warning (162, loc, "Unreachable code detected");
60 protected void CheckObsolete (Type type)
62 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
63 if (obsolete_attr == null)
66 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, loc);
70 /// Return value indicates whether all code paths emitted return.
72 protected abstract void DoEmit (EmitContext ec);
75 /// Utility wrapper routine for Error, just to beautify the code
77 public void Error (int error, string format, params object[] args)
79 Error (error, String.Format (format, args));
82 public void Error (int error, string s)
84 if (!Location.IsNull (loc))
85 Report.Error (error, loc, s);
87 Report.Error (error, s);
91 /// Return value indicates whether all code paths emitted return.
93 public virtual void Emit (EmitContext ec)
100 public sealed class EmptyStatement : Statement {
102 private EmptyStatement () {}
104 public static readonly EmptyStatement Value = new EmptyStatement ();
106 public override bool Resolve (EmitContext ec)
111 protected override void DoEmit (EmitContext ec)
116 public class If : Statement {
118 public Statement TrueStatement;
119 public Statement FalseStatement;
123 public If (Expression expr, Statement trueStatement, Location l)
126 TrueStatement = trueStatement;
130 public If (Expression expr,
131 Statement trueStatement,
132 Statement falseStatement,
136 TrueStatement = trueStatement;
137 FalseStatement = falseStatement;
141 public override bool Resolve (EmitContext ec)
143 Report.Debug (1, "START IF BLOCK", loc);
145 expr = Expression.ResolveBoolean (ec, expr, loc);
151 // Dead code elimination
153 if (expr is BoolConstant){
154 bool take = ((BoolConstant) expr).Value;
157 if (!TrueStatement.Resolve (ec))
160 if ((FalseStatement != null) &&
161 !FalseStatement.ResolveUnreachable (ec, true))
163 FalseStatement = null;
165 if (!TrueStatement.ResolveUnreachable (ec, true))
167 TrueStatement = null;
169 if ((FalseStatement != null) &&
170 !FalseStatement.Resolve (ec))
177 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
179 bool ok = TrueStatement.Resolve (ec);
181 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
183 ec.CurrentBranching.CreateSibling ();
185 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
188 ec.EndFlowBranching ();
190 Report.Debug (1, "END IF BLOCK", loc);
195 protected override void DoEmit (EmitContext ec)
197 ILGenerator ig = ec.ig;
198 Label false_target = ig.DefineLabel ();
202 // If we're a boolean expression, Resolve() already
203 // eliminated dead code for us.
205 if (expr is BoolConstant){
206 bool take = ((BoolConstant) expr).Value;
209 TrueStatement.Emit (ec);
210 else if (FalseStatement != null)
211 FalseStatement.Emit (ec);
216 expr.EmitBranchable (ec, false_target, false);
218 TrueStatement.Emit (ec);
220 if (FalseStatement != null){
221 bool branch_emitted = false;
223 end = ig.DefineLabel ();
225 ig.Emit (OpCodes.Br, end);
226 branch_emitted = true;
229 ig.MarkLabel (false_target);
230 FalseStatement.Emit (ec);
235 ig.MarkLabel (false_target);
240 public class Do : Statement {
241 public Expression expr;
242 public readonly Statement EmbeddedStatement;
245 public Do (Statement statement, Expression boolExpr, Location l)
248 EmbeddedStatement = statement;
252 public override bool Resolve (EmitContext ec)
256 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
258 if (!EmbeddedStatement.Resolve (ec))
261 expr = Expression.ResolveBoolean (ec, expr, loc);
264 else if (expr is BoolConstant){
265 bool res = ((BoolConstant) expr).Value;
271 ec.CurrentBranching.Infinite = infinite;
272 ec.EndFlowBranching ();
277 protected override void DoEmit (EmitContext ec)
279 ILGenerator ig = ec.ig;
280 Label loop = ig.DefineLabel ();
281 Label old_begin = ec.LoopBegin;
282 Label old_end = ec.LoopEnd;
284 ec.LoopBegin = ig.DefineLabel ();
285 ec.LoopEnd = ig.DefineLabel ();
288 EmbeddedStatement.Emit (ec);
289 ig.MarkLabel (ec.LoopBegin);
292 // Dead code elimination
294 if (expr is BoolConstant){
295 bool res = ((BoolConstant) expr).Value;
298 ec.ig.Emit (OpCodes.Br, loop);
300 expr.EmitBranchable (ec, loop, true);
302 ig.MarkLabel (ec.LoopEnd);
304 ec.LoopBegin = old_begin;
305 ec.LoopEnd = old_end;
309 public class While : Statement {
310 public Expression expr;
311 public readonly Statement Statement;
312 bool infinite, empty;
314 public While (Expression boolExpr, Statement statement, Location l)
316 this.expr = boolExpr;
317 Statement = statement;
321 public override bool Resolve (EmitContext ec)
325 expr = Expression.ResolveBoolean (ec, expr, loc);
330 // Inform whether we are infinite or not
332 if (expr is BoolConstant){
333 BoolConstant bc = (BoolConstant) expr;
335 if (bc.Value == false){
336 if (!Statement.ResolveUnreachable (ec, true))
344 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
346 if (!Statement.Resolve (ec))
349 ec.CurrentBranching.Infinite = infinite;
350 ec.EndFlowBranching ();
355 protected override void DoEmit (EmitContext ec)
360 ILGenerator ig = ec.ig;
361 Label old_begin = ec.LoopBegin;
362 Label old_end = ec.LoopEnd;
364 ec.LoopBegin = ig.DefineLabel ();
365 ec.LoopEnd = ig.DefineLabel ();
368 // Inform whether we are infinite or not
370 if (expr is BoolConstant){
371 ig.MarkLabel (ec.LoopBegin);
373 ig.Emit (OpCodes.Br, ec.LoopBegin);
376 // Inform that we are infinite (ie, `we return'), only
377 // if we do not `break' inside the code.
379 ig.MarkLabel (ec.LoopEnd);
381 Label while_loop = ig.DefineLabel ();
383 ig.Emit (OpCodes.Br, ec.LoopBegin);
384 ig.MarkLabel (while_loop);
388 ig.MarkLabel (ec.LoopBegin);
390 expr.EmitBranchable (ec, while_loop, true);
392 ig.MarkLabel (ec.LoopEnd);
395 ec.LoopBegin = old_begin;
396 ec.LoopEnd = old_end;
400 public class For : Statement {
402 readonly Statement InitStatement;
403 readonly Statement Increment;
404 readonly Statement Statement;
405 bool infinite, empty;
407 public For (Statement initStatement,
413 InitStatement = initStatement;
415 Increment = increment;
416 Statement = statement;
420 public override bool Resolve (EmitContext ec)
424 if (InitStatement != null){
425 if (!InitStatement.Resolve (ec))
430 Test = Expression.ResolveBoolean (ec, Test, loc);
433 else if (Test is BoolConstant){
434 BoolConstant bc = (BoolConstant) Test;
436 if (bc.Value == false){
437 if (!Statement.ResolveUnreachable (ec, true))
439 if ((Increment != null) &&
440 !Increment.ResolveUnreachable (ec, false))
450 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
452 ec.CurrentBranching.CreateSibling ();
454 if (!Statement.Resolve (ec))
457 if (Increment != null){
458 if (!Increment.Resolve (ec))
462 ec.CurrentBranching.Infinite = infinite;
463 ec.EndFlowBranching ();
468 protected override void DoEmit (EmitContext ec)
473 ILGenerator ig = ec.ig;
474 Label old_begin = ec.LoopBegin;
475 Label old_end = ec.LoopEnd;
476 Label loop = ig.DefineLabel ();
477 Label test = ig.DefineLabel ();
479 if (InitStatement != null && InitStatement != EmptyStatement.Value)
480 InitStatement.Emit (ec);
482 ec.LoopBegin = ig.DefineLabel ();
483 ec.LoopEnd = ig.DefineLabel ();
485 ig.Emit (OpCodes.Br, test);
489 ig.MarkLabel (ec.LoopBegin);
490 if (Increment != EmptyStatement.Value)
495 // If test is null, there is no test, and we are just
500 // The Resolve code already catches the case for
501 // Test == BoolConstant (false) so we know that
504 if (Test is BoolConstant)
505 ig.Emit (OpCodes.Br, loop);
507 Test.EmitBranchable (ec, loop, true);
510 ig.Emit (OpCodes.Br, loop);
511 ig.MarkLabel (ec.LoopEnd);
513 ec.LoopBegin = old_begin;
514 ec.LoopEnd = old_end;
518 public class StatementExpression : Statement {
519 ExpressionStatement expr;
521 public StatementExpression (ExpressionStatement expr, Location l)
527 public override bool Resolve (EmitContext ec)
529 expr = expr.ResolveStatement (ec);
533 protected override void DoEmit (EmitContext ec)
535 expr.EmitStatement (ec);
538 public override string ToString ()
540 return "StatementExpression (" + expr + ")";
545 /// Implements the return statement
547 public class Return : Statement {
548 public Expression Expr;
550 public Return (Expression expr, Location l)
558 public override bool Resolve (EmitContext ec)
560 if (ec.ReturnType == null){
562 Error (127, "Return with a value not allowed here");
567 Error (126, "An object of type `{0}' is expected " +
568 "for the return statement",
569 TypeManager.CSharpName (ec.ReturnType));
573 Expr = Expr.Resolve (ec);
577 if (Expr.Type != ec.ReturnType) {
578 Expr = Convert.ImplicitConversionRequired (
579 ec, Expr, ec.ReturnType, loc);
586 Error (-206, "Return statement not allowed inside iterators");
590 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
592 if (ec.CurrentBranching.InTryOrCatch (true)) {
593 ec.CurrentBranching.AddFinallyVector (vector);
595 } else if (ec.CurrentBranching.InFinally (true)) {
596 Error (157, "Control can not leave the body of the finally block");
599 vector.CheckOutParameters (ec.CurrentBranching);
601 ec.CurrentBranching.CurrentUsageVector.Return ();
605 protected override void DoEmit (EmitContext ec)
611 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
615 ec.NeedReturnLabel ();
616 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
618 ec.ig.Emit (OpCodes.Ret);
623 public class Goto : Statement {
626 LabeledStatement label;
628 public override bool Resolve (EmitContext ec)
630 label = ec.CurrentBranching.LookupLabel (target, loc);
634 // If this is a forward goto.
635 if (!label.IsDefined)
636 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
638 ec.CurrentBranching.CurrentUsageVector.Goto ();
643 public Goto (Block parent_block, string label, Location l)
645 block = parent_block;
650 public string Target {
656 protected override void DoEmit (EmitContext ec)
658 Label l = label.LabelTarget (ec);
659 ec.ig.Emit (OpCodes.Br, l);
663 public class LabeledStatement : Statement {
664 public readonly Location Location;
669 FlowBranching.UsageVector vectors;
671 public LabeledStatement (string label_name, Location l)
676 public Label LabelTarget (EmitContext ec)
680 label = ec.ig.DefineLabel ();
686 public bool IsDefined {
692 public bool HasBeenReferenced {
698 public void AddUsageVector (FlowBranching.UsageVector vector)
700 vector = vector.Clone ();
701 vector.Next = vectors;
705 public override bool Resolve (EmitContext ec)
707 ec.CurrentBranching.Label (vectors);
714 protected override void DoEmit (EmitContext ec)
717 ec.ig.MarkLabel (label);
723 /// `goto default' statement
725 public class GotoDefault : Statement {
727 public GotoDefault (Location l)
732 public override bool Resolve (EmitContext ec)
734 ec.CurrentBranching.CurrentUsageVector.Goto ();
738 protected override void DoEmit (EmitContext ec)
740 if (ec.Switch == null){
741 Report.Error (153, loc, "goto default is only valid in a switch statement");
745 if (!ec.Switch.GotDefault){
746 Report.Error (159, loc, "No default target on switch statement");
749 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
754 /// `goto case' statement
756 public class GotoCase : Statement {
760 public GotoCase (Expression e, Location l)
766 public override bool Resolve (EmitContext ec)
768 if (ec.Switch == null){
769 Report.Error (153, loc, "goto case is only valid in a switch statement");
773 expr = expr.Resolve (ec);
777 if (!(expr is Constant)){
778 Report.Error (159, loc, "Target expression for goto case is not constant");
782 object val = Expression.ConvertIntLiteral (
783 (Constant) expr, ec.Switch.SwitchType, loc);
788 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
793 "No such label 'case " + val + "': for the goto case");
797 label = sl.ILLabelCode;
799 ec.CurrentBranching.CurrentUsageVector.Goto ();
803 protected override void DoEmit (EmitContext ec)
805 ec.ig.Emit (OpCodes.Br, label);
809 public class Throw : Statement {
812 public Throw (Expression expr, Location l)
818 public override bool Resolve (EmitContext ec)
820 bool in_catch = ec.CurrentBranching.InCatch ();
821 ec.CurrentBranching.CurrentUsageVector.Throw ();
824 expr = expr.Resolve (ec);
828 ExprClass eclass = expr.eclass;
830 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
831 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
832 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
838 if ((t != TypeManager.exception_type) &&
839 !t.IsSubclassOf (TypeManager.exception_type) &&
840 !(expr is NullLiteral)) {
842 "The type caught or thrown must be derived " +
843 "from System.Exception");
846 } else if (!in_catch) {
848 "A throw statement with no argument is only " +
849 "allowed in a catch clause");
856 protected override void DoEmit (EmitContext ec)
859 ec.ig.Emit (OpCodes.Rethrow);
863 ec.ig.Emit (OpCodes.Throw);
868 public class Break : Statement {
870 public Break (Location l)
877 public override bool Resolve (EmitContext ec)
879 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
880 Error (139, "No enclosing loop or switch to continue to");
882 } else if (ec.CurrentBranching.InFinally (false)) {
883 Error (157, "Control can not leave the body of the finally block");
885 } else if (ec.CurrentBranching.InTryOrCatch (false))
886 ec.CurrentBranching.AddFinallyVector (
887 ec.CurrentBranching.CurrentUsageVector);
888 else if (ec.CurrentBranching.InLoop ())
889 ec.CurrentBranching.AddBreakVector (
890 ec.CurrentBranching.CurrentUsageVector);
892 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
894 ec.CurrentBranching.CurrentUsageVector.Break ();
898 protected override void DoEmit (EmitContext ec)
900 ILGenerator ig = ec.ig;
903 ig.Emit (OpCodes.Leave, ec.LoopEnd);
905 ec.NeedReturnLabel ();
906 ig.Emit (OpCodes.Br, ec.LoopEnd);
911 public class Continue : Statement {
913 public Continue (Location l)
920 public override bool Resolve (EmitContext ec)
922 if (!ec.CurrentBranching.InLoop () && !ec.CurrentBranching.InSwitch ()){
923 Error (139, "No enclosing loop to continue to");
925 } else if (ec.CurrentBranching.InFinally (false)) {
926 Error (157, "Control can not leave the body of the finally block");
928 } else if (ec.CurrentBranching.InTryOrCatch (false))
929 ec.CurrentBranching.AddFinallyVector (ec.CurrentBranching.CurrentUsageVector);
931 crossing_exc = ec.CurrentBranching.BreakCrossesTryCatchBoundary ();
933 ec.CurrentBranching.CurrentUsageVector.Goto ();
937 protected override void DoEmit (EmitContext ec)
939 Label begin = ec.LoopBegin;
942 ec.ig.Emit (OpCodes.Leave, begin);
944 ec.ig.Emit (OpCodes.Br, begin);
948 public class LocalInfo {
949 public Expression Type;
952 // Most of the time a variable will be stored in a LocalBuilder
954 // But sometimes, it will be stored in a field. The context of the field will
955 // be stored in the EmitContext
958 public LocalBuilder LocalBuilder;
959 public FieldBuilder FieldBuilder;
961 public Type VariableType;
962 public readonly string Name;
963 public readonly Location Location;
964 public readonly Block Block;
966 public VariableInfo VariableInfo;
976 public LocalInfo (Expression type, string name, Block block, Location l)
984 public LocalInfo (TypeContainer tc, Block block, Location l)
986 VariableType = tc.TypeBuilder;
991 public bool IsThisAssigned (EmitContext ec, Location loc)
993 if (VariableInfo == null)
994 throw new Exception ();
996 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
999 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1002 public bool IsAssigned (EmitContext ec)
1004 if (VariableInfo == null)
1005 throw new Exception ();
1007 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1010 public bool Resolve (EmitContext ec)
1012 if (VariableType == null)
1013 VariableType = ec.DeclSpace.ResolveType (Type, false, Location);
1015 if (VariableType == TypeManager.void_type) {
1016 Report.Error (1547, Location,
1017 "Keyword 'void' cannot be used in this context");
1021 if (VariableType == null)
1024 // TODO: breaks the build
1025 // if (VariableType.IsPointer && !ec.InUnsafe)
1026 // Expression.UnsafeError (Location);
1031 public void MakePinned ()
1033 TypeManager.MakePinned (LocalBuilder);
1034 flags |= Flags.Fixed;
1037 public bool IsFixed {
1039 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1046 public override string ToString ()
1048 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1049 Name, Type, VariableInfo, Location);
1054 return (flags & Flags.Used) != 0;
1057 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1061 public bool ReadOnly {
1063 return (flags & Flags.ReadOnly) != 0;
1066 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1075 /// Block represents a C# block.
1079 /// This class is used in a number of places: either to represent
1080 /// explicit blocks that the programmer places or implicit blocks.
1082 /// Implicit blocks are used as labels or to introduce variable
1085 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1086 /// they contain extra information that is not necessary on normal blocks.
1088 public class Block : Statement {
1089 public readonly Block Parent;
1090 public readonly Location StartLocation;
1091 public Location EndLocation = Location.Null;
1094 public enum Flags : byte {
1098 VariablesInitialized = 8,
1105 public bool Implicit {
1107 return (flags & Flags.Implicit) != 0;
1111 public bool Unchecked {
1113 return (flags & Flags.Unchecked) != 0;
1116 flags |= Flags.Unchecked;
1120 public bool HasVarargs {
1123 return Parent.HasVarargs;
1125 return (flags & Flags.HasVarargs) != 0;
1128 flags |= Flags.HasVarargs;
1133 // The statements in this block
1135 ArrayList statements;
1139 // An array of Blocks. We keep track of children just
1140 // to generate the local variable declarations.
1142 // Statements and child statements are handled through the
1148 // Labels. (label, block) pairs.
1153 // Keeps track of (name, type) pairs
1155 Hashtable variables;
1158 // Keeps track of constants
1159 Hashtable constants;
1162 // If this is a switch section, the enclosing switch block.
1170 public Block (Block parent)
1171 : this (parent, (Flags) 0, Location.Null, Location.Null)
1174 public Block (Block parent, Flags flags)
1175 : this (parent, flags, Location.Null, Location.Null)
1178 public Block (Block parent, Flags flags, Parameters parameters)
1179 : this (parent, flags, parameters, Location.Null, Location.Null)
1182 public Block (Block parent, Location start, Location end)
1183 : this (parent, (Flags) 0, start, end)
1186 public Block (Block parent, Parameters parameters, Location start, Location end)
1187 : this (parent, (Flags) 0, parameters, start, end)
1190 public Block (Block parent, Flags flags, Location start, Location end)
1191 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1194 public Block (Block parent, Flags flags, Parameters parameters,
1195 Location start, Location end)
1198 parent.AddChild (this);
1200 this.Parent = parent;
1202 this.parameters = parameters;
1203 this.StartLocation = start;
1204 this.EndLocation = end;
1207 statements = new ArrayList ();
1209 if (parent != null && Implicit) {
1210 if (parent.child_variable_names == null)
1211 parent.child_variable_names = new Hashtable();
1212 // share with parent
1213 child_variable_names = parent.child_variable_names;
1218 public Block CreateSwitchBlock (Location start)
1220 Block new_block = new Block (this, start, start);
1221 new_block.switch_block = this;
1231 void AddChild (Block b)
1233 if (children == null)
1234 children = new ArrayList ();
1239 public void SetEndLocation (Location loc)
1245 /// Adds a label to the current block.
1249 /// false if the name already exists in this block. true
1253 public bool AddLabel (string name, LabeledStatement target, Location loc)
1255 if (switch_block != null)
1256 return switch_block.AddLabel (name, target, loc);
1259 while (cur != null) {
1260 if (cur.DoLookupLabel (name) != null) {
1262 140, loc, "The label '{0}' is a duplicate",
1273 while (cur != null) {
1274 if (cur.DoLookupLabel (name) != null) {
1277 "The label '{0}' shadows another label " +
1278 "by the same name in a containing scope.",
1283 if (children != null) {
1284 foreach (Block b in children) {
1285 LabeledStatement s = b.DoLookupLabel (name);
1291 "The label '{0}' shadows another " +
1292 "label by the same name in a " +
1293 "containing scope.",
1304 labels = new Hashtable ();
1306 labels.Add (name, target);
1310 public LabeledStatement LookupLabel (string name)
1312 LabeledStatement s = DoLookupLabel (name);
1316 if (children == null)
1319 foreach (Block child in children) {
1320 if (!child.Implicit)
1323 s = child.LookupLabel (name);
1331 LabeledStatement DoLookupLabel (string name)
1333 if (switch_block != null)
1334 return switch_block.LookupLabel (name);
1337 if (labels.Contains (name))
1338 return ((LabeledStatement) labels [name]);
1343 LocalInfo this_variable = null;
1346 // Returns the "this" instance variable of this block.
1347 // See AddThisVariable() for more information.
1349 public LocalInfo ThisVariable {
1351 if (this_variable != null)
1352 return this_variable;
1353 else if (Parent != null)
1354 return Parent.ThisVariable;
1360 Hashtable child_variable_names;
1363 // Marks a variable with name @name as being used in a child block.
1364 // If a variable name has been used in a child block, it's illegal to
1365 // declare a variable with the same name in the current block.
1367 public void AddChildVariableName (string name)
1369 if (child_variable_names == null)
1370 child_variable_names = new Hashtable ();
1372 if (!child_variable_names.Contains (name))
1373 child_variable_names.Add (name, true);
1377 // Checks whether a variable name has already been used in a child block.
1379 public bool IsVariableNameUsedInChildBlock (string name)
1381 if (child_variable_names == null)
1384 return child_variable_names.Contains (name);
1388 // This is used by non-static `struct' constructors which do not have an
1389 // initializer - in this case, the constructor must initialize all of the
1390 // struct's fields. To do this, we add a "this" variable and use the flow
1391 // analysis code to ensure that it's been fully initialized before control
1392 // leaves the constructor.
1394 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1396 if (this_variable != null)
1397 return this_variable;
1399 if (variables == null)
1400 variables = new Hashtable ();
1402 this_variable = new LocalInfo (tc, this, l);
1403 this_variable.Used = true;
1405 variables.Add ("this", this_variable);
1407 return this_variable;
1410 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1412 if (variables == null)
1413 variables = new Hashtable ();
1415 LocalInfo vi = GetLocalInfo (name);
1417 if (vi.Block != this)
1418 Report.Error (136, l, "A local variable named `" + name + "' " +
1419 "cannot be declared in this scope since it would " +
1420 "give a different meaning to `" + name + "', which " +
1421 "is already used in a `parent or current' scope to " +
1422 "denote something else");
1424 Report.Error (128, l, "A local variable `" + name + "' is already " +
1425 "defined in this scope");
1429 if (IsVariableNameUsedInChildBlock (name)) {
1430 Report.Error (136, l, "A local variable named `" + name + "' " +
1431 "cannot be declared in this scope since it would " +
1432 "give a different meaning to `" + name + "', which " +
1433 "is already used in a `child' scope to denote something " +
1440 Parameter p = pars.GetParameterByName (name, out idx);
1442 Report.Error (136, l, "A local variable named `" + name + "' " +
1443 "cannot be declared in this scope since it would " +
1444 "give a different meaning to `" + name + "', which " +
1445 "is already used in a `parent or current' scope to " +
1446 "denote something else");
1451 vi = new LocalInfo (type, name, this, l);
1453 variables.Add (name, vi);
1455 // Mark 'name' as "used by a child block" in every surrounding block
1457 while (cur != null && cur.Implicit)
1460 for (Block par = cur.Parent; par != null; par = par.Parent)
1461 par.AddChildVariableName (name);
1463 if ((flags & Flags.VariablesInitialized) != 0)
1464 throw new Exception ();
1466 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1470 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1472 if (AddVariable (type, name, pars, l) == null)
1475 if (constants == null)
1476 constants = new Hashtable ();
1478 constants.Add (name, value);
1482 public Hashtable Variables {
1488 public LocalInfo GetLocalInfo (string name)
1490 for (Block b = this; b != null; b = b.Parent) {
1491 if (b.variables != null) {
1492 LocalInfo ret = b.variables [name] as LocalInfo;
1500 public Expression GetVariableType (string name)
1502 LocalInfo vi = GetLocalInfo (name);
1510 public Expression GetConstantExpression (string name)
1512 for (Block b = this; b != null; b = b.Parent) {
1513 if (b.constants != null) {
1514 Expression ret = b.constants [name] as Expression;
1523 /// True if the variable named @name is a constant
1525 public bool IsConstant (string name)
1527 Expression e = null;
1529 e = GetConstantExpression (name);
1534 Parameters parameters = null;
1535 public Parameters Parameters {
1538 while (b.Parent != null)
1540 return b.parameters;
1545 /// A list of labels that were not used within this block
1547 public string [] GetUnreferenced ()
1549 // FIXME: Implement me
1553 public void AddStatement (Statement s)
1556 flags |= Flags.BlockUsed;
1561 return (flags & Flags.BlockUsed) != 0;
1567 flags |= Flags.BlockUsed;
1570 public bool HasRet {
1572 return (flags & Flags.HasRet) != 0;
1576 public bool IsDestructor {
1578 return (flags & Flags.IsDestructor) != 0;
1582 public void SetDestructor ()
1584 flags |= Flags.IsDestructor;
1587 VariableMap param_map, local_map;
1589 public VariableMap ParameterMap {
1591 if ((flags & Flags.VariablesInitialized) == 0)
1592 throw new Exception ();
1598 public VariableMap LocalMap {
1600 if ((flags & Flags.VariablesInitialized) == 0)
1601 throw new Exception ();
1607 public bool LiftVariable (LocalInfo local_info)
1613 /// Emits the variable declarations and labels.
1616 /// tc: is our typecontainer (to resolve type references)
1617 /// ig: is the code generator:
1619 public void EmitMeta (EmitContext ec, InternalParameters ip)
1621 ILGenerator ig = ec.ig;
1624 // Compute the VariableMap's.
1626 // Unfortunately, we don't know the type when adding variables with
1627 // AddVariable(), so we need to compute this info here.
1631 if (variables != null) {
1632 foreach (LocalInfo li in variables.Values)
1635 locals = new LocalInfo [variables.Count];
1636 variables.Values.CopyTo (locals, 0);
1638 locals = new LocalInfo [0];
1641 local_map = new VariableMap (Parent.LocalMap, locals);
1643 local_map = new VariableMap (locals);
1645 param_map = new VariableMap (ip);
1646 flags |= Flags.VariablesInitialized;
1648 bool old_check_state = ec.ConstantCheckState;
1649 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1650 bool remap_locals = ec.RemapToProxy;
1653 // Process this block variables
1655 if (variables != null){
1656 foreach (DictionaryEntry de in variables){
1657 string name = (string) de.Key;
1658 LocalInfo vi = (LocalInfo) de.Value;
1660 if (vi.VariableType == null)
1663 Type variable_type = vi.VariableType;
1665 if (variable_type.IsPointer){
1667 // Am not really convinced that this test is required (Microsoft does it)
1668 // but the fact is that you would not be able to use the pointer variable
1671 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1677 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1679 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1681 if (constants == null)
1684 Expression cv = (Expression) constants [name];
1688 ec.CurrentBlock = this;
1689 Expression e = cv.Resolve (ec);
1693 Constant ce = e as Constant;
1695 Report.Error (133, vi.Location,
1696 "The expression being assigned to `" +
1697 name + "' must be constant (" + e + ")");
1701 if (e.Type != variable_type){
1702 e = Const.ChangeType (vi.Location, ce, variable_type);
1707 constants.Remove (name);
1708 constants.Add (name, e);
1711 ec.ConstantCheckState = old_check_state;
1714 // Now, handle the children
1716 if (children != null){
1717 foreach (Block b in children)
1718 b.EmitMeta (ec, ip);
1722 void UsageWarning (FlowBranching.UsageVector vector)
1726 if (variables != null){
1727 foreach (DictionaryEntry de in variables){
1728 LocalInfo vi = (LocalInfo) de.Value;
1733 name = (string) de.Key;
1735 if (vector.IsAssigned (vi.VariableInfo)){
1737 219, vi.Location, "The variable `" + name +
1738 "' is assigned but its value is never used");
1741 168, vi.Location, "The variable `" +
1743 "' is declared but never used");
1749 public override bool Resolve (EmitContext ec)
1751 Block prev_block = ec.CurrentBlock;
1754 int errors = Report.Errors;
1756 ec.CurrentBlock = this;
1757 ec.StartFlowBranching (this);
1759 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1761 bool unreachable = false, warning_shown = false;
1763 int statement_count = statements.Count;
1764 for (int ix = 0; ix < statement_count; ix++){
1765 Statement s = (Statement) statements [ix];
1767 if (unreachable && !(s is LabeledStatement)) {
1768 if (s == EmptyStatement.Value)
1769 s.loc = EndLocation;
1771 if (!s.ResolveUnreachable (ec, !warning_shown))
1774 if (s != EmptyStatement.Value)
1775 warning_shown = true;
1777 s.loc = Location.Null;
1779 statements [ix] = EmptyStatement.Value;
1783 if (s.Resolve (ec) == false) {
1785 statements [ix] = EmptyStatement.Value;
1789 num_statements = ix + 1;
1791 if (s is LabeledStatement)
1792 unreachable = false;
1794 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1797 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1798 ec.CurrentBranching, statement_count, num_statements);
1801 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1803 ec.CurrentBlock = prev_block;
1805 // If we're a non-static `struct' constructor which doesn't have an
1806 // initializer, then we must initialize all of the struct's fields.
1807 if ((this_variable != null) &&
1808 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1809 !this_variable.IsThisAssigned (ec, loc))
1812 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1813 foreach (LabeledStatement label in labels.Values)
1814 if (!label.HasBeenReferenced)
1815 Report.Warning (164, label.Location,
1816 "This label has not been referenced");
1819 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1821 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1822 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1823 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1824 flags |= Flags.HasRet;
1826 if (ok && (errors == Report.Errors)) {
1827 if (RootContext.WarningLevel >= 3)
1828 UsageWarning (vector);
1834 protected override void DoEmit (EmitContext ec)
1836 for (int ix = 0; ix < num_statements; ix++){
1837 Statement s = (Statement) statements [ix];
1839 // Check whether we are the last statement in a
1842 if ((Parent == null) && (ix+1 == num_statements))
1843 ec.IsLastStatement = true;
1845 ec.IsLastStatement = false;
1851 public override void Emit (EmitContext ec)
1853 Block prev_block = ec.CurrentBlock;
1855 ec.CurrentBlock = this;
1857 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1858 bool is_lexical_block = !Implicit && (Parent != null);
1860 if (emit_debug_info) {
1861 if (is_lexical_block)
1862 ec.ig.BeginScope ();
1864 if (variables != null) {
1865 foreach (DictionaryEntry de in variables) {
1866 string name = (string) de.Key;
1867 LocalInfo vi = (LocalInfo) de.Value;
1869 if (vi.LocalBuilder == null)
1872 vi.LocalBuilder.SetLocalSymInfo (name);
1877 ec.Mark (StartLocation, true);
1879 ec.Mark (EndLocation, true);
1881 if (emit_debug_info && is_lexical_block)
1884 ec.CurrentBlock = prev_block;
1890 public class ToplevelBlock : Block {
1891 public ToplevelBlock (Parameters parameters, Location start) :
1892 base (null, parameters, start, Location.Null)
1896 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1897 base (null, flags, parameters, start, Location.Null)
1902 public class SwitchLabel {
1905 public Location loc;
1906 public Label ILLabel;
1907 public Label ILLabelCode;
1910 // if expr == null, then it is the default case.
1912 public SwitchLabel (Expression expr, Location l)
1918 public Expression Label {
1924 public object Converted {
1931 // Resolves the expression, reduces it to a literal if possible
1932 // and then converts it to the requested type.
1934 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1936 ILLabel = ec.ig.DefineLabel ();
1937 ILLabelCode = ec.ig.DefineLabel ();
1942 Expression e = label.Resolve (ec);
1947 if (!(e is Constant)){
1948 Report.Error (150, loc, "A constant value is expected, got: " + e);
1952 if (e is StringConstant || e is NullLiteral){
1953 if (required_type == TypeManager.string_type){
1955 ILLabel = ec.ig.DefineLabel ();
1960 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1961 if (converted == null)
1968 public class SwitchSection {
1969 // An array of SwitchLabels.
1970 public readonly ArrayList Labels;
1971 public readonly Block Block;
1973 public SwitchSection (ArrayList labels, Block block)
1980 public class Switch : Statement {
1981 public readonly ArrayList Sections;
1982 public Expression Expr;
1985 /// Maps constants whose type type SwitchType to their SwitchLabels.
1987 public Hashtable Elements;
1990 /// The governing switch type
1992 public Type SwitchType;
1998 Label default_target;
1999 Expression new_expr;
2002 // The types allowed to be implicitly cast from
2003 // on the governing type
2005 static Type [] allowed_types;
2007 public Switch (Expression e, ArrayList sects, Location l)
2014 public bool GotDefault {
2020 public Label DefaultTarget {
2022 return default_target;
2027 // Determines the governing type for a switch. The returned
2028 // expression might be the expression from the switch, or an
2029 // expression that includes any potential conversions to the
2030 // integral types or to string.
2032 Expression SwitchGoverningType (EmitContext ec, Type t)
2034 if (t == TypeManager.int32_type ||
2035 t == TypeManager.uint32_type ||
2036 t == TypeManager.char_type ||
2037 t == TypeManager.byte_type ||
2038 t == TypeManager.sbyte_type ||
2039 t == TypeManager.ushort_type ||
2040 t == TypeManager.short_type ||
2041 t == TypeManager.uint64_type ||
2042 t == TypeManager.int64_type ||
2043 t == TypeManager.string_type ||
2044 t == TypeManager.bool_type ||
2045 t.IsSubclassOf (TypeManager.enum_type))
2048 if (allowed_types == null){
2049 allowed_types = new Type [] {
2050 TypeManager.sbyte_type,
2051 TypeManager.byte_type,
2052 TypeManager.short_type,
2053 TypeManager.ushort_type,
2054 TypeManager.int32_type,
2055 TypeManager.uint32_type,
2056 TypeManager.int64_type,
2057 TypeManager.uint64_type,
2058 TypeManager.char_type,
2059 TypeManager.bool_type,
2060 TypeManager.string_type
2065 // Try to find a *user* defined implicit conversion.
2067 // If there is no implicit conversion, or if there are multiple
2068 // conversions, we have to report an error
2070 Expression converted = null;
2071 foreach (Type tt in allowed_types){
2074 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2078 if (converted != null){
2079 Report.Error (-12, loc, "More than one conversion to an integral " +
2080 " type exists for type `" +
2081 TypeManager.CSharpName (Expr.Type)+"'");
2089 void error152 (string n)
2092 152, "The label `" + n + ":' " +
2093 "is already present on this switch statement");
2097 // Performs the basic sanity checks on the switch statement
2098 // (looks for duplicate keys and non-constant expressions).
2100 // It also returns a hashtable with the keys that we will later
2101 // use to compute the switch tables
2103 bool CheckSwitch (EmitContext ec)
2107 Elements = new Hashtable ();
2109 got_default = false;
2111 if (TypeManager.IsEnumType (SwitchType)){
2112 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2114 compare_type = SwitchType;
2116 foreach (SwitchSection ss in Sections){
2117 foreach (SwitchLabel sl in ss.Labels){
2118 if (!sl.ResolveAndReduce (ec, SwitchType)){
2123 if (sl.Label == null){
2125 error152 ("default");
2132 object key = sl.Converted;
2134 if (key is Constant)
2135 key = ((Constant) key).GetValue ();
2138 key = NullLiteral.Null;
2140 string lname = null;
2141 if (compare_type == TypeManager.uint64_type){
2142 ulong v = (ulong) key;
2144 if (Elements.Contains (v))
2145 lname = v.ToString ();
2147 Elements.Add (v, sl);
2148 } else if (compare_type == TypeManager.int64_type){
2149 long v = (long) key;
2151 if (Elements.Contains (v))
2152 lname = v.ToString ();
2154 Elements.Add (v, sl);
2155 } else if (compare_type == TypeManager.uint32_type){
2156 uint v = (uint) key;
2158 if (Elements.Contains (v))
2159 lname = v.ToString ();
2161 Elements.Add (v, sl);
2162 } else if (compare_type == TypeManager.char_type){
2163 char v = (char) key;
2165 if (Elements.Contains (v))
2166 lname = v.ToString ();
2168 Elements.Add (v, sl);
2169 } else if (compare_type == TypeManager.byte_type){
2170 byte v = (byte) key;
2172 if (Elements.Contains (v))
2173 lname = v.ToString ();
2175 Elements.Add (v, sl);
2176 } else if (compare_type == TypeManager.sbyte_type){
2177 sbyte v = (sbyte) key;
2179 if (Elements.Contains (v))
2180 lname = v.ToString ();
2182 Elements.Add (v, sl);
2183 } else if (compare_type == TypeManager.short_type){
2184 short v = (short) key;
2186 if (Elements.Contains (v))
2187 lname = v.ToString ();
2189 Elements.Add (v, sl);
2190 } else if (compare_type == TypeManager.ushort_type){
2191 ushort v = (ushort) key;
2193 if (Elements.Contains (v))
2194 lname = v.ToString ();
2196 Elements.Add (v, sl);
2197 } else if (compare_type == TypeManager.string_type){
2198 if (key is NullLiteral){
2199 if (Elements.Contains (NullLiteral.Null))
2202 Elements.Add (NullLiteral.Null, null);
2204 string s = (string) key;
2206 if (Elements.Contains (s))
2209 Elements.Add (s, sl);
2211 } else if (compare_type == TypeManager.int32_type) {
2214 if (Elements.Contains (v))
2215 lname = v.ToString ();
2217 Elements.Add (v, sl);
2218 } else if (compare_type == TypeManager.bool_type) {
2219 bool v = (bool) key;
2221 if (Elements.Contains (v))
2222 lname = v.ToString ();
2224 Elements.Add (v, sl);
2228 throw new Exception ("Unknown switch type!" +
2229 SwitchType + " " + compare_type);
2233 error152 ("case + " + lname);
2244 void EmitObjectInteger (ILGenerator ig, object k)
2247 IntConstant.EmitInt (ig, (int) k);
2248 else if (k is Constant) {
2249 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2252 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2255 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2257 IntConstant.EmitInt (ig, (int) (long) k);
2258 ig.Emit (OpCodes.Conv_I8);
2261 LongConstant.EmitLong (ig, (long) k);
2263 else if (k is ulong)
2265 if ((ulong) k < (1L<<32))
2267 IntConstant.EmitInt (ig, (int) (long) k);
2268 ig.Emit (OpCodes.Conv_U8);
2272 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2276 IntConstant.EmitInt (ig, (int) ((char) k));
2277 else if (k is sbyte)
2278 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2280 IntConstant.EmitInt (ig, (int) ((byte) k));
2281 else if (k is short)
2282 IntConstant.EmitInt (ig, (int) ((short) k));
2283 else if (k is ushort)
2284 IntConstant.EmitInt (ig, (int) ((ushort) k));
2286 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2288 throw new Exception ("Unhandled case");
2291 // structure used to hold blocks of keys while calculating table switch
2292 class KeyBlock : IComparable
2294 public KeyBlock (long _nFirst)
2296 nFirst = nLast = _nFirst;
2300 public ArrayList rgKeys = null;
2301 // how many items are in the bucket
2302 public int Size = 1;
2305 get { return (int) (nLast - nFirst + 1); }
2307 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2309 return kbLast.nLast - kbFirst.nFirst + 1;
2311 public int CompareTo (object obj)
2313 KeyBlock kb = (KeyBlock) obj;
2314 int nLength = Length;
2315 int nLengthOther = kb.Length;
2316 if (nLengthOther == nLength)
2317 return (int) (kb.nFirst - nFirst);
2318 return nLength - nLengthOther;
2323 /// This method emits code for a lookup-based switch statement (non-string)
2324 /// Basically it groups the cases into blocks that are at least half full,
2325 /// and then spits out individual lookup opcodes for each block.
2326 /// It emits the longest blocks first, and short blocks are just
2327 /// handled with direct compares.
2329 /// <param name="ec"></param>
2330 /// <param name="val"></param>
2331 /// <returns></returns>
2332 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2334 int cElements = Elements.Count;
2335 object [] rgKeys = new object [cElements];
2336 Elements.Keys.CopyTo (rgKeys, 0);
2337 Array.Sort (rgKeys);
2339 // initialize the block list with one element per key
2340 ArrayList rgKeyBlocks = new ArrayList ();
2341 foreach (object key in rgKeys)
2342 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2345 // iteratively merge the blocks while they are at least half full
2346 // there's probably a really cool way to do this with a tree...
2347 while (rgKeyBlocks.Count > 1)
2349 ArrayList rgKeyBlocksNew = new ArrayList ();
2350 kbCurr = (KeyBlock) rgKeyBlocks [0];
2351 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2353 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2354 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2357 kbCurr.nLast = kb.nLast;
2358 kbCurr.Size += kb.Size;
2362 // start a new block
2363 rgKeyBlocksNew.Add (kbCurr);
2367 rgKeyBlocksNew.Add (kbCurr);
2368 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2370 rgKeyBlocks = rgKeyBlocksNew;
2373 // initialize the key lists
2374 foreach (KeyBlock kb in rgKeyBlocks)
2375 kb.rgKeys = new ArrayList ();
2377 // fill the key lists
2379 if (rgKeyBlocks.Count > 0) {
2380 kbCurr = (KeyBlock) rgKeyBlocks [0];
2381 foreach (object key in rgKeys)
2383 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2384 System.Convert.ToInt64 (key) > kbCurr.nLast;
2386 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2387 kbCurr.rgKeys.Add (key);
2391 // sort the blocks so we can tackle the largest ones first
2392 rgKeyBlocks.Sort ();
2394 // okay now we can start...
2395 ILGenerator ig = ec.ig;
2396 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2397 Label lblDefault = ig.DefineLabel ();
2399 Type typeKeys = null;
2400 if (rgKeys.Length > 0)
2401 typeKeys = rgKeys [0].GetType (); // used for conversions
2405 if (TypeManager.IsEnumType (SwitchType))
2406 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2408 compare_type = SwitchType;
2410 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2412 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2413 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2416 foreach (object key in kb.rgKeys)
2418 ig.Emit (OpCodes.Ldloc, val);
2419 EmitObjectInteger (ig, key);
2420 SwitchLabel sl = (SwitchLabel) Elements [key];
2421 ig.Emit (OpCodes.Beq, sl.ILLabel);
2426 // TODO: if all the keys in the block are the same and there are
2427 // no gaps/defaults then just use a range-check.
2428 if (compare_type == TypeManager.int64_type ||
2429 compare_type == TypeManager.uint64_type)
2431 // TODO: optimize constant/I4 cases
2433 // check block range (could be > 2^31)
2434 ig.Emit (OpCodes.Ldloc, val);
2435 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2436 ig.Emit (OpCodes.Blt, lblDefault);
2437 ig.Emit (OpCodes.Ldloc, val);
2438 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2439 ig.Emit (OpCodes.Bgt, lblDefault);
2442 ig.Emit (OpCodes.Ldloc, val);
2445 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2446 ig.Emit (OpCodes.Sub);
2448 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2453 ig.Emit (OpCodes.Ldloc, val);
2454 int nFirst = (int) kb.nFirst;
2457 IntConstant.EmitInt (ig, nFirst);
2458 ig.Emit (OpCodes.Sub);
2460 else if (nFirst < 0)
2462 IntConstant.EmitInt (ig, -nFirst);
2463 ig.Emit (OpCodes.Add);
2467 // first, build the list of labels for the switch
2469 int cJumps = kb.Length;
2470 Label [] rgLabels = new Label [cJumps];
2471 for (int iJump = 0; iJump < cJumps; iJump++)
2473 object key = kb.rgKeys [iKey];
2474 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2476 SwitchLabel sl = (SwitchLabel) Elements [key];
2477 rgLabels [iJump] = sl.ILLabel;
2481 rgLabels [iJump] = lblDefault;
2483 // emit the switch opcode
2484 ig.Emit (OpCodes.Switch, rgLabels);
2487 // mark the default for this block
2489 ig.MarkLabel (lblDefault);
2492 // TODO: find the default case and emit it here,
2493 // to prevent having to do the following jump.
2494 // make sure to mark other labels in the default section
2496 // the last default just goes to the end
2497 ig.Emit (OpCodes.Br, lblDefault);
2499 // now emit the code for the sections
2500 bool fFoundDefault = false;
2501 foreach (SwitchSection ss in Sections)
2503 foreach (SwitchLabel sl in ss.Labels)
2505 ig.MarkLabel (sl.ILLabel);
2506 ig.MarkLabel (sl.ILLabelCode);
2507 if (sl.Label == null)
2509 ig.MarkLabel (lblDefault);
2510 fFoundDefault = true;
2514 //ig.Emit (OpCodes.Br, lblEnd);
2517 if (!fFoundDefault) {
2518 ig.MarkLabel (lblDefault);
2520 ig.MarkLabel (lblEnd);
2523 // This simple emit switch works, but does not take advantage of the
2525 // TODO: remove non-string logic from here
2526 // TODO: binary search strings?
2528 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2530 ILGenerator ig = ec.ig;
2531 Label end_of_switch = ig.DefineLabel ();
2532 Label next_test = ig.DefineLabel ();
2533 Label null_target = ig.DefineLabel ();
2534 bool default_found = false;
2535 bool first_test = true;
2536 bool pending_goto_end = false;
2538 bool default_at_end = false;
2540 ig.Emit (OpCodes.Ldloc, val);
2542 if (Elements.Contains (NullLiteral.Null)){
2543 ig.Emit (OpCodes.Brfalse, null_target);
2545 ig.Emit (OpCodes.Brfalse, default_target);
2547 ig.Emit (OpCodes.Ldloc, val);
2548 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2549 ig.Emit (OpCodes.Stloc, val);
2551 int section_count = Sections.Count;
2552 for (int section = 0; section < section_count; section++){
2553 SwitchSection ss = (SwitchSection) Sections [section];
2554 Label sec_begin = ig.DefineLabel ();
2556 if (pending_goto_end)
2557 ig.Emit (OpCodes.Br, end_of_switch);
2559 int label_count = ss.Labels.Count;
2560 bool mark_default = false;
2562 for (int label = 0; label < label_count; label++){
2563 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2564 ig.MarkLabel (sl.ILLabel);
2567 ig.MarkLabel (next_test);
2568 next_test = ig.DefineLabel ();
2571 // If we are the default target
2573 if (sl.Label == null){
2574 if (label+1 == label_count)
2575 default_at_end = true;
2576 mark_default = true;
2577 default_found = true;
2579 object lit = sl.Converted;
2581 if (lit is NullLiteral){
2583 if (label_count == 1)
2584 ig.Emit (OpCodes.Br, next_test);
2588 StringConstant str = (StringConstant) lit;
2590 ig.Emit (OpCodes.Ldloc, val);
2591 ig.Emit (OpCodes.Ldstr, str.Value);
2592 if (label_count == 1)
2593 ig.Emit (OpCodes.Bne_Un, next_test);
2595 if (label+1 == label_count)
2596 ig.Emit (OpCodes.Bne_Un, next_test);
2598 ig.Emit (OpCodes.Beq, sec_begin);
2603 ig.MarkLabel (null_target);
2604 ig.MarkLabel (sec_begin);
2605 foreach (SwitchLabel sl in ss.Labels)
2606 ig.MarkLabel (sl.ILLabelCode);
2609 ig.MarkLabel (default_target);
2611 pending_goto_end = !ss.Block.HasRet;
2614 ig.MarkLabel (next_test);
2616 if (!default_at_end)
2617 ig.Emit (OpCodes.Br, default_target);
2619 ig.MarkLabel (default_target);
2620 ig.MarkLabel (end_of_switch);
2623 public override bool Resolve (EmitContext ec)
2625 Expr = Expr.Resolve (ec);
2629 new_expr = SwitchGoverningType (ec, Expr.Type);
2630 if (new_expr == null){
2631 Report.Error (151, loc, "An integer type or string was expected for switch");
2636 SwitchType = new_expr.Type;
2638 if (!CheckSwitch (ec))
2641 Switch old_switch = ec.Switch;
2643 ec.Switch.SwitchType = SwitchType;
2645 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2646 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2649 foreach (SwitchSection ss in Sections){
2651 ec.CurrentBranching.CreateSibling (
2652 null, FlowBranching.SiblingType.SwitchSection);
2656 if (ss.Block.Resolve (ec) != true)
2662 ec.CurrentBranching.CreateSibling (
2663 null, FlowBranching.SiblingType.SwitchSection);
2665 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2666 ec.Switch = old_switch;
2668 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2674 protected override void DoEmit (EmitContext ec)
2676 // Store variable for comparission purposes
2677 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2679 ec.ig.Emit (OpCodes.Stloc, value);
2681 ILGenerator ig = ec.ig;
2683 default_target = ig.DefineLabel ();
2686 // Setup the codegen context
2688 Label old_end = ec.LoopEnd;
2689 Switch old_switch = ec.Switch;
2691 ec.LoopEnd = ig.DefineLabel ();
2695 if (SwitchType == TypeManager.string_type)
2696 SimpleSwitchEmit (ec, value);
2698 TableSwitchEmit (ec, value);
2700 // Restore context state.
2701 ig.MarkLabel (ec.LoopEnd);
2704 // Restore the previous context
2706 ec.LoopEnd = old_end;
2707 ec.Switch = old_switch;
2711 public class Lock : Statement {
2713 Statement Statement;
2715 public Lock (Expression expr, Statement stmt, Location l)
2722 public override bool Resolve (EmitContext ec)
2724 expr = expr.Resolve (ec);
2728 if (expr.Type.IsValueType){
2729 Error (185, "lock statement requires the expression to be " +
2730 " a reference type (type is: `{0}'",
2731 TypeManager.CSharpName (expr.Type));
2735 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2736 bool ok = Statement.Resolve (ec);
2737 ec.EndFlowBranching ();
2742 protected override void DoEmit (EmitContext ec)
2744 Type type = expr.Type;
2746 ILGenerator ig = ec.ig;
2747 LocalBuilder temp = ig.DeclareLocal (type);
2750 ig.Emit (OpCodes.Dup);
2751 ig.Emit (OpCodes.Stloc, temp);
2752 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2755 ig.BeginExceptionBlock ();
2756 Label finish = ig.DefineLabel ();
2757 Statement.Emit (ec);
2758 // ig.Emit (OpCodes.Leave, finish);
2760 ig.MarkLabel (finish);
2763 ig.BeginFinallyBlock ();
2764 ig.Emit (OpCodes.Ldloc, temp);
2765 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2766 ig.EndExceptionBlock ();
2770 public class Unchecked : Statement {
2771 public readonly Block Block;
2773 public Unchecked (Block b)
2779 public override bool Resolve (EmitContext ec)
2781 bool previous_state = ec.CheckState;
2782 bool previous_state_const = ec.ConstantCheckState;
2784 ec.CheckState = false;
2785 ec.ConstantCheckState = false;
2786 bool ret = Block.Resolve (ec);
2787 ec.CheckState = previous_state;
2788 ec.ConstantCheckState = previous_state_const;
2793 protected override void DoEmit (EmitContext ec)
2795 bool previous_state = ec.CheckState;
2796 bool previous_state_const = ec.ConstantCheckState;
2798 ec.CheckState = false;
2799 ec.ConstantCheckState = false;
2801 ec.CheckState = previous_state;
2802 ec.ConstantCheckState = previous_state_const;
2806 public class Checked : Statement {
2807 public readonly Block Block;
2809 public Checked (Block b)
2812 b.Unchecked = false;
2815 public override bool Resolve (EmitContext ec)
2817 bool previous_state = ec.CheckState;
2818 bool previous_state_const = ec.ConstantCheckState;
2820 ec.CheckState = true;
2821 ec.ConstantCheckState = true;
2822 bool ret = Block.Resolve (ec);
2823 ec.CheckState = previous_state;
2824 ec.ConstantCheckState = previous_state_const;
2829 protected override void DoEmit (EmitContext ec)
2831 bool previous_state = ec.CheckState;
2832 bool previous_state_const = ec.ConstantCheckState;
2834 ec.CheckState = true;
2835 ec.ConstantCheckState = true;
2837 ec.CheckState = previous_state;
2838 ec.ConstantCheckState = previous_state_const;
2842 public class Unsafe : Statement {
2843 public readonly Block Block;
2845 public Unsafe (Block b)
2850 public override bool Resolve (EmitContext ec)
2852 bool previous_state = ec.InUnsafe;
2856 val = Block.Resolve (ec);
2857 ec.InUnsafe = previous_state;
2862 protected override void DoEmit (EmitContext ec)
2864 bool previous_state = ec.InUnsafe;
2868 ec.InUnsafe = previous_state;
2875 public class Fixed : Statement {
2877 ArrayList declarators;
2878 Statement statement;
2884 public bool is_object;
2885 public LocalInfo vi;
2886 public Expression expr;
2887 public Expression converted;
2890 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2893 declarators = decls;
2898 public override bool Resolve (EmitContext ec)
2901 Expression.UnsafeError (loc);
2905 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2906 if (expr_type == null)
2909 CheckObsolete (expr_type);
2911 if (ec.RemapToProxy){
2912 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2916 data = new FixedData [declarators.Count];
2918 if (!expr_type.IsPointer){
2919 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2924 foreach (Pair p in declarators){
2925 LocalInfo vi = (LocalInfo) p.First;
2926 Expression e = (Expression) p.Second;
2928 vi.VariableInfo = null;
2932 // The rules for the possible declarators are pretty wise,
2933 // but the production on the grammar is more concise.
2935 // So we have to enforce these rules here.
2937 // We do not resolve before doing the case 1 test,
2938 // because the grammar is explicit in that the token &
2939 // is present, so we need to test for this particular case.
2943 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2948 // Case 1: & object.
2950 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2951 Expression child = ((Unary) e).Expr;
2954 if (child is ParameterReference || child is LocalVariableReference){
2957 "No need to use fixed statement for parameters or " +
2958 "local variable declarations (address is already " +
2963 ec.InFixedInitializer = true;
2965 ec.InFixedInitializer = false;
2969 child = ((Unary) e).Expr;
2971 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2974 data [i].is_object = true;
2976 data [i].converted = null;
2983 ec.InFixedInitializer = true;
2985 ec.InFixedInitializer = false;
2992 if (e.Type.IsArray){
2993 Type array_type = TypeManager.GetElementType (e.Type);
2997 // Provided that array_type is unmanaged,
2999 if (!TypeManager.VerifyUnManaged (array_type, loc))
3003 // and T* is implicitly convertible to the
3004 // pointer type given in the fixed statement.
3006 ArrayPtr array_ptr = new ArrayPtr (e, loc);
3008 Expression converted = Convert.ImplicitConversionRequired (
3009 ec, array_ptr, vi.VariableType, loc);
3010 if (converted == null)
3013 data [i].is_object = false;
3015 data [i].converted = converted;
3025 if (e.Type == TypeManager.string_type){
3026 data [i].is_object = false;
3028 data [i].converted = null;
3035 // For other cases, flag a `this is already fixed expression'
3037 if (e is LocalVariableReference || e is ParameterReference ||
3038 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3040 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3044 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3048 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3050 if (!statement.Resolve (ec)) {
3051 ec.KillFlowBranching ();
3055 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3056 has_ret = reachability.IsUnreachable;
3061 protected override void DoEmit (EmitContext ec)
3063 ILGenerator ig = ec.ig;
3065 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3067 for (int i = 0; i < data.Length; i++) {
3068 LocalInfo vi = data [i].vi;
3071 // Case 1: & object.
3073 if (data [i].is_object) {
3075 // Store pointer in pinned location
3077 data [i].expr.Emit (ec);
3078 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3079 clear_list [i] = vi.LocalBuilder;
3086 if (data [i].expr.Type.IsArray){
3088 // Store pointer in pinned location
3090 data [i].converted.Emit (ec);
3092 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3093 clear_list [i] = vi.LocalBuilder;
3100 if (data [i].expr.Type == TypeManager.string_type){
3101 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3102 TypeManager.MakePinned (pinned_string);
3103 clear_list [i] = pinned_string;
3105 data [i].expr.Emit (ec);
3106 ig.Emit (OpCodes.Stloc, pinned_string);
3108 Expression sptr = new StringPtr (pinned_string, loc);
3109 Expression converted = Convert.ImplicitConversionRequired (
3110 ec, sptr, vi.VariableType, loc);
3112 if (converted == null)
3115 converted.Emit (ec);
3116 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3120 statement.Emit (ec);
3126 // Clear the pinned variable
3128 for (int i = 0; i < data.Length; i++) {
3129 if (data [i].is_object || data [i].expr.Type.IsArray) {
3130 ig.Emit (OpCodes.Ldc_I4_0);
3131 ig.Emit (OpCodes.Conv_U);
3132 ig.Emit (OpCodes.Stloc, clear_list [i]);
3133 } else if (data [i].expr.Type == TypeManager.string_type){
3134 ig.Emit (OpCodes.Ldnull);
3135 ig.Emit (OpCodes.Stloc, clear_list [i]);
3141 public class Catch: Statement {
3142 public readonly string Name;
3143 public readonly Block Block;
3145 Expression type_expr;
3148 public Catch (Expression type, string name, Block block, Location l)
3156 public Type CatchType {
3162 public bool IsGeneral {
3164 return type_expr == null;
3168 protected override void DoEmit(EmitContext ec)
3172 public override bool Resolve (EmitContext ec)
3174 if (type_expr != null) {
3175 type = ec.DeclSpace.ResolveType (type_expr, false, loc);
3179 CheckObsolete (type);
3181 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3182 Error (155, "The type caught or thrown must be derived from System.Exception");
3188 return Block.Resolve (ec);
3192 public class Try : Statement {
3193 public readonly Block Fini, Block;
3194 public readonly ArrayList Specific;
3195 public readonly Catch General;
3198 // specific, general and fini might all be null.
3200 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3202 if (specific == null && general == null){
3203 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3207 this.Specific = specific;
3208 this.General = general;
3213 public override bool Resolve (EmitContext ec)
3217 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3219 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3221 if (!Block.Resolve (ec))
3224 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3226 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3228 Type[] prevCatches = new Type [Specific.Count];
3230 foreach (Catch c in Specific){
3231 ec.CurrentBranching.CreateSibling (
3232 c.Block, FlowBranching.SiblingType.Catch);
3234 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3236 if (c.Name != null) {
3237 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3239 throw new Exception ();
3241 vi.VariableInfo = null;
3244 if (!c.Resolve (ec))
3247 Type resolvedType = c.CatchType;
3248 for (int ii = 0; ii < last_index; ++ii) {
3249 if (resolvedType.IsSubclassOf (prevCatches [ii])) {
3250 Report.Error_T (160, c.loc, prevCatches [ii].FullName);
3255 prevCatches [last_index++] = resolvedType;
3258 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3260 if (General != null){
3261 ec.CurrentBranching.CreateSibling (
3262 General.Block, FlowBranching.SiblingType.Catch);
3264 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3266 if (!General.Resolve (ec))
3270 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3274 ec.CurrentBranching.CreateSibling (
3275 Fini, FlowBranching.SiblingType.Finally);
3277 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3279 if (!Fini.Resolve (ec))
3283 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3285 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3287 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3289 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3290 // Unfortunately, System.Reflection.Emit automatically emits a leave
3291 // to the end of the finally block. This is a problem if `returns'
3292 // is true since we may jump to a point after the end of the method.
3293 // As a workaround, emit an explicit ret here.
3294 ec.NeedReturnLabel ();
3300 protected override void DoEmit (EmitContext ec)
3302 ILGenerator ig = ec.ig;
3303 Label finish = ig.DefineLabel ();;
3305 ig.BeginExceptionBlock ();
3309 // System.Reflection.Emit provides this automatically:
3310 // ig.Emit (OpCodes.Leave, finish);
3312 foreach (Catch c in Specific){
3315 ig.BeginCatchBlock (c.CatchType);
3317 if (c.Name != null){
3318 vi = c.Block.GetLocalInfo (c.Name);
3320 throw new Exception ("Variable does not exist in this block");
3322 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3324 ig.Emit (OpCodes.Pop);
3329 if (General != null){
3330 ig.BeginCatchBlock (TypeManager.object_type);
3331 ig.Emit (OpCodes.Pop);
3332 General.Block.Emit (ec);
3335 ig.MarkLabel (finish);
3337 ig.BeginFinallyBlock ();
3341 ig.EndExceptionBlock ();
3345 public class Using : Statement {
3346 object expression_or_block;
3347 Statement Statement;
3352 Expression [] converted_vars;
3353 ExpressionStatement [] assign;
3355 public Using (object expression_or_block, Statement stmt, Location l)
3357 this.expression_or_block = expression_or_block;
3363 // Resolves for the case of using using a local variable declaration.
3365 bool ResolveLocalVariableDecls (EmitContext ec)
3367 bool need_conv = false;
3368 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3371 if (expr_type == null)
3375 // The type must be an IDisposable or an implicit conversion
3378 converted_vars = new Expression [var_list.Count];
3379 assign = new ExpressionStatement [var_list.Count];
3380 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3381 foreach (DictionaryEntry e in var_list){
3382 Expression var = (Expression) e.Key;
3384 var = var.ResolveLValue (ec, new EmptyExpression ());
3388 converted_vars [i] = Convert.ImplicitConversionRequired (
3389 ec, var, TypeManager.idisposable_type, loc);
3391 if (converted_vars [i] == null)
3399 foreach (DictionaryEntry e in var_list){
3400 LocalVariableReference var = (LocalVariableReference) e.Key;
3401 Expression new_expr = (Expression) e.Value;
3404 a = new Assign (var, new_expr, loc);
3410 converted_vars [i] = var;
3411 assign [i] = (ExpressionStatement) a;
3418 bool ResolveExpression (EmitContext ec)
3420 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3421 conv = Convert.ImplicitConversionRequired (
3422 ec, expr, TypeManager.idisposable_type, loc);
3432 // Emits the code for the case of using using a local variable declaration.
3434 bool EmitLocalVariableDecls (EmitContext ec)
3436 ILGenerator ig = ec.ig;
3439 for (i = 0; i < assign.Length; i++) {
3440 assign [i].EmitStatement (ec);
3442 ig.BeginExceptionBlock ();
3444 Statement.Emit (ec);
3446 var_list.Reverse ();
3447 foreach (DictionaryEntry e in var_list){
3448 LocalVariableReference var = (LocalVariableReference) e.Key;
3449 Label skip = ig.DefineLabel ();
3452 ig.BeginFinallyBlock ();
3454 if (!var.Type.IsValueType) {
3456 ig.Emit (OpCodes.Brfalse, skip);
3457 converted_vars [i].Emit (ec);
3458 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3460 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3462 if (!(ml is MethodGroupExpr)) {
3464 ig.Emit (OpCodes.Box, var.Type);
3465 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3467 MethodInfo mi = null;
3469 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3470 if (mk.GetParameters().Length == 0) {
3477 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3481 var.AddressOf (ec, AddressOp.Load);
3482 ig.Emit (OpCodes.Call, mi);
3486 ig.MarkLabel (skip);
3487 ig.EndExceptionBlock ();
3493 bool EmitExpression (EmitContext ec)
3496 // Make a copy of the expression and operate on that.
3498 ILGenerator ig = ec.ig;
3499 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3504 ig.Emit (OpCodes.Stloc, local_copy);
3506 ig.BeginExceptionBlock ();
3507 Statement.Emit (ec);
3509 Label skip = ig.DefineLabel ();
3510 ig.BeginFinallyBlock ();
3511 ig.Emit (OpCodes.Ldloc, local_copy);
3512 ig.Emit (OpCodes.Brfalse, skip);
3513 ig.Emit (OpCodes.Ldloc, local_copy);
3514 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3515 ig.MarkLabel (skip);
3516 ig.EndExceptionBlock ();
3521 public override bool Resolve (EmitContext ec)
3523 if (expression_or_block is DictionaryEntry){
3524 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3525 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3527 if (!ResolveLocalVariableDecls (ec))
3530 } else if (expression_or_block is Expression){
3531 expr = (Expression) expression_or_block;
3533 expr = expr.Resolve (ec);
3537 expr_type = expr.Type;
3539 if (!ResolveExpression (ec))
3543 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3545 bool ok = Statement.Resolve (ec);
3548 ec.KillFlowBranching ();
3552 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3554 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3555 // Unfortunately, System.Reflection.Emit automatically emits a leave
3556 // to the end of the finally block. This is a problem if `returns'
3557 // is true since we may jump to a point after the end of the method.
3558 // As a workaround, emit an explicit ret here.
3559 ec.NeedReturnLabel ();
3565 protected override void DoEmit (EmitContext ec)
3567 if (expression_or_block is DictionaryEntry)
3568 EmitLocalVariableDecls (ec);
3569 else if (expression_or_block is Expression)
3570 EmitExpression (ec);
3575 /// Implementation of the foreach C# statement
3577 public class Foreach : Statement {
3579 Expression variable;
3581 Statement statement;
3582 ForeachHelperMethods hm;
3583 Expression empty, conv;
3584 Type array_type, element_type;
3587 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3588 Statement stmt, Location l)
3591 this.variable = var;
3597 public override bool Resolve (EmitContext ec)
3599 expr = expr.Resolve (ec);
3603 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3604 if (var_type == null)
3608 // We need an instance variable. Not sure this is the best
3609 // way of doing this.
3611 // FIXME: When we implement propertyaccess, will those turn
3612 // out to return values in ExprClass? I think they should.
3614 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3615 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3616 error1579 (expr.Type);
3620 if (expr.Type.IsArray) {
3621 array_type = expr.Type;
3622 element_type = TypeManager.GetElementType (array_type);
3624 empty = new EmptyExpression (element_type);
3626 hm = ProbeCollectionType (ec, expr.Type);
3628 error1579 (expr.Type);
3632 array_type = expr.Type;
3633 element_type = hm.element_type;
3635 empty = new EmptyExpression (hm.element_type);
3640 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3641 ec.CurrentBranching.CreateSibling ();
3645 // FIXME: maybe we can apply the same trick we do in the
3646 // array handling to avoid creating empty and conv in some cases.
3648 // Although it is not as important in this case, as the type
3649 // will not likely be object (what the enumerator will return).
3651 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3655 variable = variable.ResolveLValue (ec, empty);
3656 if (variable == null)
3659 bool disposable = (hm != null) && hm.is_disposable;
3661 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3663 if (!statement.Resolve (ec))
3667 ec.EndFlowBranching ();
3669 ec.EndFlowBranching ();
3675 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3677 static MethodInfo FetchMethodMoveNext (Type t)
3679 MemberList move_next_list;
3681 move_next_list = TypeContainer.FindMembers (
3682 t, MemberTypes.Method,
3683 BindingFlags.Public | BindingFlags.Instance,
3684 Type.FilterName, "MoveNext");
3685 if (move_next_list.Count == 0)
3688 foreach (MemberInfo m in move_next_list){
3689 MethodInfo mi = (MethodInfo) m;
3692 args = TypeManager.GetArgumentTypes (mi);
3693 if (args != null && args.Length == 0){
3694 if (mi.ReturnType == TypeManager.bool_type)
3702 // Retrieves a `public T get_Current ()' method from the Type `t'
3704 static MethodInfo FetchMethodGetCurrent (Type t)
3706 MemberList get_current_list;
3708 get_current_list = TypeContainer.FindMembers (
3709 t, MemberTypes.Method,
3710 BindingFlags.Public | BindingFlags.Instance,
3711 Type.FilterName, "get_Current");
3712 if (get_current_list.Count == 0)
3715 foreach (MemberInfo m in get_current_list){
3716 MethodInfo mi = (MethodInfo) m;
3719 args = TypeManager.GetArgumentTypes (mi);
3720 if (args != null && args.Length == 0)
3727 // This struct records the helper methods used by the Foreach construct
3729 class ForeachHelperMethods {
3730 public EmitContext ec;
3731 public MethodInfo get_enumerator;
3732 public MethodInfo move_next;
3733 public MethodInfo get_current;
3734 public Type element_type;
3735 public Type enumerator_type;
3736 public bool is_disposable;
3738 public ForeachHelperMethods (EmitContext ec)
3741 this.element_type = TypeManager.object_type;
3742 this.enumerator_type = TypeManager.ienumerator_type;
3743 this.is_disposable = true;
3747 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3752 if (!(m is MethodInfo))
3755 if (m.Name != "GetEnumerator")
3758 MethodInfo mi = (MethodInfo) m;
3759 Type [] args = TypeManager.GetArgumentTypes (mi);
3761 if (args.Length != 0)
3764 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3765 EmitContext ec = hm.ec;
3768 // Check whether GetEnumerator is accessible to us
3770 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3772 Type declaring = mi.DeclaringType;
3773 if (prot == MethodAttributes.Private){
3774 if (declaring != ec.ContainerType)
3776 } else if (prot == MethodAttributes.FamANDAssem){
3777 // If from a different assembly, false
3778 if (!(mi is MethodBuilder))
3781 // Are we being invoked from the same class, or from a derived method?
3783 if (ec.ContainerType != declaring){
3784 if (!ec.ContainerType.IsSubclassOf (declaring))
3787 } else if (prot == MethodAttributes.FamORAssem){
3788 if (!(mi is MethodBuilder ||
3789 ec.ContainerType == declaring ||
3790 ec.ContainerType.IsSubclassOf (declaring)))
3792 } if (prot == MethodAttributes.Family){
3793 if (!(ec.ContainerType == declaring ||
3794 ec.ContainerType.IsSubclassOf (declaring)))
3798 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3800 // Apply the same optimization as MS: skip the GetEnumerator
3801 // returning an IEnumerator, and use the one returning a
3802 // CharEnumerator instead. This allows us to avoid the
3803 // try-finally block and the boxing.
3808 // Ok, we can access it, now make sure that we can do something
3809 // with this `GetEnumerator'
3812 Type return_type = mi.ReturnType;
3813 if (mi.ReturnType == TypeManager.ienumerator_type ||
3814 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3815 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3818 // If it is not an interface, lets try to find the methods ourselves.
3819 // For example, if we have:
3820 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3821 // We can avoid the iface call. This is a runtime perf boost.
3822 // even bigger if we have a ValueType, because we avoid the cost
3825 // We have to make sure that both methods exist for us to take
3826 // this path. If one of the methods does not exist, we will just
3827 // use the interface. Sadly, this complex if statement is the only
3828 // way I could do this without a goto
3831 if (return_type.IsInterface ||
3832 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3833 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3835 hm.move_next = TypeManager.bool_movenext_void;
3836 hm.get_current = TypeManager.object_getcurrent_void;
3843 // Ok, so they dont return an IEnumerable, we will have to
3844 // find if they support the GetEnumerator pattern.
3847 hm.move_next = FetchMethodMoveNext (return_type);
3848 if (hm.move_next == null)
3851 hm.get_current = FetchMethodGetCurrent (return_type);
3852 if (hm.get_current == null)
3856 hm.element_type = hm.get_current.ReturnType;
3857 hm.enumerator_type = return_type;
3858 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3859 TypeManager.ImplementsInterface (
3860 hm.enumerator_type, TypeManager.idisposable_type);
3866 /// This filter is used to find the GetEnumerator method
3867 /// on which IEnumerator operates
3869 static MemberFilter FilterEnumerator;
3873 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3876 void error1579 (Type t)
3878 Report.Error (1579, loc,
3879 "foreach statement cannot operate on variables of type `" +
3880 t.FullName + "' because that class does not provide a " +
3881 " GetEnumerator method or it is inaccessible");
3884 static bool TryType (Type t, ForeachHelperMethods hm)
3888 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3889 BindingFlags.Public | BindingFlags.NonPublic |
3890 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3891 FilterEnumerator, hm);
3896 hm.get_enumerator = (MethodInfo) mi [0];
3901 // Looks for a usable GetEnumerator in the Type, and if found returns
3902 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3904 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3906 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3908 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3909 if (TryType (tt, hm))
3915 // Now try to find the method in the interfaces
3918 Type [] ifaces = t.GetInterfaces ();
3920 foreach (Type i in ifaces){
3921 if (TryType (i, hm))
3926 // Since TypeBuilder.GetInterfaces only returns the interface
3927 // types for this type, we have to keep looping, but once
3928 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3929 // done, because it returns all the types
3931 if ((t is TypeBuilder))
3941 // FIXME: possible optimization.
3942 // We might be able to avoid creating `empty' if the type is the sam
3944 bool EmitCollectionForeach (EmitContext ec)
3946 ILGenerator ig = ec.ig;
3947 VariableStorage enumerator;
3949 enumerator = new VariableStorage (ec, hm.enumerator_type);
3950 enumerator.EmitThis ();
3952 // Instantiate the enumerator
3954 if (expr.Type.IsValueType){
3955 if (expr is IMemoryLocation){
3956 IMemoryLocation ml = (IMemoryLocation) expr;
3958 Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
3960 if (!(ml1 is MethodGroupExpr)) {
3962 ec.ig.Emit(OpCodes.Box, expr.Type);
3964 ml.AddressOf (ec, AddressOp.Load);
3967 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3968 " does not implement IMemoryLocation");
3969 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3972 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3974 enumerator.EmitStore ();
3977 // Protect the code in a try/finalize block, so that
3978 // if the beast implement IDisposable, we get rid of it
3980 if (hm.is_disposable)
3981 ig.BeginExceptionBlock ();
3983 Label end_try = ig.DefineLabel ();
3985 ig.MarkLabel (ec.LoopBegin);
3987 enumerator.EmitCall (hm.move_next);
3989 ig.Emit (OpCodes.Brfalse, end_try);
3993 enumerator.EmitCall (hm.get_current);
3997 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3999 ((IAssignMethod)variable).EmitAssign (ec, conv);
4001 statement.Emit (ec);
4002 ig.Emit (OpCodes.Br, ec.LoopBegin);
4003 ig.MarkLabel (end_try);
4005 // The runtime provides this for us.
4006 // ig.Emit (OpCodes.Leave, end);
4009 // Now the finally block
4011 if (hm.is_disposable) {
4012 Label call_dispose = ig.DefineLabel ();
4013 ig.BeginFinallyBlock ();
4015 enumerator.EmitThis ();
4016 enumerator.EmitLoad ();
4017 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4018 ig.Emit (OpCodes.Dup);
4019 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4020 ig.Emit (OpCodes.Pop);
4021 ig.Emit (OpCodes.Endfinally);
4023 ig.MarkLabel (call_dispose);
4024 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4027 // The runtime generates this anyways.
4028 // ig.Emit (OpCodes.Endfinally);
4030 ig.EndExceptionBlock ();
4033 ig.MarkLabel (ec.LoopEnd);
4038 // FIXME: possible optimization.
4039 // We might be able to avoid creating `empty' if the type is the sam
4041 bool EmitArrayForeach (EmitContext ec)
4043 int rank = array_type.GetArrayRank ();
4044 ILGenerator ig = ec.ig;
4046 VariableStorage copy = new VariableStorage (ec, array_type);
4049 // Make our copy of the array
4056 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4060 counter.EmitThis ();
4061 ig.Emit (OpCodes.Ldc_I4_0);
4062 counter.EmitStore ();
4063 test = ig.DefineLabel ();
4064 ig.Emit (OpCodes.Br, test);
4066 loop = ig.DefineLabel ();
4067 ig.MarkLabel (loop);
4074 counter.EmitThis ();
4075 counter.EmitLoad ();
4078 // Load the value, we load the value using the underlying type,
4079 // then we use the variable.EmitAssign to load using the proper cast.
4081 ArrayAccess.EmitLoadOpcode (ig, element_type);
4084 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4086 ((IAssignMethod)variable).EmitAssign (ec, conv);
4088 statement.Emit (ec);
4090 ig.MarkLabel (ec.LoopBegin);
4091 counter.EmitThis ();
4092 counter.EmitThis ();
4093 counter.EmitLoad ();
4094 ig.Emit (OpCodes.Ldc_I4_1);
4095 ig.Emit (OpCodes.Add);
4096 counter.EmitStore ();
4098 ig.MarkLabel (test);
4099 counter.EmitThis ();
4100 counter.EmitLoad ();
4103 ig.Emit (OpCodes.Ldlen);
4104 ig.Emit (OpCodes.Conv_I4);
4105 ig.Emit (OpCodes.Blt, loop);
4107 VariableStorage [] dim_len = new VariableStorage [rank];
4108 VariableStorage [] dim_count = new VariableStorage [rank];
4109 Label [] loop = new Label [rank];
4110 Label [] test = new Label [rank];
4113 for (dim = 0; dim < rank; dim++){
4114 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4115 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4116 test [dim] = ig.DefineLabel ();
4117 loop [dim] = ig.DefineLabel ();
4120 for (dim = 0; dim < rank; dim++){
4121 dim_len [dim].EmitThis ();
4124 IntLiteral.EmitInt (ig, dim);
4125 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4126 dim_len [dim].EmitStore ();
4130 for (dim = 0; dim < rank; dim++){
4131 dim_count [dim].EmitThis ();
4132 ig.Emit (OpCodes.Ldc_I4_0);
4133 dim_count [dim].EmitStore ();
4134 ig.Emit (OpCodes.Br, test [dim]);
4135 ig.MarkLabel (loop [dim]);
4142 for (dim = 0; dim < rank; dim++){
4143 dim_count [dim].EmitThis ();
4144 dim_count [dim].EmitLoad ();
4148 // FIXME: Maybe we can cache the computation of `get'?
4150 Type [] args = new Type [rank];
4153 for (int i = 0; i < rank; i++)
4154 args [i] = TypeManager.int32_type;
4156 ModuleBuilder mb = CodeGen.Module.Builder;
4157 get = mb.GetArrayMethod (
4159 CallingConventions.HasThis| CallingConventions.Standard,
4161 ig.Emit (OpCodes.Call, get);
4164 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4166 ((IAssignMethod)variable).EmitAssign (ec, conv);
4167 statement.Emit (ec);
4168 ig.MarkLabel (ec.LoopBegin);
4169 for (dim = rank - 1; dim >= 0; dim--){
4170 dim_count [dim].EmitThis ();
4171 dim_count [dim].EmitThis ();
4172 dim_count [dim].EmitLoad ();
4173 ig.Emit (OpCodes.Ldc_I4_1);
4174 ig.Emit (OpCodes.Add);
4175 dim_count [dim].EmitStore ();
4177 ig.MarkLabel (test [dim]);
4178 dim_count [dim].EmitThis ();
4179 dim_count [dim].EmitLoad ();
4180 dim_len [dim].EmitThis ();
4181 dim_len [dim].EmitLoad ();
4182 ig.Emit (OpCodes.Blt, loop [dim]);
4185 ig.MarkLabel (ec.LoopEnd);
4190 protected override void DoEmit (EmitContext ec)
4192 ILGenerator ig = ec.ig;
4194 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4195 ec.LoopBegin = ig.DefineLabel ();
4196 ec.LoopEnd = ig.DefineLabel ();
4199 EmitCollectionForeach (ec);
4201 EmitArrayForeach (ec);
4203 ec.LoopBegin = old_begin;
4204 ec.LoopEnd = old_end;