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 /// Return value indicates whether all code paths emitted return.
36 protected abstract void DoEmit (EmitContext ec);
39 /// Return value indicates whether all code paths emitted return.
41 public virtual void Emit (EmitContext ec)
47 public static void Warning_DeadCodeFound (Location loc)
49 Report.Warning (162, loc, "Unreachable code detected");
53 public sealed class EmptyStatement : Statement {
55 private EmptyStatement () {}
57 public static readonly EmptyStatement Value = new EmptyStatement ();
59 public override bool Resolve (EmitContext ec)
64 protected override void DoEmit (EmitContext ec)
69 public class If : Statement {
71 public Statement TrueStatement;
72 public Statement FalseStatement;
76 public If (Expression expr, Statement trueStatement, Location l)
79 TrueStatement = trueStatement;
83 public If (Expression expr,
84 Statement trueStatement,
85 Statement falseStatement,
89 TrueStatement = trueStatement;
90 FalseStatement = falseStatement;
94 public override bool Resolve (EmitContext ec)
96 Report.Debug (1, "START IF BLOCK", loc);
98 expr = Expression.ResolveBoolean (ec, expr, loc);
103 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
105 if (!TrueStatement.Resolve (ec)) {
106 ec.KillFlowBranching ();
110 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
112 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
114 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
115 ec.KillFlowBranching ();
119 ec.EndFlowBranching ();
121 Report.Debug (1, "END IF BLOCK", loc);
126 protected override void DoEmit (EmitContext ec)
128 ILGenerator ig = ec.ig;
129 Label false_target = ig.DefineLabel ();
133 // Dead code elimination
135 if (expr is BoolConstant){
136 bool take = ((BoolConstant) expr).Value;
139 if (FalseStatement != null){
140 Warning_DeadCodeFound (FalseStatement.loc);
142 TrueStatement.Emit (ec);
145 Warning_DeadCodeFound (TrueStatement.loc);
146 if (FalseStatement != null) {
147 FalseStatement.Emit (ec);
153 expr.EmitBranchable (ec, false_target, false);
155 TrueStatement.Emit (ec);
157 if (FalseStatement != null){
158 bool branch_emitted = false;
160 end = ig.DefineLabel ();
162 ig.Emit (OpCodes.Br, end);
163 branch_emitted = true;
166 ig.MarkLabel (false_target);
167 FalseStatement.Emit (ec);
172 ig.MarkLabel (false_target);
177 public class Do : Statement {
178 public Expression expr;
179 public readonly Statement EmbeddedStatement;
182 public Do (Statement statement, Expression boolExpr, Location l)
185 EmbeddedStatement = statement;
189 public override bool Resolve (EmitContext ec)
193 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
195 if (!EmbeddedStatement.Resolve (ec))
198 expr = Expression.ResolveBoolean (ec, expr, loc);
201 else if (expr is BoolConstant){
202 bool res = ((BoolConstant) expr).Value;
208 ec.CurrentBranching.Infinite = infinite;
209 ec.EndFlowBranching ();
214 protected override void DoEmit (EmitContext ec)
216 ILGenerator ig = ec.ig;
217 Label loop = ig.DefineLabel ();
218 Label old_begin = ec.LoopBegin;
219 Label old_end = ec.LoopEnd;
220 bool old_inloop = ec.InLoop;
221 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
223 ec.LoopBegin = ig.DefineLabel ();
224 ec.LoopEnd = ig.DefineLabel ();
226 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
229 EmbeddedStatement.Emit (ec);
230 ig.MarkLabel (ec.LoopBegin);
233 // Dead code elimination
235 if (expr is BoolConstant){
236 bool res = ((BoolConstant) expr).Value;
239 ec.ig.Emit (OpCodes.Br, loop);
241 expr.EmitBranchable (ec, loop, true);
243 ig.MarkLabel (ec.LoopEnd);
245 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
246 ec.LoopBegin = old_begin;
247 ec.LoopEnd = old_end;
248 ec.InLoop = old_inloop;
252 public class While : Statement {
253 public Expression expr;
254 public readonly Statement Statement;
255 bool empty, infinite;
257 public While (Expression boolExpr, Statement statement, Location l)
259 this.expr = boolExpr;
260 Statement = statement;
264 public override bool Resolve (EmitContext ec)
268 expr = Expression.ResolveBoolean (ec, expr, loc);
272 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
275 // Inform whether we are infinite or not
277 if (expr is BoolConstant){
278 BoolConstant bc = (BoolConstant) expr;
280 if (bc.Value == false){
281 Warning_DeadCodeFound (Statement.loc);
287 // We are not infinite, so the loop may or may not be executed.
289 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
292 if (!Statement.Resolve (ec))
296 ec.KillFlowBranching ();
298 ec.CurrentBranching.Infinite = infinite;
299 ec.EndFlowBranching ();
305 protected override void DoEmit (EmitContext ec)
310 ILGenerator ig = ec.ig;
311 Label old_begin = ec.LoopBegin;
312 Label old_end = ec.LoopEnd;
313 bool old_inloop = ec.InLoop;
314 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
316 ec.LoopBegin = ig.DefineLabel ();
317 ec.LoopEnd = ig.DefineLabel ();
319 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
322 // Inform whether we are infinite or not
324 if (expr is BoolConstant){
325 ig.MarkLabel (ec.LoopBegin);
327 ig.Emit (OpCodes.Br, ec.LoopBegin);
330 // Inform that we are infinite (ie, `we return'), only
331 // if we do not `break' inside the code.
333 ig.MarkLabel (ec.LoopEnd);
335 Label while_loop = ig.DefineLabel ();
337 ig.Emit (OpCodes.Br, ec.LoopBegin);
338 ig.MarkLabel (while_loop);
342 ig.MarkLabel (ec.LoopBegin);
344 expr.EmitBranchable (ec, while_loop, true);
346 ig.MarkLabel (ec.LoopEnd);
349 ec.LoopBegin = old_begin;
350 ec.LoopEnd = old_end;
351 ec.InLoop = old_inloop;
352 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
356 public class For : Statement {
358 readonly Statement InitStatement;
359 readonly Statement Increment;
360 readonly Statement Statement;
361 bool infinite, empty;
363 public For (Statement initStatement,
369 InitStatement = initStatement;
371 Increment = increment;
372 Statement = statement;
376 public override bool Resolve (EmitContext ec)
380 if (InitStatement != null){
381 if (!InitStatement.Resolve (ec))
386 Test = Expression.ResolveBoolean (ec, Test, loc);
389 else if (Test is BoolConstant){
390 BoolConstant bc = (BoolConstant) Test;
392 if (bc.Value == false){
393 Warning_DeadCodeFound (Statement.loc);
401 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
403 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
405 if (!Statement.Resolve (ec))
408 if (Increment != null){
409 if (!Increment.Resolve (ec))
414 ec.KillFlowBranching ();
416 ec.CurrentBranching.Infinite = infinite;
417 ec.EndFlowBranching ();
423 protected override void DoEmit (EmitContext ec)
428 ILGenerator ig = ec.ig;
429 Label old_begin = ec.LoopBegin;
430 Label old_end = ec.LoopEnd;
431 bool old_inloop = ec.InLoop;
432 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
433 Label loop = ig.DefineLabel ();
434 Label test = ig.DefineLabel ();
436 if (InitStatement != null && InitStatement != EmptyStatement.Value)
437 InitStatement.Emit (ec);
439 ec.LoopBegin = ig.DefineLabel ();
440 ec.LoopEnd = ig.DefineLabel ();
442 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
444 ig.Emit (OpCodes.Br, test);
448 ig.MarkLabel (ec.LoopBegin);
449 if (Increment != EmptyStatement.Value)
454 // If test is null, there is no test, and we are just
459 // The Resolve code already catches the case for Test == BoolConstant (false)
460 // so we know that this is true
462 if (Test is BoolConstant)
463 ig.Emit (OpCodes.Br, loop);
465 Test.EmitBranchable (ec, loop, true);
468 ig.Emit (OpCodes.Br, loop);
469 ig.MarkLabel (ec.LoopEnd);
471 ec.LoopBegin = old_begin;
472 ec.LoopEnd = old_end;
473 ec.InLoop = old_inloop;
474 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
478 public class StatementExpression : Statement {
479 ExpressionStatement expr;
481 public StatementExpression (ExpressionStatement expr, Location l)
487 public override bool Resolve (EmitContext ec)
489 expr = expr.ResolveStatement (ec);
493 protected override void DoEmit (EmitContext ec)
495 expr.EmitStatement (ec);
498 public override string ToString ()
500 return "StatementExpression (" + expr + ")";
505 /// Implements the return statement
507 public class Return : Statement {
508 public Expression Expr;
510 public Return (Expression expr, Location l)
516 public override bool Resolve (EmitContext ec)
519 Expr = Expr.Resolve (ec);
525 Report.Error (-206, loc, "Return statement not allowed inside iterators");
529 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
531 if (ec.CurrentBranching.InTryBlock ())
532 ec.CurrentBranching.AddFinallyVector (vector);
534 vector.CheckOutParameters (ec.CurrentBranching);
536 ec.CurrentBranching.CurrentUsageVector.Return ();
540 protected override void DoEmit (EmitContext ec)
543 Report.Error (157, loc, "Control can not leave the body of the finally block");
547 if (ec.ReturnType == null){
549 Report.Error (127, loc, "Return with a value not allowed here");
554 Report.Error (126, loc, "An object of type `" +
555 TypeManager.CSharpName (ec.ReturnType) + "' is " +
556 "expected for the return statement");
560 if (Expr.Type != ec.ReturnType)
561 Expr = Convert.ImplicitConversionRequired (
562 ec, Expr, ec.ReturnType, loc);
569 if (ec.InTry || ec.InCatch)
570 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
573 if (ec.InTry || ec.InCatch) {
574 if (!ec.HasReturnLabel) {
575 ec.ReturnLabel = ec.ig.DefineLabel ();
576 ec.HasReturnLabel = true;
578 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
580 ec.ig.Emit (OpCodes.Ret);
581 ec.NeedExplicitReturn = false;
586 public class Goto : Statement {
589 LabeledStatement label;
591 public override bool Resolve (EmitContext ec)
593 label = block.LookupLabel (target);
597 "No such label `" + target + "' in this scope");
601 // If this is a forward goto.
602 if (!label.IsDefined)
603 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
605 ec.CurrentBranching.CurrentUsageVector.Goto ();
610 public Goto (Block parent_block, string label, Location l)
612 block = parent_block;
617 public string Target {
623 protected override void DoEmit (EmitContext ec)
625 Label l = label.LabelTarget (ec);
626 ec.ig.Emit (OpCodes.Br, l);
630 public class LabeledStatement : Statement {
631 public readonly Location Location;
638 public LabeledStatement (string label_name, Location l)
643 public Label LabelTarget (EmitContext ec)
647 label = ec.ig.DefineLabel ();
653 public bool IsDefined {
659 public bool HasBeenReferenced {
665 public void AddUsageVector (FlowBranching.UsageVector vector)
668 vectors = new ArrayList ();
670 vectors.Add (vector.Clone ());
673 public override bool Resolve (EmitContext ec)
675 ec.CurrentBranching.Label (vectors);
682 protected override void DoEmit (EmitContext ec)
685 ec.ig.MarkLabel (label);
691 /// `goto default' statement
693 public class GotoDefault : Statement {
695 public GotoDefault (Location l)
700 public override bool Resolve (EmitContext ec)
702 ec.CurrentBranching.CurrentUsageVector.Goto ();
706 protected override void DoEmit (EmitContext ec)
708 if (ec.Switch == null){
709 Report.Error (153, loc, "goto default is only valid in a switch statement");
713 if (!ec.Switch.GotDefault){
714 Report.Error (159, loc, "No default target on switch statement");
717 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
722 /// `goto case' statement
724 public class GotoCase : Statement {
728 public GotoCase (Expression e, Location l)
734 public override bool Resolve (EmitContext ec)
736 if (ec.Switch == null){
737 Report.Error (153, loc, "goto case is only valid in a switch statement");
741 expr = expr.Resolve (ec);
745 if (!(expr is Constant)){
746 Report.Error (159, loc, "Target expression for goto case is not constant");
750 object val = Expression.ConvertIntLiteral (
751 (Constant) expr, ec.Switch.SwitchType, loc);
756 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
761 "No such label 'case " + val + "': for the goto case");
765 label = sl.ILLabelCode;
767 ec.CurrentBranching.CurrentUsageVector.Goto ();
771 protected override void DoEmit (EmitContext ec)
773 ec.ig.Emit (OpCodes.Br, label);
777 public class Throw : Statement {
780 public Throw (Expression expr, Location l)
786 public override bool Resolve (EmitContext ec)
789 expr = expr.Resolve (ec);
793 ExprClass eclass = expr.eclass;
795 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
796 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
797 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
803 if ((t != TypeManager.exception_type) &&
804 !t.IsSubclassOf (TypeManager.exception_type) &&
805 !(expr is NullLiteral)) {
806 Report.Error (155, loc,
807 "The type caught or thrown must be derived " +
808 "from System.Exception");
813 ec.CurrentBranching.CurrentUsageVector.Throw ();
817 protected override void DoEmit (EmitContext ec)
821 ec.ig.Emit (OpCodes.Rethrow);
825 "A throw statement with no argument is only " +
826 "allowed in a catch clause");
833 ec.ig.Emit (OpCodes.Throw);
837 public class Break : Statement {
839 public Break (Location l)
844 public override bool Resolve (EmitContext ec)
846 ec.CurrentBranching.CurrentUsageVector.Break ();
850 protected override void DoEmit (EmitContext ec)
852 ILGenerator ig = ec.ig;
854 if (ec.InLoop == false && ec.Switch == null){
855 Report.Error (139, loc, "No enclosing loop or switch to continue to");
859 if (ec.InTry || ec.InCatch)
860 ig.Emit (OpCodes.Leave, ec.LoopEnd);
862 ig.Emit (OpCodes.Br, ec.LoopEnd);
866 public class Continue : Statement {
868 public Continue (Location l)
873 public override bool Resolve (EmitContext ec)
875 ec.CurrentBranching.CurrentUsageVector.Goto ();
879 protected override void DoEmit (EmitContext ec)
881 Label begin = ec.LoopBegin;
884 Report.Error (139, loc, "No enclosing loop to continue to");
889 // UGH: Non trivial. This Br might cross a try/catch boundary
893 // try { ... } catch { continue; }
897 // try {} catch { while () { continue; }}
899 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
900 ec.ig.Emit (OpCodes.Leave, begin);
901 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
902 throw new Exception ("Should never happen");
904 ec.ig.Emit (OpCodes.Br, begin);
908 public class LocalInfo {
909 public Expression Type;
912 // Most of the time a variable will be stored in a LocalBuilder
914 // But sometimes, it will be stored in a field. The context of the field will
915 // be stored in the EmitContext
918 public LocalBuilder LocalBuilder;
919 public FieldBuilder FieldBuilder;
921 public Type VariableType;
922 public readonly string Name;
923 public readonly Location Location;
924 public readonly Block Block;
926 public VariableInfo VariableInfo;
936 public LocalInfo (Expression type, string name, Block block, Location l)
944 public LocalInfo (TypeContainer tc, Block block, Location l)
946 VariableType = tc.TypeBuilder;
951 public bool IsThisAssigned (EmitContext ec, Location loc)
953 if (VariableInfo == null)
954 throw new Exception ();
956 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
959 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
962 public bool IsAssigned (EmitContext ec)
964 if (VariableInfo == null)
965 throw new Exception ();
967 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
970 public bool Resolve (DeclSpace decl)
972 if (VariableType == null)
973 VariableType = decl.ResolveType (Type, false, Location);
975 if (VariableType == null)
981 public void MakePinned ()
983 TypeManager.MakePinned (LocalBuilder);
984 flags |= Flags.Fixed;
987 public bool IsFixed {
989 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
996 public override string ToString ()
998 return String.Format ("LocalInfo ({0},{1},{2},{3})",
999 Name, Type, VariableInfo, Location);
1004 return (flags & Flags.Used) != 0;
1007 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1011 public bool ReadOnly {
1013 return (flags & Flags.ReadOnly) != 0;
1016 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1025 /// Block represents a C# block.
1029 /// This class is used in a number of places: either to represent
1030 /// explicit blocks that the programmer places or implicit blocks.
1032 /// Implicit blocks are used as labels or to introduce variable
1035 public class Block : Statement {
1036 public readonly Block Parent;
1037 public readonly Location StartLocation;
1038 public Location EndLocation = Location.Null;
1041 public enum Flags : byte {
1045 VariablesInitialized = 8,
1050 public bool Implicit {
1052 return (flags & Flags.Implicit) != 0;
1056 public bool Unchecked {
1058 return (flags & Flags.Unchecked) != 0;
1061 flags |= Flags.Unchecked;
1066 // The statements in this block
1068 ArrayList statements;
1071 // An array of Blocks. We keep track of children just
1072 // to generate the local variable declarations.
1074 // Statements and child statements are handled through the
1080 // Labels. (label, block) pairs.
1085 // Keeps track of (name, type) pairs
1087 Hashtable variables;
1090 // Keeps track of constants
1091 Hashtable constants;
1094 // If this is a switch section, the enclosing switch block.
1102 public Block (Block parent)
1103 : this (parent, (Flags) 0, Location.Null, Location.Null)
1106 public Block (Block parent, Flags flags)
1107 : this (parent, flags, Location.Null, Location.Null)
1110 public Block (Block parent, Flags flags, Parameters parameters)
1111 : this (parent, flags, parameters, Location.Null, Location.Null)
1114 public Block (Block parent, Location start, Location end)
1115 : this (parent, (Flags) 0, start, end)
1118 public Block (Block parent, Parameters parameters, Location start, Location end)
1119 : this (parent, (Flags) 0, parameters, start, end)
1122 public Block (Block parent, Flags flags, Location start, Location end)
1123 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1126 public Block (Block parent, Flags flags, Parameters parameters,
1127 Location start, Location end)
1130 parent.AddChild (this);
1132 this.Parent = parent;
1134 this.parameters = parameters;
1135 this.StartLocation = start;
1136 this.EndLocation = end;
1139 statements = new ArrayList ();
1142 public Block CreateSwitchBlock (Location start)
1144 Block new_block = new Block (this, start, start);
1145 new_block.switch_block = this;
1155 void AddChild (Block b)
1157 if (children == null)
1158 children = new ArrayList ();
1163 public void SetEndLocation (Location loc)
1169 /// Adds a label to the current block.
1173 /// false if the name already exists in this block. true
1177 public bool AddLabel (string name, LabeledStatement target)
1179 if (switch_block != null)
1180 return switch_block.AddLabel (name, target);
1183 labels = new Hashtable ();
1184 if (labels.Contains (name))
1187 labels.Add (name, target);
1191 public LabeledStatement LookupLabel (string name)
1193 Hashtable l = new Hashtable ();
1195 return LookupLabel (name, l);
1199 // Lookups a label in the current block, parents and children.
1200 // It skips during child recurssion on `source'
1202 LabeledStatement LookupLabel (string name, Hashtable seen)
1204 if (switch_block != null)
1205 return switch_block.LookupLabel (name, seen);
1207 if (seen [this] != null)
1213 if (labels.Contains (name))
1214 return ((LabeledStatement) labels [name]);
1216 if (children != null){
1217 foreach (Block b in children){
1218 LabeledStatement s = b.LookupLabel (name, seen);
1225 return Parent.LookupLabel (name, seen);
1230 LocalInfo this_variable = null;
1233 // Returns the "this" instance variable of this block.
1234 // See AddThisVariable() for more information.
1236 public LocalInfo ThisVariable {
1238 if (this_variable != null)
1239 return this_variable;
1240 else if (Parent != null)
1241 return Parent.ThisVariable;
1247 Hashtable child_variable_names;
1250 // Marks a variable with name @name as being used in a child block.
1251 // If a variable name has been used in a child block, it's illegal to
1252 // declare a variable with the same name in the current block.
1254 public void AddChildVariableName (string name)
1256 if (child_variable_names == null)
1257 child_variable_names = new Hashtable ();
1259 if (!child_variable_names.Contains (name))
1260 child_variable_names.Add (name, true);
1264 // Marks all variables from block @block and all its children as being
1265 // used in a child block.
1267 public void AddChildVariableNames (Block block)
1269 if (block.Variables != null) {
1270 foreach (string name in block.Variables.Keys)
1271 AddChildVariableName (name);
1274 if (block.children != null) {
1275 foreach (Block child in block.children)
1276 AddChildVariableNames (child);
1279 if (block.child_variable_names != null) {
1280 foreach (string name in block.child_variable_names.Keys)
1281 AddChildVariableName (name);
1286 // Checks whether a variable name has already been used in a child block.
1288 public bool IsVariableNameUsedInChildBlock (string name)
1290 if (child_variable_names == null)
1293 return child_variable_names.Contains (name);
1297 // This is used by non-static `struct' constructors which do not have an
1298 // initializer - in this case, the constructor must initialize all of the
1299 // struct's fields. To do this, we add a "this" variable and use the flow
1300 // analysis code to ensure that it's been fully initialized before control
1301 // leaves the constructor.
1303 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1305 if (this_variable != null)
1306 return this_variable;
1308 if (variables == null)
1309 variables = new Hashtable ();
1311 this_variable = new LocalInfo (tc, this, l);
1312 this_variable.Used = true;
1314 variables.Add ("this", this_variable);
1316 return this_variable;
1319 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1321 if (variables == null)
1322 variables = new Hashtable ();
1324 LocalInfo vi = GetLocalInfo (name);
1326 if (vi.Block != this)
1327 Report.Error (136, l, "A local variable named `" + name + "' " +
1328 "cannot be declared in this scope since it would " +
1329 "give a different meaning to `" + name + "', which " +
1330 "is already used in a `parent or current' scope to " +
1331 "denote something else");
1333 Report.Error (128, l, "A local variable `" + name + "' is already " +
1334 "defined in this scope");
1338 if (IsVariableNameUsedInChildBlock (name)) {
1339 Report.Error (136, l, "A local variable named `" + name + "' " +
1340 "cannot be declared in this scope since it would " +
1341 "give a different meaning to `" + name + "', which " +
1342 "is already used in a `child' scope to denote something " +
1349 Parameter p = pars.GetParameterByName (name, out idx);
1351 Report.Error (136, l, "A local variable named `" + name + "' " +
1352 "cannot be declared in this scope since it would " +
1353 "give a different meaning to `" + name + "', which " +
1354 "is already used in a `parent or current' scope to " +
1355 "denote something else");
1360 vi = new LocalInfo (type, name, this, l);
1362 variables.Add (name, vi);
1364 if ((flags & Flags.VariablesInitialized) != 0)
1365 throw new Exception ();
1367 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1371 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1373 if (AddVariable (type, name, pars, l) == null)
1376 if (constants == null)
1377 constants = new Hashtable ();
1379 constants.Add (name, value);
1383 public Hashtable Variables {
1389 public LocalInfo GetLocalInfo (string name)
1391 for (Block b = this; b != null; b = b.Parent) {
1392 if (b.variables != null) {
1393 LocalInfo ret = b.variables [name] as LocalInfo;
1401 public Expression GetVariableType (string name)
1403 LocalInfo vi = GetLocalInfo (name);
1411 public Expression GetConstantExpression (string name)
1413 for (Block b = this; b != null; b = b.Parent) {
1414 if (b.constants != null) {
1415 Expression ret = b.constants [name] as Expression;
1424 /// True if the variable named @name is a constant
1426 public bool IsConstant (string name)
1428 Expression e = null;
1430 e = GetConstantExpression (name);
1436 /// Use to fetch the statement associated with this label
1438 public Statement this [string name] {
1440 return (Statement) labels [name];
1444 Parameters parameters = null;
1445 public Parameters Parameters {
1448 while (b.Parent != null)
1450 return b.parameters;
1455 /// A list of labels that were not used within this block
1457 public string [] GetUnreferenced ()
1459 // FIXME: Implement me
1463 public void AddStatement (Statement s)
1466 flags |= Flags.BlockUsed;
1471 return (flags & Flags.BlockUsed) != 0;
1477 flags |= Flags.BlockUsed;
1480 public bool HasRet {
1482 return (flags & Flags.HasRet) != 0;
1486 VariableMap param_map, local_map;
1488 public VariableMap ParameterMap {
1490 if ((flags & Flags.VariablesInitialized) == 0)
1491 throw new Exception ();
1497 public VariableMap LocalMap {
1499 if ((flags & Flags.VariablesInitialized) == 0)
1500 throw new Exception ();
1506 public bool LiftVariable (LocalInfo local_info)
1512 /// Emits the variable declarations and labels.
1515 /// tc: is our typecontainer (to resolve type references)
1516 /// ig: is the code generator:
1518 public void EmitMeta (EmitContext ec, InternalParameters ip)
1520 ILGenerator ig = ec.ig;
1523 // Compute the VariableMap's.
1525 // Unfortunately, we don't know the type when adding variables with
1526 // AddVariable(), so we need to compute this info here.
1530 if (variables != null) {
1531 foreach (LocalInfo li in variables.Values)
1532 li.Resolve (ec.DeclSpace);
1534 locals = new LocalInfo [variables.Count];
1535 variables.Values.CopyTo (locals, 0);
1537 locals = new LocalInfo [0];
1540 local_map = new VariableMap (Parent.LocalMap, locals);
1542 local_map = new VariableMap (locals);
1544 param_map = new VariableMap (ip);
1545 flags |= Flags.VariablesInitialized;
1547 bool old_check_state = ec.ConstantCheckState;
1548 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1549 bool remap_locals = ec.RemapToProxy;
1552 // Process this block variables
1554 if (variables != null){
1555 foreach (DictionaryEntry de in variables){
1556 string name = (string) de.Key;
1557 LocalInfo vi = (LocalInfo) de.Value;
1559 if (vi.VariableType == null)
1562 Type variable_type = vi.VariableType;
1564 if (variable_type.IsPointer){
1566 // Am not really convinced that this test is required (Microsoft does it)
1567 // but the fact is that you would not be able to use the pointer variable
1570 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1576 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1578 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1580 if (constants == null)
1583 Expression cv = (Expression) constants [name];
1587 ec.CurrentBlock = this;
1588 Expression e = cv.Resolve (ec);
1592 Constant ce = e as Constant;
1594 Report.Error (133, vi.Location,
1595 "The expression being assigned to `" +
1596 name + "' must be constant (" + e + ")");
1600 if (e.Type != variable_type){
1601 e = Const.ChangeType (vi.Location, ce, variable_type);
1606 constants.Remove (name);
1607 constants.Add (name, e);
1610 ec.ConstantCheckState = old_check_state;
1613 // Now, handle the children
1615 if (children != null){
1616 foreach (Block b in children)
1617 b.EmitMeta (ec, ip);
1621 void UsageWarning (FlowBranching.UsageVector vector)
1625 if (variables != null){
1626 foreach (DictionaryEntry de in variables){
1627 LocalInfo vi = (LocalInfo) de.Value;
1632 name = (string) de.Key;
1634 if (vector.IsAssigned (vi.VariableInfo)){
1636 219, vi.Location, "The variable `" + name +
1637 "' is assigned but its value is never used");
1640 168, vi.Location, "The variable `" +
1642 "' is declared but never used");
1648 public override bool Resolve (EmitContext ec)
1650 Block prev_block = ec.CurrentBlock;
1653 int errors = Report.Errors;
1655 ec.CurrentBlock = this;
1656 ec.StartFlowBranching (this);
1658 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1660 bool unreachable = false, warning_shown = false;
1662 int statement_count = statements.Count;
1663 for (int ix = 0; ix < statement_count; ix++){
1664 Statement s = (Statement) statements [ix];
1666 if (unreachable && !(s is LabeledStatement)) {
1667 if (!warning_shown && s != EmptyStatement.Value) {
1668 warning_shown = true;
1669 Warning_DeadCodeFound (s.loc);
1672 statements [ix] = EmptyStatement.Value;
1676 if (s.Resolve (ec) == false) {
1678 statements [ix] = EmptyStatement.Value;
1682 if (s is LabeledStatement)
1683 unreachable = false;
1685 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1688 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
1691 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1693 ec.CurrentBlock = prev_block;
1695 // If we're a non-static `struct' constructor which doesn't have an
1696 // initializer, then we must initialize all of the struct's fields.
1697 if ((this_variable != null) &&
1698 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1699 !this_variable.IsThisAssigned (ec, loc))
1702 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1703 foreach (LabeledStatement label in labels.Values)
1704 if (!label.HasBeenReferenced)
1705 Report.Warning (164, label.Location,
1706 "This label has not been referenced");
1709 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1711 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1712 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1713 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1714 flags |= Flags.HasRet;
1716 if (ok && (errors == Report.Errors)) {
1717 if (RootContext.WarningLevel >= 3)
1718 UsageWarning (vector);
1724 protected override void DoEmit (EmitContext ec)
1726 int statement_count = statements.Count;
1727 for (int ix = 0; ix < statement_count; ix++){
1728 Statement s = (Statement) statements [ix];
1733 public override void Emit (EmitContext ec)
1735 Block prev_block = ec.CurrentBlock;
1737 ec.CurrentBlock = this;
1739 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1740 bool is_lexical_block = !Implicit && (Parent != null);
1742 if (emit_debug_info) {
1743 if (is_lexical_block)
1744 ec.ig.BeginScope ();
1746 if (variables != null) {
1747 foreach (DictionaryEntry de in variables) {
1748 string name = (string) de.Key;
1749 LocalInfo vi = (LocalInfo) de.Value;
1751 if (vi.LocalBuilder == null)
1754 vi.LocalBuilder.SetLocalSymInfo (name);
1759 ec.Mark (StartLocation, true);
1761 ec.Mark (EndLocation, true);
1763 if (emit_debug_info && is_lexical_block)
1766 ec.CurrentBlock = prev_block;
1770 public class SwitchLabel {
1773 public Location loc;
1774 public Label ILLabel;
1775 public Label ILLabelCode;
1778 // if expr == null, then it is the default case.
1780 public SwitchLabel (Expression expr, Location l)
1786 public Expression Label {
1792 public object Converted {
1799 // Resolves the expression, reduces it to a literal if possible
1800 // and then converts it to the requested type.
1802 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1804 ILLabel = ec.ig.DefineLabel ();
1805 ILLabelCode = ec.ig.DefineLabel ();
1810 Expression e = label.Resolve (ec);
1815 if (!(e is Constant)){
1816 Report.Error (150, loc, "A constant value is expected, got: " + e);
1820 if (e is StringConstant || e is NullLiteral){
1821 if (required_type == TypeManager.string_type){
1823 ILLabel = ec.ig.DefineLabel ();
1828 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1829 if (converted == null)
1836 public class SwitchSection {
1837 // An array of SwitchLabels.
1838 public readonly ArrayList Labels;
1839 public readonly Block Block;
1841 public SwitchSection (ArrayList labels, Block block)
1848 public class Switch : Statement {
1849 public readonly ArrayList Sections;
1850 public Expression Expr;
1853 /// Maps constants whose type type SwitchType to their SwitchLabels.
1855 public Hashtable Elements;
1858 /// The governing switch type
1860 public Type SwitchType;
1866 Label default_target;
1867 Expression new_expr;
1870 // The types allowed to be implicitly cast from
1871 // on the governing type
1873 static Type [] allowed_types;
1875 public Switch (Expression e, ArrayList sects, Location l)
1882 public bool GotDefault {
1888 public Label DefaultTarget {
1890 return default_target;
1895 // Determines the governing type for a switch. The returned
1896 // expression might be the expression from the switch, or an
1897 // expression that includes any potential conversions to the
1898 // integral types or to string.
1900 Expression SwitchGoverningType (EmitContext ec, Type t)
1902 if (t == TypeManager.int32_type ||
1903 t == TypeManager.uint32_type ||
1904 t == TypeManager.char_type ||
1905 t == TypeManager.byte_type ||
1906 t == TypeManager.sbyte_type ||
1907 t == TypeManager.ushort_type ||
1908 t == TypeManager.short_type ||
1909 t == TypeManager.uint64_type ||
1910 t == TypeManager.int64_type ||
1911 t == TypeManager.string_type ||
1912 t == TypeManager.bool_type ||
1913 t.IsSubclassOf (TypeManager.enum_type))
1916 if (allowed_types == null){
1917 allowed_types = new Type [] {
1918 TypeManager.sbyte_type,
1919 TypeManager.byte_type,
1920 TypeManager.short_type,
1921 TypeManager.ushort_type,
1922 TypeManager.int32_type,
1923 TypeManager.uint32_type,
1924 TypeManager.int64_type,
1925 TypeManager.uint64_type,
1926 TypeManager.char_type,
1927 TypeManager.bool_type,
1928 TypeManager.string_type
1933 // Try to find a *user* defined implicit conversion.
1935 // If there is no implicit conversion, or if there are multiple
1936 // conversions, we have to report an error
1938 Expression converted = null;
1939 foreach (Type tt in allowed_types){
1942 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
1946 if (converted != null){
1947 Report.Error (-12, loc, "More than one conversion to an integral " +
1948 " type exists for type `" +
1949 TypeManager.CSharpName (Expr.Type)+"'");
1957 void error152 (string n)
1960 152, "The label `" + n + ":' " +
1961 "is already present on this switch statement");
1965 // Performs the basic sanity checks on the switch statement
1966 // (looks for duplicate keys and non-constant expressions).
1968 // It also returns a hashtable with the keys that we will later
1969 // use to compute the switch tables
1971 bool CheckSwitch (EmitContext ec)
1975 Elements = new Hashtable ();
1977 got_default = false;
1979 if (TypeManager.IsEnumType (SwitchType)){
1980 compare_type = TypeManager.EnumToUnderlying (SwitchType);
1982 compare_type = SwitchType;
1984 foreach (SwitchSection ss in Sections){
1985 foreach (SwitchLabel sl in ss.Labels){
1986 if (!sl.ResolveAndReduce (ec, SwitchType)){
1991 if (sl.Label == null){
1993 error152 ("default");
2000 object key = sl.Converted;
2002 if (key is Constant)
2003 key = ((Constant) key).GetValue ();
2006 key = NullLiteral.Null;
2008 string lname = null;
2009 if (compare_type == TypeManager.uint64_type){
2010 ulong v = (ulong) key;
2012 if (Elements.Contains (v))
2013 lname = v.ToString ();
2015 Elements.Add (v, sl);
2016 } else if (compare_type == TypeManager.int64_type){
2017 long v = (long) key;
2019 if (Elements.Contains (v))
2020 lname = v.ToString ();
2022 Elements.Add (v, sl);
2023 } else if (compare_type == TypeManager.uint32_type){
2024 uint v = (uint) key;
2026 if (Elements.Contains (v))
2027 lname = v.ToString ();
2029 Elements.Add (v, sl);
2030 } else if (compare_type == TypeManager.char_type){
2031 char v = (char) key;
2033 if (Elements.Contains (v))
2034 lname = v.ToString ();
2036 Elements.Add (v, sl);
2037 } else if (compare_type == TypeManager.byte_type){
2038 byte v = (byte) key;
2040 if (Elements.Contains (v))
2041 lname = v.ToString ();
2043 Elements.Add (v, sl);
2044 } else if (compare_type == TypeManager.sbyte_type){
2045 sbyte v = (sbyte) key;
2047 if (Elements.Contains (v))
2048 lname = v.ToString ();
2050 Elements.Add (v, sl);
2051 } else if (compare_type == TypeManager.short_type){
2052 short v = (short) key;
2054 if (Elements.Contains (v))
2055 lname = v.ToString ();
2057 Elements.Add (v, sl);
2058 } else if (compare_type == TypeManager.ushort_type){
2059 ushort v = (ushort) key;
2061 if (Elements.Contains (v))
2062 lname = v.ToString ();
2064 Elements.Add (v, sl);
2065 } else if (compare_type == TypeManager.string_type){
2066 if (key is NullLiteral){
2067 if (Elements.Contains (NullLiteral.Null))
2070 Elements.Add (NullLiteral.Null, null);
2072 string s = (string) key;
2074 if (Elements.Contains (s))
2077 Elements.Add (s, sl);
2079 } else if (compare_type == TypeManager.int32_type) {
2082 if (Elements.Contains (v))
2083 lname = v.ToString ();
2085 Elements.Add (v, sl);
2086 } else if (compare_type == TypeManager.bool_type) {
2087 bool v = (bool) key;
2089 if (Elements.Contains (v))
2090 lname = v.ToString ();
2092 Elements.Add (v, sl);
2096 throw new Exception ("Unknown switch type!" +
2097 SwitchType + " " + compare_type);
2101 error152 ("case + " + lname);
2112 void EmitObjectInteger (ILGenerator ig, object k)
2115 IntConstant.EmitInt (ig, (int) k);
2116 else if (k is Constant) {
2117 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2120 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2123 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2125 IntConstant.EmitInt (ig, (int) (long) k);
2126 ig.Emit (OpCodes.Conv_I8);
2129 LongConstant.EmitLong (ig, (long) k);
2131 else if (k is ulong)
2133 if ((ulong) k < (1L<<32))
2135 IntConstant.EmitInt (ig, (int) (long) k);
2136 ig.Emit (OpCodes.Conv_U8);
2140 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2144 IntConstant.EmitInt (ig, (int) ((char) k));
2145 else if (k is sbyte)
2146 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2148 IntConstant.EmitInt (ig, (int) ((byte) k));
2149 else if (k is short)
2150 IntConstant.EmitInt (ig, (int) ((short) k));
2151 else if (k is ushort)
2152 IntConstant.EmitInt (ig, (int) ((ushort) k));
2154 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2156 throw new Exception ("Unhandled case");
2159 // structure used to hold blocks of keys while calculating table switch
2160 class KeyBlock : IComparable
2162 public KeyBlock (long _nFirst)
2164 nFirst = nLast = _nFirst;
2168 public ArrayList rgKeys = null;
2171 get { return (int) (nLast - nFirst + 1); }
2173 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2175 return kbLast.nLast - kbFirst.nFirst + 1;
2177 public int CompareTo (object obj)
2179 KeyBlock kb = (KeyBlock) obj;
2180 int nLength = Length;
2181 int nLengthOther = kb.Length;
2182 if (nLengthOther == nLength)
2183 return (int) (kb.nFirst - nFirst);
2184 return nLength - nLengthOther;
2189 /// This method emits code for a lookup-based switch statement (non-string)
2190 /// Basically it groups the cases into blocks that are at least half full,
2191 /// and then spits out individual lookup opcodes for each block.
2192 /// It emits the longest blocks first, and short blocks are just
2193 /// handled with direct compares.
2195 /// <param name="ec"></param>
2196 /// <param name="val"></param>
2197 /// <returns></returns>
2198 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2200 int cElements = Elements.Count;
2201 object [] rgKeys = new object [cElements];
2202 Elements.Keys.CopyTo (rgKeys, 0);
2203 Array.Sort (rgKeys);
2205 // initialize the block list with one element per key
2206 ArrayList rgKeyBlocks = new ArrayList ();
2207 foreach (object key in rgKeys)
2208 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2211 // iteratively merge the blocks while they are at least half full
2212 // there's probably a really cool way to do this with a tree...
2213 while (rgKeyBlocks.Count > 1)
2215 ArrayList rgKeyBlocksNew = new ArrayList ();
2216 kbCurr = (KeyBlock) rgKeyBlocks [0];
2217 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2219 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2220 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2223 kbCurr.nLast = kb.nLast;
2227 // start a new block
2228 rgKeyBlocksNew.Add (kbCurr);
2232 rgKeyBlocksNew.Add (kbCurr);
2233 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2235 rgKeyBlocks = rgKeyBlocksNew;
2238 // initialize the key lists
2239 foreach (KeyBlock kb in rgKeyBlocks)
2240 kb.rgKeys = new ArrayList ();
2242 // fill the key lists
2244 if (rgKeyBlocks.Count > 0) {
2245 kbCurr = (KeyBlock) rgKeyBlocks [0];
2246 foreach (object key in rgKeys)
2248 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2249 System.Convert.ToInt64 (key) > kbCurr.nLast;
2251 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2252 kbCurr.rgKeys.Add (key);
2256 // sort the blocks so we can tackle the largest ones first
2257 rgKeyBlocks.Sort ();
2259 // okay now we can start...
2260 ILGenerator ig = ec.ig;
2261 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2262 Label lblDefault = ig.DefineLabel ();
2264 Type typeKeys = null;
2265 if (rgKeys.Length > 0)
2266 typeKeys = rgKeys [0].GetType (); // used for conversions
2270 if (TypeManager.IsEnumType (SwitchType))
2271 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2273 compare_type = SwitchType;
2275 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2277 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2278 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2281 foreach (object key in kb.rgKeys)
2283 ig.Emit (OpCodes.Ldloc, val);
2284 EmitObjectInteger (ig, key);
2285 SwitchLabel sl = (SwitchLabel) Elements [key];
2286 ig.Emit (OpCodes.Beq, sl.ILLabel);
2291 // TODO: if all the keys in the block are the same and there are
2292 // no gaps/defaults then just use a range-check.
2293 if (compare_type == TypeManager.int64_type ||
2294 compare_type == TypeManager.uint64_type)
2296 // TODO: optimize constant/I4 cases
2298 // check block range (could be > 2^31)
2299 ig.Emit (OpCodes.Ldloc, val);
2300 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2301 ig.Emit (OpCodes.Blt, lblDefault);
2302 ig.Emit (OpCodes.Ldloc, val);
2303 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2304 ig.Emit (OpCodes.Bgt, lblDefault);
2307 ig.Emit (OpCodes.Ldloc, val);
2310 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2311 ig.Emit (OpCodes.Sub);
2313 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2318 ig.Emit (OpCodes.Ldloc, val);
2319 int nFirst = (int) kb.nFirst;
2322 IntConstant.EmitInt (ig, nFirst);
2323 ig.Emit (OpCodes.Sub);
2325 else if (nFirst < 0)
2327 IntConstant.EmitInt (ig, -nFirst);
2328 ig.Emit (OpCodes.Add);
2332 // first, build the list of labels for the switch
2334 int cJumps = kb.Length;
2335 Label [] rgLabels = new Label [cJumps];
2336 for (int iJump = 0; iJump < cJumps; iJump++)
2338 object key = kb.rgKeys [iKey];
2339 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2341 SwitchLabel sl = (SwitchLabel) Elements [key];
2342 rgLabels [iJump] = sl.ILLabel;
2346 rgLabels [iJump] = lblDefault;
2348 // emit the switch opcode
2349 ig.Emit (OpCodes.Switch, rgLabels);
2352 // mark the default for this block
2354 ig.MarkLabel (lblDefault);
2357 // TODO: find the default case and emit it here,
2358 // to prevent having to do the following jump.
2359 // make sure to mark other labels in the default section
2361 // the last default just goes to the end
2362 ig.Emit (OpCodes.Br, lblDefault);
2364 // now emit the code for the sections
2365 bool fFoundDefault = false;
2366 foreach (SwitchSection ss in Sections)
2368 foreach (SwitchLabel sl in ss.Labels)
2370 ig.MarkLabel (sl.ILLabel);
2371 ig.MarkLabel (sl.ILLabelCode);
2372 if (sl.Label == null)
2374 ig.MarkLabel (lblDefault);
2375 fFoundDefault = true;
2379 //ig.Emit (OpCodes.Br, lblEnd);
2382 if (!fFoundDefault) {
2383 ig.MarkLabel (lblDefault);
2385 ig.MarkLabel (lblEnd);
2388 // This simple emit switch works, but does not take advantage of the
2390 // TODO: remove non-string logic from here
2391 // TODO: binary search strings?
2393 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2395 ILGenerator ig = ec.ig;
2396 Label end_of_switch = ig.DefineLabel ();
2397 Label next_test = ig.DefineLabel ();
2398 Label null_target = ig.DefineLabel ();
2399 bool default_found = false;
2400 bool first_test = true;
2401 bool pending_goto_end = false;
2404 ig.Emit (OpCodes.Ldloc, val);
2406 if (Elements.Contains (NullLiteral.Null)){
2407 ig.Emit (OpCodes.Brfalse, null_target);
2409 ig.Emit (OpCodes.Brfalse, default_target);
2411 ig.Emit (OpCodes.Ldloc, val);
2412 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2413 ig.Emit (OpCodes.Stloc, val);
2415 int section_count = Sections.Count;
2416 for (int section = 0; section < section_count; section++){
2417 SwitchSection ss = (SwitchSection) Sections [section];
2418 Label sec_begin = ig.DefineLabel ();
2420 if (pending_goto_end)
2421 ig.Emit (OpCodes.Br, end_of_switch);
2423 int label_count = ss.Labels.Count;
2425 for (int label = 0; label < label_count; label++){
2426 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2427 ig.MarkLabel (sl.ILLabel);
2430 ig.MarkLabel (next_test);
2431 next_test = ig.DefineLabel ();
2434 // If we are the default target
2436 if (sl.Label == null){
2437 ig.MarkLabel (default_target);
2438 default_found = true;
2440 object lit = sl.Converted;
2442 if (lit is NullLiteral){
2444 if (label_count == 1)
2445 ig.Emit (OpCodes.Br, next_test);
2449 StringConstant str = (StringConstant) lit;
2451 ig.Emit (OpCodes.Ldloc, val);
2452 ig.Emit (OpCodes.Ldstr, str.Value);
2453 if (label_count == 1)
2454 ig.Emit (OpCodes.Bne_Un, next_test);
2456 if (label+1 == label_count)
2457 ig.Emit (OpCodes.Bne_Un, next_test);
2459 ig.Emit (OpCodes.Beq, sec_begin);
2464 ig.MarkLabel (null_target);
2465 ig.MarkLabel (sec_begin);
2466 foreach (SwitchLabel sl in ss.Labels)
2467 ig.MarkLabel (sl.ILLabelCode);
2470 pending_goto_end = !ss.Block.HasRet;
2473 if (!default_found){
2474 ig.MarkLabel (default_target);
2476 ig.MarkLabel (next_test);
2477 ig.MarkLabel (end_of_switch);
2480 public override bool Resolve (EmitContext ec)
2482 Expr = Expr.Resolve (ec);
2486 new_expr = SwitchGoverningType (ec, Expr.Type);
2487 if (new_expr == null){
2488 Report.Error (151, loc, "An integer type or string was expected for switch");
2493 SwitchType = new_expr.Type;
2495 if (!CheckSwitch (ec))
2498 Switch old_switch = ec.Switch;
2500 ec.Switch.SwitchType = SwitchType;
2502 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2505 foreach (SwitchSection ss in Sections){
2507 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2511 if (ss.Block.Resolve (ec) != true)
2517 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2519 ec.EndFlowBranching ();
2520 ec.Switch = old_switch;
2525 protected override void DoEmit (EmitContext ec)
2527 // Store variable for comparission purposes
2528 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2530 ec.ig.Emit (OpCodes.Stloc, value);
2532 ILGenerator ig = ec.ig;
2534 default_target = ig.DefineLabel ();
2537 // Setup the codegen context
2539 Label old_end = ec.LoopEnd;
2540 Switch old_switch = ec.Switch;
2542 ec.LoopEnd = ig.DefineLabel ();
2546 if (SwitchType == TypeManager.string_type)
2547 SimpleSwitchEmit (ec, value);
2549 TableSwitchEmit (ec, value);
2551 // Restore context state.
2552 ig.MarkLabel (ec.LoopEnd);
2555 // Restore the previous context
2557 ec.LoopEnd = old_end;
2558 ec.Switch = old_switch;
2562 public class Lock : Statement {
2564 Statement Statement;
2566 public Lock (Expression expr, Statement stmt, Location l)
2573 public override bool Resolve (EmitContext ec)
2575 expr = expr.Resolve (ec);
2576 return Statement.Resolve (ec) && expr != null;
2579 protected override void DoEmit (EmitContext ec)
2581 Type type = expr.Type;
2583 if (type.IsValueType){
2584 Report.Error (185, loc, "lock statement requires the expression to be " +
2585 " a reference type (type is: `" +
2586 TypeManager.CSharpName (type) + "'");
2590 ILGenerator ig = ec.ig;
2591 LocalBuilder temp = ig.DeclareLocal (type);
2594 ig.Emit (OpCodes.Dup);
2595 ig.Emit (OpCodes.Stloc, temp);
2596 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2599 ig.BeginExceptionBlock ();
2600 bool old_in_try = ec.InTry;
2602 Label finish = ig.DefineLabel ();
2603 Statement.Emit (ec);
2604 ec.InTry = old_in_try;
2605 // ig.Emit (OpCodes.Leave, finish);
2607 ig.MarkLabel (finish);
2610 ig.BeginFinallyBlock ();
2611 ig.Emit (OpCodes.Ldloc, temp);
2612 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2613 ig.EndExceptionBlock ();
2617 public class Unchecked : Statement {
2618 public readonly Block Block;
2620 public Unchecked (Block b)
2626 public override bool Resolve (EmitContext ec)
2628 bool previous_state = ec.CheckState;
2629 bool previous_state_const = ec.ConstantCheckState;
2631 ec.CheckState = false;
2632 ec.ConstantCheckState = false;
2633 bool ret = Block.Resolve (ec);
2634 ec.CheckState = previous_state;
2635 ec.ConstantCheckState = previous_state_const;
2640 protected override void DoEmit (EmitContext ec)
2642 bool previous_state = ec.CheckState;
2643 bool previous_state_const = ec.ConstantCheckState;
2645 ec.CheckState = false;
2646 ec.ConstantCheckState = false;
2648 ec.CheckState = previous_state;
2649 ec.ConstantCheckState = previous_state_const;
2653 public class Checked : Statement {
2654 public readonly Block Block;
2656 public Checked (Block b)
2659 b.Unchecked = false;
2662 public override bool Resolve (EmitContext ec)
2664 bool previous_state = ec.CheckState;
2665 bool previous_state_const = ec.ConstantCheckState;
2667 ec.CheckState = true;
2668 ec.ConstantCheckState = true;
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 = true;
2682 ec.ConstantCheckState = true;
2684 ec.CheckState = previous_state;
2685 ec.ConstantCheckState = previous_state_const;
2689 public class Unsafe : Statement {
2690 public readonly Block Block;
2692 public Unsafe (Block b)
2697 public override bool Resolve (EmitContext ec)
2699 bool previous_state = ec.InUnsafe;
2703 val = Block.Resolve (ec);
2704 ec.InUnsafe = previous_state;
2709 protected override void DoEmit (EmitContext ec)
2711 bool previous_state = ec.InUnsafe;
2715 ec.InUnsafe = previous_state;
2722 public class Fixed : Statement {
2724 ArrayList declarators;
2725 Statement statement;
2731 public bool is_object;
2732 public LocalInfo vi;
2733 public Expression expr;
2734 public Expression converted;
2737 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2740 declarators = decls;
2745 public override bool Resolve (EmitContext ec)
2748 Expression.UnsafeError (loc);
2752 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2753 if (expr_type == null)
2756 if (ec.RemapToProxy){
2757 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2761 data = new FixedData [declarators.Count];
2763 if (!expr_type.IsPointer){
2764 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2769 foreach (Pair p in declarators){
2770 LocalInfo vi = (LocalInfo) p.First;
2771 Expression e = (Expression) p.Second;
2773 vi.VariableInfo = null;
2777 // The rules for the possible declarators are pretty wise,
2778 // but the production on the grammar is more concise.
2780 // So we have to enforce these rules here.
2782 // We do not resolve before doing the case 1 test,
2783 // because the grammar is explicit in that the token &
2784 // is present, so we need to test for this particular case.
2788 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2793 // Case 1: & object.
2795 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2796 Expression child = ((Unary) e).Expr;
2799 if (child is ParameterReference || child is LocalVariableReference){
2802 "No need to use fixed statement for parameters or " +
2803 "local variable declarations (address is already " +
2808 ec.InFixedInitializer = true;
2810 ec.InFixedInitializer = false;
2814 child = ((Unary) e).Expr;
2816 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2819 data [i].is_object = true;
2821 data [i].converted = null;
2828 ec.InFixedInitializer = true;
2830 ec.InFixedInitializer = false;
2837 if (e.Type.IsArray){
2838 Type array_type = TypeManager.GetElementType (e.Type);
2842 // Provided that array_type is unmanaged,
2844 if (!TypeManager.VerifyUnManaged (array_type, loc))
2848 // and T* is implicitly convertible to the
2849 // pointer type given in the fixed statement.
2851 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2853 Expression converted = Convert.ImplicitConversionRequired (
2854 ec, array_ptr, vi.VariableType, loc);
2855 if (converted == null)
2858 data [i].is_object = false;
2860 data [i].converted = converted;
2870 if (e.Type == TypeManager.string_type){
2871 data [i].is_object = false;
2873 data [i].converted = null;
2880 // For other cases, flag a `this is already fixed expression'
2882 if (e is LocalVariableReference || e is ParameterReference ||
2883 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
2885 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
2889 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
2893 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
2895 if (!statement.Resolve (ec)) {
2896 ec.KillFlowBranching ();
2900 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2901 has_ret = reachability.IsUnreachable;
2906 protected override void DoEmit (EmitContext ec)
2908 ILGenerator ig = ec.ig;
2910 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
2912 for (int i = 0; i < data.Length; i++) {
2913 LocalInfo vi = data [i].vi;
2916 // Case 1: & object.
2918 if (data [i].is_object) {
2920 // Store pointer in pinned location
2922 data [i].expr.Emit (ec);
2923 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2924 clear_list [i] = vi.LocalBuilder;
2931 if (data [i].expr.Type.IsArray){
2933 // Store pointer in pinned location
2935 data [i].converted.Emit (ec);
2937 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2938 clear_list [i] = vi.LocalBuilder;
2945 if (data [i].expr.Type == TypeManager.string_type){
2946 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
2947 TypeManager.MakePinned (pinned_string);
2948 clear_list [i] = pinned_string;
2950 data [i].expr.Emit (ec);
2951 ig.Emit (OpCodes.Stloc, pinned_string);
2953 Expression sptr = new StringPtr (pinned_string, loc);
2954 Expression converted = Convert.ImplicitConversionRequired (
2955 ec, sptr, vi.VariableType, loc);
2957 if (converted == null)
2960 converted.Emit (ec);
2961 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2965 statement.Emit (ec);
2971 // Clear the pinned variable
2973 for (int i = 0; i < data.Length; i++) {
2974 if (data [i].is_object || data [i].expr.Type.IsArray) {
2975 ig.Emit (OpCodes.Ldc_I4_0);
2976 ig.Emit (OpCodes.Conv_U);
2977 ig.Emit (OpCodes.Stloc, clear_list [i]);
2978 } else if (data [i].expr.Type == TypeManager.string_type){
2979 ig.Emit (OpCodes.Ldnull);
2980 ig.Emit (OpCodes.Stloc, clear_list [i]);
2986 public class Catch {
2987 public readonly string Name;
2988 public readonly Block Block;
2989 public readonly Location Location;
2991 Expression type_expr;
2994 public Catch (Expression type, string name, Block block, Location l)
3002 public Type CatchType {
3008 public bool IsGeneral {
3010 return type_expr == null;
3014 public bool Resolve (EmitContext ec)
3016 if (type_expr != null) {
3017 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3021 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3022 Report.Error (155, Location,
3023 "The type caught or thrown must be derived " +
3024 "from System.Exception");
3030 if (!Block.Resolve (ec))
3037 public class Try : Statement {
3038 public readonly Block Fini, Block;
3039 public readonly ArrayList Specific;
3040 public readonly Catch General;
3043 // specific, general and fini might all be null.
3045 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3047 if (specific == null && general == null){
3048 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3052 this.Specific = specific;
3053 this.General = general;
3058 public override bool Resolve (EmitContext ec)
3062 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3064 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3066 bool old_in_try = ec.InTry;
3069 if (!Block.Resolve (ec))
3072 ec.InTry = old_in_try;
3074 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3076 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3078 foreach (Catch c in Specific){
3079 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3080 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3082 if (c.Name != null) {
3083 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3085 throw new Exception ();
3087 vi.VariableInfo = null;
3090 bool old_in_catch = ec.InCatch;
3093 if (!c.Resolve (ec))
3096 ec.InCatch = old_in_catch;
3099 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3101 if (General != null){
3102 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3103 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3105 bool old_in_catch = ec.InCatch;
3108 if (!General.Resolve (ec))
3111 ec.InCatch = old_in_catch;
3114 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3118 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
3119 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3121 bool old_in_finally = ec.InFinally;
3122 ec.InFinally = true;
3124 if (!Fini.Resolve (ec))
3127 ec.InFinally = old_in_finally;
3130 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3132 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3134 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3136 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3137 // Unfortunately, System.Reflection.Emit automatically emits a leave
3138 // to the end of the finally block. This is a problem if `returns'
3139 // is true since we may jump to a point after the end of the method.
3140 // As a workaround, emit an explicit ret here.
3141 ec.NeedExplicitReturn = true;
3147 protected override void DoEmit (EmitContext ec)
3149 ILGenerator ig = ec.ig;
3150 Label finish = ig.DefineLabel ();;
3153 ig.BeginExceptionBlock ();
3154 bool old_in_try = ec.InTry;
3157 ec.InTry = old_in_try;
3160 // System.Reflection.Emit provides this automatically:
3161 // ig.Emit (OpCodes.Leave, finish);
3163 bool old_in_catch = ec.InCatch;
3166 foreach (Catch c in Specific){
3169 ig.BeginCatchBlock (c.CatchType);
3171 if (c.Name != null){
3172 vi = c.Block.GetLocalInfo (c.Name);
3174 throw new Exception ("Variable does not exist in this block");
3176 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3178 ig.Emit (OpCodes.Pop);
3183 if (General != null){
3184 ig.BeginCatchBlock (TypeManager.object_type);
3185 ig.Emit (OpCodes.Pop);
3186 General.Block.Emit (ec);
3188 ec.InCatch = old_in_catch;
3190 ig.MarkLabel (finish);
3192 ig.BeginFinallyBlock ();
3193 bool old_in_finally = ec.InFinally;
3194 ec.InFinally = true;
3196 ec.InFinally = old_in_finally;
3199 ig.EndExceptionBlock ();
3204 public class Using : Statement {
3205 object expression_or_block;
3206 Statement Statement;
3211 Expression [] converted_vars;
3212 ExpressionStatement [] assign;
3214 public Using (object expression_or_block, Statement stmt, Location l)
3216 this.expression_or_block = expression_or_block;
3222 // Resolves for the case of using using a local variable declaration.
3224 bool ResolveLocalVariableDecls (EmitContext ec)
3226 bool need_conv = false;
3227 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3230 if (expr_type == null)
3234 // The type must be an IDisposable or an implicit conversion
3237 converted_vars = new Expression [var_list.Count];
3238 assign = new ExpressionStatement [var_list.Count];
3239 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3240 foreach (DictionaryEntry e in var_list){
3241 Expression var = (Expression) e.Key;
3243 var = var.ResolveLValue (ec, new EmptyExpression ());
3247 converted_vars [i] = Convert.ImplicitConversionRequired (
3248 ec, var, TypeManager.idisposable_type, loc);
3250 if (converted_vars [i] == null)
3258 foreach (DictionaryEntry e in var_list){
3259 LocalVariableReference var = (LocalVariableReference) e.Key;
3260 Expression new_expr = (Expression) e.Value;
3263 a = new Assign (var, new_expr, loc);
3269 converted_vars [i] = var;
3270 assign [i] = (ExpressionStatement) a;
3277 bool ResolveExpression (EmitContext ec)
3279 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3280 conv = Convert.ImplicitConversionRequired (
3281 ec, expr, TypeManager.idisposable_type, loc);
3291 // Emits the code for the case of using using a local variable declaration.
3293 bool EmitLocalVariableDecls (EmitContext ec)
3295 ILGenerator ig = ec.ig;
3298 bool old_in_try = ec.InTry;
3300 for (i = 0; i < assign.Length; i++) {
3301 assign [i].EmitStatement (ec);
3303 ig.BeginExceptionBlock ();
3305 Statement.Emit (ec);
3306 ec.InTry = old_in_try;
3308 bool old_in_finally = ec.InFinally;
3309 ec.InFinally = true;
3310 var_list.Reverse ();
3311 foreach (DictionaryEntry e in var_list){
3312 LocalVariableReference var = (LocalVariableReference) e.Key;
3313 Label skip = ig.DefineLabel ();
3316 ig.BeginFinallyBlock ();
3318 if (!var.Type.IsValueType) {
3320 ig.Emit (OpCodes.Brfalse, skip);
3321 converted_vars [i].Emit (ec);
3322 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3324 Expression ml = Expression.MemberLookup(ec, typeof(IDisposable), var.Type, "Dispose", Mono.CSharp.Location.Null);
3326 if (!(ml is MethodGroupExpr)) {
3328 ig.Emit (OpCodes.Box, var.Type);
3329 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3331 MethodInfo mi = null;
3333 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3334 if (mk.GetParameters().Length == 0) {
3341 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3345 var.AddressOf (ec, AddressOp.Load);
3346 ig.Emit (OpCodes.Call, mi);
3350 ig.MarkLabel (skip);
3351 ig.EndExceptionBlock ();
3353 ec.InFinally = old_in_finally;
3358 bool EmitExpression (EmitContext ec)
3361 // Make a copy of the expression and operate on that.
3363 ILGenerator ig = ec.ig;
3364 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3369 ig.Emit (OpCodes.Stloc, local_copy);
3371 bool old_in_try = ec.InTry;
3373 ig.BeginExceptionBlock ();
3374 Statement.Emit (ec);
3375 ec.InTry = old_in_try;
3377 Label skip = ig.DefineLabel ();
3378 bool old_in_finally = ec.InFinally;
3379 ig.BeginFinallyBlock ();
3380 ig.Emit (OpCodes.Ldloc, local_copy);
3381 ig.Emit (OpCodes.Brfalse, skip);
3382 ig.Emit (OpCodes.Ldloc, local_copy);
3383 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3384 ig.MarkLabel (skip);
3385 ec.InFinally = old_in_finally;
3386 ig.EndExceptionBlock ();
3391 public override bool Resolve (EmitContext ec)
3393 if (expression_or_block is DictionaryEntry){
3394 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3395 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3397 if (!ResolveLocalVariableDecls (ec))
3400 } else if (expression_or_block is Expression){
3401 expr = (Expression) expression_or_block;
3403 expr = expr.Resolve (ec);
3407 expr_type = expr.Type;
3409 if (!ResolveExpression (ec))
3413 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
3415 bool ok = Statement.Resolve (ec);
3418 ec.KillFlowBranching ();
3422 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3424 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3425 // Unfortunately, System.Reflection.Emit automatically emits a leave
3426 // to the end of the finally block. This is a problem if `returns'
3427 // is true since we may jump to a point after the end of the method.
3428 // As a workaround, emit an explicit ret here.
3429 ec.NeedExplicitReturn = true;
3435 protected override void DoEmit (EmitContext ec)
3437 if (expression_or_block is DictionaryEntry)
3438 EmitLocalVariableDecls (ec);
3439 else if (expression_or_block is Expression)
3440 EmitExpression (ec);
3445 /// Implementation of the foreach C# statement
3447 public class Foreach : Statement {
3449 Expression variable;
3451 Statement statement;
3452 ForeachHelperMethods hm;
3453 Expression empty, conv;
3454 Type array_type, element_type;
3457 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3458 Statement stmt, Location l)
3461 this.variable = var;
3467 public override bool Resolve (EmitContext ec)
3469 expr = expr.Resolve (ec);
3473 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3474 if (var_type == null)
3478 // We need an instance variable. Not sure this is the best
3479 // way of doing this.
3481 // FIXME: When we implement propertyaccess, will those turn
3482 // out to return values in ExprClass? I think they should.
3484 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3485 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3486 error1579 (expr.Type);
3490 if (expr.Type.IsArray) {
3491 array_type = expr.Type;
3492 element_type = TypeManager.GetElementType (array_type);
3494 empty = new EmptyExpression (element_type);
3496 hm = ProbeCollectionType (ec, expr.Type);
3498 error1579 (expr.Type);
3502 array_type = expr.Type;
3503 element_type = hm.element_type;
3505 empty = new EmptyExpression (hm.element_type);
3508 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
3509 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
3513 // FIXME: maybe we can apply the same trick we do in the
3514 // array handling to avoid creating empty and conv in some cases.
3516 // Although it is not as important in this case, as the type
3517 // will not likely be object (what the enumerator will return).
3519 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3523 variable = variable.ResolveLValue (ec, empty);
3524 if (variable == null)
3527 if (!statement.Resolve (ec))
3530 ec.EndFlowBranching ();
3536 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3538 static MethodInfo FetchMethodMoveNext (Type t)
3540 MemberList move_next_list;
3542 move_next_list = TypeContainer.FindMembers (
3543 t, MemberTypes.Method,
3544 BindingFlags.Public | BindingFlags.Instance,
3545 Type.FilterName, "MoveNext");
3546 if (move_next_list.Count == 0)
3549 foreach (MemberInfo m in move_next_list){
3550 MethodInfo mi = (MethodInfo) m;
3553 args = TypeManager.GetArgumentTypes (mi);
3554 if (args != null && args.Length == 0){
3555 if (mi.ReturnType == TypeManager.bool_type)
3563 // Retrieves a `public T get_Current ()' method from the Type `t'
3565 static MethodInfo FetchMethodGetCurrent (Type t)
3567 MemberList get_current_list;
3569 get_current_list = TypeContainer.FindMembers (
3570 t, MemberTypes.Method,
3571 BindingFlags.Public | BindingFlags.Instance,
3572 Type.FilterName, "get_Current");
3573 if (get_current_list.Count == 0)
3576 foreach (MemberInfo m in get_current_list){
3577 MethodInfo mi = (MethodInfo) m;
3580 args = TypeManager.GetArgumentTypes (mi);
3581 if (args != null && args.Length == 0)
3588 // This struct records the helper methods used by the Foreach construct
3590 class ForeachHelperMethods {
3591 public EmitContext ec;
3592 public MethodInfo get_enumerator;
3593 public MethodInfo move_next;
3594 public MethodInfo get_current;
3595 public Type element_type;
3596 public Type enumerator_type;
3597 public bool is_disposable;
3599 public ForeachHelperMethods (EmitContext ec)
3602 this.element_type = TypeManager.object_type;
3603 this.enumerator_type = TypeManager.ienumerator_type;
3604 this.is_disposable = true;
3608 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3613 if (!(m is MethodInfo))
3616 if (m.Name != "GetEnumerator")
3619 MethodInfo mi = (MethodInfo) m;
3620 Type [] args = TypeManager.GetArgumentTypes (mi);
3622 if (args.Length != 0)
3625 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3626 EmitContext ec = hm.ec;
3629 // Check whether GetEnumerator is accessible to us
3631 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3633 Type declaring = mi.DeclaringType;
3634 if (prot == MethodAttributes.Private){
3635 if (declaring != ec.ContainerType)
3637 } else if (prot == MethodAttributes.FamANDAssem){
3638 // If from a different assembly, false
3639 if (!(mi is MethodBuilder))
3642 // Are we being invoked from the same class, or from a derived method?
3644 if (ec.ContainerType != declaring){
3645 if (!ec.ContainerType.IsSubclassOf (declaring))
3648 } else if (prot == MethodAttributes.FamORAssem){
3649 if (!(mi is MethodBuilder ||
3650 ec.ContainerType == declaring ||
3651 ec.ContainerType.IsSubclassOf (declaring)))
3653 } if (prot == MethodAttributes.Family){
3654 if (!(ec.ContainerType == declaring ||
3655 ec.ContainerType.IsSubclassOf (declaring)))
3659 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3661 // Apply the same optimization as MS: skip the GetEnumerator
3662 // returning an IEnumerator, and use the one returning a
3663 // CharEnumerator instead. This allows us to avoid the
3664 // try-finally block and the boxing.
3669 // Ok, we can access it, now make sure that we can do something
3670 // with this `GetEnumerator'
3673 if (mi.ReturnType == TypeManager.ienumerator_type ||
3674 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
3675 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
3676 if (declaring != TypeManager.string_type) {
3677 hm.move_next = TypeManager.bool_movenext_void;
3678 hm.get_current = TypeManager.object_getcurrent_void;
3684 // Ok, so they dont return an IEnumerable, we will have to
3685 // find if they support the GetEnumerator pattern.
3687 Type return_type = mi.ReturnType;
3689 hm.move_next = FetchMethodMoveNext (return_type);
3690 if (hm.move_next == null)
3692 hm.get_current = FetchMethodGetCurrent (return_type);
3693 if (hm.get_current == null)
3696 hm.element_type = hm.get_current.ReturnType;
3697 hm.enumerator_type = return_type;
3698 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3699 TypeManager.ImplementsInterface (
3700 hm.enumerator_type, TypeManager.idisposable_type);
3706 /// This filter is used to find the GetEnumerator method
3707 /// on which IEnumerator operates
3709 static MemberFilter FilterEnumerator;
3713 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3716 void error1579 (Type t)
3718 Report.Error (1579, loc,
3719 "foreach statement cannot operate on variables of type `" +
3720 t.FullName + "' because that class does not provide a " +
3721 " GetEnumerator method or it is inaccessible");
3724 static bool TryType (Type t, ForeachHelperMethods hm)
3728 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3729 BindingFlags.Public | BindingFlags.NonPublic |
3730 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3731 FilterEnumerator, hm);
3736 hm.get_enumerator = (MethodInfo) mi [0];
3741 // Looks for a usable GetEnumerator in the Type, and if found returns
3742 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3744 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3746 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3748 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3749 if (TryType (tt, hm))
3755 // Now try to find the method in the interfaces
3758 Type [] ifaces = t.GetInterfaces ();
3760 foreach (Type i in ifaces){
3761 if (TryType (i, hm))
3766 // Since TypeBuilder.GetInterfaces only returns the interface
3767 // types for this type, we have to keep looping, but once
3768 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3769 // done, because it returns all the types
3771 if ((t is TypeBuilder))
3781 // FIXME: possible optimization.
3782 // We might be able to avoid creating `empty' if the type is the sam
3784 bool EmitCollectionForeach (EmitContext ec)
3786 ILGenerator ig = ec.ig;
3787 VariableStorage enumerator, disposable;
3789 enumerator = new VariableStorage (ec, hm.enumerator_type);
3790 if (hm.is_disposable)
3791 disposable = new VariableStorage (ec, TypeManager.idisposable_type);
3795 enumerator.EmitThis ();
3797 // Instantiate the enumerator
3799 if (expr.Type.IsValueType){
3800 if (expr is IMemoryLocation){
3801 IMemoryLocation ml = (IMemoryLocation) expr;
3803 ml.AddressOf (ec, AddressOp.Load);
3805 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3806 " does not implement IMemoryLocation");
3807 ig.Emit (OpCodes.Call, hm.get_enumerator);
3810 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3812 enumerator.EmitStore ();
3815 // Protect the code in a try/finalize block, so that
3816 // if the beast implement IDisposable, we get rid of it
3818 bool old_in_try = ec.InTry;
3820 if (hm.is_disposable) {
3821 ig.BeginExceptionBlock ();
3825 Label end_try = ig.DefineLabel ();
3827 ig.MarkLabel (ec.LoopBegin);
3828 enumerator.EmitLoad ();
3829 ig.Emit (OpCodes.Callvirt, hm.move_next);
3830 ig.Emit (OpCodes.Brfalse, end_try);
3834 enumerator.EmitLoad ();
3835 ig.Emit (OpCodes.Callvirt, hm.get_current);
3839 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3841 ((IAssignMethod)variable).EmitAssign (ec, conv);
3843 statement.Emit (ec);
3844 ig.Emit (OpCodes.Br, ec.LoopBegin);
3845 ig.MarkLabel (end_try);
3846 ec.InTry = old_in_try;
3848 // The runtime provides this for us.
3849 // ig.Emit (OpCodes.Leave, end);
3852 // Now the finally block
3854 if (hm.is_disposable) {
3855 Label end_finally = ig.DefineLabel ();
3856 bool old_in_finally = ec.InFinally;
3857 ec.InFinally = true;
3858 ig.BeginFinallyBlock ();
3860 disposable.EmitThis ();
3861 enumerator.EmitThis ();
3862 enumerator.EmitLoad ();
3863 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3864 disposable.EmitStore ();
3865 disposable.EmitLoad ();
3866 ig.Emit (OpCodes.Brfalse, end_finally);
3867 disposable.EmitThis ();
3868 disposable.EmitLoad ();
3869 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3870 ig.MarkLabel (end_finally);
3871 ec.InFinally = old_in_finally;
3873 // The runtime generates this anyways.
3874 // ig.Emit (OpCodes.Endfinally);
3876 ig.EndExceptionBlock ();
3879 ig.MarkLabel (ec.LoopEnd);
3884 // FIXME: possible optimization.
3885 // We might be able to avoid creating `empty' if the type is the sam
3887 bool EmitArrayForeach (EmitContext ec)
3889 int rank = array_type.GetArrayRank ();
3890 ILGenerator ig = ec.ig;
3892 VariableStorage copy = new VariableStorage (ec, array_type);
3895 // Make our copy of the array
3902 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
3906 counter.EmitThis ();
3907 ig.Emit (OpCodes.Ldc_I4_0);
3908 counter.EmitStore ();
3909 test = ig.DefineLabel ();
3910 ig.Emit (OpCodes.Br, test);
3912 loop = ig.DefineLabel ();
3913 ig.MarkLabel (loop);
3920 counter.EmitThis ();
3921 counter.EmitLoad ();
3924 // Load the value, we load the value using the underlying type,
3925 // then we use the variable.EmitAssign to load using the proper cast.
3927 ArrayAccess.EmitLoadOpcode (ig, element_type);
3930 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3932 ((IAssignMethod)variable).EmitAssign (ec, conv);
3934 statement.Emit (ec);
3936 ig.MarkLabel (ec.LoopBegin);
3937 counter.EmitThis ();
3938 counter.EmitThis ();
3939 counter.EmitLoad ();
3940 ig.Emit (OpCodes.Ldc_I4_1);
3941 ig.Emit (OpCodes.Add);
3942 counter.EmitStore ();
3944 ig.MarkLabel (test);
3945 counter.EmitThis ();
3946 counter.EmitLoad ();
3949 ig.Emit (OpCodes.Ldlen);
3950 ig.Emit (OpCodes.Conv_I4);
3951 ig.Emit (OpCodes.Blt, loop);
3953 VariableStorage [] dim_len = new VariableStorage [rank];
3954 VariableStorage [] dim_count = new VariableStorage [rank];
3955 Label [] loop = new Label [rank];
3956 Label [] test = new Label [rank];
3959 for (dim = 0; dim < rank; dim++){
3960 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
3961 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
3962 test [dim] = ig.DefineLabel ();
3963 loop [dim] = ig.DefineLabel ();
3966 for (dim = 0; dim < rank; dim++){
3967 dim_len [dim].EmitThis ();
3970 IntLiteral.EmitInt (ig, dim);
3971 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
3972 dim_len [dim].EmitStore ();
3976 for (dim = 0; dim < rank; dim++){
3977 dim_count [dim].EmitThis ();
3978 ig.Emit (OpCodes.Ldc_I4_0);
3979 dim_count [dim].EmitStore ();
3980 ig.Emit (OpCodes.Br, test [dim]);
3981 ig.MarkLabel (loop [dim]);
3988 for (dim = 0; dim < rank; dim++){
3989 dim_count [dim].EmitThis ();
3990 dim_count [dim].EmitLoad ();
3994 // FIXME: Maybe we can cache the computation of `get'?
3996 Type [] args = new Type [rank];
3999 for (int i = 0; i < rank; i++)
4000 args [i] = TypeManager.int32_type;
4002 ModuleBuilder mb = CodeGen.ModuleBuilder;
4003 get = mb.GetArrayMethod (
4005 CallingConventions.HasThis| CallingConventions.Standard,
4007 ig.Emit (OpCodes.Call, get);
4010 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4012 ((IAssignMethod)variable).EmitAssign (ec, conv);
4013 statement.Emit (ec);
4014 ig.MarkLabel (ec.LoopBegin);
4015 for (dim = rank - 1; dim >= 0; dim--){
4016 dim_count [dim].EmitThis ();
4017 dim_count [dim].EmitThis ();
4018 dim_count [dim].EmitLoad ();
4019 ig.Emit (OpCodes.Ldc_I4_1);
4020 ig.Emit (OpCodes.Add);
4021 dim_count [dim].EmitStore ();
4023 ig.MarkLabel (test [dim]);
4024 dim_count [dim].EmitThis ();
4025 dim_count [dim].EmitLoad ();
4026 dim_len [dim].EmitThis ();
4027 dim_len [dim].EmitLoad ();
4028 ig.Emit (OpCodes.Blt, loop [dim]);
4031 ig.MarkLabel (ec.LoopEnd);
4036 protected override void DoEmit (EmitContext ec)
4038 ILGenerator ig = ec.ig;
4040 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4041 bool old_inloop = ec.InLoop;
4042 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4043 ec.LoopBegin = ig.DefineLabel ();
4044 ec.LoopEnd = ig.DefineLabel ();
4046 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4049 EmitCollectionForeach (ec);
4051 EmitArrayForeach (ec);
4053 ec.LoopBegin = old_begin;
4054 ec.LoopEnd = old_end;
4055 ec.InLoop = old_inloop;
4056 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;