2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 using System.Collections;
21 public abstract class Statement {
25 /// Resolves the statement, true means that all sub-statements
28 public virtual bool Resolve (EmitContext ec)
34 /// We already know that the statement is unreachable, but we still
35 /// need to resolve it to catch errors.
37 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
40 // This conflicts with csc's way of doing this, but IMHO it's
41 // the right thing to do.
43 // If something is unreachable, we still check whether it's
44 // correct. This means that you cannot use unassigned variables
45 // in unreachable code, for instance.
48 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
49 bool ok = Resolve (ec);
50 ec.KillFlowBranching ();
56 Report.Warning (162, loc, "Unreachable code detected");
61 /// Return value indicates whether all code paths emitted return.
63 protected abstract void DoEmit (EmitContext ec);
66 /// Return value indicates whether all code paths emitted return.
68 public virtual void Emit (EmitContext ec)
75 public sealed class EmptyStatement : Statement {
77 private EmptyStatement () {}
79 public static readonly EmptyStatement Value = new EmptyStatement ();
81 public override bool Resolve (EmitContext ec)
86 protected override void DoEmit (EmitContext ec)
91 public class If : Statement {
93 public Statement TrueStatement;
94 public Statement FalseStatement;
98 public If (Expression expr, Statement trueStatement, Location l)
101 TrueStatement = trueStatement;
105 public If (Expression expr,
106 Statement trueStatement,
107 Statement falseStatement,
111 TrueStatement = trueStatement;
112 FalseStatement = falseStatement;
116 public override bool Resolve (EmitContext ec)
118 Report.Debug (1, "START IF BLOCK", loc);
120 expr = Expression.ResolveBoolean (ec, expr, loc);
126 // Dead code elimination
128 if (expr is BoolConstant){
129 bool take = ((BoolConstant) expr).Value;
132 if (!TrueStatement.Resolve (ec))
135 if ((FalseStatement != null) &&
136 !FalseStatement.ResolveUnreachable (ec, true))
138 FalseStatement = null;
140 if (!TrueStatement.ResolveUnreachable (ec, true))
142 TrueStatement = null;
144 if ((FalseStatement != null) &&
145 !FalseStatement.Resolve (ec))
152 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
154 bool ok = TrueStatement.Resolve (ec);
156 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
158 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
160 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
163 ec.EndFlowBranching ();
165 Report.Debug (1, "END IF BLOCK", loc);
170 protected override void DoEmit (EmitContext ec)
172 ILGenerator ig = ec.ig;
173 Label false_target = ig.DefineLabel ();
177 // If we're a boolean expression, Resolve() already
178 // eliminated dead code for us.
180 if (expr is BoolConstant){
181 bool take = ((BoolConstant) expr).Value;
184 TrueStatement.Emit (ec);
185 else if (FalseStatement != null)
186 FalseStatement.Emit (ec);
191 expr.EmitBranchable (ec, false_target, false);
193 TrueStatement.Emit (ec);
195 if (FalseStatement != null){
196 bool branch_emitted = false;
198 end = ig.DefineLabel ();
200 ig.Emit (OpCodes.Br, end);
201 branch_emitted = true;
204 ig.MarkLabel (false_target);
205 FalseStatement.Emit (ec);
210 ig.MarkLabel (false_target);
215 public class Do : Statement {
216 public Expression expr;
217 public readonly Statement EmbeddedStatement;
220 public Do (Statement statement, Expression boolExpr, Location l)
223 EmbeddedStatement = statement;
227 public override bool Resolve (EmitContext ec)
231 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
233 if (!EmbeddedStatement.Resolve (ec))
236 expr = Expression.ResolveBoolean (ec, expr, loc);
239 else if (expr is BoolConstant){
240 bool res = ((BoolConstant) expr).Value;
246 ec.CurrentBranching.Infinite = infinite;
247 ec.EndFlowBranching ();
252 protected override void DoEmit (EmitContext ec)
254 ILGenerator ig = ec.ig;
255 Label loop = ig.DefineLabel ();
256 Label old_begin = ec.LoopBegin;
257 Label old_end = ec.LoopEnd;
258 bool old_inloop = ec.InLoop;
259 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
261 ec.LoopBegin = ig.DefineLabel ();
262 ec.LoopEnd = ig.DefineLabel ();
264 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
267 EmbeddedStatement.Emit (ec);
268 ig.MarkLabel (ec.LoopBegin);
271 // Dead code elimination
273 if (expr is BoolConstant){
274 bool res = ((BoolConstant) expr).Value;
277 ec.ig.Emit (OpCodes.Br, loop);
279 expr.EmitBranchable (ec, loop, true);
281 ig.MarkLabel (ec.LoopEnd);
283 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
284 ec.LoopBegin = old_begin;
285 ec.LoopEnd = old_end;
286 ec.InLoop = old_inloop;
290 public class While : Statement {
291 public Expression expr;
292 public readonly Statement Statement;
293 bool infinite, empty;
295 public While (Expression boolExpr, Statement statement, Location l)
297 this.expr = boolExpr;
298 Statement = statement;
302 public override bool Resolve (EmitContext ec)
306 expr = Expression.ResolveBoolean (ec, expr, loc);
311 // Inform whether we are infinite or not
313 if (expr is BoolConstant){
314 BoolConstant bc = (BoolConstant) expr;
316 if (bc.Value == false){
317 if (!Statement.ResolveUnreachable (ec, true))
325 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
327 if (!Statement.Resolve (ec))
330 ec.CurrentBranching.Infinite = infinite;
331 ec.EndFlowBranching ();
336 protected override void DoEmit (EmitContext ec)
341 ILGenerator ig = ec.ig;
342 Label old_begin = ec.LoopBegin;
343 Label old_end = ec.LoopEnd;
344 bool old_inloop = ec.InLoop;
345 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
347 ec.LoopBegin = ig.DefineLabel ();
348 ec.LoopEnd = ig.DefineLabel ();
350 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
353 // Inform whether we are infinite or not
355 if (expr is BoolConstant){
356 ig.MarkLabel (ec.LoopBegin);
358 ig.Emit (OpCodes.Br, ec.LoopBegin);
361 // Inform that we are infinite (ie, `we return'), only
362 // if we do not `break' inside the code.
364 ig.MarkLabel (ec.LoopEnd);
366 Label while_loop = ig.DefineLabel ();
368 ig.Emit (OpCodes.Br, ec.LoopBegin);
369 ig.MarkLabel (while_loop);
373 ig.MarkLabel (ec.LoopBegin);
375 expr.EmitBranchable (ec, while_loop, true);
377 ig.MarkLabel (ec.LoopEnd);
380 ec.LoopBegin = old_begin;
381 ec.LoopEnd = old_end;
382 ec.InLoop = old_inloop;
383 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
387 public class For : Statement {
389 readonly Statement InitStatement;
390 readonly Statement Increment;
391 readonly Statement Statement;
392 bool infinite, empty;
394 public For (Statement initStatement,
400 InitStatement = initStatement;
402 Increment = increment;
403 Statement = statement;
407 public override bool Resolve (EmitContext ec)
411 if (InitStatement != null){
412 if (!InitStatement.Resolve (ec))
417 Test = Expression.ResolveBoolean (ec, Test, loc);
420 else if (Test is BoolConstant){
421 BoolConstant bc = (BoolConstant) Test;
423 if (bc.Value == false){
424 if (!Statement.ResolveUnreachable (ec, true))
426 if ((Increment != null) &&
427 !Increment.ResolveUnreachable (ec, false))
437 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
439 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
441 if (!Statement.Resolve (ec))
444 if (Increment != null){
445 if (!Increment.Resolve (ec))
449 ec.CurrentBranching.Infinite = infinite;
450 ec.EndFlowBranching ();
455 protected override void DoEmit (EmitContext ec)
460 ILGenerator ig = ec.ig;
461 Label old_begin = ec.LoopBegin;
462 Label old_end = ec.LoopEnd;
463 bool old_inloop = ec.InLoop;
464 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
465 Label loop = ig.DefineLabel ();
466 Label test = ig.DefineLabel ();
468 if (InitStatement != null && InitStatement != EmptyStatement.Value)
469 InitStatement.Emit (ec);
471 ec.LoopBegin = ig.DefineLabel ();
472 ec.LoopEnd = ig.DefineLabel ();
474 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
476 ig.Emit (OpCodes.Br, test);
480 ig.MarkLabel (ec.LoopBegin);
481 if (Increment != EmptyStatement.Value)
486 // If test is null, there is no test, and we are just
491 // The Resolve code already catches the case for
492 // Test == BoolConstant (false) so we know that
495 if (Test is BoolConstant)
496 ig.Emit (OpCodes.Br, loop);
498 Test.EmitBranchable (ec, loop, true);
501 ig.Emit (OpCodes.Br, loop);
502 ig.MarkLabel (ec.LoopEnd);
504 ec.LoopBegin = old_begin;
505 ec.LoopEnd = old_end;
506 ec.InLoop = old_inloop;
507 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
511 public class StatementExpression : Statement {
512 ExpressionStatement expr;
514 public StatementExpression (ExpressionStatement expr, Location l)
520 public override bool Resolve (EmitContext ec)
522 expr = expr.ResolveStatement (ec);
526 protected override void DoEmit (EmitContext ec)
528 expr.EmitStatement (ec);
531 public override string ToString ()
533 return "StatementExpression (" + expr + ")";
538 /// Implements the return statement
540 public class Return : Statement {
541 public Expression Expr;
543 public Return (Expression expr, Location l)
549 public override bool Resolve (EmitContext ec)
552 Expr = Expr.Resolve (ec);
558 Report.Error (-206, loc, "Return statement not allowed inside iterators");
562 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
564 if (ec.CurrentBranching.InTryBlock ())
565 ec.CurrentBranching.AddFinallyVector (vector);
567 vector.CheckOutParameters (ec.CurrentBranching);
569 ec.CurrentBranching.CurrentUsageVector.Return ();
573 protected override void DoEmit (EmitContext ec)
576 Report.Error (157, loc, "Control can not leave the body of the finally block");
580 if (ec.ReturnType == null){
582 Report.Error (127, loc, "Return with a value not allowed here");
587 Report.Error (126, loc, "An object of type `" +
588 TypeManager.CSharpName (ec.ReturnType) + "' is " +
589 "expected for the return statement");
593 if (Expr.Type != ec.ReturnType)
594 Expr = Convert.ImplicitConversionRequired (
595 ec, Expr, ec.ReturnType, loc);
602 if (ec.InTry || ec.InCatch)
603 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
606 if (ec.InTry || ec.InCatch) {
607 if (!ec.HasReturnLabel) {
608 ec.ReturnLabel = ec.ig.DefineLabel ();
609 ec.HasReturnLabel = true;
611 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
613 ec.ig.Emit (OpCodes.Ret);
614 ec.NeedExplicitReturn = false;
619 public class Goto : Statement {
622 LabeledStatement label;
624 public override bool Resolve (EmitContext ec)
626 label = block.LookupLabel (target);
630 "No such label `" + target + "' in this scope");
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;
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)
701 vectors = new ArrayList ();
703 vectors.Add (vector.Clone ());
706 public override bool Resolve (EmitContext ec)
708 ec.CurrentBranching.Label (vectors);
715 protected override void DoEmit (EmitContext ec)
718 ec.ig.MarkLabel (label);
724 /// `goto default' statement
726 public class GotoDefault : Statement {
728 public GotoDefault (Location l)
733 public override bool Resolve (EmitContext ec)
735 ec.CurrentBranching.CurrentUsageVector.Goto ();
739 protected override void DoEmit (EmitContext ec)
741 if (ec.Switch == null){
742 Report.Error (153, loc, "goto default is only valid in a switch statement");
746 if (!ec.Switch.GotDefault){
747 Report.Error (159, loc, "No default target on switch statement");
750 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
755 /// `goto case' statement
757 public class GotoCase : Statement {
761 public GotoCase (Expression e, Location l)
767 public override bool Resolve (EmitContext ec)
769 if (ec.Switch == null){
770 Report.Error (153, loc, "goto case is only valid in a switch statement");
774 expr = expr.Resolve (ec);
778 if (!(expr is Constant)){
779 Report.Error (159, loc, "Target expression for goto case is not constant");
783 object val = Expression.ConvertIntLiteral (
784 (Constant) expr, ec.Switch.SwitchType, loc);
789 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
794 "No such label 'case " + val + "': for the goto case");
798 label = sl.ILLabelCode;
800 ec.CurrentBranching.CurrentUsageVector.Goto ();
804 protected override void DoEmit (EmitContext ec)
806 ec.ig.Emit (OpCodes.Br, label);
810 public class Throw : Statement {
813 public Throw (Expression expr, Location l)
819 public override bool Resolve (EmitContext ec)
822 expr = expr.Resolve (ec);
826 ExprClass eclass = expr.eclass;
828 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
829 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
830 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
836 if ((t != TypeManager.exception_type) &&
837 !t.IsSubclassOf (TypeManager.exception_type) &&
838 !(expr is NullLiteral)) {
839 Report.Error (155, loc,
840 "The type caught or thrown must be derived " +
841 "from System.Exception");
846 ec.CurrentBranching.CurrentUsageVector.Throw ();
850 protected override void DoEmit (EmitContext ec)
854 ec.ig.Emit (OpCodes.Rethrow);
858 "A throw statement with no argument is only " +
859 "allowed in a catch clause");
866 ec.ig.Emit (OpCodes.Throw);
870 public class Break : Statement {
872 public Break (Location l)
877 public override bool Resolve (EmitContext ec)
879 ec.CurrentBranching.CurrentUsageVector.Break ();
883 protected override void DoEmit (EmitContext ec)
885 ILGenerator ig = ec.ig;
887 if (ec.InLoop == false && ec.Switch == null){
888 Report.Error (139, loc, "No enclosing loop or switch to continue to");
892 if (ec.InTry || ec.InCatch)
893 ig.Emit (OpCodes.Leave, ec.LoopEnd);
895 ec.NeedExplicitReturn = true;
896 ig.Emit (OpCodes.Br, ec.LoopEnd);
901 public class Continue : Statement {
903 public Continue (Location l)
908 public override bool Resolve (EmitContext ec)
910 ec.CurrentBranching.CurrentUsageVector.Goto ();
914 protected override void DoEmit (EmitContext ec)
916 Label begin = ec.LoopBegin;
919 Report.Error (139, loc, "No enclosing loop to continue to");
924 // UGH: Non trivial. This Br might cross a try/catch boundary
928 // try { ... } catch { continue; }
932 // try {} catch { while () { continue; }}
934 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
935 ec.ig.Emit (OpCodes.Leave, begin);
936 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
937 throw new Exception ("Should never happen");
939 ec.ig.Emit (OpCodes.Br, begin);
943 public class LocalInfo {
944 public Expression Type;
947 // Most of the time a variable will be stored in a LocalBuilder
949 // But sometimes, it will be stored in a field. The context of the field will
950 // be stored in the EmitContext
953 public LocalBuilder LocalBuilder;
954 public FieldBuilder FieldBuilder;
956 public Type VariableType;
957 public readonly string Name;
958 public readonly Location Location;
959 public readonly Block Block;
961 public VariableInfo VariableInfo;
971 public LocalInfo (Expression type, string name, Block block, Location l)
979 public LocalInfo (TypeContainer tc, Block block, Location l)
981 VariableType = tc.TypeBuilder;
986 public bool IsThisAssigned (EmitContext ec, Location loc)
988 if (VariableInfo == null)
989 throw new Exception ();
991 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
994 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
997 public bool IsAssigned (EmitContext ec)
999 if (VariableInfo == null)
1000 throw new Exception ();
1002 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1005 public bool Resolve (DeclSpace decl)
1007 if (VariableType == null)
1008 VariableType = decl.ResolveType (Type, false, Location);
1010 if (VariableType == null)
1016 public void MakePinned ()
1018 TypeManager.MakePinned (LocalBuilder);
1019 flags |= Flags.Fixed;
1022 public bool IsFixed {
1024 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1031 public override string ToString ()
1033 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1034 Name, Type, VariableInfo, Location);
1039 return (flags & Flags.Used) != 0;
1042 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1046 public bool ReadOnly {
1048 return (flags & Flags.ReadOnly) != 0;
1051 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1060 /// Block represents a C# block.
1064 /// This class is used in a number of places: either to represent
1065 /// explicit blocks that the programmer places or implicit blocks.
1067 /// Implicit blocks are used as labels or to introduce variable
1070 public class Block : Statement {
1071 public readonly Block Parent;
1072 public readonly Location StartLocation;
1073 public Location EndLocation = Location.Null;
1076 public enum Flags : byte {
1080 VariablesInitialized = 8,
1085 public bool Implicit {
1087 return (flags & Flags.Implicit) != 0;
1091 public bool Unchecked {
1093 return (flags & Flags.Unchecked) != 0;
1096 flags |= Flags.Unchecked;
1101 // The statements in this block
1103 ArrayList statements;
1106 // An array of Blocks. We keep track of children just
1107 // to generate the local variable declarations.
1109 // Statements and child statements are handled through the
1115 // Labels. (label, block) pairs.
1120 // Keeps track of (name, type) pairs
1122 Hashtable variables;
1125 // Keeps track of constants
1126 Hashtable constants;
1129 // If this is a switch section, the enclosing switch block.
1137 public Block (Block parent)
1138 : this (parent, (Flags) 0, Location.Null, Location.Null)
1141 public Block (Block parent, Flags flags)
1142 : this (parent, flags, Location.Null, Location.Null)
1145 public Block (Block parent, Flags flags, Parameters parameters)
1146 : this (parent, flags, parameters, Location.Null, Location.Null)
1149 public Block (Block parent, Location start, Location end)
1150 : this (parent, (Flags) 0, start, end)
1153 public Block (Block parent, Parameters parameters, Location start, Location end)
1154 : this (parent, (Flags) 0, parameters, start, end)
1157 public Block (Block parent, Flags flags, Location start, Location end)
1158 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1161 public Block (Block parent, Flags flags, Parameters parameters,
1162 Location start, Location end)
1165 parent.AddChild (this);
1167 this.Parent = parent;
1169 this.parameters = parameters;
1170 this.StartLocation = start;
1171 this.EndLocation = end;
1174 statements = new ArrayList ();
1177 public Block CreateSwitchBlock (Location start)
1179 Block new_block = new Block (this, start, start);
1180 new_block.switch_block = this;
1190 void AddChild (Block b)
1192 if (children == null)
1193 children = new ArrayList ();
1198 public void SetEndLocation (Location loc)
1204 /// Adds a label to the current block.
1208 /// false if the name already exists in this block. true
1212 public bool AddLabel (string name, LabeledStatement target)
1214 if (switch_block != null)
1215 return switch_block.AddLabel (name, target);
1218 labels = new Hashtable ();
1219 if (labels.Contains (name))
1222 labels.Add (name, target);
1226 public LabeledStatement LookupLabel (string name)
1228 Hashtable l = new Hashtable ();
1230 return LookupLabel (name, l);
1234 // Lookups a label in the current block, parents and children.
1235 // It skips during child recurssion on `source'
1237 LabeledStatement LookupLabel (string name, Hashtable seen)
1239 if (switch_block != null)
1240 return switch_block.LookupLabel (name, seen);
1242 if (seen [this] != null)
1248 if (labels.Contains (name))
1249 return ((LabeledStatement) labels [name]);
1251 if (children != null){
1252 foreach (Block b in children){
1253 LabeledStatement s = b.LookupLabel (name, seen);
1260 return Parent.LookupLabel (name, seen);
1265 LocalInfo this_variable = null;
1268 // Returns the "this" instance variable of this block.
1269 // See AddThisVariable() for more information.
1271 public LocalInfo ThisVariable {
1273 if (this_variable != null)
1274 return this_variable;
1275 else if (Parent != null)
1276 return Parent.ThisVariable;
1282 Hashtable child_variable_names;
1285 // Marks a variable with name @name as being used in a child block.
1286 // If a variable name has been used in a child block, it's illegal to
1287 // declare a variable with the same name in the current block.
1289 public void AddChildVariableName (string name)
1291 if (child_variable_names == null)
1292 child_variable_names = new Hashtable ();
1294 if (!child_variable_names.Contains (name))
1295 child_variable_names.Add (name, true);
1299 // Marks all variables from block @block and all its children as being
1300 // used in a child block.
1302 public void AddChildVariableNames (Block block)
1304 if (block.Variables != null) {
1305 foreach (string name in block.Variables.Keys)
1306 AddChildVariableName (name);
1309 if (block.children != null) {
1310 foreach (Block child in block.children)
1311 AddChildVariableNames (child);
1314 if (block.child_variable_names != null) {
1315 foreach (string name in block.child_variable_names.Keys)
1316 AddChildVariableName (name);
1321 // Checks whether a variable name has already been used in a child block.
1323 public bool IsVariableNameUsedInChildBlock (string name)
1325 if (child_variable_names == null)
1328 return child_variable_names.Contains (name);
1332 // This is used by non-static `struct' constructors which do not have an
1333 // initializer - in this case, the constructor must initialize all of the
1334 // struct's fields. To do this, we add a "this" variable and use the flow
1335 // analysis code to ensure that it's been fully initialized before control
1336 // leaves the constructor.
1338 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1340 if (this_variable != null)
1341 return this_variable;
1343 if (variables == null)
1344 variables = new Hashtable ();
1346 this_variable = new LocalInfo (tc, this, l);
1347 this_variable.Used = true;
1349 variables.Add ("this", this_variable);
1351 return this_variable;
1354 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1356 if (variables == null)
1357 variables = new Hashtable ();
1359 LocalInfo vi = GetLocalInfo (name);
1361 if (vi.Block != this)
1362 Report.Error (136, l, "A local variable named `" + name + "' " +
1363 "cannot be declared in this scope since it would " +
1364 "give a different meaning to `" + name + "', which " +
1365 "is already used in a `parent or current' scope to " +
1366 "denote something else");
1368 Report.Error (128, l, "A local variable `" + name + "' is already " +
1369 "defined in this scope");
1373 if (IsVariableNameUsedInChildBlock (name)) {
1374 Report.Error (136, l, "A local variable named `" + name + "' " +
1375 "cannot be declared in this scope since it would " +
1376 "give a different meaning to `" + name + "', which " +
1377 "is already used in a `child' scope to denote something " +
1384 Parameter p = pars.GetParameterByName (name, out idx);
1386 Report.Error (136, l, "A local variable named `" + name + "' " +
1387 "cannot be declared in this scope since it would " +
1388 "give a different meaning to `" + name + "', which " +
1389 "is already used in a `parent or current' scope to " +
1390 "denote something else");
1395 vi = new LocalInfo (type, name, this, l);
1397 variables.Add (name, vi);
1399 if ((flags & Flags.VariablesInitialized) != 0)
1400 throw new Exception ();
1402 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1406 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1408 if (AddVariable (type, name, pars, l) == null)
1411 if (constants == null)
1412 constants = new Hashtable ();
1414 constants.Add (name, value);
1418 public Hashtable Variables {
1424 public LocalInfo GetLocalInfo (string name)
1426 for (Block b = this; b != null; b = b.Parent) {
1427 if (b.variables != null) {
1428 LocalInfo ret = b.variables [name] as LocalInfo;
1436 public Expression GetVariableType (string name)
1438 LocalInfo vi = GetLocalInfo (name);
1446 public Expression GetConstantExpression (string name)
1448 for (Block b = this; b != null; b = b.Parent) {
1449 if (b.constants != null) {
1450 Expression ret = b.constants [name] as Expression;
1459 /// True if the variable named @name is a constant
1461 public bool IsConstant (string name)
1463 Expression e = null;
1465 e = GetConstantExpression (name);
1471 /// Use to fetch the statement associated with this label
1473 public Statement this [string name] {
1475 return (Statement) labels [name];
1479 Parameters parameters = null;
1480 public Parameters Parameters {
1483 while (b.Parent != null)
1485 return b.parameters;
1490 /// A list of labels that were not used within this block
1492 public string [] GetUnreferenced ()
1494 // FIXME: Implement me
1498 public void AddStatement (Statement s)
1501 flags |= Flags.BlockUsed;
1506 return (flags & Flags.BlockUsed) != 0;
1512 flags |= Flags.BlockUsed;
1515 public bool HasRet {
1517 return (flags & Flags.HasRet) != 0;
1521 VariableMap param_map, local_map;
1523 public VariableMap ParameterMap {
1525 if ((flags & Flags.VariablesInitialized) == 0)
1526 throw new Exception ();
1532 public VariableMap LocalMap {
1534 if ((flags & Flags.VariablesInitialized) == 0)
1535 throw new Exception ();
1541 public bool LiftVariable (LocalInfo local_info)
1547 /// Emits the variable declarations and labels.
1550 /// tc: is our typecontainer (to resolve type references)
1551 /// ig: is the code generator:
1553 public void EmitMeta (EmitContext ec, InternalParameters ip)
1555 ILGenerator ig = ec.ig;
1558 // Compute the VariableMap's.
1560 // Unfortunately, we don't know the type when adding variables with
1561 // AddVariable(), so we need to compute this info here.
1565 if (variables != null) {
1566 foreach (LocalInfo li in variables.Values)
1567 li.Resolve (ec.DeclSpace);
1569 locals = new LocalInfo [variables.Count];
1570 variables.Values.CopyTo (locals, 0);
1572 locals = new LocalInfo [0];
1575 local_map = new VariableMap (Parent.LocalMap, locals);
1577 local_map = new VariableMap (locals);
1579 param_map = new VariableMap (ip);
1580 flags |= Flags.VariablesInitialized;
1582 bool old_check_state = ec.ConstantCheckState;
1583 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1584 bool remap_locals = ec.RemapToProxy;
1587 // Process this block variables
1589 if (variables != null){
1590 foreach (DictionaryEntry de in variables){
1591 string name = (string) de.Key;
1592 LocalInfo vi = (LocalInfo) de.Value;
1594 if (vi.VariableType == null)
1597 Type variable_type = vi.VariableType;
1599 if (variable_type.IsPointer){
1601 // Am not really convinced that this test is required (Microsoft does it)
1602 // but the fact is that you would not be able to use the pointer variable
1605 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1611 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1613 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1615 if (constants == null)
1618 Expression cv = (Expression) constants [name];
1622 ec.CurrentBlock = this;
1623 Expression e = cv.Resolve (ec);
1627 Constant ce = e as Constant;
1629 Report.Error (133, vi.Location,
1630 "The expression being assigned to `" +
1631 name + "' must be constant (" + e + ")");
1635 if (e.Type != variable_type){
1636 e = Const.ChangeType (vi.Location, ce, variable_type);
1641 constants.Remove (name);
1642 constants.Add (name, e);
1645 ec.ConstantCheckState = old_check_state;
1648 // Now, handle the children
1650 if (children != null){
1651 foreach (Block b in children)
1652 b.EmitMeta (ec, ip);
1656 void UsageWarning (FlowBranching.UsageVector vector)
1660 if (variables != null){
1661 foreach (DictionaryEntry de in variables){
1662 LocalInfo vi = (LocalInfo) de.Value;
1667 name = (string) de.Key;
1669 if (vector.IsAssigned (vi.VariableInfo)){
1671 219, vi.Location, "The variable `" + name +
1672 "' is assigned but its value is never used");
1675 168, vi.Location, "The variable `" +
1677 "' is declared but never used");
1683 public override bool Resolve (EmitContext ec)
1685 Block prev_block = ec.CurrentBlock;
1688 int errors = Report.Errors;
1690 ec.CurrentBlock = this;
1691 ec.StartFlowBranching (this);
1693 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1695 bool unreachable = false, warning_shown = false;
1697 int statement_count = statements.Count;
1698 for (int ix = 0; ix < statement_count; ix++){
1699 Statement s = (Statement) statements [ix];
1701 if (unreachable && !(s is LabeledStatement)) {
1702 if (!s.ResolveUnreachable (ec, !warning_shown))
1705 if (s != EmptyStatement.Value)
1706 warning_shown = true;
1708 statements [ix] = EmptyStatement.Value;
1712 if (s.Resolve (ec) == false) {
1714 statements [ix] = EmptyStatement.Value;
1718 if (s is LabeledStatement)
1719 unreachable = false;
1721 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1724 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
1727 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1729 ec.CurrentBlock = prev_block;
1731 // If we're a non-static `struct' constructor which doesn't have an
1732 // initializer, then we must initialize all of the struct's fields.
1733 if ((this_variable != null) &&
1734 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1735 !this_variable.IsThisAssigned (ec, loc))
1738 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1739 foreach (LabeledStatement label in labels.Values)
1740 if (!label.HasBeenReferenced)
1741 Report.Warning (164, label.Location,
1742 "This label has not been referenced");
1745 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1747 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1748 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1749 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1750 flags |= Flags.HasRet;
1752 if (ok && (errors == Report.Errors)) {
1753 if (RootContext.WarningLevel >= 3)
1754 UsageWarning (vector);
1760 protected override void DoEmit (EmitContext ec)
1762 int statement_count = statements.Count;
1763 for (int ix = 0; ix < statement_count; ix++){
1764 Statement s = (Statement) statements [ix];
1769 public override void Emit (EmitContext ec)
1771 Block prev_block = ec.CurrentBlock;
1773 ec.CurrentBlock = this;
1775 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1776 bool is_lexical_block = !Implicit && (Parent != null);
1778 if (emit_debug_info) {
1779 if (is_lexical_block)
1780 ec.ig.BeginScope ();
1782 if (variables != null) {
1783 foreach (DictionaryEntry de in variables) {
1784 string name = (string) de.Key;
1785 LocalInfo vi = (LocalInfo) de.Value;
1787 if (vi.LocalBuilder == null)
1790 vi.LocalBuilder.SetLocalSymInfo (name);
1795 ec.Mark (StartLocation, true);
1797 ec.Mark (EndLocation, true);
1799 if (emit_debug_info && is_lexical_block)
1802 ec.CurrentBlock = prev_block;
1806 public class SwitchLabel {
1809 public Location loc;
1810 public Label ILLabel;
1811 public Label ILLabelCode;
1814 // if expr == null, then it is the default case.
1816 public SwitchLabel (Expression expr, Location l)
1822 public Expression Label {
1828 public object Converted {
1835 // Resolves the expression, reduces it to a literal if possible
1836 // and then converts it to the requested type.
1838 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1840 ILLabel = ec.ig.DefineLabel ();
1841 ILLabelCode = ec.ig.DefineLabel ();
1846 Expression e = label.Resolve (ec);
1851 if (!(e is Constant)){
1852 Report.Error (150, loc, "A constant value is expected, got: " + e);
1856 if (e is StringConstant || e is NullLiteral){
1857 if (required_type == TypeManager.string_type){
1859 ILLabel = ec.ig.DefineLabel ();
1864 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1865 if (converted == null)
1872 public class SwitchSection {
1873 // An array of SwitchLabels.
1874 public readonly ArrayList Labels;
1875 public readonly Block Block;
1877 public SwitchSection (ArrayList labels, Block block)
1884 public class Switch : Statement {
1885 public readonly ArrayList Sections;
1886 public Expression Expr;
1889 /// Maps constants whose type type SwitchType to their SwitchLabels.
1891 public Hashtable Elements;
1894 /// The governing switch type
1896 public Type SwitchType;
1902 Label default_target;
1903 Expression new_expr;
1906 // The types allowed to be implicitly cast from
1907 // on the governing type
1909 static Type [] allowed_types;
1911 public Switch (Expression e, ArrayList sects, Location l)
1918 public bool GotDefault {
1924 public Label DefaultTarget {
1926 return default_target;
1931 // Determines the governing type for a switch. The returned
1932 // expression might be the expression from the switch, or an
1933 // expression that includes any potential conversions to the
1934 // integral types or to string.
1936 Expression SwitchGoverningType (EmitContext ec, Type t)
1938 if (t == TypeManager.int32_type ||
1939 t == TypeManager.uint32_type ||
1940 t == TypeManager.char_type ||
1941 t == TypeManager.byte_type ||
1942 t == TypeManager.sbyte_type ||
1943 t == TypeManager.ushort_type ||
1944 t == TypeManager.short_type ||
1945 t == TypeManager.uint64_type ||
1946 t == TypeManager.int64_type ||
1947 t == TypeManager.string_type ||
1948 t == TypeManager.bool_type ||
1949 t.IsSubclassOf (TypeManager.enum_type))
1952 if (allowed_types == null){
1953 allowed_types = new Type [] {
1954 TypeManager.sbyte_type,
1955 TypeManager.byte_type,
1956 TypeManager.short_type,
1957 TypeManager.ushort_type,
1958 TypeManager.int32_type,
1959 TypeManager.uint32_type,
1960 TypeManager.int64_type,
1961 TypeManager.uint64_type,
1962 TypeManager.char_type,
1963 TypeManager.bool_type,
1964 TypeManager.string_type
1969 // Try to find a *user* defined implicit conversion.
1971 // If there is no implicit conversion, or if there are multiple
1972 // conversions, we have to report an error
1974 Expression converted = null;
1975 foreach (Type tt in allowed_types){
1978 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
1982 if (converted != null){
1983 Report.Error (-12, loc, "More than one conversion to an integral " +
1984 " type exists for type `" +
1985 TypeManager.CSharpName (Expr.Type)+"'");
1993 void error152 (string n)
1996 152, "The label `" + n + ":' " +
1997 "is already present on this switch statement");
2001 // Performs the basic sanity checks on the switch statement
2002 // (looks for duplicate keys and non-constant expressions).
2004 // It also returns a hashtable with the keys that we will later
2005 // use to compute the switch tables
2007 bool CheckSwitch (EmitContext ec)
2011 Elements = new Hashtable ();
2013 got_default = false;
2015 if (TypeManager.IsEnumType (SwitchType)){
2016 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2018 compare_type = SwitchType;
2020 foreach (SwitchSection ss in Sections){
2021 foreach (SwitchLabel sl in ss.Labels){
2022 if (!sl.ResolveAndReduce (ec, SwitchType)){
2027 if (sl.Label == null){
2029 error152 ("default");
2036 object key = sl.Converted;
2038 if (key is Constant)
2039 key = ((Constant) key).GetValue ();
2042 key = NullLiteral.Null;
2044 string lname = null;
2045 if (compare_type == TypeManager.uint64_type){
2046 ulong v = (ulong) key;
2048 if (Elements.Contains (v))
2049 lname = v.ToString ();
2051 Elements.Add (v, sl);
2052 } else if (compare_type == TypeManager.int64_type){
2053 long v = (long) key;
2055 if (Elements.Contains (v))
2056 lname = v.ToString ();
2058 Elements.Add (v, sl);
2059 } else if (compare_type == TypeManager.uint32_type){
2060 uint v = (uint) key;
2062 if (Elements.Contains (v))
2063 lname = v.ToString ();
2065 Elements.Add (v, sl);
2066 } else if (compare_type == TypeManager.char_type){
2067 char v = (char) key;
2069 if (Elements.Contains (v))
2070 lname = v.ToString ();
2072 Elements.Add (v, sl);
2073 } else if (compare_type == TypeManager.byte_type){
2074 byte v = (byte) key;
2076 if (Elements.Contains (v))
2077 lname = v.ToString ();
2079 Elements.Add (v, sl);
2080 } else if (compare_type == TypeManager.sbyte_type){
2081 sbyte v = (sbyte) key;
2083 if (Elements.Contains (v))
2084 lname = v.ToString ();
2086 Elements.Add (v, sl);
2087 } else if (compare_type == TypeManager.short_type){
2088 short v = (short) key;
2090 if (Elements.Contains (v))
2091 lname = v.ToString ();
2093 Elements.Add (v, sl);
2094 } else if (compare_type == TypeManager.ushort_type){
2095 ushort v = (ushort) key;
2097 if (Elements.Contains (v))
2098 lname = v.ToString ();
2100 Elements.Add (v, sl);
2101 } else if (compare_type == TypeManager.string_type){
2102 if (key is NullLiteral){
2103 if (Elements.Contains (NullLiteral.Null))
2106 Elements.Add (NullLiteral.Null, null);
2108 string s = (string) key;
2110 if (Elements.Contains (s))
2113 Elements.Add (s, sl);
2115 } else if (compare_type == TypeManager.int32_type) {
2118 if (Elements.Contains (v))
2119 lname = v.ToString ();
2121 Elements.Add (v, sl);
2122 } else if (compare_type == TypeManager.bool_type) {
2123 bool v = (bool) key;
2125 if (Elements.Contains (v))
2126 lname = v.ToString ();
2128 Elements.Add (v, sl);
2132 throw new Exception ("Unknown switch type!" +
2133 SwitchType + " " + compare_type);
2137 error152 ("case + " + lname);
2148 void EmitObjectInteger (ILGenerator ig, object k)
2151 IntConstant.EmitInt (ig, (int) k);
2152 else if (k is Constant) {
2153 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2156 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2159 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2161 IntConstant.EmitInt (ig, (int) (long) k);
2162 ig.Emit (OpCodes.Conv_I8);
2165 LongConstant.EmitLong (ig, (long) k);
2167 else if (k is ulong)
2169 if ((ulong) k < (1L<<32))
2171 IntConstant.EmitInt (ig, (int) (long) k);
2172 ig.Emit (OpCodes.Conv_U8);
2176 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2180 IntConstant.EmitInt (ig, (int) ((char) k));
2181 else if (k is sbyte)
2182 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2184 IntConstant.EmitInt (ig, (int) ((byte) k));
2185 else if (k is short)
2186 IntConstant.EmitInt (ig, (int) ((short) k));
2187 else if (k is ushort)
2188 IntConstant.EmitInt (ig, (int) ((ushort) k));
2190 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2192 throw new Exception ("Unhandled case");
2195 // structure used to hold blocks of keys while calculating table switch
2196 class KeyBlock : IComparable
2198 public KeyBlock (long _nFirst)
2200 nFirst = nLast = _nFirst;
2204 public ArrayList rgKeys = null;
2207 get { return (int) (nLast - nFirst + 1); }
2209 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2211 return kbLast.nLast - kbFirst.nFirst + 1;
2213 public int CompareTo (object obj)
2215 KeyBlock kb = (KeyBlock) obj;
2216 int nLength = Length;
2217 int nLengthOther = kb.Length;
2218 if (nLengthOther == nLength)
2219 return (int) (kb.nFirst - nFirst);
2220 return nLength - nLengthOther;
2225 /// This method emits code for a lookup-based switch statement (non-string)
2226 /// Basically it groups the cases into blocks that are at least half full,
2227 /// and then spits out individual lookup opcodes for each block.
2228 /// It emits the longest blocks first, and short blocks are just
2229 /// handled with direct compares.
2231 /// <param name="ec"></param>
2232 /// <param name="val"></param>
2233 /// <returns></returns>
2234 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2236 int cElements = Elements.Count;
2237 object [] rgKeys = new object [cElements];
2238 Elements.Keys.CopyTo (rgKeys, 0);
2239 Array.Sort (rgKeys);
2241 // initialize the block list with one element per key
2242 ArrayList rgKeyBlocks = new ArrayList ();
2243 foreach (object key in rgKeys)
2244 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2247 // iteratively merge the blocks while they are at least half full
2248 // there's probably a really cool way to do this with a tree...
2249 while (rgKeyBlocks.Count > 1)
2251 ArrayList rgKeyBlocksNew = new ArrayList ();
2252 kbCurr = (KeyBlock) rgKeyBlocks [0];
2253 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2255 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2256 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2259 kbCurr.nLast = kb.nLast;
2263 // start a new block
2264 rgKeyBlocksNew.Add (kbCurr);
2268 rgKeyBlocksNew.Add (kbCurr);
2269 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2271 rgKeyBlocks = rgKeyBlocksNew;
2274 // initialize the key lists
2275 foreach (KeyBlock kb in rgKeyBlocks)
2276 kb.rgKeys = new ArrayList ();
2278 // fill the key lists
2280 if (rgKeyBlocks.Count > 0) {
2281 kbCurr = (KeyBlock) rgKeyBlocks [0];
2282 foreach (object key in rgKeys)
2284 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2285 System.Convert.ToInt64 (key) > kbCurr.nLast;
2287 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2288 kbCurr.rgKeys.Add (key);
2292 // sort the blocks so we can tackle the largest ones first
2293 rgKeyBlocks.Sort ();
2295 // okay now we can start...
2296 ILGenerator ig = ec.ig;
2297 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2298 Label lblDefault = ig.DefineLabel ();
2300 Type typeKeys = null;
2301 if (rgKeys.Length > 0)
2302 typeKeys = rgKeys [0].GetType (); // used for conversions
2306 if (TypeManager.IsEnumType (SwitchType))
2307 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2309 compare_type = SwitchType;
2311 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2313 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2314 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2317 foreach (object key in kb.rgKeys)
2319 ig.Emit (OpCodes.Ldloc, val);
2320 EmitObjectInteger (ig, key);
2321 SwitchLabel sl = (SwitchLabel) Elements [key];
2322 ig.Emit (OpCodes.Beq, sl.ILLabel);
2327 // TODO: if all the keys in the block are the same and there are
2328 // no gaps/defaults then just use a range-check.
2329 if (compare_type == TypeManager.int64_type ||
2330 compare_type == TypeManager.uint64_type)
2332 // TODO: optimize constant/I4 cases
2334 // check block range (could be > 2^31)
2335 ig.Emit (OpCodes.Ldloc, val);
2336 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2337 ig.Emit (OpCodes.Blt, lblDefault);
2338 ig.Emit (OpCodes.Ldloc, val);
2339 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2340 ig.Emit (OpCodes.Bgt, lblDefault);
2343 ig.Emit (OpCodes.Ldloc, val);
2346 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2347 ig.Emit (OpCodes.Sub);
2349 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2354 ig.Emit (OpCodes.Ldloc, val);
2355 int nFirst = (int) kb.nFirst;
2358 IntConstant.EmitInt (ig, nFirst);
2359 ig.Emit (OpCodes.Sub);
2361 else if (nFirst < 0)
2363 IntConstant.EmitInt (ig, -nFirst);
2364 ig.Emit (OpCodes.Add);
2368 // first, build the list of labels for the switch
2370 int cJumps = kb.Length;
2371 Label [] rgLabels = new Label [cJumps];
2372 for (int iJump = 0; iJump < cJumps; iJump++)
2374 object key = kb.rgKeys [iKey];
2375 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2377 SwitchLabel sl = (SwitchLabel) Elements [key];
2378 rgLabels [iJump] = sl.ILLabel;
2382 rgLabels [iJump] = lblDefault;
2384 // emit the switch opcode
2385 ig.Emit (OpCodes.Switch, rgLabels);
2388 // mark the default for this block
2390 ig.MarkLabel (lblDefault);
2393 // TODO: find the default case and emit it here,
2394 // to prevent having to do the following jump.
2395 // make sure to mark other labels in the default section
2397 // the last default just goes to the end
2398 ig.Emit (OpCodes.Br, lblDefault);
2400 // now emit the code for the sections
2401 bool fFoundDefault = false;
2402 foreach (SwitchSection ss in Sections)
2404 foreach (SwitchLabel sl in ss.Labels)
2406 ig.MarkLabel (sl.ILLabel);
2407 ig.MarkLabel (sl.ILLabelCode);
2408 if (sl.Label == null)
2410 ig.MarkLabel (lblDefault);
2411 fFoundDefault = true;
2415 //ig.Emit (OpCodes.Br, lblEnd);
2418 if (!fFoundDefault) {
2419 ig.MarkLabel (lblDefault);
2421 ig.MarkLabel (lblEnd);
2424 // This simple emit switch works, but does not take advantage of the
2426 // TODO: remove non-string logic from here
2427 // TODO: binary search strings?
2429 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2431 ILGenerator ig = ec.ig;
2432 Label end_of_switch = ig.DefineLabel ();
2433 Label next_test = ig.DefineLabel ();
2434 Label null_target = ig.DefineLabel ();
2435 bool default_found = false;
2436 bool first_test = true;
2437 bool pending_goto_end = false;
2440 ig.Emit (OpCodes.Ldloc, val);
2442 if (Elements.Contains (NullLiteral.Null)){
2443 ig.Emit (OpCodes.Brfalse, null_target);
2445 ig.Emit (OpCodes.Brfalse, default_target);
2447 ig.Emit (OpCodes.Ldloc, val);
2448 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2449 ig.Emit (OpCodes.Stloc, val);
2451 int section_count = Sections.Count;
2452 for (int section = 0; section < section_count; section++){
2453 SwitchSection ss = (SwitchSection) Sections [section];
2454 Label sec_begin = ig.DefineLabel ();
2456 if (pending_goto_end)
2457 ig.Emit (OpCodes.Br, end_of_switch);
2459 int label_count = ss.Labels.Count;
2461 for (int label = 0; label < label_count; label++){
2462 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2463 ig.MarkLabel (sl.ILLabel);
2466 ig.MarkLabel (next_test);
2467 next_test = ig.DefineLabel ();
2470 // If we are the default target
2472 if (sl.Label == null){
2473 ig.MarkLabel (default_target);
2474 default_found = true;
2476 object lit = sl.Converted;
2478 if (lit is NullLiteral){
2480 if (label_count == 1)
2481 ig.Emit (OpCodes.Br, next_test);
2485 StringConstant str = (StringConstant) lit;
2487 ig.Emit (OpCodes.Ldloc, val);
2488 ig.Emit (OpCodes.Ldstr, str.Value);
2489 if (label_count == 1)
2490 ig.Emit (OpCodes.Bne_Un, next_test);
2492 if (label+1 == label_count)
2493 ig.Emit (OpCodes.Bne_Un, next_test);
2495 ig.Emit (OpCodes.Beq, sec_begin);
2500 ig.MarkLabel (null_target);
2501 ig.MarkLabel (sec_begin);
2502 foreach (SwitchLabel sl in ss.Labels)
2503 ig.MarkLabel (sl.ILLabelCode);
2506 pending_goto_end = !ss.Block.HasRet;
2509 if (!default_found){
2510 ig.MarkLabel (default_target);
2512 ig.MarkLabel (next_test);
2513 ig.MarkLabel (end_of_switch);
2516 public override bool Resolve (EmitContext ec)
2518 Expr = Expr.Resolve (ec);
2522 new_expr = SwitchGoverningType (ec, Expr.Type);
2523 if (new_expr == null){
2524 Report.Error (151, loc, "An integer type or string was expected for switch");
2529 SwitchType = new_expr.Type;
2531 if (!CheckSwitch (ec))
2534 Switch old_switch = ec.Switch;
2536 ec.Switch.SwitchType = SwitchType;
2538 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2541 foreach (SwitchSection ss in Sections){
2543 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2547 if (ss.Block.Resolve (ec) != true)
2553 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2555 ec.EndFlowBranching ();
2556 ec.Switch = old_switch;
2561 protected override void DoEmit (EmitContext ec)
2563 // Store variable for comparission purposes
2564 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2566 ec.ig.Emit (OpCodes.Stloc, value);
2568 ILGenerator ig = ec.ig;
2570 default_target = ig.DefineLabel ();
2573 // Setup the codegen context
2575 Label old_end = ec.LoopEnd;
2576 Switch old_switch = ec.Switch;
2578 ec.LoopEnd = ig.DefineLabel ();
2582 if (SwitchType == TypeManager.string_type)
2583 SimpleSwitchEmit (ec, value);
2585 TableSwitchEmit (ec, value);
2587 // Restore context state.
2588 ig.MarkLabel (ec.LoopEnd);
2591 // Restore the previous context
2593 ec.LoopEnd = old_end;
2594 ec.Switch = old_switch;
2598 public class Lock : Statement {
2600 Statement Statement;
2602 public Lock (Expression expr, Statement stmt, Location l)
2609 public override bool Resolve (EmitContext ec)
2611 expr = expr.Resolve (ec);
2612 return Statement.Resolve (ec) && expr != null;
2615 protected override void DoEmit (EmitContext ec)
2617 Type type = expr.Type;
2619 if (type.IsValueType){
2620 Report.Error (185, loc, "lock statement requires the expression to be " +
2621 " a reference type (type is: `" +
2622 TypeManager.CSharpName (type) + "'");
2626 ILGenerator ig = ec.ig;
2627 LocalBuilder temp = ig.DeclareLocal (type);
2630 ig.Emit (OpCodes.Dup);
2631 ig.Emit (OpCodes.Stloc, temp);
2632 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2635 ig.BeginExceptionBlock ();
2636 bool old_in_try = ec.InTry;
2638 Label finish = ig.DefineLabel ();
2639 Statement.Emit (ec);
2640 ec.InTry = old_in_try;
2641 // ig.Emit (OpCodes.Leave, finish);
2643 ig.MarkLabel (finish);
2646 ig.BeginFinallyBlock ();
2647 ig.Emit (OpCodes.Ldloc, temp);
2648 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2649 ig.EndExceptionBlock ();
2653 public class Unchecked : Statement {
2654 public readonly Block Block;
2656 public Unchecked (Block b)
2662 public override bool Resolve (EmitContext ec)
2664 bool previous_state = ec.CheckState;
2665 bool previous_state_const = ec.ConstantCheckState;
2667 ec.CheckState = false;
2668 ec.ConstantCheckState = false;
2669 bool ret = Block.Resolve (ec);
2670 ec.CheckState = previous_state;
2671 ec.ConstantCheckState = previous_state_const;
2676 protected override void DoEmit (EmitContext ec)
2678 bool previous_state = ec.CheckState;
2679 bool previous_state_const = ec.ConstantCheckState;
2681 ec.CheckState = false;
2682 ec.ConstantCheckState = false;
2684 ec.CheckState = previous_state;
2685 ec.ConstantCheckState = previous_state_const;
2689 public class Checked : Statement {
2690 public readonly Block Block;
2692 public Checked (Block b)
2695 b.Unchecked = false;
2698 public override bool Resolve (EmitContext ec)
2700 bool previous_state = ec.CheckState;
2701 bool previous_state_const = ec.ConstantCheckState;
2703 ec.CheckState = true;
2704 ec.ConstantCheckState = true;
2705 bool ret = Block.Resolve (ec);
2706 ec.CheckState = previous_state;
2707 ec.ConstantCheckState = previous_state_const;
2712 protected override void DoEmit (EmitContext ec)
2714 bool previous_state = ec.CheckState;
2715 bool previous_state_const = ec.ConstantCheckState;
2717 ec.CheckState = true;
2718 ec.ConstantCheckState = true;
2720 ec.CheckState = previous_state;
2721 ec.ConstantCheckState = previous_state_const;
2725 public class Unsafe : Statement {
2726 public readonly Block Block;
2728 public Unsafe (Block b)
2733 public override bool Resolve (EmitContext ec)
2735 bool previous_state = ec.InUnsafe;
2739 val = Block.Resolve (ec);
2740 ec.InUnsafe = previous_state;
2745 protected override void DoEmit (EmitContext ec)
2747 bool previous_state = ec.InUnsafe;
2751 ec.InUnsafe = previous_state;
2758 public class Fixed : Statement {
2760 ArrayList declarators;
2761 Statement statement;
2767 public bool is_object;
2768 public LocalInfo vi;
2769 public Expression expr;
2770 public Expression converted;
2773 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2776 declarators = decls;
2781 public override bool Resolve (EmitContext ec)
2784 Expression.UnsafeError (loc);
2788 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2789 if (expr_type == null)
2792 if (ec.RemapToProxy){
2793 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2797 data = new FixedData [declarators.Count];
2799 if (!expr_type.IsPointer){
2800 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2805 foreach (Pair p in declarators){
2806 LocalInfo vi = (LocalInfo) p.First;
2807 Expression e = (Expression) p.Second;
2809 vi.VariableInfo = null;
2813 // The rules for the possible declarators are pretty wise,
2814 // but the production on the grammar is more concise.
2816 // So we have to enforce these rules here.
2818 // We do not resolve before doing the case 1 test,
2819 // because the grammar is explicit in that the token &
2820 // is present, so we need to test for this particular case.
2824 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2829 // Case 1: & object.
2831 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2832 Expression child = ((Unary) e).Expr;
2835 if (child is ParameterReference || child is LocalVariableReference){
2838 "No need to use fixed statement for parameters or " +
2839 "local variable declarations (address is already " +
2844 ec.InFixedInitializer = true;
2846 ec.InFixedInitializer = false;
2850 child = ((Unary) e).Expr;
2852 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2855 data [i].is_object = true;
2857 data [i].converted = null;
2864 ec.InFixedInitializer = true;
2866 ec.InFixedInitializer = false;
2873 if (e.Type.IsArray){
2874 Type array_type = TypeManager.GetElementType (e.Type);
2878 // Provided that array_type is unmanaged,
2880 if (!TypeManager.VerifyUnManaged (array_type, loc))
2884 // and T* is implicitly convertible to the
2885 // pointer type given in the fixed statement.
2887 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2889 Expression converted = Convert.ImplicitConversionRequired (
2890 ec, array_ptr, vi.VariableType, loc);
2891 if (converted == null)
2894 data [i].is_object = false;
2896 data [i].converted = converted;
2906 if (e.Type == TypeManager.string_type){
2907 data [i].is_object = false;
2909 data [i].converted = null;
2916 // For other cases, flag a `this is already fixed expression'
2918 if (e is LocalVariableReference || e is ParameterReference ||
2919 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
2921 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
2925 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
2929 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
2931 if (!statement.Resolve (ec)) {
2932 ec.KillFlowBranching ();
2936 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2937 has_ret = reachability.IsUnreachable;
2942 protected override void DoEmit (EmitContext ec)
2944 ILGenerator ig = ec.ig;
2946 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
2948 for (int i = 0; i < data.Length; i++) {
2949 LocalInfo vi = data [i].vi;
2952 // Case 1: & object.
2954 if (data [i].is_object) {
2956 // Store pointer in pinned location
2958 data [i].expr.Emit (ec);
2959 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2960 clear_list [i] = vi.LocalBuilder;
2967 if (data [i].expr.Type.IsArray){
2969 // Store pointer in pinned location
2971 data [i].converted.Emit (ec);
2973 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2974 clear_list [i] = vi.LocalBuilder;
2981 if (data [i].expr.Type == TypeManager.string_type){
2982 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
2983 TypeManager.MakePinned (pinned_string);
2984 clear_list [i] = pinned_string;
2986 data [i].expr.Emit (ec);
2987 ig.Emit (OpCodes.Stloc, pinned_string);
2989 Expression sptr = new StringPtr (pinned_string, loc);
2990 Expression converted = Convert.ImplicitConversionRequired (
2991 ec, sptr, vi.VariableType, loc);
2993 if (converted == null)
2996 converted.Emit (ec);
2997 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3001 statement.Emit (ec);
3007 // Clear the pinned variable
3009 for (int i = 0; i < data.Length; i++) {
3010 if (data [i].is_object || data [i].expr.Type.IsArray) {
3011 ig.Emit (OpCodes.Ldc_I4_0);
3012 ig.Emit (OpCodes.Conv_U);
3013 ig.Emit (OpCodes.Stloc, clear_list [i]);
3014 } else if (data [i].expr.Type == TypeManager.string_type){
3015 ig.Emit (OpCodes.Ldnull);
3016 ig.Emit (OpCodes.Stloc, clear_list [i]);
3022 public class Catch {
3023 public readonly string Name;
3024 public readonly Block Block;
3025 public readonly Location Location;
3027 Expression type_expr;
3030 public Catch (Expression type, string name, Block block, Location l)
3038 public Type CatchType {
3044 public bool IsGeneral {
3046 return type_expr == null;
3050 public bool Resolve (EmitContext ec)
3052 if (type_expr != null) {
3053 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3057 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3058 Report.Error (155, Location,
3059 "The type caught or thrown must be derived " +
3060 "from System.Exception");
3066 if (!Block.Resolve (ec))
3073 public class Try : Statement {
3074 public readonly Block Fini, Block;
3075 public readonly ArrayList Specific;
3076 public readonly Catch General;
3079 // specific, general and fini might all be null.
3081 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3083 if (specific == null && general == null){
3084 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3088 this.Specific = specific;
3089 this.General = general;
3094 public override bool Resolve (EmitContext ec)
3098 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3100 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3102 bool old_in_try = ec.InTry;
3105 if (!Block.Resolve (ec))
3108 ec.InTry = old_in_try;
3110 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3112 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3114 foreach (Catch c in Specific){
3115 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3116 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3118 if (c.Name != null) {
3119 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3121 throw new Exception ();
3123 vi.VariableInfo = null;
3126 bool old_in_catch = ec.InCatch;
3129 if (!c.Resolve (ec))
3132 ec.InCatch = old_in_catch;
3135 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3137 if (General != null){
3138 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3139 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3141 bool old_in_catch = ec.InCatch;
3144 if (!General.Resolve (ec))
3147 ec.InCatch = old_in_catch;
3150 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3154 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
3155 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3157 bool old_in_finally = ec.InFinally;
3158 ec.InFinally = true;
3160 if (!Fini.Resolve (ec))
3163 ec.InFinally = old_in_finally;
3166 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3168 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3170 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3172 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3173 // Unfortunately, System.Reflection.Emit automatically emits a leave
3174 // to the end of the finally block. This is a problem if `returns'
3175 // is true since we may jump to a point after the end of the method.
3176 // As a workaround, emit an explicit ret here.
3177 ec.NeedExplicitReturn = true;
3183 protected override void DoEmit (EmitContext ec)
3185 ILGenerator ig = ec.ig;
3186 Label finish = ig.DefineLabel ();;
3189 ig.BeginExceptionBlock ();
3190 bool old_in_try = ec.InTry;
3193 ec.InTry = old_in_try;
3196 // System.Reflection.Emit provides this automatically:
3197 // ig.Emit (OpCodes.Leave, finish);
3199 bool old_in_catch = ec.InCatch;
3202 foreach (Catch c in Specific){
3205 ig.BeginCatchBlock (c.CatchType);
3207 if (c.Name != null){
3208 vi = c.Block.GetLocalInfo (c.Name);
3210 throw new Exception ("Variable does not exist in this block");
3212 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3214 ig.Emit (OpCodes.Pop);
3219 if (General != null){
3220 ig.BeginCatchBlock (TypeManager.object_type);
3221 ig.Emit (OpCodes.Pop);
3222 General.Block.Emit (ec);
3224 ec.InCatch = old_in_catch;
3226 ig.MarkLabel (finish);
3228 ig.BeginFinallyBlock ();
3229 bool old_in_finally = ec.InFinally;
3230 ec.InFinally = true;
3232 ec.InFinally = old_in_finally;
3235 ig.EndExceptionBlock ();
3240 public class Using : Statement {
3241 object expression_or_block;
3242 Statement Statement;
3247 Expression [] converted_vars;
3248 ExpressionStatement [] assign;
3250 public Using (object expression_or_block, Statement stmt, Location l)
3252 this.expression_or_block = expression_or_block;
3258 // Resolves for the case of using using a local variable declaration.
3260 bool ResolveLocalVariableDecls (EmitContext ec)
3262 bool need_conv = false;
3263 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3266 if (expr_type == null)
3270 // The type must be an IDisposable or an implicit conversion
3273 converted_vars = new Expression [var_list.Count];
3274 assign = new ExpressionStatement [var_list.Count];
3275 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3276 foreach (DictionaryEntry e in var_list){
3277 Expression var = (Expression) e.Key;
3279 var = var.ResolveLValue (ec, new EmptyExpression ());
3283 converted_vars [i] = Convert.ImplicitConversionRequired (
3284 ec, var, TypeManager.idisposable_type, loc);
3286 if (converted_vars [i] == null)
3294 foreach (DictionaryEntry e in var_list){
3295 LocalVariableReference var = (LocalVariableReference) e.Key;
3296 Expression new_expr = (Expression) e.Value;
3299 a = new Assign (var, new_expr, loc);
3305 converted_vars [i] = var;
3306 assign [i] = (ExpressionStatement) a;
3313 bool ResolveExpression (EmitContext ec)
3315 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3316 conv = Convert.ImplicitConversionRequired (
3317 ec, expr, TypeManager.idisposable_type, loc);
3327 // Emits the code for the case of using using a local variable declaration.
3329 bool EmitLocalVariableDecls (EmitContext ec)
3331 ILGenerator ig = ec.ig;
3334 bool old_in_try = ec.InTry;
3336 for (i = 0; i < assign.Length; i++) {
3337 assign [i].EmitStatement (ec);
3339 ig.BeginExceptionBlock ();
3341 Statement.Emit (ec);
3342 ec.InTry = old_in_try;
3344 bool old_in_finally = ec.InFinally;
3345 ec.InFinally = true;
3346 var_list.Reverse ();
3347 foreach (DictionaryEntry e in var_list){
3348 LocalVariableReference var = (LocalVariableReference) e.Key;
3349 Label skip = ig.DefineLabel ();
3352 ig.BeginFinallyBlock ();
3354 if (!var.Type.IsValueType) {
3356 ig.Emit (OpCodes.Brfalse, skip);
3357 converted_vars [i].Emit (ec);
3358 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3360 Expression ml = Expression.MemberLookup(ec, typeof(IDisposable), var.Type, "Dispose", Mono.CSharp.Location.Null);
3362 if (!(ml is MethodGroupExpr)) {
3364 ig.Emit (OpCodes.Box, var.Type);
3365 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3367 MethodInfo mi = null;
3369 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3370 if (mk.GetParameters().Length == 0) {
3377 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3381 var.AddressOf (ec, AddressOp.Load);
3382 ig.Emit (OpCodes.Call, mi);
3386 ig.MarkLabel (skip);
3387 ig.EndExceptionBlock ();
3389 ec.InFinally = old_in_finally;
3394 bool EmitExpression (EmitContext ec)
3397 // Make a copy of the expression and operate on that.
3399 ILGenerator ig = ec.ig;
3400 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3405 ig.Emit (OpCodes.Stloc, local_copy);
3407 bool old_in_try = ec.InTry;
3409 ig.BeginExceptionBlock ();
3410 Statement.Emit (ec);
3411 ec.InTry = old_in_try;
3413 Label skip = ig.DefineLabel ();
3414 bool old_in_finally = ec.InFinally;
3415 ig.BeginFinallyBlock ();
3416 ig.Emit (OpCodes.Ldloc, local_copy);
3417 ig.Emit (OpCodes.Brfalse, skip);
3418 ig.Emit (OpCodes.Ldloc, local_copy);
3419 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3420 ig.MarkLabel (skip);
3421 ec.InFinally = old_in_finally;
3422 ig.EndExceptionBlock ();
3427 public override bool Resolve (EmitContext ec)
3429 if (expression_or_block is DictionaryEntry){
3430 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3431 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3433 if (!ResolveLocalVariableDecls (ec))
3436 } else if (expression_or_block is Expression){
3437 expr = (Expression) expression_or_block;
3439 expr = expr.Resolve (ec);
3443 expr_type = expr.Type;
3445 if (!ResolveExpression (ec))
3449 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
3451 bool ok = Statement.Resolve (ec);
3454 ec.KillFlowBranching ();
3458 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3460 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3461 // Unfortunately, System.Reflection.Emit automatically emits a leave
3462 // to the end of the finally block. This is a problem if `returns'
3463 // is true since we may jump to a point after the end of the method.
3464 // As a workaround, emit an explicit ret here.
3465 ec.NeedExplicitReturn = true;
3471 protected override void DoEmit (EmitContext ec)
3473 if (expression_or_block is DictionaryEntry)
3474 EmitLocalVariableDecls (ec);
3475 else if (expression_or_block is Expression)
3476 EmitExpression (ec);
3481 /// Implementation of the foreach C# statement
3483 public class Foreach : Statement {
3485 Expression variable;
3487 Statement statement;
3488 ForeachHelperMethods hm;
3489 Expression empty, conv;
3490 Type array_type, element_type;
3493 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3494 Statement stmt, Location l)
3497 this.variable = var;
3503 public override bool Resolve (EmitContext ec)
3505 expr = expr.Resolve (ec);
3509 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3510 if (var_type == null)
3514 // We need an instance variable. Not sure this is the best
3515 // way of doing this.
3517 // FIXME: When we implement propertyaccess, will those turn
3518 // out to return values in ExprClass? I think they should.
3520 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3521 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3522 error1579 (expr.Type);
3526 if (expr.Type.IsArray) {
3527 array_type = expr.Type;
3528 element_type = TypeManager.GetElementType (array_type);
3530 empty = new EmptyExpression (element_type);
3532 hm = ProbeCollectionType (ec, expr.Type);
3534 error1579 (expr.Type);
3538 array_type = expr.Type;
3539 element_type = hm.element_type;
3541 empty = new EmptyExpression (hm.element_type);
3544 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
3545 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
3549 // FIXME: maybe we can apply the same trick we do in the
3550 // array handling to avoid creating empty and conv in some cases.
3552 // Although it is not as important in this case, as the type
3553 // will not likely be object (what the enumerator will return).
3555 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3559 variable = variable.ResolveLValue (ec, empty);
3560 if (variable == null)
3563 if (!statement.Resolve (ec))
3566 ec.EndFlowBranching ();
3572 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3574 static MethodInfo FetchMethodMoveNext (Type t)
3576 MemberList move_next_list;
3578 move_next_list = TypeContainer.FindMembers (
3579 t, MemberTypes.Method,
3580 BindingFlags.Public | BindingFlags.Instance,
3581 Type.FilterName, "MoveNext");
3582 if (move_next_list.Count == 0)
3585 foreach (MemberInfo m in move_next_list){
3586 MethodInfo mi = (MethodInfo) m;
3589 args = TypeManager.GetArgumentTypes (mi);
3590 if (args != null && args.Length == 0){
3591 if (mi.ReturnType == TypeManager.bool_type)
3599 // Retrieves a `public T get_Current ()' method from the Type `t'
3601 static MethodInfo FetchMethodGetCurrent (Type t)
3603 MemberList get_current_list;
3605 get_current_list = TypeContainer.FindMembers (
3606 t, MemberTypes.Method,
3607 BindingFlags.Public | BindingFlags.Instance,
3608 Type.FilterName, "get_Current");
3609 if (get_current_list.Count == 0)
3612 foreach (MemberInfo m in get_current_list){
3613 MethodInfo mi = (MethodInfo) m;
3616 args = TypeManager.GetArgumentTypes (mi);
3617 if (args != null && args.Length == 0)
3624 // This struct records the helper methods used by the Foreach construct
3626 class ForeachHelperMethods {
3627 public EmitContext ec;
3628 public MethodInfo get_enumerator;
3629 public MethodInfo move_next;
3630 public MethodInfo get_current;
3631 public Type element_type;
3632 public Type enumerator_type;
3633 public bool is_disposable;
3635 public ForeachHelperMethods (EmitContext ec)
3638 this.element_type = TypeManager.object_type;
3639 this.enumerator_type = TypeManager.ienumerator_type;
3640 this.is_disposable = true;
3644 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3649 if (!(m is MethodInfo))
3652 if (m.Name != "GetEnumerator")
3655 MethodInfo mi = (MethodInfo) m;
3656 Type [] args = TypeManager.GetArgumentTypes (mi);
3658 if (args.Length != 0)
3661 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3662 EmitContext ec = hm.ec;
3665 // Check whether GetEnumerator is accessible to us
3667 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3669 Type declaring = mi.DeclaringType;
3670 if (prot == MethodAttributes.Private){
3671 if (declaring != ec.ContainerType)
3673 } else if (prot == MethodAttributes.FamANDAssem){
3674 // If from a different assembly, false
3675 if (!(mi is MethodBuilder))
3678 // Are we being invoked from the same class, or from a derived method?
3680 if (ec.ContainerType != declaring){
3681 if (!ec.ContainerType.IsSubclassOf (declaring))
3684 } else if (prot == MethodAttributes.FamORAssem){
3685 if (!(mi is MethodBuilder ||
3686 ec.ContainerType == declaring ||
3687 ec.ContainerType.IsSubclassOf (declaring)))
3689 } if (prot == MethodAttributes.Family){
3690 if (!(ec.ContainerType == declaring ||
3691 ec.ContainerType.IsSubclassOf (declaring)))
3695 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3697 // Apply the same optimization as MS: skip the GetEnumerator
3698 // returning an IEnumerator, and use the one returning a
3699 // CharEnumerator instead. This allows us to avoid the
3700 // try-finally block and the boxing.
3705 // Ok, we can access it, now make sure that we can do something
3706 // with this `GetEnumerator'
3709 if (mi.ReturnType == TypeManager.ienumerator_type ||
3710 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
3711 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
3712 if (declaring != TypeManager.string_type) {
3713 hm.move_next = TypeManager.bool_movenext_void;
3714 hm.get_current = TypeManager.object_getcurrent_void;
3720 // Ok, so they dont return an IEnumerable, we will have to
3721 // find if they support the GetEnumerator pattern.
3723 Type return_type = mi.ReturnType;
3725 hm.move_next = FetchMethodMoveNext (return_type);
3726 if (hm.move_next == null)
3728 hm.get_current = FetchMethodGetCurrent (return_type);
3729 if (hm.get_current == null)
3732 hm.element_type = hm.get_current.ReturnType;
3733 hm.enumerator_type = return_type;
3734 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3735 TypeManager.ImplementsInterface (
3736 hm.enumerator_type, TypeManager.idisposable_type);
3742 /// This filter is used to find the GetEnumerator method
3743 /// on which IEnumerator operates
3745 static MemberFilter FilterEnumerator;
3749 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3752 void error1579 (Type t)
3754 Report.Error (1579, loc,
3755 "foreach statement cannot operate on variables of type `" +
3756 t.FullName + "' because that class does not provide a " +
3757 " GetEnumerator method or it is inaccessible");
3760 static bool TryType (Type t, ForeachHelperMethods hm)
3764 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3765 BindingFlags.Public | BindingFlags.NonPublic |
3766 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3767 FilterEnumerator, hm);
3772 hm.get_enumerator = (MethodInfo) mi [0];
3777 // Looks for a usable GetEnumerator in the Type, and if found returns
3778 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3780 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3782 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3784 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3785 if (TryType (tt, hm))
3791 // Now try to find the method in the interfaces
3794 Type [] ifaces = t.GetInterfaces ();
3796 foreach (Type i in ifaces){
3797 if (TryType (i, hm))
3802 // Since TypeBuilder.GetInterfaces only returns the interface
3803 // types for this type, we have to keep looping, but once
3804 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3805 // done, because it returns all the types
3807 if ((t is TypeBuilder))
3817 // FIXME: possible optimization.
3818 // We might be able to avoid creating `empty' if the type is the sam
3820 bool EmitCollectionForeach (EmitContext ec)
3822 ILGenerator ig = ec.ig;
3823 VariableStorage enumerator, disposable;
3825 enumerator = new VariableStorage (ec, hm.enumerator_type);
3826 if (hm.is_disposable)
3827 disposable = new VariableStorage (ec, TypeManager.idisposable_type);
3831 enumerator.EmitThis ();
3833 // Instantiate the enumerator
3835 if (expr.Type.IsValueType){
3836 if (expr is IMemoryLocation){
3837 IMemoryLocation ml = (IMemoryLocation) expr;
3839 ml.AddressOf (ec, AddressOp.Load);
3841 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3842 " does not implement IMemoryLocation");
3843 ig.Emit (OpCodes.Call, hm.get_enumerator);
3846 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3848 enumerator.EmitStore ();
3851 // Protect the code in a try/finalize block, so that
3852 // if the beast implement IDisposable, we get rid of it
3854 bool old_in_try = ec.InTry;
3856 if (hm.is_disposable) {
3857 ig.BeginExceptionBlock ();
3861 Label end_try = ig.DefineLabel ();
3863 ig.MarkLabel (ec.LoopBegin);
3864 enumerator.EmitLoad ();
3865 ig.Emit (OpCodes.Callvirt, hm.move_next);
3866 ig.Emit (OpCodes.Brfalse, end_try);
3870 enumerator.EmitLoad ();
3871 ig.Emit (OpCodes.Callvirt, hm.get_current);
3875 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3877 ((IAssignMethod)variable).EmitAssign (ec, conv);
3879 statement.Emit (ec);
3880 ig.Emit (OpCodes.Br, ec.LoopBegin);
3881 ig.MarkLabel (end_try);
3882 ec.InTry = old_in_try;
3884 // The runtime provides this for us.
3885 // ig.Emit (OpCodes.Leave, end);
3888 // Now the finally block
3890 if (hm.is_disposable) {
3891 Label end_finally = ig.DefineLabel ();
3892 bool old_in_finally = ec.InFinally;
3893 ec.InFinally = true;
3894 ig.BeginFinallyBlock ();
3896 disposable.EmitThis ();
3897 enumerator.EmitThis ();
3898 enumerator.EmitLoad ();
3899 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3900 disposable.EmitStore ();
3901 disposable.EmitLoad ();
3902 ig.Emit (OpCodes.Brfalse, end_finally);
3903 disposable.EmitThis ();
3904 disposable.EmitLoad ();
3905 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3906 ig.MarkLabel (end_finally);
3907 ec.InFinally = old_in_finally;
3909 // The runtime generates this anyways.
3910 // ig.Emit (OpCodes.Endfinally);
3912 ig.EndExceptionBlock ();
3915 ig.MarkLabel (ec.LoopEnd);
3920 // FIXME: possible optimization.
3921 // We might be able to avoid creating `empty' if the type is the sam
3923 bool EmitArrayForeach (EmitContext ec)
3925 int rank = array_type.GetArrayRank ();
3926 ILGenerator ig = ec.ig;
3928 VariableStorage copy = new VariableStorage (ec, array_type);
3931 // Make our copy of the array
3938 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
3942 counter.EmitThis ();
3943 ig.Emit (OpCodes.Ldc_I4_0);
3944 counter.EmitStore ();
3945 test = ig.DefineLabel ();
3946 ig.Emit (OpCodes.Br, test);
3948 loop = ig.DefineLabel ();
3949 ig.MarkLabel (loop);
3956 counter.EmitThis ();
3957 counter.EmitLoad ();
3960 // Load the value, we load the value using the underlying type,
3961 // then we use the variable.EmitAssign to load using the proper cast.
3963 ArrayAccess.EmitLoadOpcode (ig, element_type);
3966 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3968 ((IAssignMethod)variable).EmitAssign (ec, conv);
3970 statement.Emit (ec);
3972 ig.MarkLabel (ec.LoopBegin);
3973 counter.EmitThis ();
3974 counter.EmitThis ();
3975 counter.EmitLoad ();
3976 ig.Emit (OpCodes.Ldc_I4_1);
3977 ig.Emit (OpCodes.Add);
3978 counter.EmitStore ();
3980 ig.MarkLabel (test);
3981 counter.EmitThis ();
3982 counter.EmitLoad ();
3985 ig.Emit (OpCodes.Ldlen);
3986 ig.Emit (OpCodes.Conv_I4);
3987 ig.Emit (OpCodes.Blt, loop);
3989 VariableStorage [] dim_len = new VariableStorage [rank];
3990 VariableStorage [] dim_count = new VariableStorage [rank];
3991 Label [] loop = new Label [rank];
3992 Label [] test = new Label [rank];
3995 for (dim = 0; dim < rank; dim++){
3996 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
3997 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
3998 test [dim] = ig.DefineLabel ();
3999 loop [dim] = ig.DefineLabel ();
4002 for (dim = 0; dim < rank; dim++){
4003 dim_len [dim].EmitThis ();
4006 IntLiteral.EmitInt (ig, dim);
4007 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4008 dim_len [dim].EmitStore ();
4012 for (dim = 0; dim < rank; dim++){
4013 dim_count [dim].EmitThis ();
4014 ig.Emit (OpCodes.Ldc_I4_0);
4015 dim_count [dim].EmitStore ();
4016 ig.Emit (OpCodes.Br, test [dim]);
4017 ig.MarkLabel (loop [dim]);
4024 for (dim = 0; dim < rank; dim++){
4025 dim_count [dim].EmitThis ();
4026 dim_count [dim].EmitLoad ();
4030 // FIXME: Maybe we can cache the computation of `get'?
4032 Type [] args = new Type [rank];
4035 for (int i = 0; i < rank; i++)
4036 args [i] = TypeManager.int32_type;
4038 ModuleBuilder mb = CodeGen.ModuleBuilder;
4039 get = mb.GetArrayMethod (
4041 CallingConventions.HasThis| CallingConventions.Standard,
4043 ig.Emit (OpCodes.Call, get);
4046 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4048 ((IAssignMethod)variable).EmitAssign (ec, conv);
4049 statement.Emit (ec);
4050 ig.MarkLabel (ec.LoopBegin);
4051 for (dim = rank - 1; dim >= 0; dim--){
4052 dim_count [dim].EmitThis ();
4053 dim_count [dim].EmitThis ();
4054 dim_count [dim].EmitLoad ();
4055 ig.Emit (OpCodes.Ldc_I4_1);
4056 ig.Emit (OpCodes.Add);
4057 dim_count [dim].EmitStore ();
4059 ig.MarkLabel (test [dim]);
4060 dim_count [dim].EmitThis ();
4061 dim_count [dim].EmitLoad ();
4062 dim_len [dim].EmitThis ();
4063 dim_len [dim].EmitLoad ();
4064 ig.Emit (OpCodes.Blt, loop [dim]);
4067 ig.MarkLabel (ec.LoopEnd);
4072 protected override void DoEmit (EmitContext ec)
4074 ILGenerator ig = ec.ig;
4076 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4077 bool old_inloop = ec.InLoop;
4078 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4079 ec.LoopBegin = ig.DefineLabel ();
4080 ec.LoopEnd = ig.DefineLabel ();
4082 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4085 EmitCollectionForeach (ec);
4087 EmitArrayForeach (ec);
4089 ec.LoopBegin = old_begin;
4090 ec.LoopEnd = old_end;
4091 ec.InLoop = old_inloop;
4092 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;