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,
1104 public bool Implicit {
1106 return (flags & Flags.Implicit) != 0;
1110 public bool Unchecked {
1112 return (flags & Flags.Unchecked) != 0;
1115 flags |= Flags.Unchecked;
1120 // The statements in this block
1122 ArrayList statements;
1126 // An array of Blocks. We keep track of children just
1127 // to generate the local variable declarations.
1129 // Statements and child statements are handled through the
1135 // Labels. (label, block) pairs.
1140 // Keeps track of (name, type) pairs
1142 Hashtable variables;
1145 // Keeps track of constants
1146 Hashtable constants;
1149 // If this is a switch section, the enclosing switch block.
1157 public Block (Block parent)
1158 : this (parent, (Flags) 0, Location.Null, Location.Null)
1161 public Block (Block parent, Flags flags)
1162 : this (parent, flags, Location.Null, Location.Null)
1165 public Block (Block parent, Flags flags, Parameters parameters)
1166 : this (parent, flags, parameters, Location.Null, Location.Null)
1169 public Block (Block parent, Location start, Location end)
1170 : this (parent, (Flags) 0, start, end)
1173 public Block (Block parent, Parameters parameters, Location start, Location end)
1174 : this (parent, (Flags) 0, parameters, start, end)
1177 public Block (Block parent, Flags flags, Location start, Location end)
1178 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1181 public Block (Block parent, Flags flags, Parameters parameters,
1182 Location start, Location end)
1185 parent.AddChild (this);
1187 this.Parent = parent;
1189 this.parameters = parameters;
1190 this.StartLocation = start;
1191 this.EndLocation = end;
1194 statements = new ArrayList ();
1196 if (parent != null && Implicit) {
1197 if (parent.child_variable_names == null)
1198 parent.child_variable_names = new Hashtable();
1199 // share with parent
1200 child_variable_names = parent.child_variable_names;
1205 public Block CreateSwitchBlock (Location start)
1207 Block new_block = new Block (this, start, start);
1208 new_block.switch_block = this;
1218 void AddChild (Block b)
1220 if (children == null)
1221 children = new ArrayList ();
1226 public void SetEndLocation (Location loc)
1232 /// Adds a label to the current block.
1236 /// false if the name already exists in this block. true
1240 public bool AddLabel (string name, LabeledStatement target, Location loc)
1242 if (switch_block != null)
1243 return switch_block.AddLabel (name, target, loc);
1246 while (cur != null) {
1247 if (cur.DoLookupLabel (name) != null) {
1249 140, loc, "The label '{0}' is a duplicate",
1260 while (cur != null) {
1261 if (cur.DoLookupLabel (name) != null) {
1264 "The label '{0}' shadows another label " +
1265 "by the same name in a containing scope.",
1270 if (children != null) {
1271 foreach (Block b in children) {
1272 LabeledStatement s = b.DoLookupLabel (name);
1278 "The label '{0}' shadows another " +
1279 "label by the same name in a " +
1280 "containing scope.",
1291 labels = new Hashtable ();
1293 labels.Add (name, target);
1297 public LabeledStatement LookupLabel (string name)
1299 LabeledStatement s = DoLookupLabel (name);
1303 if (children == null)
1306 foreach (Block child in children) {
1307 if (!child.Implicit)
1310 s = child.LookupLabel (name);
1318 LabeledStatement DoLookupLabel (string name)
1320 if (switch_block != null)
1321 return switch_block.LookupLabel (name);
1324 if (labels.Contains (name))
1325 return ((LabeledStatement) labels [name]);
1330 LocalInfo this_variable = null;
1333 // Returns the "this" instance variable of this block.
1334 // See AddThisVariable() for more information.
1336 public LocalInfo ThisVariable {
1338 if (this_variable != null)
1339 return this_variable;
1340 else if (Parent != null)
1341 return Parent.ThisVariable;
1347 Hashtable child_variable_names;
1350 // Marks a variable with name @name as being used in a child block.
1351 // If a variable name has been used in a child block, it's illegal to
1352 // declare a variable with the same name in the current block.
1354 public void AddChildVariableName (string name)
1356 if (child_variable_names == null)
1357 child_variable_names = new Hashtable ();
1359 if (!child_variable_names.Contains (name))
1360 child_variable_names.Add (name, true);
1364 // Checks whether a variable name has already been used in a child block.
1366 public bool IsVariableNameUsedInChildBlock (string name)
1368 if (child_variable_names == null)
1371 return child_variable_names.Contains (name);
1375 // This is used by non-static `struct' constructors which do not have an
1376 // initializer - in this case, the constructor must initialize all of the
1377 // struct's fields. To do this, we add a "this" variable and use the flow
1378 // analysis code to ensure that it's been fully initialized before control
1379 // leaves the constructor.
1381 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1383 if (this_variable != null)
1384 return this_variable;
1386 if (variables == null)
1387 variables = new Hashtable ();
1389 this_variable = new LocalInfo (tc, this, l);
1390 this_variable.Used = true;
1392 variables.Add ("this", this_variable);
1394 return this_variable;
1397 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1399 if (variables == null)
1400 variables = new Hashtable ();
1402 LocalInfo vi = GetLocalInfo (name);
1404 if (vi.Block != this)
1405 Report.Error (136, l, "A local variable named `" + name + "' " +
1406 "cannot be declared in this scope since it would " +
1407 "give a different meaning to `" + name + "', which " +
1408 "is already used in a `parent or current' scope to " +
1409 "denote something else");
1411 Report.Error (128, l, "A local variable `" + name + "' is already " +
1412 "defined in this scope");
1416 if (IsVariableNameUsedInChildBlock (name)) {
1417 Report.Error (136, l, "A local variable named `" + name + "' " +
1418 "cannot be declared in this scope since it would " +
1419 "give a different meaning to `" + name + "', which " +
1420 "is already used in a `child' scope to denote something " +
1427 Parameter p = pars.GetParameterByName (name, out idx);
1429 Report.Error (136, l, "A local variable named `" + name + "' " +
1430 "cannot be declared in this scope since it would " +
1431 "give a different meaning to `" + name + "', which " +
1432 "is already used in a `parent or current' scope to " +
1433 "denote something else");
1438 vi = new LocalInfo (type, name, this, l);
1440 variables.Add (name, vi);
1442 // Mark 'name' as "used by a child block" in every surrounding block
1444 while (cur != null && cur.Implicit)
1447 for (Block par = cur.Parent; par != null; par = par.Parent)
1448 par.AddChildVariableName (name);
1450 if ((flags & Flags.VariablesInitialized) != 0)
1451 throw new Exception ();
1453 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1457 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1459 if (AddVariable (type, name, pars, l) == null)
1462 if (constants == null)
1463 constants = new Hashtable ();
1465 constants.Add (name, value);
1469 public Hashtable Variables {
1475 public LocalInfo GetLocalInfo (string name)
1477 for (Block b = this; b != null; b = b.Parent) {
1478 if (b.variables != null) {
1479 LocalInfo ret = b.variables [name] as LocalInfo;
1487 public Expression GetVariableType (string name)
1489 LocalInfo vi = GetLocalInfo (name);
1497 public Expression GetConstantExpression (string name)
1499 for (Block b = this; b != null; b = b.Parent) {
1500 if (b.constants != null) {
1501 Expression ret = b.constants [name] as Expression;
1510 /// True if the variable named @name is a constant
1512 public bool IsConstant (string name)
1514 Expression e = null;
1516 e = GetConstantExpression (name);
1521 Parameters parameters = null;
1522 public Parameters Parameters {
1525 while (b.Parent != null)
1527 return b.parameters;
1532 /// A list of labels that were not used within this block
1534 public string [] GetUnreferenced ()
1536 // FIXME: Implement me
1540 public void AddStatement (Statement s)
1543 flags |= Flags.BlockUsed;
1548 return (flags & Flags.BlockUsed) != 0;
1554 flags |= Flags.BlockUsed;
1557 public bool HasRet {
1559 return (flags & Flags.HasRet) != 0;
1563 public bool IsDestructor {
1565 return (flags & Flags.IsDestructor) != 0;
1569 public void SetDestructor ()
1571 flags |= Flags.IsDestructor;
1574 VariableMap param_map, local_map;
1576 public VariableMap ParameterMap {
1578 if ((flags & Flags.VariablesInitialized) == 0)
1579 throw new Exception ();
1585 public VariableMap LocalMap {
1587 if ((flags & Flags.VariablesInitialized) == 0)
1588 throw new Exception ();
1594 public bool LiftVariable (LocalInfo local_info)
1600 /// Emits the variable declarations and labels.
1603 /// tc: is our typecontainer (to resolve type references)
1604 /// ig: is the code generator:
1606 public void EmitMeta (EmitContext ec, InternalParameters ip)
1608 ILGenerator ig = ec.ig;
1611 // Compute the VariableMap's.
1613 // Unfortunately, we don't know the type when adding variables with
1614 // AddVariable(), so we need to compute this info here.
1618 if (variables != null) {
1619 foreach (LocalInfo li in variables.Values)
1622 locals = new LocalInfo [variables.Count];
1623 variables.Values.CopyTo (locals, 0);
1625 locals = new LocalInfo [0];
1628 local_map = new VariableMap (Parent.LocalMap, locals);
1630 local_map = new VariableMap (locals);
1632 param_map = new VariableMap (ip);
1633 flags |= Flags.VariablesInitialized;
1635 bool old_check_state = ec.ConstantCheckState;
1636 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1637 bool remap_locals = ec.RemapToProxy;
1640 // Process this block variables
1642 if (variables != null){
1643 foreach (DictionaryEntry de in variables){
1644 string name = (string) de.Key;
1645 LocalInfo vi = (LocalInfo) de.Value;
1647 if (vi.VariableType == null)
1650 Type variable_type = vi.VariableType;
1652 if (variable_type.IsPointer){
1654 // Am not really convinced that this test is required (Microsoft does it)
1655 // but the fact is that you would not be able to use the pointer variable
1658 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1664 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1666 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1668 if (constants == null)
1671 Expression cv = (Expression) constants [name];
1675 ec.CurrentBlock = this;
1676 Expression e = cv.Resolve (ec);
1680 Constant ce = e as Constant;
1682 Report.Error (133, vi.Location,
1683 "The expression being assigned to `" +
1684 name + "' must be constant (" + e + ")");
1688 if (e.Type != variable_type){
1689 e = Const.ChangeType (vi.Location, ce, variable_type);
1694 constants.Remove (name);
1695 constants.Add (name, e);
1698 ec.ConstantCheckState = old_check_state;
1701 // Now, handle the children
1703 if (children != null){
1704 foreach (Block b in children)
1705 b.EmitMeta (ec, ip);
1709 void UsageWarning (FlowBranching.UsageVector vector)
1713 if (variables != null){
1714 foreach (DictionaryEntry de in variables){
1715 LocalInfo vi = (LocalInfo) de.Value;
1720 name = (string) de.Key;
1722 if (vector.IsAssigned (vi.VariableInfo)){
1724 219, vi.Location, "The variable `" + name +
1725 "' is assigned but its value is never used");
1728 168, vi.Location, "The variable `" +
1730 "' is declared but never used");
1736 public override bool Resolve (EmitContext ec)
1738 Block prev_block = ec.CurrentBlock;
1741 int errors = Report.Errors;
1743 ec.CurrentBlock = this;
1744 ec.StartFlowBranching (this);
1746 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1748 bool unreachable = false, warning_shown = false;
1750 int statement_count = statements.Count;
1751 for (int ix = 0; ix < statement_count; ix++){
1752 Statement s = (Statement) statements [ix];
1754 if (unreachable && !(s is LabeledStatement)) {
1755 if (s == EmptyStatement.Value)
1756 s.loc = EndLocation;
1758 if (!s.ResolveUnreachable (ec, !warning_shown))
1761 if (s != EmptyStatement.Value)
1762 warning_shown = true;
1764 s.loc = Location.Null;
1766 statements [ix] = EmptyStatement.Value;
1770 if (s.Resolve (ec) == false) {
1772 statements [ix] = EmptyStatement.Value;
1776 num_statements = ix + 1;
1778 if (s is LabeledStatement)
1779 unreachable = false;
1781 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1784 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation,
1785 ec.CurrentBranching, statement_count, num_statements);
1788 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1790 ec.CurrentBlock = prev_block;
1792 // If we're a non-static `struct' constructor which doesn't have an
1793 // initializer, then we must initialize all of the struct's fields.
1794 if ((this_variable != null) &&
1795 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1796 !this_variable.IsThisAssigned (ec, loc))
1799 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1800 foreach (LabeledStatement label in labels.Values)
1801 if (!label.HasBeenReferenced)
1802 Report.Warning (164, label.Location,
1803 "This label has not been referenced");
1806 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1808 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1809 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1810 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1811 flags |= Flags.HasRet;
1813 if (ok && (errors == Report.Errors)) {
1814 if (RootContext.WarningLevel >= 3)
1815 UsageWarning (vector);
1821 protected override void DoEmit (EmitContext ec)
1823 for (int ix = 0; ix < num_statements; ix++){
1824 Statement s = (Statement) statements [ix];
1826 // Check whether we are the last statement in a
1829 if ((Parent == null) && (ix+1 == num_statements))
1830 ec.IsLastStatement = true;
1832 ec.IsLastStatement = false;
1838 public override void Emit (EmitContext ec)
1840 Block prev_block = ec.CurrentBlock;
1842 ec.CurrentBlock = this;
1844 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1845 bool is_lexical_block = !Implicit && (Parent != null);
1847 if (emit_debug_info) {
1848 if (is_lexical_block)
1849 ec.ig.BeginScope ();
1851 if (variables != null) {
1852 foreach (DictionaryEntry de in variables) {
1853 string name = (string) de.Key;
1854 LocalInfo vi = (LocalInfo) de.Value;
1856 if (vi.LocalBuilder == null)
1859 vi.LocalBuilder.SetLocalSymInfo (name);
1864 ec.Mark (StartLocation, true);
1866 ec.Mark (EndLocation, true);
1868 if (emit_debug_info && is_lexical_block)
1871 ec.CurrentBlock = prev_block;
1877 public class ToplevelBlock : Block {
1878 public ToplevelBlock (Parameters parameters, Location start) :
1879 base (null, parameters, start, Location.Null)
1883 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1884 base (null, flags, parameters, start, Location.Null)
1889 public class SwitchLabel {
1892 public Location loc;
1893 public Label ILLabel;
1894 public Label ILLabelCode;
1897 // if expr == null, then it is the default case.
1899 public SwitchLabel (Expression expr, Location l)
1905 public Expression Label {
1911 public object Converted {
1918 // Resolves the expression, reduces it to a literal if possible
1919 // and then converts it to the requested type.
1921 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1923 ILLabel = ec.ig.DefineLabel ();
1924 ILLabelCode = ec.ig.DefineLabel ();
1929 Expression e = label.Resolve (ec);
1934 if (!(e is Constant)){
1935 Report.Error (150, loc, "A constant value is expected, got: " + e);
1939 if (e is StringConstant || e is NullLiteral){
1940 if (required_type == TypeManager.string_type){
1942 ILLabel = ec.ig.DefineLabel ();
1947 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1948 if (converted == null)
1955 public class SwitchSection {
1956 // An array of SwitchLabels.
1957 public readonly ArrayList Labels;
1958 public readonly Block Block;
1960 public SwitchSection (ArrayList labels, Block block)
1967 public class Switch : Statement {
1968 public readonly ArrayList Sections;
1969 public Expression Expr;
1972 /// Maps constants whose type type SwitchType to their SwitchLabels.
1974 public Hashtable Elements;
1977 /// The governing switch type
1979 public Type SwitchType;
1985 Label default_target;
1986 Expression new_expr;
1989 // The types allowed to be implicitly cast from
1990 // on the governing type
1992 static Type [] allowed_types;
1994 public Switch (Expression e, ArrayList sects, Location l)
2001 public bool GotDefault {
2007 public Label DefaultTarget {
2009 return default_target;
2014 // Determines the governing type for a switch. The returned
2015 // expression might be the expression from the switch, or an
2016 // expression that includes any potential conversions to the
2017 // integral types or to string.
2019 Expression SwitchGoverningType (EmitContext ec, Type t)
2021 if (t == TypeManager.int32_type ||
2022 t == TypeManager.uint32_type ||
2023 t == TypeManager.char_type ||
2024 t == TypeManager.byte_type ||
2025 t == TypeManager.sbyte_type ||
2026 t == TypeManager.ushort_type ||
2027 t == TypeManager.short_type ||
2028 t == TypeManager.uint64_type ||
2029 t == TypeManager.int64_type ||
2030 t == TypeManager.string_type ||
2031 t == TypeManager.bool_type ||
2032 t.IsSubclassOf (TypeManager.enum_type))
2035 if (allowed_types == null){
2036 allowed_types = new Type [] {
2037 TypeManager.sbyte_type,
2038 TypeManager.byte_type,
2039 TypeManager.short_type,
2040 TypeManager.ushort_type,
2041 TypeManager.int32_type,
2042 TypeManager.uint32_type,
2043 TypeManager.int64_type,
2044 TypeManager.uint64_type,
2045 TypeManager.char_type,
2046 TypeManager.bool_type,
2047 TypeManager.string_type
2052 // Try to find a *user* defined implicit conversion.
2054 // If there is no implicit conversion, or if there are multiple
2055 // conversions, we have to report an error
2057 Expression converted = null;
2058 foreach (Type tt in allowed_types){
2061 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
2065 if (converted != null){
2066 Report.Error (-12, loc, "More than one conversion to an integral " +
2067 " type exists for type `" +
2068 TypeManager.CSharpName (Expr.Type)+"'");
2076 void error152 (string n)
2079 152, "The label `" + n + ":' " +
2080 "is already present on this switch statement");
2084 // Performs the basic sanity checks on the switch statement
2085 // (looks for duplicate keys and non-constant expressions).
2087 // It also returns a hashtable with the keys that we will later
2088 // use to compute the switch tables
2090 bool CheckSwitch (EmitContext ec)
2094 Elements = new Hashtable ();
2096 got_default = false;
2098 if (TypeManager.IsEnumType (SwitchType)){
2099 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2101 compare_type = SwitchType;
2103 foreach (SwitchSection ss in Sections){
2104 foreach (SwitchLabel sl in ss.Labels){
2105 if (!sl.ResolveAndReduce (ec, SwitchType)){
2110 if (sl.Label == null){
2112 error152 ("default");
2119 object key = sl.Converted;
2121 if (key is Constant)
2122 key = ((Constant) key).GetValue ();
2125 key = NullLiteral.Null;
2127 string lname = null;
2128 if (compare_type == TypeManager.uint64_type){
2129 ulong v = (ulong) key;
2131 if (Elements.Contains (v))
2132 lname = v.ToString ();
2134 Elements.Add (v, sl);
2135 } else if (compare_type == TypeManager.int64_type){
2136 long v = (long) key;
2138 if (Elements.Contains (v))
2139 lname = v.ToString ();
2141 Elements.Add (v, sl);
2142 } else if (compare_type == TypeManager.uint32_type){
2143 uint v = (uint) key;
2145 if (Elements.Contains (v))
2146 lname = v.ToString ();
2148 Elements.Add (v, sl);
2149 } else if (compare_type == TypeManager.char_type){
2150 char v = (char) key;
2152 if (Elements.Contains (v))
2153 lname = v.ToString ();
2155 Elements.Add (v, sl);
2156 } else if (compare_type == TypeManager.byte_type){
2157 byte v = (byte) key;
2159 if (Elements.Contains (v))
2160 lname = v.ToString ();
2162 Elements.Add (v, sl);
2163 } else if (compare_type == TypeManager.sbyte_type){
2164 sbyte v = (sbyte) key;
2166 if (Elements.Contains (v))
2167 lname = v.ToString ();
2169 Elements.Add (v, sl);
2170 } else if (compare_type == TypeManager.short_type){
2171 short v = (short) key;
2173 if (Elements.Contains (v))
2174 lname = v.ToString ();
2176 Elements.Add (v, sl);
2177 } else if (compare_type == TypeManager.ushort_type){
2178 ushort v = (ushort) key;
2180 if (Elements.Contains (v))
2181 lname = v.ToString ();
2183 Elements.Add (v, sl);
2184 } else if (compare_type == TypeManager.string_type){
2185 if (key is NullLiteral){
2186 if (Elements.Contains (NullLiteral.Null))
2189 Elements.Add (NullLiteral.Null, null);
2191 string s = (string) key;
2193 if (Elements.Contains (s))
2196 Elements.Add (s, sl);
2198 } else if (compare_type == TypeManager.int32_type) {
2201 if (Elements.Contains (v))
2202 lname = v.ToString ();
2204 Elements.Add (v, sl);
2205 } else if (compare_type == TypeManager.bool_type) {
2206 bool v = (bool) key;
2208 if (Elements.Contains (v))
2209 lname = v.ToString ();
2211 Elements.Add (v, sl);
2215 throw new Exception ("Unknown switch type!" +
2216 SwitchType + " " + compare_type);
2220 error152 ("case + " + lname);
2231 void EmitObjectInteger (ILGenerator ig, object k)
2234 IntConstant.EmitInt (ig, (int) k);
2235 else if (k is Constant) {
2236 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2239 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2242 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2244 IntConstant.EmitInt (ig, (int) (long) k);
2245 ig.Emit (OpCodes.Conv_I8);
2248 LongConstant.EmitLong (ig, (long) k);
2250 else if (k is ulong)
2252 if ((ulong) k < (1L<<32))
2254 IntConstant.EmitInt (ig, (int) (long) k);
2255 ig.Emit (OpCodes.Conv_U8);
2259 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2263 IntConstant.EmitInt (ig, (int) ((char) k));
2264 else if (k is sbyte)
2265 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2267 IntConstant.EmitInt (ig, (int) ((byte) k));
2268 else if (k is short)
2269 IntConstant.EmitInt (ig, (int) ((short) k));
2270 else if (k is ushort)
2271 IntConstant.EmitInt (ig, (int) ((ushort) k));
2273 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2275 throw new Exception ("Unhandled case");
2278 // structure used to hold blocks of keys while calculating table switch
2279 class KeyBlock : IComparable
2281 public KeyBlock (long _nFirst)
2283 nFirst = nLast = _nFirst;
2287 public ArrayList rgKeys = null;
2288 // how many items are in the bucket
2289 public int Size = 1;
2292 get { return (int) (nLast - nFirst + 1); }
2294 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2296 return kbLast.nLast - kbFirst.nFirst + 1;
2298 public int CompareTo (object obj)
2300 KeyBlock kb = (KeyBlock) obj;
2301 int nLength = Length;
2302 int nLengthOther = kb.Length;
2303 if (nLengthOther == nLength)
2304 return (int) (kb.nFirst - nFirst);
2305 return nLength - nLengthOther;
2310 /// This method emits code for a lookup-based switch statement (non-string)
2311 /// Basically it groups the cases into blocks that are at least half full,
2312 /// and then spits out individual lookup opcodes for each block.
2313 /// It emits the longest blocks first, and short blocks are just
2314 /// handled with direct compares.
2316 /// <param name="ec"></param>
2317 /// <param name="val"></param>
2318 /// <returns></returns>
2319 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2321 int cElements = Elements.Count;
2322 object [] rgKeys = new object [cElements];
2323 Elements.Keys.CopyTo (rgKeys, 0);
2324 Array.Sort (rgKeys);
2326 // initialize the block list with one element per key
2327 ArrayList rgKeyBlocks = new ArrayList ();
2328 foreach (object key in rgKeys)
2329 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2332 // iteratively merge the blocks while they are at least half full
2333 // there's probably a really cool way to do this with a tree...
2334 while (rgKeyBlocks.Count > 1)
2336 ArrayList rgKeyBlocksNew = new ArrayList ();
2337 kbCurr = (KeyBlock) rgKeyBlocks [0];
2338 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2340 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2341 if ((kbCurr.Size + kb.Size) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2344 kbCurr.nLast = kb.nLast;
2345 kbCurr.Size += kb.Size;
2349 // start a new block
2350 rgKeyBlocksNew.Add (kbCurr);
2354 rgKeyBlocksNew.Add (kbCurr);
2355 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2357 rgKeyBlocks = rgKeyBlocksNew;
2360 // initialize the key lists
2361 foreach (KeyBlock kb in rgKeyBlocks)
2362 kb.rgKeys = new ArrayList ();
2364 // fill the key lists
2366 if (rgKeyBlocks.Count > 0) {
2367 kbCurr = (KeyBlock) rgKeyBlocks [0];
2368 foreach (object key in rgKeys)
2370 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2371 System.Convert.ToInt64 (key) > kbCurr.nLast;
2373 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2374 kbCurr.rgKeys.Add (key);
2378 // sort the blocks so we can tackle the largest ones first
2379 rgKeyBlocks.Sort ();
2381 // okay now we can start...
2382 ILGenerator ig = ec.ig;
2383 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2384 Label lblDefault = ig.DefineLabel ();
2386 Type typeKeys = null;
2387 if (rgKeys.Length > 0)
2388 typeKeys = rgKeys [0].GetType (); // used for conversions
2392 if (TypeManager.IsEnumType (SwitchType))
2393 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2395 compare_type = SwitchType;
2397 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2399 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2400 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2403 foreach (object key in kb.rgKeys)
2405 ig.Emit (OpCodes.Ldloc, val);
2406 EmitObjectInteger (ig, key);
2407 SwitchLabel sl = (SwitchLabel) Elements [key];
2408 ig.Emit (OpCodes.Beq, sl.ILLabel);
2413 // TODO: if all the keys in the block are the same and there are
2414 // no gaps/defaults then just use a range-check.
2415 if (compare_type == TypeManager.int64_type ||
2416 compare_type == TypeManager.uint64_type)
2418 // TODO: optimize constant/I4 cases
2420 // check block range (could be > 2^31)
2421 ig.Emit (OpCodes.Ldloc, val);
2422 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2423 ig.Emit (OpCodes.Blt, lblDefault);
2424 ig.Emit (OpCodes.Ldloc, val);
2425 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2426 ig.Emit (OpCodes.Bgt, lblDefault);
2429 ig.Emit (OpCodes.Ldloc, val);
2432 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2433 ig.Emit (OpCodes.Sub);
2435 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2440 ig.Emit (OpCodes.Ldloc, val);
2441 int nFirst = (int) kb.nFirst;
2444 IntConstant.EmitInt (ig, nFirst);
2445 ig.Emit (OpCodes.Sub);
2447 else if (nFirst < 0)
2449 IntConstant.EmitInt (ig, -nFirst);
2450 ig.Emit (OpCodes.Add);
2454 // first, build the list of labels for the switch
2456 int cJumps = kb.Length;
2457 Label [] rgLabels = new Label [cJumps];
2458 for (int iJump = 0; iJump < cJumps; iJump++)
2460 object key = kb.rgKeys [iKey];
2461 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2463 SwitchLabel sl = (SwitchLabel) Elements [key];
2464 rgLabels [iJump] = sl.ILLabel;
2468 rgLabels [iJump] = lblDefault;
2470 // emit the switch opcode
2471 ig.Emit (OpCodes.Switch, rgLabels);
2474 // mark the default for this block
2476 ig.MarkLabel (lblDefault);
2479 // TODO: find the default case and emit it here,
2480 // to prevent having to do the following jump.
2481 // make sure to mark other labels in the default section
2483 // the last default just goes to the end
2484 ig.Emit (OpCodes.Br, lblDefault);
2486 // now emit the code for the sections
2487 bool fFoundDefault = false;
2488 foreach (SwitchSection ss in Sections)
2490 foreach (SwitchLabel sl in ss.Labels)
2492 ig.MarkLabel (sl.ILLabel);
2493 ig.MarkLabel (sl.ILLabelCode);
2494 if (sl.Label == null)
2496 ig.MarkLabel (lblDefault);
2497 fFoundDefault = true;
2501 //ig.Emit (OpCodes.Br, lblEnd);
2504 if (!fFoundDefault) {
2505 ig.MarkLabel (lblDefault);
2507 ig.MarkLabel (lblEnd);
2510 // This simple emit switch works, but does not take advantage of the
2512 // TODO: remove non-string logic from here
2513 // TODO: binary search strings?
2515 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2517 ILGenerator ig = ec.ig;
2518 Label end_of_switch = ig.DefineLabel ();
2519 Label next_test = ig.DefineLabel ();
2520 Label null_target = ig.DefineLabel ();
2521 bool default_found = false;
2522 bool first_test = true;
2523 bool pending_goto_end = false;
2525 bool default_at_end = false;
2527 ig.Emit (OpCodes.Ldloc, val);
2529 if (Elements.Contains (NullLiteral.Null)){
2530 ig.Emit (OpCodes.Brfalse, null_target);
2532 ig.Emit (OpCodes.Brfalse, default_target);
2534 ig.Emit (OpCodes.Ldloc, val);
2535 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2536 ig.Emit (OpCodes.Stloc, val);
2538 int section_count = Sections.Count;
2539 for (int section = 0; section < section_count; section++){
2540 SwitchSection ss = (SwitchSection) Sections [section];
2541 Label sec_begin = ig.DefineLabel ();
2543 if (pending_goto_end)
2544 ig.Emit (OpCodes.Br, end_of_switch);
2546 int label_count = ss.Labels.Count;
2547 bool mark_default = false;
2549 for (int label = 0; label < label_count; label++){
2550 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2551 ig.MarkLabel (sl.ILLabel);
2554 ig.MarkLabel (next_test);
2555 next_test = ig.DefineLabel ();
2558 // If we are the default target
2560 if (sl.Label == null){
2561 if (label+1 == label_count)
2562 default_at_end = true;
2563 mark_default = true;
2564 default_found = true;
2566 object lit = sl.Converted;
2568 if (lit is NullLiteral){
2570 if (label_count == 1)
2571 ig.Emit (OpCodes.Br, next_test);
2575 StringConstant str = (StringConstant) lit;
2577 ig.Emit (OpCodes.Ldloc, val);
2578 ig.Emit (OpCodes.Ldstr, str.Value);
2579 if (label_count == 1)
2580 ig.Emit (OpCodes.Bne_Un, next_test);
2582 if (label+1 == label_count)
2583 ig.Emit (OpCodes.Bne_Un, next_test);
2585 ig.Emit (OpCodes.Beq, sec_begin);
2590 ig.MarkLabel (null_target);
2591 ig.MarkLabel (sec_begin);
2592 foreach (SwitchLabel sl in ss.Labels)
2593 ig.MarkLabel (sl.ILLabelCode);
2596 ig.MarkLabel (default_target);
2598 pending_goto_end = !ss.Block.HasRet;
2601 ig.MarkLabel (next_test);
2603 if (!default_at_end)
2604 ig.Emit (OpCodes.Br, default_target);
2606 ig.MarkLabel (default_target);
2607 ig.MarkLabel (end_of_switch);
2610 public override bool Resolve (EmitContext ec)
2612 Expr = Expr.Resolve (ec);
2616 new_expr = SwitchGoverningType (ec, Expr.Type);
2617 if (new_expr == null){
2618 Report.Error (151, loc, "An integer type or string was expected for switch");
2623 SwitchType = new_expr.Type;
2625 if (!CheckSwitch (ec))
2628 Switch old_switch = ec.Switch;
2630 ec.Switch.SwitchType = SwitchType;
2632 Report.Debug (1, "START OF SWITCH BLOCK", loc, ec.CurrentBranching);
2633 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2636 foreach (SwitchSection ss in Sections){
2638 ec.CurrentBranching.CreateSibling (
2639 null, FlowBranching.SiblingType.SwitchSection);
2643 if (ss.Block.Resolve (ec) != true)
2649 ec.CurrentBranching.CreateSibling (
2650 null, FlowBranching.SiblingType.SwitchSection);
2652 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2653 ec.Switch = old_switch;
2655 Report.Debug (1, "END OF SWITCH BLOCK", loc, ec.CurrentBranching,
2661 protected override void DoEmit (EmitContext ec)
2663 // Store variable for comparission purposes
2664 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2666 ec.ig.Emit (OpCodes.Stloc, value);
2668 ILGenerator ig = ec.ig;
2670 default_target = ig.DefineLabel ();
2673 // Setup the codegen context
2675 Label old_end = ec.LoopEnd;
2676 Switch old_switch = ec.Switch;
2678 ec.LoopEnd = ig.DefineLabel ();
2682 if (SwitchType == TypeManager.string_type)
2683 SimpleSwitchEmit (ec, value);
2685 TableSwitchEmit (ec, value);
2687 // Restore context state.
2688 ig.MarkLabel (ec.LoopEnd);
2691 // Restore the previous context
2693 ec.LoopEnd = old_end;
2694 ec.Switch = old_switch;
2698 public class Lock : Statement {
2700 Statement Statement;
2702 public Lock (Expression expr, Statement stmt, Location l)
2709 public override bool Resolve (EmitContext ec)
2711 expr = expr.Resolve (ec);
2715 if (expr.Type.IsValueType){
2716 Error (185, "lock statement requires the expression to be " +
2717 " a reference type (type is: `{0}'",
2718 TypeManager.CSharpName (expr.Type));
2722 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
2723 bool ok = Statement.Resolve (ec);
2724 ec.EndFlowBranching ();
2729 protected override void DoEmit (EmitContext ec)
2731 Type type = expr.Type;
2733 ILGenerator ig = ec.ig;
2734 LocalBuilder temp = ig.DeclareLocal (type);
2737 ig.Emit (OpCodes.Dup);
2738 ig.Emit (OpCodes.Stloc, temp);
2739 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2742 ig.BeginExceptionBlock ();
2743 Label finish = ig.DefineLabel ();
2744 Statement.Emit (ec);
2745 // ig.Emit (OpCodes.Leave, finish);
2747 ig.MarkLabel (finish);
2750 ig.BeginFinallyBlock ();
2751 ig.Emit (OpCodes.Ldloc, temp);
2752 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2753 ig.EndExceptionBlock ();
2757 public class Unchecked : Statement {
2758 public readonly Block Block;
2760 public Unchecked (Block b)
2766 public override bool Resolve (EmitContext ec)
2768 bool previous_state = ec.CheckState;
2769 bool previous_state_const = ec.ConstantCheckState;
2771 ec.CheckState = false;
2772 ec.ConstantCheckState = false;
2773 bool ret = Block.Resolve (ec);
2774 ec.CheckState = previous_state;
2775 ec.ConstantCheckState = previous_state_const;
2780 protected override void DoEmit (EmitContext ec)
2782 bool previous_state = ec.CheckState;
2783 bool previous_state_const = ec.ConstantCheckState;
2785 ec.CheckState = false;
2786 ec.ConstantCheckState = false;
2788 ec.CheckState = previous_state;
2789 ec.ConstantCheckState = previous_state_const;
2793 public class Checked : Statement {
2794 public readonly Block Block;
2796 public Checked (Block b)
2799 b.Unchecked = false;
2802 public override bool Resolve (EmitContext ec)
2804 bool previous_state = ec.CheckState;
2805 bool previous_state_const = ec.ConstantCheckState;
2807 ec.CheckState = true;
2808 ec.ConstantCheckState = true;
2809 bool ret = Block.Resolve (ec);
2810 ec.CheckState = previous_state;
2811 ec.ConstantCheckState = previous_state_const;
2816 protected override void DoEmit (EmitContext ec)
2818 bool previous_state = ec.CheckState;
2819 bool previous_state_const = ec.ConstantCheckState;
2821 ec.CheckState = true;
2822 ec.ConstantCheckState = true;
2824 ec.CheckState = previous_state;
2825 ec.ConstantCheckState = previous_state_const;
2829 public class Unsafe : Statement {
2830 public readonly Block Block;
2832 public Unsafe (Block b)
2837 public override bool Resolve (EmitContext ec)
2839 bool previous_state = ec.InUnsafe;
2843 val = Block.Resolve (ec);
2844 ec.InUnsafe = previous_state;
2849 protected override void DoEmit (EmitContext ec)
2851 bool previous_state = ec.InUnsafe;
2855 ec.InUnsafe = previous_state;
2862 public class Fixed : Statement {
2864 ArrayList declarators;
2865 Statement statement;
2871 public bool is_object;
2872 public LocalInfo vi;
2873 public Expression expr;
2874 public Expression converted;
2877 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2880 declarators = decls;
2885 public override bool Resolve (EmitContext ec)
2888 Expression.UnsafeError (loc);
2892 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2893 if (expr_type == null)
2896 CheckObsolete (expr_type);
2898 if (ec.RemapToProxy){
2899 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2903 data = new FixedData [declarators.Count];
2905 if (!expr_type.IsPointer){
2906 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2911 foreach (Pair p in declarators){
2912 LocalInfo vi = (LocalInfo) p.First;
2913 Expression e = (Expression) p.Second;
2915 vi.VariableInfo = null;
2919 // The rules for the possible declarators are pretty wise,
2920 // but the production on the grammar is more concise.
2922 // So we have to enforce these rules here.
2924 // We do not resolve before doing the case 1 test,
2925 // because the grammar is explicit in that the token &
2926 // is present, so we need to test for this particular case.
2930 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2935 // Case 1: & object.
2937 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2938 Expression child = ((Unary) e).Expr;
2941 if (child is ParameterReference || child is LocalVariableReference){
2944 "No need to use fixed statement for parameters or " +
2945 "local variable declarations (address is already " +
2950 ec.InFixedInitializer = true;
2952 ec.InFixedInitializer = false;
2956 child = ((Unary) e).Expr;
2958 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2961 data [i].is_object = true;
2963 data [i].converted = null;
2970 ec.InFixedInitializer = true;
2972 ec.InFixedInitializer = false;
2979 if (e.Type.IsArray){
2980 Type array_type = TypeManager.GetElementType (e.Type);
2984 // Provided that array_type is unmanaged,
2986 if (!TypeManager.VerifyUnManaged (array_type, loc))
2990 // and T* is implicitly convertible to the
2991 // pointer type given in the fixed statement.
2993 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2995 Expression converted = Convert.ImplicitConversionRequired (
2996 ec, array_ptr, vi.VariableType, loc);
2997 if (converted == null)
3000 data [i].is_object = false;
3002 data [i].converted = converted;
3012 if (e.Type == TypeManager.string_type){
3013 data [i].is_object = false;
3015 data [i].converted = null;
3022 // For other cases, flag a `this is already fixed expression'
3024 if (e is LocalVariableReference || e is ParameterReference ||
3025 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
3027 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
3031 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
3035 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
3037 if (!statement.Resolve (ec)) {
3038 ec.KillFlowBranching ();
3042 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3043 has_ret = reachability.IsUnreachable;
3048 protected override void DoEmit (EmitContext ec)
3050 ILGenerator ig = ec.ig;
3052 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
3054 for (int i = 0; i < data.Length; i++) {
3055 LocalInfo vi = data [i].vi;
3058 // Case 1: & object.
3060 if (data [i].is_object) {
3062 // Store pointer in pinned location
3064 data [i].expr.Emit (ec);
3065 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3066 clear_list [i] = vi.LocalBuilder;
3073 if (data [i].expr.Type.IsArray){
3075 // Store pointer in pinned location
3077 data [i].converted.Emit (ec);
3079 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3080 clear_list [i] = vi.LocalBuilder;
3087 if (data [i].expr.Type == TypeManager.string_type){
3088 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3089 TypeManager.MakePinned (pinned_string);
3090 clear_list [i] = pinned_string;
3092 data [i].expr.Emit (ec);
3093 ig.Emit (OpCodes.Stloc, pinned_string);
3095 Expression sptr = new StringPtr (pinned_string, loc);
3096 Expression converted = Convert.ImplicitConversionRequired (
3097 ec, sptr, vi.VariableType, loc);
3099 if (converted == null)
3102 converted.Emit (ec);
3103 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3107 statement.Emit (ec);
3113 // Clear the pinned variable
3115 for (int i = 0; i < data.Length; i++) {
3116 if (data [i].is_object || data [i].expr.Type.IsArray) {
3117 ig.Emit (OpCodes.Ldc_I4_0);
3118 ig.Emit (OpCodes.Conv_U);
3119 ig.Emit (OpCodes.Stloc, clear_list [i]);
3120 } else if (data [i].expr.Type == TypeManager.string_type){
3121 ig.Emit (OpCodes.Ldnull);
3122 ig.Emit (OpCodes.Stloc, clear_list [i]);
3128 public class Catch: Statement {
3129 public readonly string Name;
3130 public readonly Block Block;
3132 Expression type_expr;
3135 public Catch (Expression type, string name, Block block, Location l)
3143 public Type CatchType {
3149 public bool IsGeneral {
3151 return type_expr == null;
3155 protected override void DoEmit(EmitContext ec)
3159 public override bool Resolve (EmitContext ec)
3161 if (type_expr != null) {
3162 type = ec.DeclSpace.ResolveType (type_expr, false, loc);
3166 CheckObsolete (type);
3168 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3169 Error (155, "The type caught or thrown must be derived from System.Exception");
3175 return Block.Resolve (ec);
3179 public class Try : Statement {
3180 public readonly Block Fini, Block;
3181 public readonly ArrayList Specific;
3182 public readonly Catch General;
3185 // specific, general and fini might all be null.
3187 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3189 if (specific == null && general == null){
3190 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3194 this.Specific = specific;
3195 this.General = general;
3200 public override bool Resolve (EmitContext ec)
3204 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3206 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3208 if (!Block.Resolve (ec))
3211 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3213 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3215 Type[] prevCatches = new Type [Specific.Count];
3217 foreach (Catch c in Specific){
3218 ec.CurrentBranching.CreateSibling (
3219 c.Block, FlowBranching.SiblingType.Catch);
3221 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3223 if (c.Name != null) {
3224 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3226 throw new Exception ();
3228 vi.VariableInfo = null;
3231 if (!c.Resolve (ec))
3234 Type resolvedType = c.CatchType;
3235 for (int ii = 0; ii < last_index; ++ii) {
3236 if (resolvedType.IsSubclassOf (prevCatches [ii])) {
3237 Report.Error_T (160, c.loc, prevCatches [ii].FullName);
3242 prevCatches [last_index++] = resolvedType;
3245 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3247 if (General != null){
3248 ec.CurrentBranching.CreateSibling (
3249 General.Block, FlowBranching.SiblingType.Catch);
3251 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3253 if (!General.Resolve (ec))
3257 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3261 ec.CurrentBranching.CreateSibling (
3262 Fini, FlowBranching.SiblingType.Finally);
3264 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3266 if (!Fini.Resolve (ec))
3270 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3272 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3274 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3276 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3277 // Unfortunately, System.Reflection.Emit automatically emits a leave
3278 // to the end of the finally block. This is a problem if `returns'
3279 // is true since we may jump to a point after the end of the method.
3280 // As a workaround, emit an explicit ret here.
3281 ec.NeedReturnLabel ();
3287 protected override void DoEmit (EmitContext ec)
3289 ILGenerator ig = ec.ig;
3290 Label finish = ig.DefineLabel ();;
3292 ig.BeginExceptionBlock ();
3296 // System.Reflection.Emit provides this automatically:
3297 // ig.Emit (OpCodes.Leave, finish);
3299 foreach (Catch c in Specific){
3302 ig.BeginCatchBlock (c.CatchType);
3304 if (c.Name != null){
3305 vi = c.Block.GetLocalInfo (c.Name);
3307 throw new Exception ("Variable does not exist in this block");
3309 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3311 ig.Emit (OpCodes.Pop);
3316 if (General != null){
3317 ig.BeginCatchBlock (TypeManager.object_type);
3318 ig.Emit (OpCodes.Pop);
3319 General.Block.Emit (ec);
3322 ig.MarkLabel (finish);
3324 ig.BeginFinallyBlock ();
3328 ig.EndExceptionBlock ();
3332 public class Using : Statement {
3333 object expression_or_block;
3334 Statement Statement;
3339 Expression [] converted_vars;
3340 ExpressionStatement [] assign;
3342 public Using (object expression_or_block, Statement stmt, Location l)
3344 this.expression_or_block = expression_or_block;
3350 // Resolves for the case of using using a local variable declaration.
3352 bool ResolveLocalVariableDecls (EmitContext ec)
3354 bool need_conv = false;
3355 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3358 if (expr_type == null)
3362 // The type must be an IDisposable or an implicit conversion
3365 converted_vars = new Expression [var_list.Count];
3366 assign = new ExpressionStatement [var_list.Count];
3367 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3368 foreach (DictionaryEntry e in var_list){
3369 Expression var = (Expression) e.Key;
3371 var = var.ResolveLValue (ec, new EmptyExpression ());
3375 converted_vars [i] = Convert.ImplicitConversionRequired (
3376 ec, var, TypeManager.idisposable_type, loc);
3378 if (converted_vars [i] == null)
3386 foreach (DictionaryEntry e in var_list){
3387 LocalVariableReference var = (LocalVariableReference) e.Key;
3388 Expression new_expr = (Expression) e.Value;
3391 a = new Assign (var, new_expr, loc);
3397 converted_vars [i] = var;
3398 assign [i] = (ExpressionStatement) a;
3405 bool ResolveExpression (EmitContext ec)
3407 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3408 conv = Convert.ImplicitConversionRequired (
3409 ec, expr, TypeManager.idisposable_type, loc);
3419 // Emits the code for the case of using using a local variable declaration.
3421 bool EmitLocalVariableDecls (EmitContext ec)
3423 ILGenerator ig = ec.ig;
3426 for (i = 0; i < assign.Length; i++) {
3427 assign [i].EmitStatement (ec);
3429 ig.BeginExceptionBlock ();
3431 Statement.Emit (ec);
3433 var_list.Reverse ();
3434 foreach (DictionaryEntry e in var_list){
3435 LocalVariableReference var = (LocalVariableReference) e.Key;
3436 Label skip = ig.DefineLabel ();
3439 ig.BeginFinallyBlock ();
3441 if (!var.Type.IsValueType) {
3443 ig.Emit (OpCodes.Brfalse, skip);
3444 converted_vars [i].Emit (ec);
3445 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3447 Expression ml = Expression.MemberLookup(ec, TypeManager.idisposable_type, var.Type, "Dispose", Mono.CSharp.Location.Null);
3449 if (!(ml is MethodGroupExpr)) {
3451 ig.Emit (OpCodes.Box, var.Type);
3452 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3454 MethodInfo mi = null;
3456 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3457 if (mk.GetParameters().Length == 0) {
3464 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3468 var.AddressOf (ec, AddressOp.Load);
3469 ig.Emit (OpCodes.Call, mi);
3473 ig.MarkLabel (skip);
3474 ig.EndExceptionBlock ();
3480 bool EmitExpression (EmitContext ec)
3483 // Make a copy of the expression and operate on that.
3485 ILGenerator ig = ec.ig;
3486 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3491 ig.Emit (OpCodes.Stloc, local_copy);
3493 ig.BeginExceptionBlock ();
3494 Statement.Emit (ec);
3496 Label skip = ig.DefineLabel ();
3497 ig.BeginFinallyBlock ();
3498 ig.Emit (OpCodes.Ldloc, local_copy);
3499 ig.Emit (OpCodes.Brfalse, skip);
3500 ig.Emit (OpCodes.Ldloc, local_copy);
3501 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3502 ig.MarkLabel (skip);
3503 ig.EndExceptionBlock ();
3508 public override bool Resolve (EmitContext ec)
3510 if (expression_or_block is DictionaryEntry){
3511 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3512 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3514 if (!ResolveLocalVariableDecls (ec))
3517 } else if (expression_or_block is Expression){
3518 expr = (Expression) expression_or_block;
3520 expr = expr.Resolve (ec);
3524 expr_type = expr.Type;
3526 if (!ResolveExpression (ec))
3530 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3532 bool ok = Statement.Resolve (ec);
3535 ec.KillFlowBranching ();
3539 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3541 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3542 // Unfortunately, System.Reflection.Emit automatically emits a leave
3543 // to the end of the finally block. This is a problem if `returns'
3544 // is true since we may jump to a point after the end of the method.
3545 // As a workaround, emit an explicit ret here.
3546 ec.NeedReturnLabel ();
3552 protected override void DoEmit (EmitContext ec)
3554 if (expression_or_block is DictionaryEntry)
3555 EmitLocalVariableDecls (ec);
3556 else if (expression_or_block is Expression)
3557 EmitExpression (ec);
3562 /// Implementation of the foreach C# statement
3564 public class Foreach : Statement {
3566 Expression variable;
3568 Statement statement;
3569 ForeachHelperMethods hm;
3570 Expression empty, conv;
3571 Type array_type, element_type;
3574 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3575 Statement stmt, Location l)
3578 this.variable = var;
3584 public override bool Resolve (EmitContext ec)
3586 expr = expr.Resolve (ec);
3590 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3591 if (var_type == null)
3595 // We need an instance variable. Not sure this is the best
3596 // way of doing this.
3598 // FIXME: When we implement propertyaccess, will those turn
3599 // out to return values in ExprClass? I think they should.
3601 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3602 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3603 error1579 (expr.Type);
3607 if (expr.Type.IsArray) {
3608 array_type = expr.Type;
3609 element_type = TypeManager.GetElementType (array_type);
3611 empty = new EmptyExpression (element_type);
3613 hm = ProbeCollectionType (ec, expr.Type);
3615 error1579 (expr.Type);
3619 array_type = expr.Type;
3620 element_type = hm.element_type;
3622 empty = new EmptyExpression (hm.element_type);
3627 ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
3628 ec.CurrentBranching.CreateSibling ();
3632 // FIXME: maybe we can apply the same trick we do in the
3633 // array handling to avoid creating empty and conv in some cases.
3635 // Although it is not as important in this case, as the type
3636 // will not likely be object (what the enumerator will return).
3638 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3642 variable = variable.ResolveLValue (ec, empty);
3643 if (variable == null)
3646 bool disposable = (hm != null) && hm.is_disposable;
3648 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, loc);
3650 if (!statement.Resolve (ec))
3654 ec.EndFlowBranching ();
3656 ec.EndFlowBranching ();
3662 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3664 static MethodInfo FetchMethodMoveNext (Type t)
3666 MemberList move_next_list;
3668 move_next_list = TypeContainer.FindMembers (
3669 t, MemberTypes.Method,
3670 BindingFlags.Public | BindingFlags.Instance,
3671 Type.FilterName, "MoveNext");
3672 if (move_next_list.Count == 0)
3675 foreach (MemberInfo m in move_next_list){
3676 MethodInfo mi = (MethodInfo) m;
3679 args = TypeManager.GetArgumentTypes (mi);
3680 if (args != null && args.Length == 0){
3681 if (mi.ReturnType == TypeManager.bool_type)
3689 // Retrieves a `public T get_Current ()' method from the Type `t'
3691 static MethodInfo FetchMethodGetCurrent (Type t)
3693 MemberList get_current_list;
3695 get_current_list = TypeContainer.FindMembers (
3696 t, MemberTypes.Method,
3697 BindingFlags.Public | BindingFlags.Instance,
3698 Type.FilterName, "get_Current");
3699 if (get_current_list.Count == 0)
3702 foreach (MemberInfo m in get_current_list){
3703 MethodInfo mi = (MethodInfo) m;
3706 args = TypeManager.GetArgumentTypes (mi);
3707 if (args != null && args.Length == 0)
3714 // This struct records the helper methods used by the Foreach construct
3716 class ForeachHelperMethods {
3717 public EmitContext ec;
3718 public MethodInfo get_enumerator;
3719 public MethodInfo move_next;
3720 public MethodInfo get_current;
3721 public Type element_type;
3722 public Type enumerator_type;
3723 public bool is_disposable;
3725 public ForeachHelperMethods (EmitContext ec)
3728 this.element_type = TypeManager.object_type;
3729 this.enumerator_type = TypeManager.ienumerator_type;
3730 this.is_disposable = true;
3734 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3739 if (!(m is MethodInfo))
3742 if (m.Name != "GetEnumerator")
3745 MethodInfo mi = (MethodInfo) m;
3746 Type [] args = TypeManager.GetArgumentTypes (mi);
3748 if (args.Length != 0)
3751 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3752 EmitContext ec = hm.ec;
3755 // Check whether GetEnumerator is accessible to us
3757 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3759 Type declaring = mi.DeclaringType;
3760 if (prot == MethodAttributes.Private){
3761 if (declaring != ec.ContainerType)
3763 } else if (prot == MethodAttributes.FamANDAssem){
3764 // If from a different assembly, false
3765 if (!(mi is MethodBuilder))
3768 // Are we being invoked from the same class, or from a derived method?
3770 if (ec.ContainerType != declaring){
3771 if (!ec.ContainerType.IsSubclassOf (declaring))
3774 } else if (prot == MethodAttributes.FamORAssem){
3775 if (!(mi is MethodBuilder ||
3776 ec.ContainerType == declaring ||
3777 ec.ContainerType.IsSubclassOf (declaring)))
3779 } if (prot == MethodAttributes.Family){
3780 if (!(ec.ContainerType == declaring ||
3781 ec.ContainerType.IsSubclassOf (declaring)))
3785 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3787 // Apply the same optimization as MS: skip the GetEnumerator
3788 // returning an IEnumerator, and use the one returning a
3789 // CharEnumerator instead. This allows us to avoid the
3790 // try-finally block and the boxing.
3795 // Ok, we can access it, now make sure that we can do something
3796 // with this `GetEnumerator'
3799 Type return_type = mi.ReturnType;
3800 if (mi.ReturnType == TypeManager.ienumerator_type ||
3801 TypeManager.ienumerator_type.IsAssignableFrom (return_type) ||
3802 (!RootContext.StdLib && TypeManager.ImplementsInterface (return_type, TypeManager.ienumerator_type))) {
3805 // If it is not an interface, lets try to find the methods ourselves.
3806 // For example, if we have:
3807 // public class Foo : IEnumerator { public bool MoveNext () {} public int Current { get {}}}
3808 // We can avoid the iface call. This is a runtime perf boost.
3809 // even bigger if we have a ValueType, because we avoid the cost
3812 // We have to make sure that both methods exist for us to take
3813 // this path. If one of the methods does not exist, we will just
3814 // use the interface. Sadly, this complex if statement is the only
3815 // way I could do this without a goto
3818 if (return_type.IsInterface ||
3819 (hm.move_next = FetchMethodMoveNext (return_type)) == null ||
3820 (hm.get_current = FetchMethodGetCurrent (return_type)) == null) {
3822 hm.move_next = TypeManager.bool_movenext_void;
3823 hm.get_current = TypeManager.object_getcurrent_void;
3830 // Ok, so they dont return an IEnumerable, we will have to
3831 // find if they support the GetEnumerator pattern.
3834 hm.move_next = FetchMethodMoveNext (return_type);
3835 if (hm.move_next == null)
3838 hm.get_current = FetchMethodGetCurrent (return_type);
3839 if (hm.get_current == null)
3843 hm.element_type = hm.get_current.ReturnType;
3844 hm.enumerator_type = return_type;
3845 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3846 TypeManager.ImplementsInterface (
3847 hm.enumerator_type, TypeManager.idisposable_type);
3853 /// This filter is used to find the GetEnumerator method
3854 /// on which IEnumerator operates
3856 static MemberFilter FilterEnumerator;
3860 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3863 void error1579 (Type t)
3865 Report.Error (1579, loc,
3866 "foreach statement cannot operate on variables of type `" +
3867 t.FullName + "' because that class does not provide a " +
3868 " GetEnumerator method or it is inaccessible");
3871 static bool TryType (Type t, ForeachHelperMethods hm)
3875 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3876 BindingFlags.Public | BindingFlags.NonPublic |
3877 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3878 FilterEnumerator, hm);
3883 hm.get_enumerator = (MethodInfo) mi [0];
3888 // Looks for a usable GetEnumerator in the Type, and if found returns
3889 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3891 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3893 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3895 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3896 if (TryType (tt, hm))
3902 // Now try to find the method in the interfaces
3905 Type [] ifaces = t.GetInterfaces ();
3907 foreach (Type i in ifaces){
3908 if (TryType (i, hm))
3913 // Since TypeBuilder.GetInterfaces only returns the interface
3914 // types for this type, we have to keep looping, but once
3915 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3916 // done, because it returns all the types
3918 if ((t is TypeBuilder))
3928 // FIXME: possible optimization.
3929 // We might be able to avoid creating `empty' if the type is the sam
3931 bool EmitCollectionForeach (EmitContext ec)
3933 ILGenerator ig = ec.ig;
3934 VariableStorage enumerator;
3936 enumerator = new VariableStorage (ec, hm.enumerator_type);
3937 enumerator.EmitThis ();
3939 // Instantiate the enumerator
3941 if (expr.Type.IsValueType){
3942 if (expr is IMemoryLocation){
3943 IMemoryLocation ml = (IMemoryLocation) expr;
3945 Expression ml1 = Expression.MemberLookup(ec, TypeManager.ienumerator_type, expr.Type, "GetEnumerator", Mono.CSharp.Location.Null);
3947 if (!(ml1 is MethodGroupExpr)) {
3949 ec.ig.Emit(OpCodes.Box, expr.Type);
3951 ml.AddressOf (ec, AddressOp.Load);
3954 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3955 " does not implement IMemoryLocation");
3956 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3959 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3961 enumerator.EmitStore ();
3964 // Protect the code in a try/finalize block, so that
3965 // if the beast implement IDisposable, we get rid of it
3967 if (hm.is_disposable)
3968 ig.BeginExceptionBlock ();
3970 Label end_try = ig.DefineLabel ();
3972 ig.MarkLabel (ec.LoopBegin);
3974 enumerator.EmitCall (hm.move_next);
3976 ig.Emit (OpCodes.Brfalse, end_try);
3980 enumerator.EmitCall (hm.get_current);
3984 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3986 ((IAssignMethod)variable).EmitAssign (ec, conv);
3988 statement.Emit (ec);
3989 ig.Emit (OpCodes.Br, ec.LoopBegin);
3990 ig.MarkLabel (end_try);
3992 // The runtime provides this for us.
3993 // ig.Emit (OpCodes.Leave, end);
3996 // Now the finally block
3998 if (hm.is_disposable) {
3999 Label call_dispose = ig.DefineLabel ();
4000 ig.BeginFinallyBlock ();
4002 enumerator.EmitThis ();
4003 enumerator.EmitLoad ();
4004 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
4005 ig.Emit (OpCodes.Dup);
4006 ig.Emit (OpCodes.Brtrue_S, call_dispose);
4007 ig.Emit (OpCodes.Pop);
4008 ig.Emit (OpCodes.Endfinally);
4010 ig.MarkLabel (call_dispose);
4011 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
4014 // The runtime generates this anyways.
4015 // ig.Emit (OpCodes.Endfinally);
4017 ig.EndExceptionBlock ();
4020 ig.MarkLabel (ec.LoopEnd);
4025 // FIXME: possible optimization.
4026 // We might be able to avoid creating `empty' if the type is the sam
4028 bool EmitArrayForeach (EmitContext ec)
4030 int rank = array_type.GetArrayRank ();
4031 ILGenerator ig = ec.ig;
4033 VariableStorage copy = new VariableStorage (ec, array_type);
4036 // Make our copy of the array
4043 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
4047 counter.EmitThis ();
4048 ig.Emit (OpCodes.Ldc_I4_0);
4049 counter.EmitStore ();
4050 test = ig.DefineLabel ();
4051 ig.Emit (OpCodes.Br, test);
4053 loop = ig.DefineLabel ();
4054 ig.MarkLabel (loop);
4061 counter.EmitThis ();
4062 counter.EmitLoad ();
4065 // Load the value, we load the value using the underlying type,
4066 // then we use the variable.EmitAssign to load using the proper cast.
4068 ArrayAccess.EmitLoadOpcode (ig, element_type);
4071 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4073 ((IAssignMethod)variable).EmitAssign (ec, conv);
4075 statement.Emit (ec);
4077 ig.MarkLabel (ec.LoopBegin);
4078 counter.EmitThis ();
4079 counter.EmitThis ();
4080 counter.EmitLoad ();
4081 ig.Emit (OpCodes.Ldc_I4_1);
4082 ig.Emit (OpCodes.Add);
4083 counter.EmitStore ();
4085 ig.MarkLabel (test);
4086 counter.EmitThis ();
4087 counter.EmitLoad ();
4090 ig.Emit (OpCodes.Ldlen);
4091 ig.Emit (OpCodes.Conv_I4);
4092 ig.Emit (OpCodes.Blt, loop);
4094 VariableStorage [] dim_len = new VariableStorage [rank];
4095 VariableStorage [] dim_count = new VariableStorage [rank];
4096 Label [] loop = new Label [rank];
4097 Label [] test = new Label [rank];
4100 for (dim = 0; dim < rank; dim++){
4101 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4102 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4103 test [dim] = ig.DefineLabel ();
4104 loop [dim] = ig.DefineLabel ();
4107 for (dim = 0; dim < rank; dim++){
4108 dim_len [dim].EmitThis ();
4111 IntLiteral.EmitInt (ig, dim);
4112 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4113 dim_len [dim].EmitStore ();
4117 for (dim = 0; dim < rank; dim++){
4118 dim_count [dim].EmitThis ();
4119 ig.Emit (OpCodes.Ldc_I4_0);
4120 dim_count [dim].EmitStore ();
4121 ig.Emit (OpCodes.Br, test [dim]);
4122 ig.MarkLabel (loop [dim]);
4129 for (dim = 0; dim < rank; dim++){
4130 dim_count [dim].EmitThis ();
4131 dim_count [dim].EmitLoad ();
4135 // FIXME: Maybe we can cache the computation of `get'?
4137 Type [] args = new Type [rank];
4140 for (int i = 0; i < rank; i++)
4141 args [i] = TypeManager.int32_type;
4143 ModuleBuilder mb = CodeGen.Module.Builder;
4144 get = mb.GetArrayMethod (
4146 CallingConventions.HasThis| CallingConventions.Standard,
4148 ig.Emit (OpCodes.Call, get);
4151 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4153 ((IAssignMethod)variable).EmitAssign (ec, conv);
4154 statement.Emit (ec);
4155 ig.MarkLabel (ec.LoopBegin);
4156 for (dim = rank - 1; dim >= 0; dim--){
4157 dim_count [dim].EmitThis ();
4158 dim_count [dim].EmitThis ();
4159 dim_count [dim].EmitLoad ();
4160 ig.Emit (OpCodes.Ldc_I4_1);
4161 ig.Emit (OpCodes.Add);
4162 dim_count [dim].EmitStore ();
4164 ig.MarkLabel (test [dim]);
4165 dim_count [dim].EmitThis ();
4166 dim_count [dim].EmitLoad ();
4167 dim_len [dim].EmitThis ();
4168 dim_len [dim].EmitLoad ();
4169 ig.Emit (OpCodes.Blt, loop [dim]);
4172 ig.MarkLabel (ec.LoopEnd);
4177 protected override void DoEmit (EmitContext ec)
4179 ILGenerator ig = ec.ig;
4181 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4182 ec.LoopBegin = ig.DefineLabel ();
4183 ec.LoopEnd = ig.DefineLabel ();
4186 EmitCollectionForeach (ec);
4188 EmitArrayForeach (ec);
4190 ec.LoopBegin = old_begin;
4191 ec.LoopEnd = old_end;