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)
48 /// Encapsulates the emission of a boolean test and jumping to a
51 /// This will emit the bool expression in `bool_expr' and if
52 /// `target_is_for_true' is true, then the code will generate a
53 /// brtrue to the target. Otherwise a brfalse.
55 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
56 Label target, bool target_is_for_true)
58 ILGenerator ig = ec.ig;
61 if (bool_expr is Unary){
62 Unary u = (Unary) bool_expr;
64 if (u.Oper == Unary.Operator.LogicalNot){
67 u.EmitLogicalNot (ec);
69 } else if (bool_expr is Binary){
70 Binary b = (Binary) bool_expr;
72 if (b.EmitBranchable (ec, target, target_is_for_true))
79 if (target_is_for_true){
81 ig.Emit (OpCodes.Brfalse, target);
83 ig.Emit (OpCodes.Brtrue, target);
86 ig.Emit (OpCodes.Brtrue, target);
88 ig.Emit (OpCodes.Brfalse, target);
92 public static void Warning_DeadCodeFound (Location loc)
94 Report.Warning (162, loc, "Unreachable code detected");
98 public sealed class EmptyStatement : Statement {
100 private EmptyStatement () {}
102 public static readonly EmptyStatement Value = new EmptyStatement ();
104 public override bool Resolve (EmitContext ec)
109 protected override void DoEmit (EmitContext ec)
114 public class If : Statement {
116 public Statement TrueStatement;
117 public Statement FalseStatement;
121 public If (Expression expr, Statement trueStatement, Location l)
124 TrueStatement = trueStatement;
128 public If (Expression expr,
129 Statement trueStatement,
130 Statement falseStatement,
134 TrueStatement = trueStatement;
135 FalseStatement = falseStatement;
139 public override bool Resolve (EmitContext ec)
141 Report.Debug (1, "START IF BLOCK", loc);
143 expr = Expression.ResolveBoolean (ec, expr, loc);
148 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
150 if (!TrueStatement.Resolve (ec)) {
151 ec.KillFlowBranching ();
155 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
157 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
159 if ((FalseStatement != null) && !FalseStatement.Resolve (ec)) {
160 ec.KillFlowBranching ();
164 ec.EndFlowBranching ();
166 Report.Debug (1, "END IF BLOCK", loc);
171 protected override void DoEmit (EmitContext ec)
173 ILGenerator ig = ec.ig;
174 Label false_target = ig.DefineLabel ();
178 // Dead code elimination
180 if (expr is BoolConstant){
181 bool take = ((BoolConstant) expr).Value;
184 if (FalseStatement != null){
185 Warning_DeadCodeFound (FalseStatement.loc);
187 TrueStatement.Emit (ec);
190 Warning_DeadCodeFound (TrueStatement.loc);
191 if (FalseStatement != null) {
192 FalseStatement.Emit (ec);
198 EmitBoolExpression (ec, expr, false_target, false);
200 TrueStatement.Emit (ec);
202 if (FalseStatement != null){
203 bool branch_emitted = false;
205 end = ig.DefineLabel ();
207 ig.Emit (OpCodes.Br, end);
208 branch_emitted = true;
211 ig.MarkLabel (false_target);
212 FalseStatement.Emit (ec);
217 ig.MarkLabel (false_target);
222 public class Do : Statement {
223 public Expression expr;
224 public readonly Statement EmbeddedStatement;
225 bool infinite, may_return;
227 public Do (Statement statement, Expression boolExpr, Location l)
230 EmbeddedStatement = statement;
234 public override bool Resolve (EmitContext ec)
238 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
240 if (!EmbeddedStatement.Resolve (ec))
243 expr = Expression.ResolveBoolean (ec, expr, loc);
246 else if (expr is BoolConstant){
247 bool res = ((BoolConstant) expr).Value;
253 ec.CurrentBranching.Infinite = infinite;
254 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
255 may_return = reachability.Returns != FlowBranching.FlowReturns.Never;
260 protected override void DoEmit (EmitContext ec)
262 ILGenerator ig = ec.ig;
263 Label loop = ig.DefineLabel ();
264 Label old_begin = ec.LoopBegin;
265 Label old_end = ec.LoopEnd;
266 bool old_inloop = ec.InLoop;
267 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
269 ec.LoopBegin = ig.DefineLabel ();
270 ec.LoopEnd = ig.DefineLabel ();
272 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
275 EmbeddedStatement.Emit (ec);
276 ig.MarkLabel (ec.LoopBegin);
279 // Dead code elimination
281 if (expr is BoolConstant){
282 bool res = ((BoolConstant) expr).Value;
285 ec.ig.Emit (OpCodes.Br, loop);
287 EmitBoolExpression (ec, expr, loop, true);
289 ig.MarkLabel (ec.LoopEnd);
291 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
292 ec.LoopBegin = old_begin;
293 ec.LoopEnd = old_end;
294 ec.InLoop = old_inloop;
298 public class While : Statement {
299 public Expression expr;
300 public readonly Statement Statement;
301 bool may_return, empty, infinite;
303 public While (Expression boolExpr, Statement statement, Location l)
305 this.expr = boolExpr;
306 Statement = statement;
310 public override bool Resolve (EmitContext ec)
314 expr = Expression.ResolveBoolean (ec, expr, loc);
318 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
321 // Inform whether we are infinite or not
323 if (expr is BoolConstant){
324 BoolConstant bc = (BoolConstant) expr;
326 if (bc.Value == false){
327 Warning_DeadCodeFound (Statement.loc);
333 // We are not infinite, so the loop may or may not be executed.
335 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
338 if (!Statement.Resolve (ec))
342 ec.KillFlowBranching ();
344 ec.CurrentBranching.Infinite = infinite;
345 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
346 may_return = reachability.Returns != FlowBranching.FlowReturns.Never;
352 protected override void DoEmit (EmitContext ec)
357 ILGenerator ig = ec.ig;
358 Label old_begin = ec.LoopBegin;
359 Label old_end = ec.LoopEnd;
360 bool old_inloop = ec.InLoop;
361 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
364 ec.LoopBegin = ig.DefineLabel ();
365 ec.LoopEnd = ig.DefineLabel ();
367 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
370 // Inform whether we are infinite or not
372 if (expr is BoolConstant){
373 BoolConstant bc = (BoolConstant) expr;
375 ig.MarkLabel (ec.LoopBegin);
377 ig.Emit (OpCodes.Br, ec.LoopBegin);
380 // Inform that we are infinite (ie, `we return'), only
381 // if we do not `break' inside the code.
383 ret = may_return == false;
384 ig.MarkLabel (ec.LoopEnd);
386 Label while_loop = ig.DefineLabel ();
388 ig.Emit (OpCodes.Br, ec.LoopBegin);
389 ig.MarkLabel (while_loop);
393 ig.MarkLabel (ec.LoopBegin);
395 EmitBoolExpression (ec, expr, while_loop, true);
396 ig.MarkLabel (ec.LoopEnd);
401 ec.LoopBegin = old_begin;
402 ec.LoopEnd = old_end;
403 ec.InLoop = old_inloop;
404 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
408 public class For : Statement {
410 readonly Statement InitStatement;
411 readonly Statement Increment;
412 readonly Statement Statement;
413 bool may_return, infinite, empty;
415 public For (Statement initStatement,
421 InitStatement = initStatement;
423 Increment = increment;
424 Statement = statement;
428 public override bool Resolve (EmitContext ec)
432 if (InitStatement != null){
433 if (!InitStatement.Resolve (ec))
438 Test = Expression.ResolveBoolean (ec, Test, loc);
441 else if (Test is BoolConstant){
442 BoolConstant bc = (BoolConstant) Test;
444 if (bc.Value == false){
445 Warning_DeadCodeFound (Statement.loc);
453 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
455 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
457 if (!Statement.Resolve (ec))
460 if (Increment != null){
461 if (!Increment.Resolve (ec))
466 ec.KillFlowBranching ();
468 ec.CurrentBranching.Infinite = infinite;
469 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
470 may_return = reachability.Returns != FlowBranching.FlowReturns.Never;
476 protected override void DoEmit (EmitContext ec)
481 ILGenerator ig = ec.ig;
482 Label old_begin = ec.LoopBegin;
483 Label old_end = ec.LoopEnd;
484 bool old_inloop = ec.InLoop;
485 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
486 Label loop = ig.DefineLabel ();
487 Label test = ig.DefineLabel ();
489 if (InitStatement != null && InitStatement != EmptyStatement.Value)
490 InitStatement.Emit (ec);
492 ec.LoopBegin = ig.DefineLabel ();
493 ec.LoopEnd = ig.DefineLabel ();
495 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
497 ig.Emit (OpCodes.Br, test);
501 ig.MarkLabel (ec.LoopBegin);
502 if (Increment != EmptyStatement.Value)
507 // If test is null, there is no test, and we are just
512 // The Resolve code already catches the case for Test == BoolConstant (false)
513 // so we know that this is true
515 if (Test is BoolConstant)
516 ig.Emit (OpCodes.Br, loop);
518 EmitBoolExpression (ec, Test, loop, true);
520 ig.Emit (OpCodes.Br, loop);
521 ig.MarkLabel (ec.LoopEnd);
523 ec.LoopBegin = old_begin;
524 ec.LoopEnd = old_end;
525 ec.InLoop = old_inloop;
526 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
530 public class StatementExpression : Statement {
531 ExpressionStatement expr;
533 public StatementExpression (ExpressionStatement expr, Location l)
539 public override bool Resolve (EmitContext ec)
541 expr = expr.ResolveStatement (ec);
545 protected override void DoEmit (EmitContext ec)
547 ILGenerator ig = ec.ig;
549 expr.EmitStatement (ec);
552 public override string ToString ()
554 return "StatementExpression (" + expr + ")";
559 /// Implements the return statement
561 public class Return : Statement {
562 public Expression Expr;
564 public Return (Expression expr, Location l)
570 public override bool Resolve (EmitContext ec)
573 Expr = Expr.Resolve (ec);
579 Report.Error (-206, loc, "Return statement not allowed inside iterators");
583 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
585 if (ec.CurrentBranching.InTryBlock ())
586 ec.CurrentBranching.AddFinallyVector (vector);
588 vector.CheckOutParameters (ec.CurrentBranching);
590 ec.CurrentBranching.CurrentUsageVector.Return ();
594 protected override void DoEmit (EmitContext ec)
597 Report.Error (157, loc, "Control can not leave the body of the finally block");
601 if (ec.ReturnType == null){
603 Report.Error (127, loc, "Return with a value not allowed here");
608 Report.Error (126, loc, "An object of type `" +
609 TypeManager.CSharpName (ec.ReturnType) + "' is " +
610 "expected for the return statement");
614 if (Expr.Type != ec.ReturnType)
615 Expr = Convert.ImplicitConversionRequired (
616 ec, Expr, ec.ReturnType, loc);
623 if (ec.InTry || ec.InCatch)
624 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
627 if (ec.InTry || ec.InCatch) {
628 if (!ec.HasReturnLabel) {
629 ec.ReturnLabel = ec.ig.DefineLabel ();
630 ec.HasReturnLabel = true;
632 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
634 ec.ig.Emit (OpCodes.Ret);
635 ec.NeedExplicitReturn = false;
640 public class Goto : Statement {
643 LabeledStatement label;
645 public override bool Resolve (EmitContext ec)
647 label = block.LookupLabel (target);
651 "No such label `" + target + "' in this scope");
655 // If this is a forward goto.
656 if (!label.IsDefined)
657 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
659 ec.CurrentBranching.CurrentUsageVector.Goto ();
664 public Goto (Block parent_block, string label, Location l)
666 block = parent_block;
671 public string Target {
677 protected override void DoEmit (EmitContext ec)
679 Label l = label.LabelTarget (ec);
680 ec.ig.Emit (OpCodes.Br, l);
684 public class LabeledStatement : Statement {
685 public readonly Location Location;
693 public LabeledStatement (string label_name, Location l)
695 this.label_name = label_name;
699 public Label LabelTarget (EmitContext ec)
703 label = ec.ig.DefineLabel ();
709 public bool IsDefined {
715 public bool HasBeenReferenced {
721 public void AddUsageVector (FlowBranching.UsageVector vector)
724 vectors = new ArrayList ();
726 vectors.Add (vector.Clone ());
729 public override bool Resolve (EmitContext ec)
731 ec.CurrentBranching.Label (vectors);
738 protected override void DoEmit (EmitContext ec)
741 ec.ig.MarkLabel (label);
747 /// `goto default' statement
749 public class GotoDefault : Statement {
751 public GotoDefault (Location l)
756 public override bool Resolve (EmitContext ec)
758 ec.CurrentBranching.CurrentUsageVector.Goto ();
762 protected override void DoEmit (EmitContext ec)
764 if (ec.Switch == null){
765 Report.Error (153, loc, "goto default is only valid in a switch statement");
769 if (!ec.Switch.GotDefault){
770 Report.Error (159, loc, "No default target on switch statement");
773 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
778 /// `goto case' statement
780 public class GotoCase : Statement {
784 public GotoCase (Expression e, Location l)
790 public override bool Resolve (EmitContext ec)
792 if (ec.Switch == null){
793 Report.Error (153, loc, "goto case is only valid in a switch statement");
797 expr = expr.Resolve (ec);
801 if (!(expr is Constant)){
802 Report.Error (159, loc, "Target expression for goto case is not constant");
806 object val = Expression.ConvertIntLiteral (
807 (Constant) expr, ec.Switch.SwitchType, loc);
812 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
817 "No such label 'case " + val + "': for the goto case");
821 label = sl.ILLabelCode;
823 ec.CurrentBranching.CurrentUsageVector.Goto ();
827 protected override void DoEmit (EmitContext ec)
829 ec.ig.Emit (OpCodes.Br, label);
833 public class Throw : Statement {
836 public Throw (Expression expr, Location l)
842 public override bool Resolve (EmitContext ec)
845 expr = expr.Resolve (ec);
849 ExprClass eclass = expr.eclass;
851 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
852 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
853 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
859 if ((t != TypeManager.exception_type) &&
860 !t.IsSubclassOf (TypeManager.exception_type) &&
861 !(expr is NullLiteral)) {
862 Report.Error (155, loc,
863 "The type caught or thrown must be derived " +
864 "from System.Exception");
869 ec.CurrentBranching.CurrentUsageVector.Throw ();
873 protected override void DoEmit (EmitContext ec)
877 ec.ig.Emit (OpCodes.Rethrow);
881 "A throw statement with no argument is only " +
882 "allowed in a catch clause");
889 ec.ig.Emit (OpCodes.Throw);
893 public class Break : Statement {
895 public Break (Location l)
900 public override bool Resolve (EmitContext ec)
902 ec.CurrentBranching.CurrentUsageVector.Break ();
906 protected override void DoEmit (EmitContext ec)
908 ILGenerator ig = ec.ig;
910 if (ec.InLoop == false && ec.Switch == null){
911 Report.Error (139, loc, "No enclosing loop or switch to continue to");
915 if (ec.InTry || ec.InCatch)
916 ig.Emit (OpCodes.Leave, ec.LoopEnd);
918 ig.Emit (OpCodes.Br, ec.LoopEnd);
922 public class Continue : Statement {
924 public Continue (Location l)
929 public override bool Resolve (EmitContext ec)
931 ec.CurrentBranching.CurrentUsageVector.Goto ();
935 protected override void DoEmit (EmitContext ec)
937 Label begin = ec.LoopBegin;
940 Report.Error (139, loc, "No enclosing loop to continue to");
945 // UGH: Non trivial. This Br might cross a try/catch boundary
949 // try { ... } catch { continue; }
953 // try {} catch { while () { continue; }}
955 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
956 ec.ig.Emit (OpCodes.Leave, begin);
957 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
958 throw new Exception ("Should never happen");
960 ec.ig.Emit (OpCodes.Br, begin);
964 public class LocalInfo {
965 public Expression Type;
968 // Most of the time a variable will be stored in a LocalBuilder
970 // But sometimes, it will be stored in a field. The context of the field will
971 // be stored in the EmitContext
974 public LocalBuilder LocalBuilder;
975 public FieldBuilder FieldBuilder;
977 public Type VariableType;
978 public readonly string Name;
979 public readonly Location Location;
980 public readonly Block Block;
982 public VariableInfo VariableInfo;
993 public LocalInfo (Expression type, string name, Block block, Location l)
1001 public LocalInfo (TypeContainer tc, Block block, Location l)
1003 VariableType = tc.TypeBuilder;
1008 public bool IsThisAssigned (EmitContext ec, Location loc)
1010 if (VariableInfo == null)
1011 throw new Exception ();
1013 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
1016 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
1019 public bool Resolve (DeclSpace decl)
1021 if (VariableType == null)
1022 VariableType = decl.ResolveType (Type, false, Location);
1024 if (VariableType == null)
1030 public void MakePinned ()
1032 TypeManager.MakePinned (LocalBuilder);
1033 flags |= Flags.Fixed;
1036 public bool IsFixed {
1038 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1045 public override string ToString ()
1047 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1048 Name, Type, VariableInfo, Location);
1053 return (flags & Flags.Used) != 0;
1056 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1060 public bool Assigned {
1062 return (flags & Flags.Assigned) != 0;
1065 flags = value ? (flags | Flags.Assigned) : (flags & ~Flags.Assigned);
1069 public bool ReadOnly {
1071 return (flags & Flags.ReadOnly) != 0;
1074 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1083 /// Block represents a C# block.
1087 /// This class is used in a number of places: either to represent
1088 /// explicit blocks that the programmer places or implicit blocks.
1090 /// Implicit blocks are used as labels or to introduce variable
1093 public class Block : Statement {
1094 public readonly Block Parent;
1095 public readonly Location StartLocation;
1096 public Location EndLocation = Location.Null;
1099 public enum Flags : byte {
1103 VariablesInitialized = 8,
1108 public bool Implicit {
1110 return (flags & Flags.Implicit) != 0;
1114 public bool Unchecked {
1116 return (flags & Flags.Unchecked) != 0;
1119 flags |= Flags.Unchecked;
1124 // The statements in this block
1126 ArrayList statements;
1129 // An array of Blocks. We keep track of children just
1130 // to generate the local variable declarations.
1132 // Statements and child statements are handled through the
1138 // Labels. (label, block) pairs.
1143 // Keeps track of (name, type) pairs
1145 Hashtable variables;
1148 // Keeps track of constants
1149 Hashtable constants;
1152 // If this is a switch section, the enclosing switch block.
1160 public Block (Block parent)
1161 : this (parent, (Flags) 0, Location.Null, Location.Null)
1164 public Block (Block parent, Flags flags)
1165 : this (parent, flags, Location.Null, Location.Null)
1168 public Block (Block parent, Flags flags, Parameters parameters)
1169 : this (parent, flags, parameters, Location.Null, Location.Null)
1172 public Block (Block parent, Location start, Location end)
1173 : this (parent, (Flags) 0, start, end)
1176 public Block (Block parent, Parameters parameters, Location start, Location end)
1177 : this (parent, (Flags) 0, parameters, start, end)
1180 public Block (Block parent, Flags flags, Location start, Location end)
1181 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1184 public Block (Block parent, Flags flags, Parameters parameters,
1185 Location start, Location end)
1188 parent.AddChild (this);
1190 this.Parent = parent;
1192 this.parameters = parameters;
1193 this.StartLocation = start;
1194 this.EndLocation = end;
1197 statements = new ArrayList ();
1200 public Block CreateSwitchBlock (Location start)
1202 Block new_block = new Block (this, start, start);
1203 new_block.switch_block = this;
1213 void AddChild (Block b)
1215 if (children == null)
1216 children = new ArrayList ();
1221 public void SetEndLocation (Location loc)
1227 /// Adds a label to the current block.
1231 /// false if the name already exists in this block. true
1235 public bool AddLabel (string name, LabeledStatement target)
1237 if (switch_block != null)
1238 return switch_block.AddLabel (name, target);
1241 labels = new Hashtable ();
1242 if (labels.Contains (name))
1245 labels.Add (name, target);
1249 public LabeledStatement LookupLabel (string name)
1251 Hashtable l = new Hashtable ();
1253 return LookupLabel (name, l);
1257 // Lookups a label in the current block, parents and children.
1258 // It skips during child recurssion on `source'
1260 LabeledStatement LookupLabel (string name, Hashtable seen)
1262 if (switch_block != null)
1263 return switch_block.LookupLabel (name, seen);
1265 if (seen [this] != null)
1271 if (labels.Contains (name))
1272 return ((LabeledStatement) labels [name]);
1274 if (children != null){
1275 foreach (Block b in children){
1276 LabeledStatement s = b.LookupLabel (name, seen);
1283 return Parent.LookupLabel (name, seen);
1288 LocalInfo this_variable = null;
1291 // Returns the "this" instance variable of this block.
1292 // See AddThisVariable() for more information.
1294 public LocalInfo ThisVariable {
1296 if (this_variable != null)
1297 return this_variable;
1298 else if (Parent != null)
1299 return Parent.ThisVariable;
1305 Hashtable child_variable_names;
1308 // Marks a variable with name @name as being used in a child block.
1309 // If a variable name has been used in a child block, it's illegal to
1310 // declare a variable with the same name in the current block.
1312 public void AddChildVariableName (string name)
1314 if (child_variable_names == null)
1315 child_variable_names = new Hashtable ();
1317 if (!child_variable_names.Contains (name))
1318 child_variable_names.Add (name, true);
1322 // Marks all variables from block @block and all its children as being
1323 // used in a child block.
1325 public void AddChildVariableNames (Block block)
1327 if (block.Variables != null) {
1328 foreach (string name in block.Variables.Keys)
1329 AddChildVariableName (name);
1332 if (block.children != null) {
1333 foreach (Block child in block.children)
1334 AddChildVariableNames (child);
1337 if (block.child_variable_names != null) {
1338 foreach (string name in block.child_variable_names.Keys)
1339 AddChildVariableName (name);
1344 // Checks whether a variable name has already been used in a child block.
1346 public bool IsVariableNameUsedInChildBlock (string name)
1348 if (child_variable_names == null)
1351 return child_variable_names.Contains (name);
1355 // This is used by non-static `struct' constructors which do not have an
1356 // initializer - in this case, the constructor must initialize all of the
1357 // struct's fields. To do this, we add a "this" variable and use the flow
1358 // analysis code to ensure that it's been fully initialized before control
1359 // leaves the constructor.
1361 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1363 if (this_variable != null)
1364 return this_variable;
1366 if (variables == null)
1367 variables = new Hashtable ();
1369 this_variable = new LocalInfo (tc, this, l);
1371 variables.Add ("this", this_variable);
1373 return this_variable;
1376 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1378 if (variables == null)
1379 variables = new Hashtable ();
1381 LocalInfo vi = GetLocalInfo (name);
1383 if (vi.Block != this)
1384 Report.Error (136, l, "A local variable named `" + name + "' " +
1385 "cannot be declared in this scope since it would " +
1386 "give a different meaning to `" + name + "', which " +
1387 "is already used in a `parent or current' scope to " +
1388 "denote something else");
1390 Report.Error (128, l, "A local variable `" + name + "' is already " +
1391 "defined in this scope");
1395 if (IsVariableNameUsedInChildBlock (name)) {
1396 Report.Error (136, l, "A local variable named `" + name + "' " +
1397 "cannot be declared in this scope since it would " +
1398 "give a different meaning to `" + name + "', which " +
1399 "is already used in a `child' scope to denote something " +
1406 Parameter p = pars.GetParameterByName (name, out idx);
1408 Report.Error (136, l, "A local variable named `" + name + "' " +
1409 "cannot be declared in this scope since it would " +
1410 "give a different meaning to `" + name + "', which " +
1411 "is already used in a `parent or current' scope to " +
1412 "denote something else");
1417 vi = new LocalInfo (type, name, this, l);
1419 variables.Add (name, vi);
1421 if ((flags & Flags.VariablesInitialized) != 0)
1422 throw new Exception ();
1424 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1428 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1430 if (AddVariable (type, name, pars, l) == null)
1433 if (constants == null)
1434 constants = new Hashtable ();
1436 constants.Add (name, value);
1440 public Hashtable Variables {
1446 public LocalInfo GetLocalInfo (string name)
1448 for (Block b = this; b != null; b = b.Parent) {
1449 if (b.variables != null) {
1450 LocalInfo ret = b.variables [name] as LocalInfo;
1458 public Expression GetVariableType (string name)
1460 LocalInfo vi = GetLocalInfo (name);
1468 public Expression GetConstantExpression (string name)
1470 for (Block b = this; b != null; b = b.Parent) {
1471 if (b.constants != null) {
1472 Expression ret = b.constants [name] as Expression;
1481 /// True if the variable named @name is a constant
1483 public bool IsConstant (string name)
1485 Expression e = null;
1487 e = GetConstantExpression (name);
1493 /// Use to fetch the statement associated with this label
1495 public Statement this [string name] {
1497 return (Statement) labels [name];
1501 Parameters parameters = null;
1502 public Parameters Parameters {
1505 while (b.Parent != null)
1507 return b.parameters;
1512 /// A list of labels that were not used within this block
1514 public string [] GetUnreferenced ()
1516 // FIXME: Implement me
1520 public void AddStatement (Statement s)
1523 flags |= Flags.BlockUsed;
1528 return (flags & Flags.BlockUsed) != 0;
1534 flags |= Flags.BlockUsed;
1537 public bool HasRet {
1539 return (flags & Flags.HasRet) != 0;
1543 VariableMap param_map, local_map;
1545 public VariableMap ParameterMap {
1547 if ((flags & Flags.VariablesInitialized) == 0)
1548 throw new Exception ();
1554 public VariableMap LocalMap {
1556 if ((flags & Flags.VariablesInitialized) == 0)
1557 throw new Exception ();
1563 public bool LiftVariable (LocalInfo local_info)
1569 /// Emits the variable declarations and labels.
1572 /// tc: is our typecontainer (to resolve type references)
1573 /// ig: is the code generator:
1575 public void EmitMeta (EmitContext ec, InternalParameters ip)
1577 DeclSpace ds = ec.DeclSpace;
1578 ILGenerator ig = ec.ig;
1581 // Compute the VariableMap's.
1583 // Unfortunately, we don't know the type when adding variables with
1584 // AddVariable(), so we need to compute this info here.
1588 if (variables != null) {
1589 foreach (LocalInfo li in variables.Values)
1590 li.Resolve (ec.DeclSpace);
1592 locals = new LocalInfo [variables.Count];
1593 variables.Values.CopyTo (locals, 0);
1595 locals = new LocalInfo [0];
1598 local_map = new VariableMap (Parent.LocalMap, locals);
1600 local_map = new VariableMap (locals);
1602 param_map = new VariableMap (ip);
1603 flags |= Flags.VariablesInitialized;
1605 bool old_check_state = ec.ConstantCheckState;
1606 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1607 bool remap_locals = ec.RemapToProxy;
1610 // Process this block variables
1612 if (variables != null){
1613 foreach (DictionaryEntry de in variables){
1614 string name = (string) de.Key;
1615 LocalInfo vi = (LocalInfo) de.Value;
1617 if (vi.VariableType == null)
1620 Type variable_type = vi.VariableType;
1622 if (variable_type.IsPointer){
1624 // Am not really convinced that this test is required (Microsoft does it)
1625 // but the fact is that you would not be able to use the pointer variable
1628 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1634 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1636 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1638 if (constants == null)
1641 Expression cv = (Expression) constants [name];
1645 ec.CurrentBlock = this;
1646 Expression e = cv.Resolve (ec);
1650 Constant ce = e as Constant;
1652 Report.Error (133, vi.Location,
1653 "The expression being assigned to `" +
1654 name + "' must be constant (" + e + ")");
1658 if (e.Type != variable_type){
1659 e = Const.ChangeType (vi.Location, ce, variable_type);
1664 constants.Remove (name);
1665 constants.Add (name, e);
1668 ec.ConstantCheckState = old_check_state;
1671 // Now, handle the children
1673 if (children != null){
1674 foreach (Block b in children)
1675 b.EmitMeta (ec, ip);
1679 public void UsageWarning ()
1683 if (variables != null){
1684 foreach (DictionaryEntry de in variables){
1685 LocalInfo vi = (LocalInfo) de.Value;
1690 name = (string) de.Key;
1694 219, vi.Location, "The variable `" + name +
1695 "' is assigned but its value is never used");
1698 168, vi.Location, "The variable `" +
1700 "' is declared but never used");
1705 if (children != null)
1706 foreach (Block b in children)
1710 public override bool Resolve (EmitContext ec)
1712 Block prev_block = ec.CurrentBlock;
1715 ec.CurrentBlock = this;
1716 ec.StartFlowBranching (this);
1718 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1720 bool unreachable = false, warning_shown = false;
1722 int statement_count = statements.Count;
1723 for (int ix = 0; ix < statement_count; ix++){
1724 Statement s = (Statement) statements [ix];
1726 if (unreachable && !(s is LabeledStatement)) {
1727 if (!warning_shown && s != EmptyStatement.Value) {
1728 warning_shown = true;
1729 Warning_DeadCodeFound (s.loc);
1732 statements [ix] = EmptyStatement.Value;
1736 if (s.Resolve (ec) == false) {
1738 statements [ix] = EmptyStatement.Value;
1742 if (s is LabeledStatement)
1743 unreachable = false;
1745 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1748 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
1750 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
1751 ec.CurrentBlock = prev_block;
1753 // If we're a non-static `struct' constructor which doesn't have an
1754 // initializer, then we must initialize all of the struct's fields.
1755 if ((this_variable != null) &&
1756 (reachability.Throws != FlowBranching.FlowReturns.Always) &&
1757 !this_variable.IsThisAssigned (ec, loc))
1760 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1761 foreach (LabeledStatement label in labels.Values)
1762 if (!label.HasBeenReferenced)
1763 Report.Warning (164, label.Location,
1764 "This label has not been referenced");
1767 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, reachability);
1769 if ((reachability.Returns == FlowBranching.FlowReturns.Always) ||
1770 (reachability.Throws == FlowBranching.FlowReturns.Always) ||
1771 (reachability.Reachable == FlowBranching.FlowReturns.Never))
1772 flags |= Flags.HasRet;
1777 protected override void DoEmit (EmitContext ec)
1779 int statement_count = statements.Count;
1780 for (int ix = 0; ix < statement_count; ix++){
1781 Statement s = (Statement) statements [ix];
1786 public override void Emit (EmitContext ec)
1788 Block prev_block = ec.CurrentBlock;
1790 ec.CurrentBlock = this;
1792 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1793 bool is_lexical_block = !Implicit && (Parent != null);
1795 if (emit_debug_info) {
1796 if (is_lexical_block)
1797 ec.ig.BeginScope ();
1799 if (variables != null) {
1800 foreach (DictionaryEntry de in variables) {
1801 string name = (string) de.Key;
1802 LocalInfo vi = (LocalInfo) de.Value;
1804 if (vi.LocalBuilder == null)
1807 vi.LocalBuilder.SetLocalSymInfo (name);
1812 ec.Mark (StartLocation, true);
1814 ec.Mark (EndLocation, true);
1816 if (emit_debug_info && is_lexical_block)
1819 ec.CurrentBlock = prev_block;
1823 public class SwitchLabel {
1826 public Location loc;
1827 public Label ILLabel;
1828 public Label ILLabelCode;
1831 // if expr == null, then it is the default case.
1833 public SwitchLabel (Expression expr, Location l)
1839 public Expression Label {
1845 public object Converted {
1852 // Resolves the expression, reduces it to a literal if possible
1853 // and then converts it to the requested type.
1855 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1857 ILLabel = ec.ig.DefineLabel ();
1858 ILLabelCode = ec.ig.DefineLabel ();
1863 Expression e = label.Resolve (ec);
1868 if (!(e is Constant)){
1869 Report.Error (150, loc, "A constant value is expected, got: " + e);
1873 if (e is StringConstant || e is NullLiteral){
1874 if (required_type == TypeManager.string_type){
1876 ILLabel = ec.ig.DefineLabel ();
1881 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1882 if (converted == null)
1889 public class SwitchSection {
1890 // An array of SwitchLabels.
1891 public readonly ArrayList Labels;
1892 public readonly Block Block;
1894 public SwitchSection (ArrayList labels, Block block)
1901 public class Switch : Statement {
1902 public readonly ArrayList Sections;
1903 public Expression Expr;
1906 /// Maps constants whose type type SwitchType to their SwitchLabels.
1908 public Hashtable Elements;
1911 /// The governing switch type
1913 public Type SwitchType;
1919 Label default_target;
1920 Expression new_expr;
1923 // The types allowed to be implicitly cast from
1924 // on the governing type
1926 static Type [] allowed_types;
1928 public Switch (Expression e, ArrayList sects, Location l)
1935 public bool GotDefault {
1941 public Label DefaultTarget {
1943 return default_target;
1948 // Determines the governing type for a switch. The returned
1949 // expression might be the expression from the switch, or an
1950 // expression that includes any potential conversions to the
1951 // integral types or to string.
1953 Expression SwitchGoverningType (EmitContext ec, Type t)
1955 if (t == TypeManager.int32_type ||
1956 t == TypeManager.uint32_type ||
1957 t == TypeManager.char_type ||
1958 t == TypeManager.byte_type ||
1959 t == TypeManager.sbyte_type ||
1960 t == TypeManager.ushort_type ||
1961 t == TypeManager.short_type ||
1962 t == TypeManager.uint64_type ||
1963 t == TypeManager.int64_type ||
1964 t == TypeManager.string_type ||
1965 t == TypeManager.bool_type ||
1966 t.IsSubclassOf (TypeManager.enum_type))
1969 if (allowed_types == null){
1970 allowed_types = new Type [] {
1971 TypeManager.sbyte_type,
1972 TypeManager.byte_type,
1973 TypeManager.short_type,
1974 TypeManager.ushort_type,
1975 TypeManager.int32_type,
1976 TypeManager.uint32_type,
1977 TypeManager.int64_type,
1978 TypeManager.uint64_type,
1979 TypeManager.char_type,
1980 TypeManager.bool_type,
1981 TypeManager.string_type
1986 // Try to find a *user* defined implicit conversion.
1988 // If there is no implicit conversion, or if there are multiple
1989 // conversions, we have to report an error
1991 Expression converted = null;
1992 foreach (Type tt in allowed_types){
1995 e = Convert.ImplicitUserConversion (ec, Expr, tt, loc);
1999 if (converted != null){
2000 Report.Error (-12, loc, "More than one conversion to an integral " +
2001 " type exists for type `" +
2002 TypeManager.CSharpName (Expr.Type)+"'");
2010 void error152 (string n)
2013 152, "The label `" + n + ":' " +
2014 "is already present on this switch statement");
2018 // Performs the basic sanity checks on the switch statement
2019 // (looks for duplicate keys and non-constant expressions).
2021 // It also returns a hashtable with the keys that we will later
2022 // use to compute the switch tables
2024 bool CheckSwitch (EmitContext ec)
2028 Elements = new Hashtable ();
2030 got_default = false;
2032 if (TypeManager.IsEnumType (SwitchType)){
2033 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2035 compare_type = SwitchType;
2037 foreach (SwitchSection ss in Sections){
2038 foreach (SwitchLabel sl in ss.Labels){
2039 if (!sl.ResolveAndReduce (ec, SwitchType)){
2044 if (sl.Label == null){
2046 error152 ("default");
2053 object key = sl.Converted;
2055 if (key is Constant)
2056 key = ((Constant) key).GetValue ();
2059 key = NullLiteral.Null;
2061 string lname = null;
2062 if (compare_type == TypeManager.uint64_type){
2063 ulong v = (ulong) key;
2065 if (Elements.Contains (v))
2066 lname = v.ToString ();
2068 Elements.Add (v, sl);
2069 } else if (compare_type == TypeManager.int64_type){
2070 long v = (long) key;
2072 if (Elements.Contains (v))
2073 lname = v.ToString ();
2075 Elements.Add (v, sl);
2076 } else if (compare_type == TypeManager.uint32_type){
2077 uint v = (uint) key;
2079 if (Elements.Contains (v))
2080 lname = v.ToString ();
2082 Elements.Add (v, sl);
2083 } else if (compare_type == TypeManager.char_type){
2084 char v = (char) key;
2086 if (Elements.Contains (v))
2087 lname = v.ToString ();
2089 Elements.Add (v, sl);
2090 } else if (compare_type == TypeManager.byte_type){
2091 byte v = (byte) key;
2093 if (Elements.Contains (v))
2094 lname = v.ToString ();
2096 Elements.Add (v, sl);
2097 } else if (compare_type == TypeManager.sbyte_type){
2098 sbyte v = (sbyte) key;
2100 if (Elements.Contains (v))
2101 lname = v.ToString ();
2103 Elements.Add (v, sl);
2104 } else if (compare_type == TypeManager.short_type){
2105 short v = (short) key;
2107 if (Elements.Contains (v))
2108 lname = v.ToString ();
2110 Elements.Add (v, sl);
2111 } else if (compare_type == TypeManager.ushort_type){
2112 ushort v = (ushort) key;
2114 if (Elements.Contains (v))
2115 lname = v.ToString ();
2117 Elements.Add (v, sl);
2118 } else if (compare_type == TypeManager.string_type){
2119 if (key is NullLiteral){
2120 if (Elements.Contains (NullLiteral.Null))
2123 Elements.Add (NullLiteral.Null, null);
2125 string s = (string) key;
2127 if (Elements.Contains (s))
2130 Elements.Add (s, sl);
2132 } else if (compare_type == TypeManager.int32_type) {
2135 if (Elements.Contains (v))
2136 lname = v.ToString ();
2138 Elements.Add (v, sl);
2139 } else if (compare_type == TypeManager.bool_type) {
2140 bool v = (bool) key;
2142 if (Elements.Contains (v))
2143 lname = v.ToString ();
2145 Elements.Add (v, sl);
2149 throw new Exception ("Unknown switch type!" +
2150 SwitchType + " " + compare_type);
2154 error152 ("case + " + lname);
2165 void EmitObjectInteger (ILGenerator ig, object k)
2168 IntConstant.EmitInt (ig, (int) k);
2169 else if (k is Constant) {
2170 EmitObjectInteger (ig, ((Constant) k).GetValue ());
2173 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
2176 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
2178 IntConstant.EmitInt (ig, (int) (long) k);
2179 ig.Emit (OpCodes.Conv_I8);
2182 LongConstant.EmitLong (ig, (long) k);
2184 else if (k is ulong)
2186 if ((ulong) k < (1L<<32))
2188 IntConstant.EmitInt (ig, (int) (long) k);
2189 ig.Emit (OpCodes.Conv_U8);
2193 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
2197 IntConstant.EmitInt (ig, (int) ((char) k));
2198 else if (k is sbyte)
2199 IntConstant.EmitInt (ig, (int) ((sbyte) k));
2201 IntConstant.EmitInt (ig, (int) ((byte) k));
2202 else if (k is short)
2203 IntConstant.EmitInt (ig, (int) ((short) k));
2204 else if (k is ushort)
2205 IntConstant.EmitInt (ig, (int) ((ushort) k));
2207 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
2209 throw new Exception ("Unhandled case");
2212 // structure used to hold blocks of keys while calculating table switch
2213 class KeyBlock : IComparable
2215 public KeyBlock (long _nFirst)
2217 nFirst = nLast = _nFirst;
2221 public ArrayList rgKeys = null;
2224 get { return (int) (nLast - nFirst + 1); }
2226 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
2228 return kbLast.nLast - kbFirst.nFirst + 1;
2230 public int CompareTo (object obj)
2232 KeyBlock kb = (KeyBlock) obj;
2233 int nLength = Length;
2234 int nLengthOther = kb.Length;
2235 if (nLengthOther == nLength)
2236 return (int) (kb.nFirst - nFirst);
2237 return nLength - nLengthOther;
2242 /// This method emits code for a lookup-based switch statement (non-string)
2243 /// Basically it groups the cases into blocks that are at least half full,
2244 /// and then spits out individual lookup opcodes for each block.
2245 /// It emits the longest blocks first, and short blocks are just
2246 /// handled with direct compares.
2248 /// <param name="ec"></param>
2249 /// <param name="val"></param>
2250 /// <returns></returns>
2251 void TableSwitchEmit (EmitContext ec, LocalBuilder val)
2253 int cElements = Elements.Count;
2254 object [] rgKeys = new object [cElements];
2255 Elements.Keys.CopyTo (rgKeys, 0);
2256 Array.Sort (rgKeys);
2258 // initialize the block list with one element per key
2259 ArrayList rgKeyBlocks = new ArrayList ();
2260 foreach (object key in rgKeys)
2261 rgKeyBlocks.Add (new KeyBlock (System.Convert.ToInt64 (key)));
2264 // iteratively merge the blocks while they are at least half full
2265 // there's probably a really cool way to do this with a tree...
2266 while (rgKeyBlocks.Count > 1)
2268 ArrayList rgKeyBlocksNew = new ArrayList ();
2269 kbCurr = (KeyBlock) rgKeyBlocks [0];
2270 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
2272 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
2273 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
2276 kbCurr.nLast = kb.nLast;
2280 // start a new block
2281 rgKeyBlocksNew.Add (kbCurr);
2285 rgKeyBlocksNew.Add (kbCurr);
2286 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
2288 rgKeyBlocks = rgKeyBlocksNew;
2291 // initialize the key lists
2292 foreach (KeyBlock kb in rgKeyBlocks)
2293 kb.rgKeys = new ArrayList ();
2295 // fill the key lists
2297 if (rgKeyBlocks.Count > 0) {
2298 kbCurr = (KeyBlock) rgKeyBlocks [0];
2299 foreach (object key in rgKeys)
2301 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast :
2302 System.Convert.ToInt64 (key) > kbCurr.nLast;
2304 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
2305 kbCurr.rgKeys.Add (key);
2309 // sort the blocks so we can tackle the largest ones first
2310 rgKeyBlocks.Sort ();
2312 // okay now we can start...
2313 ILGenerator ig = ec.ig;
2314 Label lblEnd = ig.DefineLabel (); // at the end ;-)
2315 Label lblDefault = ig.DefineLabel ();
2317 Type typeKeys = null;
2318 if (rgKeys.Length > 0)
2319 typeKeys = rgKeys [0].GetType (); // used for conversions
2323 if (TypeManager.IsEnumType (SwitchType))
2324 compare_type = TypeManager.EnumToUnderlying (SwitchType);
2326 compare_type = SwitchType;
2328 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
2330 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
2331 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
2334 foreach (object key in kb.rgKeys)
2336 ig.Emit (OpCodes.Ldloc, val);
2337 EmitObjectInteger (ig, key);
2338 SwitchLabel sl = (SwitchLabel) Elements [key];
2339 ig.Emit (OpCodes.Beq, sl.ILLabel);
2344 // TODO: if all the keys in the block are the same and there are
2345 // no gaps/defaults then just use a range-check.
2346 if (compare_type == TypeManager.int64_type ||
2347 compare_type == TypeManager.uint64_type)
2349 // TODO: optimize constant/I4 cases
2351 // check block range (could be > 2^31)
2352 ig.Emit (OpCodes.Ldloc, val);
2353 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2354 ig.Emit (OpCodes.Blt, lblDefault);
2355 ig.Emit (OpCodes.Ldloc, val);
2356 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nLast, typeKeys));
2357 ig.Emit (OpCodes.Bgt, lblDefault);
2360 ig.Emit (OpCodes.Ldloc, val);
2363 EmitObjectInteger (ig, System.Convert.ChangeType (kb.nFirst, typeKeys));
2364 ig.Emit (OpCodes.Sub);
2366 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
2371 ig.Emit (OpCodes.Ldloc, val);
2372 int nFirst = (int) kb.nFirst;
2375 IntConstant.EmitInt (ig, nFirst);
2376 ig.Emit (OpCodes.Sub);
2378 else if (nFirst < 0)
2380 IntConstant.EmitInt (ig, -nFirst);
2381 ig.Emit (OpCodes.Add);
2385 // first, build the list of labels for the switch
2387 int cJumps = kb.Length;
2388 Label [] rgLabels = new Label [cJumps];
2389 for (int iJump = 0; iJump < cJumps; iJump++)
2391 object key = kb.rgKeys [iKey];
2392 if (System.Convert.ToInt64 (key) == kb.nFirst + iJump)
2394 SwitchLabel sl = (SwitchLabel) Elements [key];
2395 rgLabels [iJump] = sl.ILLabel;
2399 rgLabels [iJump] = lblDefault;
2401 // emit the switch opcode
2402 ig.Emit (OpCodes.Switch, rgLabels);
2405 // mark the default for this block
2407 ig.MarkLabel (lblDefault);
2410 // TODO: find the default case and emit it here,
2411 // to prevent having to do the following jump.
2412 // make sure to mark other labels in the default section
2414 // the last default just goes to the end
2415 ig.Emit (OpCodes.Br, lblDefault);
2417 // now emit the code for the sections
2418 bool fFoundDefault = false;
2419 foreach (SwitchSection ss in Sections)
2421 foreach (SwitchLabel sl in ss.Labels)
2423 ig.MarkLabel (sl.ILLabel);
2424 ig.MarkLabel (sl.ILLabelCode);
2425 if (sl.Label == null)
2427 ig.MarkLabel (lblDefault);
2428 fFoundDefault = true;
2432 //ig.Emit (OpCodes.Br, lblEnd);
2435 if (!fFoundDefault) {
2436 ig.MarkLabel (lblDefault);
2438 ig.MarkLabel (lblEnd);
2441 // This simple emit switch works, but does not take advantage of the
2443 // TODO: remove non-string logic from here
2444 // TODO: binary search strings?
2446 void SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
2448 ILGenerator ig = ec.ig;
2449 Label end_of_switch = ig.DefineLabel ();
2450 Label next_test = ig.DefineLabel ();
2451 Label null_target = ig.DefineLabel ();
2452 bool default_found = false;
2453 bool first_test = true;
2454 bool pending_goto_end = false;
2457 ig.Emit (OpCodes.Ldloc, val);
2459 if (Elements.Contains (NullLiteral.Null)){
2460 ig.Emit (OpCodes.Brfalse, null_target);
2462 ig.Emit (OpCodes.Brfalse, default_target);
2464 ig.Emit (OpCodes.Ldloc, val);
2465 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
2466 ig.Emit (OpCodes.Stloc, val);
2468 int section_count = Sections.Count;
2469 for (int section = 0; section < section_count; section++){
2470 SwitchSection ss = (SwitchSection) Sections [section];
2471 Label sec_begin = ig.DefineLabel ();
2473 if (pending_goto_end)
2474 ig.Emit (OpCodes.Br, end_of_switch);
2476 int label_count = ss.Labels.Count;
2478 for (int label = 0; label < label_count; label++){
2479 SwitchLabel sl = (SwitchLabel) ss.Labels [label];
2480 ig.MarkLabel (sl.ILLabel);
2483 ig.MarkLabel (next_test);
2484 next_test = ig.DefineLabel ();
2487 // If we are the default target
2489 if (sl.Label == null){
2490 ig.MarkLabel (default_target);
2491 default_found = true;
2493 object lit = sl.Converted;
2495 if (lit is NullLiteral){
2497 if (label_count == 1)
2498 ig.Emit (OpCodes.Br, next_test);
2502 StringConstant str = (StringConstant) lit;
2504 ig.Emit (OpCodes.Ldloc, val);
2505 ig.Emit (OpCodes.Ldstr, str.Value);
2506 if (label_count == 1)
2507 ig.Emit (OpCodes.Bne_Un, next_test);
2509 if (label+1 == label_count)
2510 ig.Emit (OpCodes.Bne_Un, next_test);
2512 ig.Emit (OpCodes.Beq, sec_begin);
2517 ig.MarkLabel (null_target);
2518 ig.MarkLabel (sec_begin);
2519 foreach (SwitchLabel sl in ss.Labels)
2520 ig.MarkLabel (sl.ILLabelCode);
2523 pending_goto_end = !ss.Block.HasRet;
2526 if (!default_found){
2527 ig.MarkLabel (default_target);
2529 ig.MarkLabel (next_test);
2530 ig.MarkLabel (end_of_switch);
2533 public override bool Resolve (EmitContext ec)
2535 Expr = Expr.Resolve (ec);
2539 new_expr = SwitchGoverningType (ec, Expr.Type);
2540 if (new_expr == null){
2541 Report.Error (151, loc, "An integer type or string was expected for switch");
2546 SwitchType = new_expr.Type;
2548 if (!CheckSwitch (ec))
2551 Switch old_switch = ec.Switch;
2553 ec.Switch.SwitchType = SwitchType;
2555 ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
2558 foreach (SwitchSection ss in Sections){
2560 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2564 if (ss.Block.Resolve (ec) != true)
2570 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.SwitchSection);
2572 ec.EndFlowBranching ();
2573 ec.Switch = old_switch;
2578 protected override void DoEmit (EmitContext ec)
2580 // Store variable for comparission purposes
2581 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2583 ec.ig.Emit (OpCodes.Stloc, value);
2585 ILGenerator ig = ec.ig;
2587 default_target = ig.DefineLabel ();
2590 // Setup the codegen context
2592 Label old_end = ec.LoopEnd;
2593 Switch old_switch = ec.Switch;
2595 ec.LoopEnd = ig.DefineLabel ();
2599 if (SwitchType == TypeManager.string_type)
2600 SimpleSwitchEmit (ec, value);
2602 TableSwitchEmit (ec, value);
2604 // Restore context state.
2605 ig.MarkLabel (ec.LoopEnd);
2608 // Restore the previous context
2610 ec.LoopEnd = old_end;
2611 ec.Switch = old_switch;
2615 public class Lock : Statement {
2617 Statement Statement;
2619 public Lock (Expression expr, Statement stmt, Location l)
2626 public override bool Resolve (EmitContext ec)
2628 expr = expr.Resolve (ec);
2629 return Statement.Resolve (ec) && expr != null;
2632 protected override void DoEmit (EmitContext ec)
2634 Type type = expr.Type;
2637 if (type.IsValueType){
2638 Report.Error (185, loc, "lock statement requires the expression to be " +
2639 " a reference type (type is: `" +
2640 TypeManager.CSharpName (type) + "'");
2644 ILGenerator ig = ec.ig;
2645 LocalBuilder temp = ig.DeclareLocal (type);
2648 ig.Emit (OpCodes.Dup);
2649 ig.Emit (OpCodes.Stloc, temp);
2650 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2653 Label end = ig.BeginExceptionBlock ();
2654 bool old_in_try = ec.InTry;
2656 Label finish = ig.DefineLabel ();
2657 Statement.Emit (ec);
2658 ec.InTry = old_in_try;
2659 // ig.Emit (OpCodes.Leave, finish);
2661 ig.MarkLabel (finish);
2664 ig.BeginFinallyBlock ();
2665 ig.Emit (OpCodes.Ldloc, temp);
2666 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2667 ig.EndExceptionBlock ();
2671 public class Unchecked : Statement {
2672 public readonly Block Block;
2674 public Unchecked (Block b)
2680 public override bool Resolve (EmitContext ec)
2682 bool previous_state = ec.CheckState;
2683 bool previous_state_const = ec.ConstantCheckState;
2685 ec.CheckState = false;
2686 ec.ConstantCheckState = false;
2687 bool ret = Block.Resolve (ec);
2688 ec.CheckState = previous_state;
2689 ec.ConstantCheckState = previous_state_const;
2694 protected override void DoEmit (EmitContext ec)
2696 bool previous_state = ec.CheckState;
2697 bool previous_state_const = ec.ConstantCheckState;
2699 ec.CheckState = false;
2700 ec.ConstantCheckState = false;
2702 ec.CheckState = previous_state;
2703 ec.ConstantCheckState = previous_state_const;
2707 public class Checked : Statement {
2708 public readonly Block Block;
2710 public Checked (Block b)
2713 b.Unchecked = false;
2716 public override bool Resolve (EmitContext ec)
2718 bool previous_state = ec.CheckState;
2719 bool previous_state_const = ec.ConstantCheckState;
2721 ec.CheckState = true;
2722 ec.ConstantCheckState = true;
2723 bool ret = Block.Resolve (ec);
2724 ec.CheckState = previous_state;
2725 ec.ConstantCheckState = previous_state_const;
2730 protected override void DoEmit (EmitContext ec)
2732 bool previous_state = ec.CheckState;
2733 bool previous_state_const = ec.ConstantCheckState;
2735 ec.CheckState = true;
2736 ec.ConstantCheckState = true;
2738 ec.CheckState = previous_state;
2739 ec.ConstantCheckState = previous_state_const;
2743 public class Unsafe : Statement {
2744 public readonly Block Block;
2746 public Unsafe (Block b)
2751 public override bool Resolve (EmitContext ec)
2753 bool previous_state = ec.InUnsafe;
2757 val = Block.Resolve (ec);
2758 ec.InUnsafe = previous_state;
2763 protected override void DoEmit (EmitContext ec)
2765 bool previous_state = ec.InUnsafe;
2769 ec.InUnsafe = previous_state;
2776 public class Fixed : Statement {
2778 ArrayList declarators;
2779 Statement statement;
2785 public bool is_object;
2786 public LocalInfo vi;
2787 public Expression expr;
2788 public Expression converted;
2791 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2794 declarators = decls;
2799 public override bool Resolve (EmitContext ec)
2802 Expression.UnsafeError (loc);
2806 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2807 if (expr_type == null)
2810 if (ec.RemapToProxy){
2811 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2815 data = new FixedData [declarators.Count];
2817 if (!expr_type.IsPointer){
2818 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2823 foreach (Pair p in declarators){
2824 LocalInfo vi = (LocalInfo) p.First;
2825 Expression e = (Expression) p.Second;
2827 vi.VariableInfo = null;
2831 // The rules for the possible declarators are pretty wise,
2832 // but the production on the grammar is more concise.
2834 // So we have to enforce these rules here.
2836 // We do not resolve before doing the case 1 test,
2837 // because the grammar is explicit in that the token &
2838 // is present, so we need to test for this particular case.
2842 // Case 1: & object.
2844 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2845 Expression child = ((Unary) e).Expr;
2848 if (child is ParameterReference || child is LocalVariableReference){
2851 "No need to use fixed statement for parameters or " +
2852 "local variable declarations (address is already " +
2857 ec.InFixedInitializer = true;
2859 ec.InFixedInitializer = false;
2863 child = ((Unary) e).Expr;
2865 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2868 data [i].is_object = true;
2870 data [i].converted = null;
2877 ec.InFixedInitializer = true;
2879 ec.InFixedInitializer = false;
2886 if (e.Type.IsArray){
2887 Type array_type = TypeManager.GetElementType (e.Type);
2891 // Provided that array_type is unmanaged,
2893 if (!TypeManager.VerifyUnManaged (array_type, loc))
2897 // and T* is implicitly convertible to the
2898 // pointer type given in the fixed statement.
2900 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2902 Expression converted = Convert.ImplicitConversionRequired (
2903 ec, array_ptr, vi.VariableType, loc);
2904 if (converted == null)
2907 data [i].is_object = false;
2909 data [i].converted = converted;
2919 if (e.Type == TypeManager.string_type){
2920 data [i].is_object = false;
2922 data [i].converted = null;
2928 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
2930 if (!statement.Resolve (ec)) {
2931 ec.KillFlowBranching ();
2935 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2936 has_ret = reachability.IsUnreachable;
2941 protected override void DoEmit (EmitContext ec)
2943 ILGenerator ig = ec.ig;
2945 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
2947 for (int i = 0; i < data.Length; i++) {
2948 LocalInfo vi = data [i].vi;
2951 // Case 1: & object.
2953 if (data [i].is_object) {
2955 // Store pointer in pinned location
2957 data [i].expr.Emit (ec);
2958 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2959 clear_list [i] = vi.LocalBuilder;
2966 if (data [i].expr.Type.IsArray){
2968 // Store pointer in pinned location
2970 data [i].converted.Emit (ec);
2972 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2973 clear_list [i] = vi.LocalBuilder;
2980 if (data [i].expr.Type == TypeManager.string_type){
2981 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
2982 TypeManager.MakePinned (pinned_string);
2983 clear_list [i] = pinned_string;
2985 data [i].expr.Emit (ec);
2986 ig.Emit (OpCodes.Stloc, pinned_string);
2988 Expression sptr = new StringPtr (pinned_string, loc);
2989 Expression converted = Convert.ImplicitConversionRequired (
2990 ec, sptr, vi.VariableType, loc);
2992 if (converted == null)
2995 converted.Emit (ec);
2996 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3000 statement.Emit (ec);
3006 // Clear the pinned variable
3008 for (int i = 0; i < data.Length; i++) {
3009 LocalInfo vi = data [i].vi;
3011 if (data [i].is_object || data [i].expr.Type.IsArray) {
3012 ig.Emit (OpCodes.Ldc_I4_0);
3013 ig.Emit (OpCodes.Conv_U);
3014 ig.Emit (OpCodes.Stloc, clear_list [i]);
3015 } else if (data [i].expr.Type == TypeManager.string_type){
3016 ig.Emit (OpCodes.Ldnull);
3017 ig.Emit (OpCodes.Stloc, clear_list [i]);
3023 public class Catch {
3024 public readonly string Name;
3025 public readonly Block Block;
3026 public readonly Location Location;
3028 Expression type_expr;
3031 public Catch (Expression type, string name, Block block, Location l)
3039 public Type CatchType {
3045 public bool IsGeneral {
3047 return type_expr == null;
3051 public bool Resolve (EmitContext ec)
3053 if (type_expr != null) {
3054 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3058 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3059 Report.Error (155, Location,
3060 "The type caught or thrown must be derived " +
3061 "from System.Exception");
3067 if (!Block.Resolve (ec))
3074 public class Try : Statement {
3075 public readonly Block Fini, Block;
3076 public readonly ArrayList Specific;
3077 public readonly Catch General;
3080 // specific, general and fini might all be null.
3082 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3084 if (specific == null && general == null){
3085 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3089 this.Specific = specific;
3090 this.General = general;
3095 public override bool Resolve (EmitContext ec)
3099 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3101 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3103 bool old_in_try = ec.InTry;
3106 if (!Block.Resolve (ec))
3109 ec.InTry = old_in_try;
3111 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3113 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3115 foreach (Catch c in Specific){
3116 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3117 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3119 if (c.Name != null) {
3120 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3122 throw new Exception ();
3124 vi.VariableInfo = null;
3127 bool old_in_catch = ec.InCatch;
3130 if (!c.Resolve (ec))
3133 ec.InCatch = old_in_catch;
3136 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3138 if (General != null){
3139 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3140 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3142 bool old_in_catch = ec.InCatch;
3145 if (!General.Resolve (ec))
3148 ec.InCatch = old_in_catch;
3151 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3155 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
3156 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3158 bool old_in_finally = ec.InFinally;
3159 ec.InFinally = true;
3161 if (!Fini.Resolve (ec))
3164 ec.InFinally = old_in_finally;
3167 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3169 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3171 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3173 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3174 // Unfortunately, System.Reflection.Emit automatically emits a leave
3175 // to the end of the finally block. This is a problem if `returns'
3176 // is true since we may jump to a point after the end of the method.
3177 // As a workaround, emit an explicit ret here.
3178 ec.NeedExplicitReturn = true;
3184 protected override void DoEmit (EmitContext ec)
3186 ILGenerator ig = ec.ig;
3188 Label finish = ig.DefineLabel ();;
3191 end = ig.BeginExceptionBlock ();
3192 bool old_in_try = ec.InTry;
3195 ec.InTry = old_in_try;
3198 // System.Reflection.Emit provides this automatically:
3199 // ig.Emit (OpCodes.Leave, finish);
3201 bool old_in_catch = ec.InCatch;
3203 DeclSpace ds = ec.DeclSpace;
3205 foreach (Catch c in Specific){
3208 ig.BeginCatchBlock (c.CatchType);
3210 if (c.Name != null){
3211 vi = c.Block.GetLocalInfo (c.Name);
3213 throw new Exception ("Variable does not exist in this block");
3215 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3217 ig.Emit (OpCodes.Pop);
3222 if (General != null){
3223 ig.BeginCatchBlock (TypeManager.object_type);
3224 ig.Emit (OpCodes.Pop);
3225 General.Block.Emit (ec);
3227 ec.InCatch = old_in_catch;
3229 ig.MarkLabel (finish);
3231 ig.BeginFinallyBlock ();
3232 bool old_in_finally = ec.InFinally;
3233 ec.InFinally = true;
3235 ec.InFinally = old_in_finally;
3238 ig.EndExceptionBlock ();
3243 public class Using : Statement {
3244 object expression_or_block;
3245 Statement Statement;
3250 Expression [] converted_vars;
3251 ExpressionStatement [] assign;
3253 public Using (object expression_or_block, Statement stmt, Location l)
3255 this.expression_or_block = expression_or_block;
3261 // Resolves for the case of using using a local variable declaration.
3263 bool ResolveLocalVariableDecls (EmitContext ec)
3265 bool need_conv = false;
3266 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3269 if (expr_type == null)
3273 // The type must be an IDisposable or an implicit conversion
3276 converted_vars = new Expression [var_list.Count];
3277 assign = new ExpressionStatement [var_list.Count];
3278 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3279 foreach (DictionaryEntry e in var_list){
3280 Expression var = (Expression) e.Key;
3282 var = var.ResolveLValue (ec, new EmptyExpression ());
3286 converted_vars [i] = Convert.ImplicitConversionRequired (
3287 ec, var, TypeManager.idisposable_type, loc);
3289 if (converted_vars [i] == null)
3297 foreach (DictionaryEntry e in var_list){
3298 LocalVariableReference var = (LocalVariableReference) e.Key;
3299 Expression new_expr = (Expression) e.Value;
3302 a = new Assign (var, new_expr, loc);
3308 converted_vars [i] = var;
3309 assign [i] = (ExpressionStatement) a;
3316 bool ResolveExpression (EmitContext ec)
3318 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3319 conv = Convert.ImplicitConversionRequired (
3320 ec, expr, TypeManager.idisposable_type, loc);
3330 // Emits the code for the case of using using a local variable declaration.
3332 bool EmitLocalVariableDecls (EmitContext ec)
3334 ILGenerator ig = ec.ig;
3337 bool old_in_try = ec.InTry;
3339 for (i = 0; i < assign.Length; i++) {
3340 assign [i].EmitStatement (ec);
3342 ig.BeginExceptionBlock ();
3344 Statement.Emit (ec);
3345 ec.InTry = old_in_try;
3347 bool old_in_finally = ec.InFinally;
3348 ec.InFinally = true;
3349 var_list.Reverse ();
3350 foreach (DictionaryEntry e in var_list){
3351 LocalVariableReference var = (LocalVariableReference) e.Key;
3352 Label skip = ig.DefineLabel ();
3355 ig.BeginFinallyBlock ();
3358 ig.Emit (OpCodes.Brfalse, skip);
3359 converted_vars [i].Emit (ec);
3360 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3361 ig.MarkLabel (skip);
3362 ig.EndExceptionBlock ();
3364 ec.InFinally = old_in_finally;
3369 bool EmitExpression (EmitContext ec)
3372 // Make a copy of the expression and operate on that.
3374 ILGenerator ig = ec.ig;
3375 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3380 ig.Emit (OpCodes.Stloc, local_copy);
3382 bool old_in_try = ec.InTry;
3384 ig.BeginExceptionBlock ();
3385 Statement.Emit (ec);
3386 ec.InTry = old_in_try;
3388 Label skip = ig.DefineLabel ();
3389 bool old_in_finally = ec.InFinally;
3390 ig.BeginFinallyBlock ();
3391 ig.Emit (OpCodes.Ldloc, local_copy);
3392 ig.Emit (OpCodes.Brfalse, skip);
3393 ig.Emit (OpCodes.Ldloc, local_copy);
3394 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3395 ig.MarkLabel (skip);
3396 ec.InFinally = old_in_finally;
3397 ig.EndExceptionBlock ();
3402 public override bool Resolve (EmitContext ec)
3404 if (expression_or_block is DictionaryEntry){
3405 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3406 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3408 if (!ResolveLocalVariableDecls (ec))
3411 } else if (expression_or_block is Expression){
3412 expr = (Expression) expression_or_block;
3414 expr = expr.Resolve (ec);
3418 expr_type = expr.Type;
3420 if (!ResolveExpression (ec))
3424 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
3426 bool ok = Statement.Resolve (ec);
3429 ec.KillFlowBranching ();
3433 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3435 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3436 // Unfortunately, System.Reflection.Emit automatically emits a leave
3437 // to the end of the finally block. This is a problem if `returns'
3438 // is true since we may jump to a point after the end of the method.
3439 // As a workaround, emit an explicit ret here.
3440 ec.NeedExplicitReturn = true;
3446 protected override void DoEmit (EmitContext ec)
3448 if (expression_or_block is DictionaryEntry)
3449 EmitLocalVariableDecls (ec);
3450 else if (expression_or_block is Expression)
3451 EmitExpression (ec);
3456 /// Implementation of the foreach C# statement
3458 public class Foreach : Statement {
3460 Expression variable;
3462 Statement statement;
3463 ForeachHelperMethods hm;
3464 Expression empty, conv;
3465 Type array_type, element_type;
3468 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3469 Statement stmt, Location l)
3472 this.variable = var;
3478 public override bool Resolve (EmitContext ec)
3480 expr = expr.Resolve (ec);
3484 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3485 if (var_type == null)
3489 // We need an instance variable. Not sure this is the best
3490 // way of doing this.
3492 // FIXME: When we implement propertyaccess, will those turn
3493 // out to return values in ExprClass? I think they should.
3495 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3496 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3497 error1579 (expr.Type);
3501 if (expr.Type.IsArray) {
3502 array_type = expr.Type;
3503 element_type = TypeManager.GetElementType (array_type);
3505 empty = new EmptyExpression (element_type);
3507 hm = ProbeCollectionType (ec, expr.Type);
3509 error1579 (expr.Type);
3513 array_type = expr.Type;
3514 element_type = hm.element_type;
3516 empty = new EmptyExpression (hm.element_type);
3519 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
3520 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
3524 // FIXME: maybe we can apply the same trick we do in the
3525 // array handling to avoid creating empty and conv in some cases.
3527 // Although it is not as important in this case, as the type
3528 // will not likely be object (what the enumerator will return).
3530 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3534 variable = variable.ResolveLValue (ec, empty);
3535 if (variable == null)
3538 if (!statement.Resolve (ec))
3541 ec.EndFlowBranching ();
3547 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3549 static MethodInfo FetchMethodMoveNext (Type t)
3551 MemberList move_next_list;
3553 move_next_list = TypeContainer.FindMembers (
3554 t, MemberTypes.Method,
3555 BindingFlags.Public | BindingFlags.Instance,
3556 Type.FilterName, "MoveNext");
3557 if (move_next_list.Count == 0)
3560 foreach (MemberInfo m in move_next_list){
3561 MethodInfo mi = (MethodInfo) m;
3564 args = TypeManager.GetArgumentTypes (mi);
3565 if (args != null && args.Length == 0){
3566 if (mi.ReturnType == TypeManager.bool_type)
3574 // Retrieves a `public T get_Current ()' method from the Type `t'
3576 static MethodInfo FetchMethodGetCurrent (Type t)
3578 MemberList get_current_list;
3580 get_current_list = TypeContainer.FindMembers (
3581 t, MemberTypes.Method,
3582 BindingFlags.Public | BindingFlags.Instance,
3583 Type.FilterName, "get_Current");
3584 if (get_current_list.Count == 0)
3587 foreach (MemberInfo m in get_current_list){
3588 MethodInfo mi = (MethodInfo) m;
3591 args = TypeManager.GetArgumentTypes (mi);
3592 if (args != null && args.Length == 0)
3599 // This struct records the helper methods used by the Foreach construct
3601 class ForeachHelperMethods {
3602 public EmitContext ec;
3603 public MethodInfo get_enumerator;
3604 public MethodInfo move_next;
3605 public MethodInfo get_current;
3606 public Type element_type;
3607 public Type enumerator_type;
3608 public bool is_disposable;
3610 public ForeachHelperMethods (EmitContext ec)
3613 this.element_type = TypeManager.object_type;
3614 this.enumerator_type = TypeManager.ienumerator_type;
3615 this.is_disposable = true;
3619 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3624 if (!(m is MethodInfo))
3627 if (m.Name != "GetEnumerator")
3630 MethodInfo mi = (MethodInfo) m;
3631 Type [] args = TypeManager.GetArgumentTypes (mi);
3633 if (args.Length != 0)
3636 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3637 EmitContext ec = hm.ec;
3640 // Check whether GetEnumerator is accessible to us
3642 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3644 Type declaring = mi.DeclaringType;
3645 if (prot == MethodAttributes.Private){
3646 if (declaring != ec.ContainerType)
3648 } else if (prot == MethodAttributes.FamANDAssem){
3649 // If from a different assembly, false
3650 if (!(mi is MethodBuilder))
3653 // Are we being invoked from the same class, or from a derived method?
3655 if (ec.ContainerType != declaring){
3656 if (!ec.ContainerType.IsSubclassOf (declaring))
3659 } else if (prot == MethodAttributes.FamORAssem){
3660 if (!(mi is MethodBuilder ||
3661 ec.ContainerType == declaring ||
3662 ec.ContainerType.IsSubclassOf (declaring)))
3664 } if (prot == MethodAttributes.Family){
3665 if (!(ec.ContainerType == declaring ||
3666 ec.ContainerType.IsSubclassOf (declaring)))
3670 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3672 // Apply the same optimization as MS: skip the GetEnumerator
3673 // returning an IEnumerator, and use the one returning a
3674 // CharEnumerator instead. This allows us to avoid the
3675 // try-finally block and the boxing.
3680 // Ok, we can access it, now make sure that we can do something
3681 // with this `GetEnumerator'
3684 if (mi.ReturnType == TypeManager.ienumerator_type ||
3685 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
3686 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
3687 if (declaring != TypeManager.string_type) {
3688 hm.move_next = TypeManager.bool_movenext_void;
3689 hm.get_current = TypeManager.object_getcurrent_void;
3695 // Ok, so they dont return an IEnumerable, we will have to
3696 // find if they support the GetEnumerator pattern.
3698 Type return_type = mi.ReturnType;
3700 hm.move_next = FetchMethodMoveNext (return_type);
3701 if (hm.move_next == null)
3703 hm.get_current = FetchMethodGetCurrent (return_type);
3704 if (hm.get_current == null)
3707 hm.element_type = hm.get_current.ReturnType;
3708 hm.enumerator_type = return_type;
3709 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3710 TypeManager.ImplementsInterface (
3711 hm.enumerator_type, TypeManager.idisposable_type);
3717 /// This filter is used to find the GetEnumerator method
3718 /// on which IEnumerator operates
3720 static MemberFilter FilterEnumerator;
3724 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3727 void error1579 (Type t)
3729 Report.Error (1579, loc,
3730 "foreach statement cannot operate on variables of type `" +
3731 t.FullName + "' because that class does not provide a " +
3732 " GetEnumerator method or it is inaccessible");
3735 static bool TryType (Type t, ForeachHelperMethods hm)
3739 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3740 BindingFlags.Public | BindingFlags.NonPublic |
3741 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3742 FilterEnumerator, hm);
3747 hm.get_enumerator = (MethodInfo) mi [0];
3752 // Looks for a usable GetEnumerator in the Type, and if found returns
3753 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3755 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3757 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3759 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3760 if (TryType (tt, hm))
3766 // Now try to find the method in the interfaces
3769 Type [] ifaces = t.GetInterfaces ();
3771 foreach (Type i in ifaces){
3772 if (TryType (i, hm))
3777 // Since TypeBuilder.GetInterfaces only returns the interface
3778 // types for this type, we have to keep looping, but once
3779 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3780 // done, because it returns all the types
3782 if ((t is TypeBuilder))
3792 // FIXME: possible optimization.
3793 // We might be able to avoid creating `empty' if the type is the sam
3795 bool EmitCollectionForeach (EmitContext ec)
3797 ILGenerator ig = ec.ig;
3798 VariableStorage enumerator, disposable;
3800 enumerator = new VariableStorage (ec, hm.enumerator_type);
3801 if (hm.is_disposable)
3802 disposable = new VariableStorage (ec, TypeManager.idisposable_type);
3806 enumerator.EmitThis ();
3808 // Instantiate the enumerator
3810 if (expr.Type.IsValueType){
3811 if (expr is IMemoryLocation){
3812 IMemoryLocation ml = (IMemoryLocation) expr;
3814 ml.AddressOf (ec, AddressOp.Load);
3816 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3817 " does not implement IMemoryLocation");
3818 ig.Emit (OpCodes.Call, hm.get_enumerator);
3821 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3823 enumerator.EmitStore ();
3826 // Protect the code in a try/finalize block, so that
3827 // if the beast implement IDisposable, we get rid of it
3830 bool old_in_try = ec.InTry;
3832 if (hm.is_disposable) {
3833 l = ig.BeginExceptionBlock ();
3837 Label end_try = ig.DefineLabel ();
3839 ig.MarkLabel (ec.LoopBegin);
3840 enumerator.EmitLoad ();
3841 ig.Emit (OpCodes.Callvirt, hm.move_next);
3842 ig.Emit (OpCodes.Brfalse, end_try);
3846 enumerator.EmitLoad ();
3847 ig.Emit (OpCodes.Callvirt, hm.get_current);
3851 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3853 ((IAssignMethod)variable).EmitAssign (ec, conv);
3855 statement.Emit (ec);
3856 ig.Emit (OpCodes.Br, ec.LoopBegin);
3857 ig.MarkLabel (end_try);
3858 ec.InTry = old_in_try;
3860 // The runtime provides this for us.
3861 // ig.Emit (OpCodes.Leave, end);
3864 // Now the finally block
3866 if (hm.is_disposable) {
3867 Label end_finally = ig.DefineLabel ();
3868 bool old_in_finally = ec.InFinally;
3869 ec.InFinally = true;
3870 ig.BeginFinallyBlock ();
3872 disposable.EmitThis ();
3873 enumerator.EmitThis ();
3874 enumerator.EmitLoad ();
3875 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3876 disposable.EmitStore ();
3877 disposable.EmitLoad ();
3878 ig.Emit (OpCodes.Brfalse, end_finally);
3879 disposable.EmitThis ();
3880 disposable.EmitLoad ();
3881 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3882 ig.MarkLabel (end_finally);
3883 ec.InFinally = old_in_finally;
3885 // The runtime generates this anyways.
3886 // ig.Emit (OpCodes.Endfinally);
3888 ig.EndExceptionBlock ();
3891 ig.MarkLabel (ec.LoopEnd);
3896 // FIXME: possible optimization.
3897 // We might be able to avoid creating `empty' if the type is the sam
3899 bool EmitArrayForeach (EmitContext ec)
3901 int rank = array_type.GetArrayRank ();
3902 ILGenerator ig = ec.ig;
3904 VariableStorage copy = new VariableStorage (ec, array_type);
3907 // Make our copy of the array
3914 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
3918 counter.EmitThis ();
3919 ig.Emit (OpCodes.Ldc_I4_0);
3920 counter.EmitStore ();
3921 test = ig.DefineLabel ();
3922 ig.Emit (OpCodes.Br, test);
3924 loop = ig.DefineLabel ();
3925 ig.MarkLabel (loop);
3932 counter.EmitThis ();
3933 counter.EmitLoad ();
3936 // Load the value, we load the value using the underlying type,
3937 // then we use the variable.EmitAssign to load using the proper cast.
3939 ArrayAccess.EmitLoadOpcode (ig, element_type);
3942 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3944 ((IAssignMethod)variable).EmitAssign (ec, conv);
3946 statement.Emit (ec);
3948 ig.MarkLabel (ec.LoopBegin);
3949 counter.EmitThis ();
3950 counter.EmitThis ();
3951 counter.EmitLoad ();
3952 ig.Emit (OpCodes.Ldc_I4_1);
3953 ig.Emit (OpCodes.Add);
3954 counter.EmitStore ();
3956 ig.MarkLabel (test);
3957 counter.EmitThis ();
3958 counter.EmitLoad ();
3961 ig.Emit (OpCodes.Ldlen);
3962 ig.Emit (OpCodes.Conv_I4);
3963 ig.Emit (OpCodes.Blt, loop);
3965 VariableStorage [] dim_len = new VariableStorage [rank];
3966 VariableStorage [] dim_count = new VariableStorage [rank];
3967 Label [] loop = new Label [rank];
3968 Label [] test = new Label [rank];
3971 for (dim = 0; dim < rank; dim++){
3972 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
3973 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
3974 test [dim] = ig.DefineLabel ();
3975 loop [dim] = ig.DefineLabel ();
3978 for (dim = 0; dim < rank; dim++){
3979 dim_len [dim].EmitThis ();
3982 IntLiteral.EmitInt (ig, dim);
3983 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
3984 dim_len [dim].EmitStore ();
3988 for (dim = 0; dim < rank; dim++){
3989 dim_count [dim].EmitThis ();
3990 ig.Emit (OpCodes.Ldc_I4_0);
3991 dim_count [dim].EmitStore ();
3992 ig.Emit (OpCodes.Br, test [dim]);
3993 ig.MarkLabel (loop [dim]);
4000 for (dim = 0; dim < rank; dim++){
4001 dim_count [dim].EmitThis ();
4002 dim_count [dim].EmitLoad ();
4006 // FIXME: Maybe we can cache the computation of `get'?
4008 Type [] args = new Type [rank];
4011 for (int i = 0; i < rank; i++)
4012 args [i] = TypeManager.int32_type;
4014 ModuleBuilder mb = CodeGen.ModuleBuilder;
4015 get = mb.GetArrayMethod (
4017 CallingConventions.HasThis| CallingConventions.Standard,
4019 ig.Emit (OpCodes.Call, get);
4022 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4024 ((IAssignMethod)variable).EmitAssign (ec, conv);
4025 statement.Emit (ec);
4026 ig.MarkLabel (ec.LoopBegin);
4027 for (dim = rank - 1; dim >= 0; dim--){
4028 dim_count [dim].EmitThis ();
4029 dim_count [dim].EmitThis ();
4030 dim_count [dim].EmitLoad ();
4031 ig.Emit (OpCodes.Ldc_I4_1);
4032 ig.Emit (OpCodes.Add);
4033 dim_count [dim].EmitStore ();
4035 ig.MarkLabel (test [dim]);
4036 dim_count [dim].EmitThis ();
4037 dim_count [dim].EmitLoad ();
4038 dim_len [dim].EmitThis ();
4039 dim_len [dim].EmitLoad ();
4040 ig.Emit (OpCodes.Blt, loop [dim]);
4043 ig.MarkLabel (ec.LoopEnd);
4048 protected override void DoEmit (EmitContext ec)
4052 ILGenerator ig = ec.ig;
4054 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4055 bool old_inloop = ec.InLoop;
4056 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4057 ec.LoopBegin = ig.DefineLabel ();
4058 ec.LoopEnd = ig.DefineLabel ();
4060 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4063 ret_val = EmitCollectionForeach (ec);
4065 ret_val = EmitArrayForeach (ec);
4067 ec.LoopBegin = old_begin;
4068 ec.LoopEnd = old_end;
4069 ec.InLoop = old_inloop;
4070 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;