2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
6 // Martin Baulig (martin@gnome.org)
8 // (C) 2001, 2002, 2003 Ximian, Inc.
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Diagnostics;
17 namespace Mono.CSharp {
19 using System.Collections;
21 public abstract class Statement {
25 /// Resolves the statement, true means that all sub-statements
28 public virtual bool Resolve (EmitContext ec)
34 /// We already know that the statement is unreachable, but we still
35 /// need to resolve it to catch errors.
37 public virtual bool ResolveUnreachable (EmitContext ec, bool warn)
40 // This conflicts with csc's way of doing this, but IMHO it's
41 // the right thing to do.
43 // If something is unreachable, we still check whether it's
44 // correct. This means that you cannot use unassigned variables
45 // in unreachable code, for instance.
48 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
49 bool ok = Resolve (ec);
50 ec.KillFlowBranching ();
56 Report.Warning (162, loc, "Unreachable code detected");
61 /// Return value indicates whether all code paths emitted return.
63 protected abstract void DoEmit (EmitContext ec);
66 /// Return value indicates whether all code paths emitted return.
68 public virtual void Emit (EmitContext ec)
75 public sealed class EmptyStatement : Statement {
77 private EmptyStatement () {}
79 public static readonly EmptyStatement Value = new EmptyStatement ();
81 public override bool Resolve (EmitContext ec)
86 protected override void DoEmit (EmitContext ec)
91 public class If : Statement {
93 public Statement TrueStatement;
94 public Statement FalseStatement;
98 public If (Expression expr, Statement trueStatement, Location l)
101 TrueStatement = trueStatement;
105 public If (Expression expr,
106 Statement trueStatement,
107 Statement falseStatement,
111 TrueStatement = trueStatement;
112 FalseStatement = falseStatement;
116 public override bool Resolve (EmitContext ec)
118 Report.Debug (1, "START IF BLOCK", loc);
120 expr = Expression.ResolveBoolean (ec, expr, loc);
126 // Dead code elimination
128 if (expr is BoolConstant){
129 bool take = ((BoolConstant) expr).Value;
132 if (!TrueStatement.Resolve (ec))
135 if ((FalseStatement != null) &&
136 !FalseStatement.ResolveUnreachable (ec, true))
138 FalseStatement = null;
140 if (!TrueStatement.ResolveUnreachable (ec, true))
142 TrueStatement = null;
144 if ((FalseStatement != null) &&
145 !FalseStatement.Resolve (ec))
152 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
154 bool ok = TrueStatement.Resolve (ec);
156 is_true_ret = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
158 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
160 if ((FalseStatement != null) && !FalseStatement.Resolve (ec))
163 ec.EndFlowBranching ();
165 Report.Debug (1, "END IF BLOCK", loc);
170 protected override void DoEmit (EmitContext ec)
172 ILGenerator ig = ec.ig;
173 Label false_target = ig.DefineLabel ();
177 // If we're a boolean expression, Resolve() already
178 // eliminated dead code for us.
180 if (expr is BoolConstant){
181 bool take = ((BoolConstant) expr).Value;
184 TrueStatement.Emit (ec);
185 else if (FalseStatement != null)
186 FalseStatement.Emit (ec);
191 expr.EmitBranchable (ec, false_target, false);
193 TrueStatement.Emit (ec);
195 if (FalseStatement != null){
196 bool branch_emitted = false;
198 end = ig.DefineLabel ();
200 ig.Emit (OpCodes.Br, end);
201 branch_emitted = true;
204 ig.MarkLabel (false_target);
205 FalseStatement.Emit (ec);
210 ig.MarkLabel (false_target);
215 public class Do : Statement {
216 public Expression expr;
217 public readonly Statement EmbeddedStatement;
220 public Do (Statement statement, Expression boolExpr, Location l)
223 EmbeddedStatement = statement;
227 public override bool Resolve (EmitContext ec)
231 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
233 if (!EmbeddedStatement.Resolve (ec))
236 expr = Expression.ResolveBoolean (ec, expr, loc);
239 else if (expr is BoolConstant){
240 bool res = ((BoolConstant) expr).Value;
246 ec.CurrentBranching.Infinite = infinite;
247 ec.EndFlowBranching ();
252 protected override void DoEmit (EmitContext ec)
254 ILGenerator ig = ec.ig;
255 Label loop = ig.DefineLabel ();
256 Label old_begin = ec.LoopBegin;
257 Label old_end = ec.LoopEnd;
258 bool old_inloop = ec.InLoop;
259 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
261 ec.LoopBegin = ig.DefineLabel ();
262 ec.LoopEnd = ig.DefineLabel ();
264 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
267 EmbeddedStatement.Emit (ec);
268 ig.MarkLabel (ec.LoopBegin);
271 // Dead code elimination
273 if (expr is BoolConstant){
274 bool res = ((BoolConstant) expr).Value;
277 ec.ig.Emit (OpCodes.Br, loop);
279 expr.EmitBranchable (ec, loop, true);
281 ig.MarkLabel (ec.LoopEnd);
283 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
284 ec.LoopBegin = old_begin;
285 ec.LoopEnd = old_end;
286 ec.InLoop = old_inloop;
290 public class While : Statement {
291 public Expression expr;
292 public readonly Statement Statement;
293 bool infinite, empty;
295 public While (Expression boolExpr, Statement statement, Location l)
297 this.expr = boolExpr;
298 Statement = statement;
302 public override bool Resolve (EmitContext ec)
306 expr = Expression.ResolveBoolean (ec, expr, loc);
311 // Inform whether we are infinite or not
313 if (expr is BoolConstant){
314 BoolConstant bc = (BoolConstant) expr;
316 if (bc.Value == false){
317 if (!Statement.ResolveUnreachable (ec, true))
325 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
327 if (!Statement.Resolve (ec))
330 ec.CurrentBranching.Infinite = infinite;
331 ec.EndFlowBranching ();
336 protected override void DoEmit (EmitContext ec)
341 ILGenerator ig = ec.ig;
342 Label old_begin = ec.LoopBegin;
343 Label old_end = ec.LoopEnd;
344 bool old_inloop = ec.InLoop;
345 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
347 ec.LoopBegin = ig.DefineLabel ();
348 ec.LoopEnd = ig.DefineLabel ();
350 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
353 // Inform whether we are infinite or not
355 if (expr is BoolConstant){
356 ig.MarkLabel (ec.LoopBegin);
358 ig.Emit (OpCodes.Br, ec.LoopBegin);
361 // Inform that we are infinite (ie, `we return'), only
362 // if we do not `break' inside the code.
364 ig.MarkLabel (ec.LoopEnd);
366 Label while_loop = ig.DefineLabel ();
368 ig.Emit (OpCodes.Br, ec.LoopBegin);
369 ig.MarkLabel (while_loop);
373 ig.MarkLabel (ec.LoopBegin);
375 expr.EmitBranchable (ec, while_loop, true);
377 ig.MarkLabel (ec.LoopEnd);
380 ec.LoopBegin = old_begin;
381 ec.LoopEnd = old_end;
382 ec.InLoop = old_inloop;
383 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
387 public class For : Statement {
389 readonly Statement InitStatement;
390 readonly Statement Increment;
391 readonly Statement Statement;
392 bool infinite, empty;
394 public For (Statement initStatement,
400 InitStatement = initStatement;
402 Increment = increment;
403 Statement = statement;
407 public override bool Resolve (EmitContext ec)
411 if (InitStatement != null){
412 if (!InitStatement.Resolve (ec))
417 Test = Expression.ResolveBoolean (ec, Test, loc);
420 else if (Test is BoolConstant){
421 BoolConstant bc = (BoolConstant) Test;
423 if (bc.Value == false){
424 if (!Statement.ResolveUnreachable (ec, true))
426 if ((Increment != null) &&
427 !Increment.ResolveUnreachable (ec, false))
437 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
439 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
441 if (!Statement.Resolve (ec))
444 if (Increment != null){
445 if (!Increment.Resolve (ec))
449 ec.CurrentBranching.Infinite = infinite;
450 ec.EndFlowBranching ();
455 protected override void DoEmit (EmitContext ec)
460 ILGenerator ig = ec.ig;
461 Label old_begin = ec.LoopBegin;
462 Label old_end = ec.LoopEnd;
463 bool old_inloop = ec.InLoop;
464 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
465 Label loop = ig.DefineLabel ();
466 Label test = ig.DefineLabel ();
468 if (InitStatement != null && InitStatement != EmptyStatement.Value)
469 InitStatement.Emit (ec);
471 ec.LoopBegin = ig.DefineLabel ();
472 ec.LoopEnd = ig.DefineLabel ();
474 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
476 ig.Emit (OpCodes.Br, test);
480 ig.MarkLabel (ec.LoopBegin);
481 if (Increment != EmptyStatement.Value)
486 // If test is null, there is no test, and we are just
491 // The Resolve code already catches the case for
492 // Test == BoolConstant (false) so we know that
495 if (Test is BoolConstant)
496 ig.Emit (OpCodes.Br, loop);
498 Test.EmitBranchable (ec, loop, true);
501 ig.Emit (OpCodes.Br, loop);
502 ig.MarkLabel (ec.LoopEnd);
504 ec.LoopBegin = old_begin;
505 ec.LoopEnd = old_end;
506 ec.InLoop = old_inloop;
507 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;
511 public class StatementExpression : Statement {
512 ExpressionStatement expr;
514 public StatementExpression (ExpressionStatement expr, Location l)
520 public override bool Resolve (EmitContext ec)
522 expr = expr.ResolveStatement (ec);
526 protected override void DoEmit (EmitContext ec)
528 expr.EmitStatement (ec);
531 public override string ToString ()
533 return "StatementExpression (" + expr + ")";
538 /// Implements the return statement
540 public class Return : Statement {
541 public Expression Expr;
543 public Return (Expression expr, Location l)
549 public override bool Resolve (EmitContext ec)
552 Expr = Expr.Resolve (ec);
558 Report.Error (-206, loc, "Return statement not allowed inside iterators");
562 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
564 if (ec.CurrentBranching.InTryBlock ())
565 ec.CurrentBranching.AddFinallyVector (vector);
567 vector.CheckOutParameters (ec.CurrentBranching);
569 ec.CurrentBranching.CurrentUsageVector.Return ();
573 protected override void DoEmit (EmitContext ec)
576 Report.Error (157, loc, "Control can not leave the body of the finally block");
580 if (ec.ReturnType == null){
582 Report.Error (127, loc, "Return with a value not allowed here");
587 Report.Error (126, loc, "An object of type `" +
588 TypeManager.CSharpName (ec.ReturnType) + "' is " +
589 "expected for the return statement");
593 if (Expr.Type != ec.ReturnType)
594 Expr = Convert.ImplicitConversionRequired (
595 ec, Expr, ec.ReturnType, loc);
602 if (ec.InTry || ec.InCatch)
603 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
606 if (ec.InTry || ec.InCatch) {
607 if (!ec.HasReturnLabel) {
608 ec.ReturnLabel = ec.ig.DefineLabel ();
609 ec.HasReturnLabel = true;
611 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
613 ec.ig.Emit (OpCodes.Ret);
614 ec.NeedExplicitReturn = false;
619 public class Goto : Statement {
622 LabeledStatement label;
624 public override bool Resolve (EmitContext ec)
626 label = block.LookupLabel (target);
630 "No such label `" + target + "' in this scope");
634 // If this is a forward goto.
635 if (!label.IsDefined)
636 label.AddUsageVector (ec.CurrentBranching.CurrentUsageVector);
638 ec.CurrentBranching.CurrentUsageVector.Goto ();
643 public Goto (Block parent_block, string label, Location l)
645 block = parent_block;
650 public string Target {
656 protected override void DoEmit (EmitContext ec)
658 Label l = label.LabelTarget (ec);
659 ec.ig.Emit (OpCodes.Br, l);
663 public class LabeledStatement : Statement {
664 public readonly Location Location;
671 public LabeledStatement (string label_name, Location l)
676 public Label LabelTarget (EmitContext ec)
680 label = ec.ig.DefineLabel ();
686 public bool IsDefined {
692 public bool HasBeenReferenced {
698 public void AddUsageVector (FlowBranching.UsageVector vector)
701 vectors = new ArrayList ();
703 vectors.Add (vector.Clone ());
706 public override bool Resolve (EmitContext ec)
708 ec.CurrentBranching.Label (vectors);
715 protected override void DoEmit (EmitContext ec)
718 ec.ig.MarkLabel (label);
724 /// `goto default' statement
726 public class GotoDefault : Statement {
728 public GotoDefault (Location l)
733 public override bool Resolve (EmitContext ec)
735 ec.CurrentBranching.CurrentUsageVector.Goto ();
739 protected override void DoEmit (EmitContext ec)
741 if (ec.Switch == null){
742 Report.Error (153, loc, "goto default is only valid in a switch statement");
746 if (!ec.Switch.GotDefault){
747 Report.Error (159, loc, "No default target on switch statement");
750 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
755 /// `goto case' statement
757 public class GotoCase : Statement {
761 public GotoCase (Expression e, Location l)
767 public override bool Resolve (EmitContext ec)
769 if (ec.Switch == null){
770 Report.Error (153, loc, "goto case is only valid in a switch statement");
774 expr = expr.Resolve (ec);
778 if (!(expr is Constant)){
779 Report.Error (159, loc, "Target expression for goto case is not constant");
783 object val = Expression.ConvertIntLiteral (
784 (Constant) expr, ec.Switch.SwitchType, loc);
789 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
794 "No such label 'case " + val + "': for the goto case");
798 label = sl.ILLabelCode;
800 ec.CurrentBranching.CurrentUsageVector.Goto ();
804 protected override void DoEmit (EmitContext ec)
806 ec.ig.Emit (OpCodes.Br, label);
810 public class Throw : Statement {
813 public Throw (Expression expr, Location l)
819 public override bool Resolve (EmitContext ec)
822 expr = expr.Resolve (ec);
826 ExprClass eclass = expr.eclass;
828 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
829 eclass == ExprClass.Value || eclass == ExprClass.IndexerAccess)) {
830 expr.Error_UnexpectedKind ("value, variable, property or indexer access ");
836 if ((t != TypeManager.exception_type) &&
837 !t.IsSubclassOf (TypeManager.exception_type) &&
838 !(expr is NullLiteral)) {
839 Report.Error (155, loc,
840 "The type caught or thrown must be derived " +
841 "from System.Exception");
846 ec.CurrentBranching.CurrentUsageVector.Throw ();
850 protected override void DoEmit (EmitContext ec)
854 ec.ig.Emit (OpCodes.Rethrow);
858 "A throw statement with no argument is only " +
859 "allowed in a catch clause");
866 ec.ig.Emit (OpCodes.Throw);
870 public class Break : Statement {
872 public Break (Location l)
877 public override bool Resolve (EmitContext ec)
879 ec.CurrentBranching.CurrentUsageVector.Break ();
883 protected override void DoEmit (EmitContext ec)
885 ILGenerator ig = ec.ig;
887 if (ec.InLoop == false && ec.Switch == null){
888 Report.Error (139, loc, "No enclosing loop or switch to continue to");
892 if (ec.InTry || ec.InCatch)
893 ig.Emit (OpCodes.Leave, ec.LoopEnd);
895 ec.NeedExplicitReturn = true;
896 ig.Emit (OpCodes.Br, ec.LoopEnd);
901 public class Continue : Statement {
903 public Continue (Location l)
908 public override bool Resolve (EmitContext ec)
910 ec.CurrentBranching.CurrentUsageVector.Goto ();
914 protected override void DoEmit (EmitContext ec)
916 Label begin = ec.LoopBegin;
919 Report.Error (139, loc, "No enclosing loop to continue to");
924 // UGH: Non trivial. This Br might cross a try/catch boundary
928 // try { ... } catch { continue; }
932 // try {} catch { while () { continue; }}
934 if (ec.TryCatchLevel > ec.LoopBeginTryCatchLevel)
935 ec.ig.Emit (OpCodes.Leave, begin);
936 else if (ec.TryCatchLevel < ec.LoopBeginTryCatchLevel)
937 throw new Exception ("Should never happen");
939 ec.ig.Emit (OpCodes.Br, begin);
943 public class LocalInfo {
944 public Expression Type;
947 // Most of the time a variable will be stored in a LocalBuilder
949 // But sometimes, it will be stored in a field. The context of the field will
950 // be stored in the EmitContext
953 public LocalBuilder LocalBuilder;
954 public FieldBuilder FieldBuilder;
956 public Type VariableType;
957 public readonly string Name;
958 public readonly Location Location;
959 public readonly Block Block;
961 public VariableInfo VariableInfo;
971 public LocalInfo (Expression type, string name, Block block, Location l)
979 public LocalInfo (TypeContainer tc, Block block, Location l)
981 VariableType = tc.TypeBuilder;
986 public bool IsThisAssigned (EmitContext ec, Location loc)
988 if (VariableInfo == null)
989 throw new Exception ();
991 if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
994 return VariableInfo.TypeInfo.IsFullyInitialized (ec.CurrentBranching, VariableInfo, loc);
997 public bool IsAssigned (EmitContext ec)
999 if (VariableInfo == null)
1000 throw new Exception ();
1002 return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
1005 public bool Resolve (DeclSpace decl)
1007 if (VariableType == null)
1008 VariableType = decl.ResolveType (Type, false, Location);
1010 if (VariableType == null)
1016 public void MakePinned ()
1018 TypeManager.MakePinned (LocalBuilder);
1019 flags |= Flags.Fixed;
1022 public bool IsFixed {
1024 if (((flags & Flags.Fixed) != 0) || TypeManager.IsValueType (VariableType))
1031 public override string ToString ()
1033 return String.Format ("LocalInfo ({0},{1},{2},{3})",
1034 Name, Type, VariableInfo, Location);
1039 return (flags & Flags.Used) != 0;
1042 flags = value ? (flags | Flags.Used) : (flags & ~Flags.Used);
1046 public bool ReadOnly {
1048 return (flags & Flags.ReadOnly) != 0;
1051 flags = value ? (flags | Flags.ReadOnly) : (flags & ~Flags.ReadOnly);
1060 /// Block represents a C# block.
1064 /// This class is used in a number of places: either to represent
1065 /// explicit blocks that the programmer places or implicit blocks.
1067 /// Implicit blocks are used as labels or to introduce variable
1070 /// Top-level blocks derive from Block, and they are called ToplevelBlock
1071 /// they contain extra information that is not necessary on normal blocks.
1073 public class Block : Statement {
1074 public readonly Block Parent;
1075 public readonly Location StartLocation;
1076 public Location EndLocation = Location.Null;
1079 public enum Flags : byte {
1083 VariablesInitialized = 8,
1088 public bool Implicit {
1090 return (flags & Flags.Implicit) != 0;
1094 public bool Unchecked {
1096 return (flags & Flags.Unchecked) != 0;
1099 flags |= Flags.Unchecked;
1104 // The statements in this block
1106 ArrayList statements;
1109 // An array of Blocks. We keep track of children just
1110 // to generate the local variable declarations.
1112 // Statements and child statements are handled through the
1118 // Labels. (label, block) pairs.
1123 // Keeps track of (name, type) pairs
1125 Hashtable variables;
1128 // Keeps track of constants
1129 Hashtable constants;
1132 // If this is a switch section, the enclosing switch block.
1140 public Block (Block parent)
1141 : this (parent, (Flags) 0, Location.Null, Location.Null)
1144 public Block (Block parent, Flags flags)
1145 : this (parent, flags, Location.Null, Location.Null)
1148 public Block (Block parent, Flags flags, Parameters parameters)
1149 : this (parent, flags, parameters, Location.Null, Location.Null)
1152 public Block (Block parent, Location start, Location end)
1153 : this (parent, (Flags) 0, start, end)
1156 public Block (Block parent, Parameters parameters, Location start, Location end)
1157 : this (parent, (Flags) 0, parameters, start, end)
1160 public Block (Block parent, Flags flags, Location start, Location end)
1161 : this (parent, flags, Parameters.EmptyReadOnlyParameters, start, end)
1164 public Block (Block parent, Flags flags, Parameters parameters,
1165 Location start, Location end)
1168 parent.AddChild (this);
1170 this.Parent = parent;
1172 this.parameters = parameters;
1173 this.StartLocation = start;
1174 this.EndLocation = end;
1177 statements = new ArrayList ();
1180 public Block CreateSwitchBlock (Location start)
1182 Block new_block = new Block (this, start, start);
1183 new_block.switch_block = this;
1193 void AddChild (Block b)
1195 if (children == null)
1196 children = new ArrayList ();
1201 public void SetEndLocation (Location loc)
1207 /// Adds a label to the current block.
1211 /// false if the name already exists in this block. true
1215 public bool AddLabel (string name, LabeledStatement target)
1217 if (switch_block != null)
1218 return switch_block.AddLabel (name, target);
1221 labels = new Hashtable ();
1222 if (labels.Contains (name))
1225 labels.Add (name, target);
1229 public LabeledStatement LookupLabel (string name)
1231 Hashtable l = new Hashtable ();
1233 return LookupLabel (name, l);
1237 // Lookups a label in the current block, parents and children.
1238 // It skips during child recurssion on `source'
1240 LabeledStatement LookupLabel (string name, Hashtable seen)
1242 if (switch_block != null)
1243 return switch_block.LookupLabel (name, seen);
1245 if (seen [this] != null)
1251 if (labels.Contains (name))
1252 return ((LabeledStatement) labels [name]);
1254 if (children != null){
1255 foreach (Block b in children){
1256 LabeledStatement s = b.LookupLabel (name, seen);
1263 return Parent.LookupLabel (name, seen);
1268 LocalInfo this_variable = null;
1271 // Returns the "this" instance variable of this block.
1272 // See AddThisVariable() for more information.
1274 public LocalInfo ThisVariable {
1276 if (this_variable != null)
1277 return this_variable;
1278 else if (Parent != null)
1279 return Parent.ThisVariable;
1285 Hashtable child_variable_names;
1288 // Marks a variable with name @name as being used in a child block.
1289 // If a variable name has been used in a child block, it's illegal to
1290 // declare a variable with the same name in the current block.
1292 public void AddChildVariableName (string name)
1294 if (child_variable_names == null)
1295 child_variable_names = new Hashtable ();
1297 if (!child_variable_names.Contains (name))
1298 child_variable_names.Add (name, true);
1302 // Marks all variables from block @block and all its children as being
1303 // used in a child block.
1305 public void AddChildVariableNames (Block block)
1307 if (block.Variables != null) {
1308 foreach (string name in block.Variables.Keys)
1309 AddChildVariableName (name);
1312 if (block.children != null) {
1313 foreach (Block child in block.children)
1314 AddChildVariableNames (child);
1317 if (block.child_variable_names != null) {
1318 foreach (string name in block.child_variable_names.Keys)
1319 AddChildVariableName (name);
1324 // Checks whether a variable name has already been used in a child block.
1326 public bool IsVariableNameUsedInChildBlock (string name)
1328 if (child_variable_names == null)
1331 return child_variable_names.Contains (name);
1335 // This is used by non-static `struct' constructors which do not have an
1336 // initializer - in this case, the constructor must initialize all of the
1337 // struct's fields. To do this, we add a "this" variable and use the flow
1338 // analysis code to ensure that it's been fully initialized before control
1339 // leaves the constructor.
1341 public LocalInfo AddThisVariable (TypeContainer tc, Location l)
1343 if (this_variable != null)
1344 return this_variable;
1346 if (variables == null)
1347 variables = new Hashtable ();
1349 this_variable = new LocalInfo (tc, this, l);
1350 this_variable.Used = true;
1352 variables.Add ("this", this_variable);
1354 return this_variable;
1357 public LocalInfo AddVariable (Expression type, string name, Parameters pars, Location l)
1359 if (variables == null)
1360 variables = new Hashtable ();
1362 LocalInfo vi = GetLocalInfo (name);
1364 if (vi.Block != this)
1365 Report.Error (136, l, "A local variable named `" + name + "' " +
1366 "cannot be declared in this scope since it would " +
1367 "give a different meaning to `" + name + "', which " +
1368 "is already used in a `parent or current' scope to " +
1369 "denote something else");
1371 Report.Error (128, l, "A local variable `" + name + "' is already " +
1372 "defined in this scope");
1376 if (IsVariableNameUsedInChildBlock (name)) {
1377 Report.Error (136, l, "A local variable named `" + name + "' " +
1378 "cannot be declared in this scope since it would " +
1379 "give a different meaning to `" + name + "', which " +
1380 "is already used in a `child' scope to denote something " +
1387 Parameter p = pars.GetParameterByName (name, out idx);
1389 Report.Error (136, l, "A local variable named `" + name + "' " +
1390 "cannot be declared in this scope since it would " +
1391 "give a different meaning to `" + name + "', which " +
1392 "is already used in a `parent or current' scope to " +
1393 "denote something else");
1398 vi = new LocalInfo (type, name, this, l);
1400 variables.Add (name, vi);
1402 if ((flags & Flags.VariablesInitialized) != 0)
1403 throw new Exception ();
1405 // Console.WriteLine ("Adding {0} to {1}", name, ID);
1409 public bool AddConstant (Expression type, string name, Expression value, Parameters pars, Location l)
1411 if (AddVariable (type, name, pars, l) == null)
1414 if (constants == null)
1415 constants = new Hashtable ();
1417 constants.Add (name, value);
1421 public Hashtable Variables {
1427 public LocalInfo GetLocalInfo (string name)
1429 for (Block b = this; b != null; b = b.Parent) {
1430 if (b.variables != null) {
1431 LocalInfo ret = b.variables [name] as LocalInfo;
1439 public Expression GetVariableType (string name)
1441 LocalInfo vi = GetLocalInfo (name);
1449 public Expression GetConstantExpression (string name)
1451 for (Block b = this; b != null; b = b.Parent) {
1452 if (b.constants != null) {
1453 Expression ret = b.constants [name] as Expression;
1462 /// True if the variable named @name is a constant
1464 public bool IsConstant (string name)
1466 Expression e = null;
1468 e = GetConstantExpression (name);
1474 /// Use to fetch the statement associated with this label
1476 public Statement this [string name] {
1478 return (Statement) labels [name];
1482 Parameters parameters = null;
1483 public Parameters Parameters {
1486 while (b.Parent != null)
1488 return b.parameters;
1493 /// A list of labels that were not used within this block
1495 public string [] GetUnreferenced ()
1497 // FIXME: Implement me
1501 public void AddStatement (Statement s)
1504 flags |= Flags.BlockUsed;
1509 return (flags & Flags.BlockUsed) != 0;
1515 flags |= Flags.BlockUsed;
1518 public bool HasRet {
1520 return (flags & Flags.HasRet) != 0;
1524 VariableMap param_map, local_map;
1526 public VariableMap ParameterMap {
1528 if ((flags & Flags.VariablesInitialized) == 0)
1529 throw new Exception ();
1535 public VariableMap LocalMap {
1537 if ((flags & Flags.VariablesInitialized) == 0)
1538 throw new Exception ();
1544 public bool LiftVariable (LocalInfo local_info)
1550 /// Emits the variable declarations and labels.
1553 /// tc: is our typecontainer (to resolve type references)
1554 /// ig: is the code generator:
1556 public void EmitMeta (EmitContext ec, InternalParameters ip)
1558 ILGenerator ig = ec.ig;
1561 // Compute the VariableMap's.
1563 // Unfortunately, we don't know the type when adding variables with
1564 // AddVariable(), so we need to compute this info here.
1568 if (variables != null) {
1569 foreach (LocalInfo li in variables.Values)
1570 li.Resolve (ec.DeclSpace);
1572 locals = new LocalInfo [variables.Count];
1573 variables.Values.CopyTo (locals, 0);
1575 locals = new LocalInfo [0];
1578 local_map = new VariableMap (Parent.LocalMap, locals);
1580 local_map = new VariableMap (locals);
1582 param_map = new VariableMap (ip);
1583 flags |= Flags.VariablesInitialized;
1585 bool old_check_state = ec.ConstantCheckState;
1586 ec.ConstantCheckState = (flags & Flags.Unchecked) == 0;
1587 bool remap_locals = ec.RemapToProxy;
1590 // Process this block variables
1592 if (variables != null){
1593 foreach (DictionaryEntry de in variables){
1594 string name = (string) de.Key;
1595 LocalInfo vi = (LocalInfo) de.Value;
1597 if (vi.VariableType == null)
1600 Type variable_type = vi.VariableType;
1602 if (variable_type.IsPointer){
1604 // Am not really convinced that this test is required (Microsoft does it)
1605 // but the fact is that you would not be able to use the pointer variable
1608 if (!TypeManager.VerifyUnManaged (TypeManager.GetElementType (variable_type),
1614 vi.FieldBuilder = ec.MapVariable (name, vi.VariableType);
1616 vi.LocalBuilder = ig.DeclareLocal (vi.VariableType);
1618 if (constants == null)
1621 Expression cv = (Expression) constants [name];
1625 ec.CurrentBlock = this;
1626 Expression e = cv.Resolve (ec);
1630 Constant ce = e as Constant;
1632 Report.Error (133, vi.Location,
1633 "The expression being assigned to `" +
1634 name + "' must be constant (" + e + ")");
1638 if (e.Type != variable_type){
1639 e = Const.ChangeType (vi.Location, ce, variable_type);
1644 constants.Remove (name);
1645 constants.Add (name, e);
1648 ec.ConstantCheckState = old_check_state;
1651 // Now, handle the children
1653 if (children != null){
1654 foreach (Block b in children)
1655 b.EmitMeta (ec, ip);
1659 void UsageWarning (FlowBranching.UsageVector vector)
1663 if (variables != null){
1664 foreach (DictionaryEntry de in variables){
1665 LocalInfo vi = (LocalInfo) de.Value;
1670 name = (string) de.Key;
1672 if (vector.IsAssigned (vi.VariableInfo)){
1674 219, vi.Location, "The variable `" + name +
1675 "' is assigned but its value is never used");
1678 168, vi.Location, "The variable `" +
1680 "' is declared but never used");
1686 public override bool Resolve (EmitContext ec)
1688 Block prev_block = ec.CurrentBlock;
1691 int errors = Report.Errors;
1693 ec.CurrentBlock = this;
1694 ec.StartFlowBranching (this);
1696 Report.Debug (4, "RESOLVE BLOCK", StartLocation, ec.CurrentBranching);
1698 bool unreachable = false, warning_shown = false;
1700 int statement_count = statements.Count;
1701 for (int ix = 0; ix < statement_count; ix++){
1702 Statement s = (Statement) statements [ix];
1704 if (unreachable && !(s is LabeledStatement)) {
1705 if (!s.ResolveUnreachable (ec, !warning_shown))
1708 if (s != EmptyStatement.Value)
1709 warning_shown = true;
1711 statements [ix] = EmptyStatement.Value;
1715 if (s.Resolve (ec) == false) {
1717 statements [ix] = EmptyStatement.Value;
1721 if (s is LabeledStatement)
1722 unreachable = false;
1724 unreachable = ec.CurrentBranching.CurrentUsageVector.Reachability.IsUnreachable;
1727 Report.Debug (4, "RESOLVE BLOCK DONE", StartLocation, ec.CurrentBranching);
1730 FlowBranching.UsageVector vector = ec.DoEndFlowBranching ();
1732 ec.CurrentBlock = prev_block;
1734 // If we're a non-static `struct' constructor which doesn't have an
1735 // initializer, then we must initialize all of the struct's fields.
1736 if ((this_variable != null) &&
1737 (vector.Reachability.Throws != FlowBranching.FlowReturns.Always) &&
1738 !this_variable.IsThisAssigned (ec, loc))
1741 if ((labels != null) && (RootContext.WarningLevel >= 2)) {
1742 foreach (LabeledStatement label in labels.Values)
1743 if (!label.HasBeenReferenced)
1744 Report.Warning (164, label.Location,
1745 "This label has not been referenced");
1748 Report.Debug (4, "RESOLVE BLOCK DONE #2", StartLocation, vector);
1750 if ((vector.Reachability.Returns == FlowBranching.FlowReturns.Always) ||
1751 (vector.Reachability.Throws == FlowBranching.FlowReturns.Always) ||
1752 (vector.Reachability.Reachable == FlowBranching.FlowReturns.Never))
1753 flags |= Flags.HasRet;
1755 if (ok && (errors == Report.Errors)) {
1756 if (RootContext.WarningLevel >= 3)
1757 UsageWarning (vector);
1763 protected override void DoEmit (EmitContext ec)
1765 int statement_count = statements.Count;
1766 for (int ix = 0; ix < statement_count; ix++){
1767 Statement s = (Statement) statements [ix];
1772 public override void Emit (EmitContext ec)
1774 Block prev_block = ec.CurrentBlock;
1776 ec.CurrentBlock = this;
1778 bool emit_debug_info = (CodeGen.SymbolWriter != null);
1779 bool is_lexical_block = !Implicit && (Parent != null);
1781 if (emit_debug_info) {
1782 if (is_lexical_block)
1783 ec.ig.BeginScope ();
1785 if (variables != null) {
1786 foreach (DictionaryEntry de in variables) {
1787 string name = (string) de.Key;
1788 LocalInfo vi = (LocalInfo) de.Value;
1790 if (vi.LocalBuilder == null)
1793 vi.LocalBuilder.SetLocalSymInfo (name);
1798 ec.Mark (StartLocation, true);
1800 ec.Mark (EndLocation, true);
1802 if (emit_debug_info && is_lexical_block)
1805 ec.CurrentBlock = prev_block;
1811 public class ToplevelBlock : Block {
1812 public ToplevelBlock (Parameters parameters, Location start) :
1813 base (null, parameters, start, Location.Null)
1817 public ToplevelBlock (Flags flags, Parameters parameters, Location start) :
1818 base (null, flags, parameters, start, Location.Null)
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;
2636 if (type.IsValueType){
2637 Report.Error (185, loc, "lock statement requires the expression to be " +
2638 " a reference type (type is: `" +
2639 TypeManager.CSharpName (type) + "'");
2643 ILGenerator ig = ec.ig;
2644 LocalBuilder temp = ig.DeclareLocal (type);
2647 ig.Emit (OpCodes.Dup);
2648 ig.Emit (OpCodes.Stloc, temp);
2649 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2652 ig.BeginExceptionBlock ();
2653 bool old_in_try = ec.InTry;
2655 Label finish = ig.DefineLabel ();
2656 Statement.Emit (ec);
2657 ec.InTry = old_in_try;
2658 // ig.Emit (OpCodes.Leave, finish);
2660 ig.MarkLabel (finish);
2663 ig.BeginFinallyBlock ();
2664 ig.Emit (OpCodes.Ldloc, temp);
2665 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2666 ig.EndExceptionBlock ();
2670 public class Unchecked : Statement {
2671 public readonly Block Block;
2673 public Unchecked (Block b)
2679 public override bool Resolve (EmitContext ec)
2681 bool previous_state = ec.CheckState;
2682 bool previous_state_const = ec.ConstantCheckState;
2684 ec.CheckState = false;
2685 ec.ConstantCheckState = false;
2686 bool ret = Block.Resolve (ec);
2687 ec.CheckState = previous_state;
2688 ec.ConstantCheckState = previous_state_const;
2693 protected override void DoEmit (EmitContext ec)
2695 bool previous_state = ec.CheckState;
2696 bool previous_state_const = ec.ConstantCheckState;
2698 ec.CheckState = false;
2699 ec.ConstantCheckState = false;
2701 ec.CheckState = previous_state;
2702 ec.ConstantCheckState = previous_state_const;
2706 public class Checked : Statement {
2707 public readonly Block Block;
2709 public Checked (Block b)
2712 b.Unchecked = false;
2715 public override bool Resolve (EmitContext ec)
2717 bool previous_state = ec.CheckState;
2718 bool previous_state_const = ec.ConstantCheckState;
2720 ec.CheckState = true;
2721 ec.ConstantCheckState = true;
2722 bool ret = Block.Resolve (ec);
2723 ec.CheckState = previous_state;
2724 ec.ConstantCheckState = previous_state_const;
2729 protected override void DoEmit (EmitContext ec)
2731 bool previous_state = ec.CheckState;
2732 bool previous_state_const = ec.ConstantCheckState;
2734 ec.CheckState = true;
2735 ec.ConstantCheckState = true;
2737 ec.CheckState = previous_state;
2738 ec.ConstantCheckState = previous_state_const;
2742 public class Unsafe : Statement {
2743 public readonly Block Block;
2745 public Unsafe (Block b)
2750 public override bool Resolve (EmitContext ec)
2752 bool previous_state = ec.InUnsafe;
2756 val = Block.Resolve (ec);
2757 ec.InUnsafe = previous_state;
2762 protected override void DoEmit (EmitContext ec)
2764 bool previous_state = ec.InUnsafe;
2768 ec.InUnsafe = previous_state;
2775 public class Fixed : Statement {
2777 ArrayList declarators;
2778 Statement statement;
2784 public bool is_object;
2785 public LocalInfo vi;
2786 public Expression expr;
2787 public Expression converted;
2790 public Fixed (Expression type, ArrayList decls, Statement stmt, Location l)
2793 declarators = decls;
2798 public override bool Resolve (EmitContext ec)
2801 Expression.UnsafeError (loc);
2805 expr_type = ec.DeclSpace.ResolveType (type, false, loc);
2806 if (expr_type == null)
2809 if (ec.RemapToProxy){
2810 Report.Error (-210, loc, "Fixed statement not allowed in iterators");
2814 data = new FixedData [declarators.Count];
2816 if (!expr_type.IsPointer){
2817 Report.Error (209, loc, "Variables in a fixed statement must be pointers");
2822 foreach (Pair p in declarators){
2823 LocalInfo vi = (LocalInfo) p.First;
2824 Expression e = (Expression) p.Second;
2826 vi.VariableInfo = null;
2830 // The rules for the possible declarators are pretty wise,
2831 // but the production on the grammar is more concise.
2833 // So we have to enforce these rules here.
2835 // We do not resolve before doing the case 1 test,
2836 // because the grammar is explicit in that the token &
2837 // is present, so we need to test for this particular case.
2841 Report.Error (254, loc, "Cast expression not allowed as right hand expression in fixed statement");
2846 // Case 1: & object.
2848 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2849 Expression child = ((Unary) e).Expr;
2852 if (child is ParameterReference || child is LocalVariableReference){
2855 "No need to use fixed statement for parameters or " +
2856 "local variable declarations (address is already " +
2861 ec.InFixedInitializer = true;
2863 ec.InFixedInitializer = false;
2867 child = ((Unary) e).Expr;
2869 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2872 data [i].is_object = true;
2874 data [i].converted = null;
2881 ec.InFixedInitializer = true;
2883 ec.InFixedInitializer = false;
2890 if (e.Type.IsArray){
2891 Type array_type = TypeManager.GetElementType (e.Type);
2895 // Provided that array_type is unmanaged,
2897 if (!TypeManager.VerifyUnManaged (array_type, loc))
2901 // and T* is implicitly convertible to the
2902 // pointer type given in the fixed statement.
2904 ArrayPtr array_ptr = new ArrayPtr (e, loc);
2906 Expression converted = Convert.ImplicitConversionRequired (
2907 ec, array_ptr, vi.VariableType, loc);
2908 if (converted == null)
2911 data [i].is_object = false;
2913 data [i].converted = converted;
2923 if (e.Type == TypeManager.string_type){
2924 data [i].is_object = false;
2926 data [i].converted = null;
2933 // For other cases, flag a `this is already fixed expression'
2935 if (e is LocalVariableReference || e is ParameterReference ||
2936 Convert.ImplicitConversionExists (ec, e, vi.VariableType)){
2938 Report.Error (245, loc, "right hand expression is already fixed, no need to use fixed statement ");
2942 Report.Error (245, loc, "Fixed statement only allowed on strings, arrays or address-of expressions");
2946 ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
2948 if (!statement.Resolve (ec)) {
2949 ec.KillFlowBranching ();
2953 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
2954 has_ret = reachability.IsUnreachable;
2959 protected override void DoEmit (EmitContext ec)
2961 ILGenerator ig = ec.ig;
2963 LocalBuilder [] clear_list = new LocalBuilder [data.Length];
2965 for (int i = 0; i < data.Length; i++) {
2966 LocalInfo vi = data [i].vi;
2969 // Case 1: & object.
2971 if (data [i].is_object) {
2973 // Store pointer in pinned location
2975 data [i].expr.Emit (ec);
2976 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2977 clear_list [i] = vi.LocalBuilder;
2984 if (data [i].expr.Type.IsArray){
2986 // Store pointer in pinned location
2988 data [i].converted.Emit (ec);
2990 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2991 clear_list [i] = vi.LocalBuilder;
2998 if (data [i].expr.Type == TypeManager.string_type){
2999 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
3000 TypeManager.MakePinned (pinned_string);
3001 clear_list [i] = pinned_string;
3003 data [i].expr.Emit (ec);
3004 ig.Emit (OpCodes.Stloc, pinned_string);
3006 Expression sptr = new StringPtr (pinned_string, loc);
3007 Expression converted = Convert.ImplicitConversionRequired (
3008 ec, sptr, vi.VariableType, loc);
3010 if (converted == null)
3013 converted.Emit (ec);
3014 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3018 statement.Emit (ec);
3024 // Clear the pinned variable
3026 for (int i = 0; i < data.Length; i++) {
3027 if (data [i].is_object || data [i].expr.Type.IsArray) {
3028 ig.Emit (OpCodes.Ldc_I4_0);
3029 ig.Emit (OpCodes.Conv_U);
3030 ig.Emit (OpCodes.Stloc, clear_list [i]);
3031 } else if (data [i].expr.Type == TypeManager.string_type){
3032 ig.Emit (OpCodes.Ldnull);
3033 ig.Emit (OpCodes.Stloc, clear_list [i]);
3039 public class Catch {
3040 public readonly string Name;
3041 public readonly Block Block;
3042 public readonly Location Location;
3044 Expression type_expr;
3047 public Catch (Expression type, string name, Block block, Location l)
3055 public Type CatchType {
3061 public bool IsGeneral {
3063 return type_expr == null;
3067 public bool Resolve (EmitContext ec)
3069 if (type_expr != null) {
3070 type = ec.DeclSpace.ResolveType (type_expr, false, Location);
3074 if (type != TypeManager.exception_type && !type.IsSubclassOf (TypeManager.exception_type)){
3075 Report.Error (155, Location,
3076 "The type caught or thrown must be derived " +
3077 "from System.Exception");
3083 if (!Block.Resolve (ec))
3090 public class Try : Statement {
3091 public readonly Block Fini, Block;
3092 public readonly ArrayList Specific;
3093 public readonly Catch General;
3096 // specific, general and fini might all be null.
3098 public Try (Block block, ArrayList specific, Catch general, Block fini, Location l)
3100 if (specific == null && general == null){
3101 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
3105 this.Specific = specific;
3106 this.General = general;
3111 public override bool Resolve (EmitContext ec)
3115 ec.StartFlowBranching (FlowBranching.BranchingType.Exception, Block.StartLocation);
3117 Report.Debug (1, "START OF TRY BLOCK", Block.StartLocation);
3119 bool old_in_try = ec.InTry;
3122 if (!Block.Resolve (ec))
3125 ec.InTry = old_in_try;
3127 FlowBranching.UsageVector vector = ec.CurrentBranching.CurrentUsageVector;
3129 Report.Debug (1, "START OF CATCH BLOCKS", vector);
3131 foreach (Catch c in Specific){
3132 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3133 Report.Debug (1, "STARTED SIBLING FOR CATCH", ec.CurrentBranching);
3135 if (c.Name != null) {
3136 LocalInfo vi = c.Block.GetLocalInfo (c.Name);
3138 throw new Exception ();
3140 vi.VariableInfo = null;
3143 bool old_in_catch = ec.InCatch;
3146 if (!c.Resolve (ec))
3149 ec.InCatch = old_in_catch;
3152 Report.Debug (1, "END OF CATCH BLOCKS", ec.CurrentBranching);
3154 if (General != null){
3155 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Catch);
3156 Report.Debug (1, "STARTED SIBLING FOR GENERAL", ec.CurrentBranching);
3158 bool old_in_catch = ec.InCatch;
3161 if (!General.Resolve (ec))
3164 ec.InCatch = old_in_catch;
3167 Report.Debug (1, "END OF GENERAL CATCH BLOCKS", ec.CurrentBranching);
3171 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Finally);
3172 Report.Debug (1, "STARTED SIBLING FOR FINALLY", ec.CurrentBranching, vector);
3174 bool old_in_finally = ec.InFinally;
3175 ec.InFinally = true;
3177 if (!Fini.Resolve (ec))
3180 ec.InFinally = old_in_finally;
3183 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3185 FlowBranching.UsageVector f_vector = ec.CurrentBranching.CurrentUsageVector;
3187 Report.Debug (1, "END OF TRY", ec.CurrentBranching, reachability, vector, f_vector);
3189 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3190 // Unfortunately, System.Reflection.Emit automatically emits a leave
3191 // to the end of the finally block. This is a problem if `returns'
3192 // is true since we may jump to a point after the end of the method.
3193 // As a workaround, emit an explicit ret here.
3194 ec.NeedExplicitReturn = true;
3200 protected override void DoEmit (EmitContext ec)
3202 ILGenerator ig = ec.ig;
3203 Label finish = ig.DefineLabel ();;
3206 ig.BeginExceptionBlock ();
3207 bool old_in_try = ec.InTry;
3210 ec.InTry = old_in_try;
3213 // System.Reflection.Emit provides this automatically:
3214 // ig.Emit (OpCodes.Leave, finish);
3216 bool old_in_catch = ec.InCatch;
3219 foreach (Catch c in Specific){
3222 ig.BeginCatchBlock (c.CatchType);
3224 if (c.Name != null){
3225 vi = c.Block.GetLocalInfo (c.Name);
3227 throw new Exception ("Variable does not exist in this block");
3229 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3231 ig.Emit (OpCodes.Pop);
3236 if (General != null){
3237 ig.BeginCatchBlock (TypeManager.object_type);
3238 ig.Emit (OpCodes.Pop);
3239 General.Block.Emit (ec);
3241 ec.InCatch = old_in_catch;
3243 ig.MarkLabel (finish);
3245 ig.BeginFinallyBlock ();
3246 bool old_in_finally = ec.InFinally;
3247 ec.InFinally = true;
3249 ec.InFinally = old_in_finally;
3252 ig.EndExceptionBlock ();
3257 public class Using : Statement {
3258 object expression_or_block;
3259 Statement Statement;
3264 Expression [] converted_vars;
3265 ExpressionStatement [] assign;
3267 public Using (object expression_or_block, Statement stmt, Location l)
3269 this.expression_or_block = expression_or_block;
3275 // Resolves for the case of using using a local variable declaration.
3277 bool ResolveLocalVariableDecls (EmitContext ec)
3279 bool need_conv = false;
3280 expr_type = ec.DeclSpace.ResolveType (expr, false, loc);
3283 if (expr_type == null)
3287 // The type must be an IDisposable or an implicit conversion
3290 converted_vars = new Expression [var_list.Count];
3291 assign = new ExpressionStatement [var_list.Count];
3292 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3293 foreach (DictionaryEntry e in var_list){
3294 Expression var = (Expression) e.Key;
3296 var = var.ResolveLValue (ec, new EmptyExpression ());
3300 converted_vars [i] = Convert.ImplicitConversionRequired (
3301 ec, var, TypeManager.idisposable_type, loc);
3303 if (converted_vars [i] == null)
3311 foreach (DictionaryEntry e in var_list){
3312 LocalVariableReference var = (LocalVariableReference) e.Key;
3313 Expression new_expr = (Expression) e.Value;
3316 a = new Assign (var, new_expr, loc);
3322 converted_vars [i] = var;
3323 assign [i] = (ExpressionStatement) a;
3330 bool ResolveExpression (EmitContext ec)
3332 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
3333 conv = Convert.ImplicitConversionRequired (
3334 ec, expr, TypeManager.idisposable_type, loc);
3344 // Emits the code for the case of using using a local variable declaration.
3346 bool EmitLocalVariableDecls (EmitContext ec)
3348 ILGenerator ig = ec.ig;
3351 bool old_in_try = ec.InTry;
3353 for (i = 0; i < assign.Length; i++) {
3354 assign [i].EmitStatement (ec);
3356 ig.BeginExceptionBlock ();
3358 Statement.Emit (ec);
3359 ec.InTry = old_in_try;
3361 bool old_in_finally = ec.InFinally;
3362 ec.InFinally = true;
3363 var_list.Reverse ();
3364 foreach (DictionaryEntry e in var_list){
3365 LocalVariableReference var = (LocalVariableReference) e.Key;
3366 Label skip = ig.DefineLabel ();
3369 ig.BeginFinallyBlock ();
3371 if (!var.Type.IsValueType) {
3373 ig.Emit (OpCodes.Brfalse, skip);
3374 converted_vars [i].Emit (ec);
3375 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3377 Expression ml = Expression.MemberLookup(ec, typeof(IDisposable), var.Type, "Dispose", Mono.CSharp.Location.Null);
3379 if (!(ml is MethodGroupExpr)) {
3381 ig.Emit (OpCodes.Box, var.Type);
3382 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3384 MethodInfo mi = null;
3386 foreach (MethodInfo mk in ((MethodGroupExpr) ml).Methods) {
3387 if (mk.GetParameters().Length == 0) {
3394 Report.Error(-100, Mono.CSharp.Location.Null, "Internal error: No Dispose method which takes 0 parameters.");
3398 var.AddressOf (ec, AddressOp.Load);
3399 ig.Emit (OpCodes.Call, mi);
3403 ig.MarkLabel (skip);
3404 ig.EndExceptionBlock ();
3406 ec.InFinally = old_in_finally;
3411 bool EmitExpression (EmitContext ec)
3414 // Make a copy of the expression and operate on that.
3416 ILGenerator ig = ec.ig;
3417 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
3422 ig.Emit (OpCodes.Stloc, local_copy);
3424 bool old_in_try = ec.InTry;
3426 ig.BeginExceptionBlock ();
3427 Statement.Emit (ec);
3428 ec.InTry = old_in_try;
3430 Label skip = ig.DefineLabel ();
3431 bool old_in_finally = ec.InFinally;
3432 ig.BeginFinallyBlock ();
3433 ig.Emit (OpCodes.Ldloc, local_copy);
3434 ig.Emit (OpCodes.Brfalse, skip);
3435 ig.Emit (OpCodes.Ldloc, local_copy);
3436 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3437 ig.MarkLabel (skip);
3438 ec.InFinally = old_in_finally;
3439 ig.EndExceptionBlock ();
3444 public override bool Resolve (EmitContext ec)
3446 if (expression_or_block is DictionaryEntry){
3447 expr = (Expression) ((DictionaryEntry) expression_or_block).Key;
3448 var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
3450 if (!ResolveLocalVariableDecls (ec))
3453 } else if (expression_or_block is Expression){
3454 expr = (Expression) expression_or_block;
3456 expr = expr.Resolve (ec);
3460 expr_type = expr.Type;
3462 if (!ResolveExpression (ec))
3466 ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
3468 bool ok = Statement.Resolve (ec);
3471 ec.KillFlowBranching ();
3475 FlowBranching.Reachability reachability = ec.EndFlowBranching ();
3477 if (reachability.Returns != FlowBranching.FlowReturns.Always) {
3478 // Unfortunately, System.Reflection.Emit automatically emits a leave
3479 // to the end of the finally block. This is a problem if `returns'
3480 // is true since we may jump to a point after the end of the method.
3481 // As a workaround, emit an explicit ret here.
3482 ec.NeedExplicitReturn = true;
3488 protected override void DoEmit (EmitContext ec)
3490 if (expression_or_block is DictionaryEntry)
3491 EmitLocalVariableDecls (ec);
3492 else if (expression_or_block is Expression)
3493 EmitExpression (ec);
3498 /// Implementation of the foreach C# statement
3500 public class Foreach : Statement {
3502 Expression variable;
3504 Statement statement;
3505 ForeachHelperMethods hm;
3506 Expression empty, conv;
3507 Type array_type, element_type;
3510 public Foreach (Expression type, LocalVariableReference var, Expression expr,
3511 Statement stmt, Location l)
3514 this.variable = var;
3520 public override bool Resolve (EmitContext ec)
3522 expr = expr.Resolve (ec);
3526 var_type = ec.DeclSpace.ResolveType (type, false, loc);
3527 if (var_type == null)
3531 // We need an instance variable. Not sure this is the best
3532 // way of doing this.
3534 // FIXME: When we implement propertyaccess, will those turn
3535 // out to return values in ExprClass? I think they should.
3537 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3538 expr.eclass == ExprClass.PropertyAccess || expr.eclass == ExprClass.IndexerAccess)){
3539 error1579 (expr.Type);
3543 if (expr.Type.IsArray) {
3544 array_type = expr.Type;
3545 element_type = TypeManager.GetElementType (array_type);
3547 empty = new EmptyExpression (element_type);
3549 hm = ProbeCollectionType (ec, expr.Type);
3551 error1579 (expr.Type);
3555 array_type = expr.Type;
3556 element_type = hm.element_type;
3558 empty = new EmptyExpression (hm.element_type);
3561 ec.StartFlowBranching (FlowBranching.BranchingType.LoopBlock, loc);
3562 ec.CurrentBranching.CreateSibling (FlowBranching.SiblingType.Conditional);
3566 // FIXME: maybe we can apply the same trick we do in the
3567 // array handling to avoid creating empty and conv in some cases.
3569 // Although it is not as important in this case, as the type
3570 // will not likely be object (what the enumerator will return).
3572 conv = Convert.ExplicitConversion (ec, empty, var_type, loc);
3576 variable = variable.ResolveLValue (ec, empty);
3577 if (variable == null)
3580 if (!statement.Resolve (ec))
3583 ec.EndFlowBranching ();
3589 // Retrieves a `public bool MoveNext ()' method from the Type `t'
3591 static MethodInfo FetchMethodMoveNext (Type t)
3593 MemberList move_next_list;
3595 move_next_list = TypeContainer.FindMembers (
3596 t, MemberTypes.Method,
3597 BindingFlags.Public | BindingFlags.Instance,
3598 Type.FilterName, "MoveNext");
3599 if (move_next_list.Count == 0)
3602 foreach (MemberInfo m in move_next_list){
3603 MethodInfo mi = (MethodInfo) m;
3606 args = TypeManager.GetArgumentTypes (mi);
3607 if (args != null && args.Length == 0){
3608 if (mi.ReturnType == TypeManager.bool_type)
3616 // Retrieves a `public T get_Current ()' method from the Type `t'
3618 static MethodInfo FetchMethodGetCurrent (Type t)
3620 MemberList get_current_list;
3622 get_current_list = TypeContainer.FindMembers (
3623 t, MemberTypes.Method,
3624 BindingFlags.Public | BindingFlags.Instance,
3625 Type.FilterName, "get_Current");
3626 if (get_current_list.Count == 0)
3629 foreach (MemberInfo m in get_current_list){
3630 MethodInfo mi = (MethodInfo) m;
3633 args = TypeManager.GetArgumentTypes (mi);
3634 if (args != null && args.Length == 0)
3641 // This struct records the helper methods used by the Foreach construct
3643 class ForeachHelperMethods {
3644 public EmitContext ec;
3645 public MethodInfo get_enumerator;
3646 public MethodInfo move_next;
3647 public MethodInfo get_current;
3648 public Type element_type;
3649 public Type enumerator_type;
3650 public bool is_disposable;
3652 public ForeachHelperMethods (EmitContext ec)
3655 this.element_type = TypeManager.object_type;
3656 this.enumerator_type = TypeManager.ienumerator_type;
3657 this.is_disposable = true;
3661 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
3666 if (!(m is MethodInfo))
3669 if (m.Name != "GetEnumerator")
3672 MethodInfo mi = (MethodInfo) m;
3673 Type [] args = TypeManager.GetArgumentTypes (mi);
3675 if (args.Length != 0)
3678 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
3679 EmitContext ec = hm.ec;
3682 // Check whether GetEnumerator is accessible to us
3684 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
3686 Type declaring = mi.DeclaringType;
3687 if (prot == MethodAttributes.Private){
3688 if (declaring != ec.ContainerType)
3690 } else if (prot == MethodAttributes.FamANDAssem){
3691 // If from a different assembly, false
3692 if (!(mi is MethodBuilder))
3695 // Are we being invoked from the same class, or from a derived method?
3697 if (ec.ContainerType != declaring){
3698 if (!ec.ContainerType.IsSubclassOf (declaring))
3701 } else if (prot == MethodAttributes.FamORAssem){
3702 if (!(mi is MethodBuilder ||
3703 ec.ContainerType == declaring ||
3704 ec.ContainerType.IsSubclassOf (declaring)))
3706 } if (prot == MethodAttributes.Family){
3707 if (!(ec.ContainerType == declaring ||
3708 ec.ContainerType.IsSubclassOf (declaring)))
3712 if ((mi.ReturnType == TypeManager.ienumerator_type) && (declaring == TypeManager.string_type))
3714 // Apply the same optimization as MS: skip the GetEnumerator
3715 // returning an IEnumerator, and use the one returning a
3716 // CharEnumerator instead. This allows us to avoid the
3717 // try-finally block and the boxing.
3722 // Ok, we can access it, now make sure that we can do something
3723 // with this `GetEnumerator'
3726 if (mi.ReturnType == TypeManager.ienumerator_type ||
3727 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType) ||
3728 (!RootContext.StdLib && TypeManager.ImplementsInterface (mi.ReturnType, TypeManager.ienumerator_type))) {
3729 if (declaring != TypeManager.string_type) {
3730 hm.move_next = TypeManager.bool_movenext_void;
3731 hm.get_current = TypeManager.object_getcurrent_void;
3737 // Ok, so they dont return an IEnumerable, we will have to
3738 // find if they support the GetEnumerator pattern.
3740 Type return_type = mi.ReturnType;
3742 hm.move_next = FetchMethodMoveNext (return_type);
3743 if (hm.move_next == null)
3745 hm.get_current = FetchMethodGetCurrent (return_type);
3746 if (hm.get_current == null)
3749 hm.element_type = hm.get_current.ReturnType;
3750 hm.enumerator_type = return_type;
3751 hm.is_disposable = !hm.enumerator_type.IsSealed ||
3752 TypeManager.ImplementsInterface (
3753 hm.enumerator_type, TypeManager.idisposable_type);
3759 /// This filter is used to find the GetEnumerator method
3760 /// on which IEnumerator operates
3762 static MemberFilter FilterEnumerator;
3766 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
3769 void error1579 (Type t)
3771 Report.Error (1579, loc,
3772 "foreach statement cannot operate on variables of type `" +
3773 t.FullName + "' because that class does not provide a " +
3774 " GetEnumerator method or it is inaccessible");
3777 static bool TryType (Type t, ForeachHelperMethods hm)
3781 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
3782 BindingFlags.Public | BindingFlags.NonPublic |
3783 BindingFlags.Instance | BindingFlags.DeclaredOnly,
3784 FilterEnumerator, hm);
3789 hm.get_enumerator = (MethodInfo) mi [0];
3794 // Looks for a usable GetEnumerator in the Type, and if found returns
3795 // the three methods that participate: GetEnumerator, MoveNext and get_Current
3797 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
3799 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
3801 for (Type tt = t; tt != null && tt != TypeManager.object_type;){
3802 if (TryType (tt, hm))
3808 // Now try to find the method in the interfaces
3811 Type [] ifaces = t.GetInterfaces ();
3813 foreach (Type i in ifaces){
3814 if (TryType (i, hm))
3819 // Since TypeBuilder.GetInterfaces only returns the interface
3820 // types for this type, we have to keep looping, but once
3821 // we hit a non-TypeBuilder (ie, a Type), then we know we are
3822 // done, because it returns all the types
3824 if ((t is TypeBuilder))
3834 // FIXME: possible optimization.
3835 // We might be able to avoid creating `empty' if the type is the sam
3837 bool EmitCollectionForeach (EmitContext ec)
3839 ILGenerator ig = ec.ig;
3840 VariableStorage enumerator, disposable;
3842 enumerator = new VariableStorage (ec, hm.enumerator_type);
3843 if (hm.is_disposable)
3844 disposable = new VariableStorage (ec, TypeManager.idisposable_type);
3848 enumerator.EmitThis ();
3850 // Instantiate the enumerator
3852 if (expr.Type.IsValueType){
3853 if (expr is IMemoryLocation){
3854 IMemoryLocation ml = (IMemoryLocation) expr;
3856 ml.AddressOf (ec, AddressOp.Load);
3858 throw new Exception ("Expr " + expr + " of type " + expr.Type +
3859 " does not implement IMemoryLocation");
3860 ig.Emit (OpCodes.Call, hm.get_enumerator);
3863 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
3865 enumerator.EmitStore ();
3868 // Protect the code in a try/finalize block, so that
3869 // if the beast implement IDisposable, we get rid of it
3871 bool old_in_try = ec.InTry;
3873 if (hm.is_disposable) {
3874 ig.BeginExceptionBlock ();
3878 Label end_try = ig.DefineLabel ();
3880 ig.MarkLabel (ec.LoopBegin);
3881 enumerator.EmitLoad ();
3882 ig.Emit (OpCodes.Callvirt, hm.move_next);
3883 ig.Emit (OpCodes.Brfalse, end_try);
3887 enumerator.EmitLoad ();
3888 ig.Emit (OpCodes.Callvirt, hm.get_current);
3892 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3894 ((IAssignMethod)variable).EmitAssign (ec, conv);
3896 statement.Emit (ec);
3897 ig.Emit (OpCodes.Br, ec.LoopBegin);
3898 ig.MarkLabel (end_try);
3899 ec.InTry = old_in_try;
3901 // The runtime provides this for us.
3902 // ig.Emit (OpCodes.Leave, end);
3905 // Now the finally block
3907 if (hm.is_disposable) {
3908 Label end_finally = ig.DefineLabel ();
3909 bool old_in_finally = ec.InFinally;
3910 ec.InFinally = true;
3911 ig.BeginFinallyBlock ();
3913 disposable.EmitThis ();
3914 enumerator.EmitThis ();
3915 enumerator.EmitLoad ();
3916 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
3917 disposable.EmitStore ();
3918 disposable.EmitLoad ();
3919 ig.Emit (OpCodes.Brfalse, end_finally);
3920 disposable.EmitThis ();
3921 disposable.EmitLoad ();
3922 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
3923 ig.MarkLabel (end_finally);
3924 ec.InFinally = old_in_finally;
3926 // The runtime generates this anyways.
3927 // ig.Emit (OpCodes.Endfinally);
3929 ig.EndExceptionBlock ();
3932 ig.MarkLabel (ec.LoopEnd);
3937 // FIXME: possible optimization.
3938 // We might be able to avoid creating `empty' if the type is the sam
3940 bool EmitArrayForeach (EmitContext ec)
3942 int rank = array_type.GetArrayRank ();
3943 ILGenerator ig = ec.ig;
3945 VariableStorage copy = new VariableStorage (ec, array_type);
3948 // Make our copy of the array
3955 VariableStorage counter = new VariableStorage (ec,TypeManager.int32_type);
3959 counter.EmitThis ();
3960 ig.Emit (OpCodes.Ldc_I4_0);
3961 counter.EmitStore ();
3962 test = ig.DefineLabel ();
3963 ig.Emit (OpCodes.Br, test);
3965 loop = ig.DefineLabel ();
3966 ig.MarkLabel (loop);
3973 counter.EmitThis ();
3974 counter.EmitLoad ();
3977 // Load the value, we load the value using the underlying type,
3978 // then we use the variable.EmitAssign to load using the proper cast.
3980 ArrayAccess.EmitLoadOpcode (ig, element_type);
3983 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
3985 ((IAssignMethod)variable).EmitAssign (ec, conv);
3987 statement.Emit (ec);
3989 ig.MarkLabel (ec.LoopBegin);
3990 counter.EmitThis ();
3991 counter.EmitThis ();
3992 counter.EmitLoad ();
3993 ig.Emit (OpCodes.Ldc_I4_1);
3994 ig.Emit (OpCodes.Add);
3995 counter.EmitStore ();
3997 ig.MarkLabel (test);
3998 counter.EmitThis ();
3999 counter.EmitLoad ();
4002 ig.Emit (OpCodes.Ldlen);
4003 ig.Emit (OpCodes.Conv_I4);
4004 ig.Emit (OpCodes.Blt, loop);
4006 VariableStorage [] dim_len = new VariableStorage [rank];
4007 VariableStorage [] dim_count = new VariableStorage [rank];
4008 Label [] loop = new Label [rank];
4009 Label [] test = new Label [rank];
4012 for (dim = 0; dim < rank; dim++){
4013 dim_len [dim] = new VariableStorage (ec, TypeManager.int32_type);
4014 dim_count [dim] = new VariableStorage (ec, TypeManager.int32_type);
4015 test [dim] = ig.DefineLabel ();
4016 loop [dim] = ig.DefineLabel ();
4019 for (dim = 0; dim < rank; dim++){
4020 dim_len [dim].EmitThis ();
4023 IntLiteral.EmitInt (ig, dim);
4024 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
4025 dim_len [dim].EmitStore ();
4029 for (dim = 0; dim < rank; dim++){
4030 dim_count [dim].EmitThis ();
4031 ig.Emit (OpCodes.Ldc_I4_0);
4032 dim_count [dim].EmitStore ();
4033 ig.Emit (OpCodes.Br, test [dim]);
4034 ig.MarkLabel (loop [dim]);
4041 for (dim = 0; dim < rank; dim++){
4042 dim_count [dim].EmitThis ();
4043 dim_count [dim].EmitLoad ();
4047 // FIXME: Maybe we can cache the computation of `get'?
4049 Type [] args = new Type [rank];
4052 for (int i = 0; i < rank; i++)
4053 args [i] = TypeManager.int32_type;
4055 ModuleBuilder mb = CodeGen.ModuleBuilder;
4056 get = mb.GetArrayMethod (
4058 CallingConventions.HasThis| CallingConventions.Standard,
4060 ig.Emit (OpCodes.Call, get);
4063 ig.Emit (OpCodes.Stfld, ((FieldExpr) variable).FieldInfo);
4065 ((IAssignMethod)variable).EmitAssign (ec, conv);
4066 statement.Emit (ec);
4067 ig.MarkLabel (ec.LoopBegin);
4068 for (dim = rank - 1; dim >= 0; dim--){
4069 dim_count [dim].EmitThis ();
4070 dim_count [dim].EmitThis ();
4071 dim_count [dim].EmitLoad ();
4072 ig.Emit (OpCodes.Ldc_I4_1);
4073 ig.Emit (OpCodes.Add);
4074 dim_count [dim].EmitStore ();
4076 ig.MarkLabel (test [dim]);
4077 dim_count [dim].EmitThis ();
4078 dim_count [dim].EmitLoad ();
4079 dim_len [dim].EmitThis ();
4080 dim_len [dim].EmitLoad ();
4081 ig.Emit (OpCodes.Blt, loop [dim]);
4084 ig.MarkLabel (ec.LoopEnd);
4089 protected override void DoEmit (EmitContext ec)
4091 ILGenerator ig = ec.ig;
4093 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
4094 bool old_inloop = ec.InLoop;
4095 int old_loop_begin_try_catch_level = ec.LoopBeginTryCatchLevel;
4096 ec.LoopBegin = ig.DefineLabel ();
4097 ec.LoopEnd = ig.DefineLabel ();
4099 ec.LoopBeginTryCatchLevel = ec.TryCatchLevel;
4102 EmitCollectionForeach (ec);
4104 EmitArrayForeach (ec);
4106 ec.LoopBegin = old_begin;
4107 ec.LoopEnd = old_end;
4108 ec.InLoop = old_inloop;
4109 ec.LoopBeginTryCatchLevel = old_loop_begin_try_catch_level;