2 // statement.cs: Statement representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001, 2002 Ximian, Inc.
11 using System.Reflection;
12 using System.Reflection.Emit;
13 using System.Diagnostics;
15 namespace Mono.CSharp {
17 using System.Collections;
19 public abstract class Statement {
23 /// Resolves the statement, true means that all sub-statements
26 public virtual bool Resolve (EmitContext ec)
32 /// Return value indicates whether all code paths emitted return.
34 public abstract bool Emit (EmitContext ec);
36 public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
42 if (e.Type != TypeManager.bool_type){
43 e = Expression.ConvertImplicit (ec, e, TypeManager.bool_type,
49 31, loc, "Can not convert the expression to a boolean");
52 if (CodeGen.SymbolWriter != null)
59 /// Emits a bool expression.
61 public static void EmitBoolExpression (EmitContext ec, Expression bool_expr,
62 Label target, bool isTrue)
64 ILGenerator ig = ec.ig;
67 if (bool_expr is Unary){
68 Unary u = (Unary) bool_expr;
70 if (u.Oper == Unary.Operator.LogicalNot){
73 u.EmitLogicalNot (ec);
82 ig.Emit (OpCodes.Brfalse, target);
84 ig.Emit (OpCodes.Brtrue, target);
87 ig.Emit (OpCodes.Brtrue, target);
89 ig.Emit (OpCodes.Brfalse, target);
93 public static void Warning_DeadCodeFound (Location loc)
95 Report.Warning (162, loc, "Unreachable code detected");
99 public class EmptyStatement : Statement {
100 public override bool Resolve (EmitContext ec)
105 public override bool Emit (EmitContext ec)
111 public class If : Statement {
113 public Statement TrueStatement;
114 public Statement FalseStatement;
116 public If (Expression expr, Statement trueStatement, Location l)
119 TrueStatement = trueStatement;
123 public If (Expression expr,
124 Statement trueStatement,
125 Statement falseStatement,
129 TrueStatement = trueStatement;
130 FalseStatement = falseStatement;
134 public override bool Resolve (EmitContext ec)
136 expr = ResolveBoolean (ec, expr, loc);
141 if (TrueStatement.Resolve (ec)){
142 if (FalseStatement != null){
143 if (FalseStatement.Resolve (ec))
153 public override bool Emit (EmitContext ec)
155 ILGenerator ig = ec.ig;
156 Label false_target = ig.DefineLabel ();
158 bool is_true_ret, is_false_ret;
161 // Dead code elimination
163 if (expr is BoolConstant){
164 bool take = ((BoolConstant) expr).Value;
167 if (FalseStatement != null){
168 Warning_DeadCodeFound (FalseStatement.loc);
170 return TrueStatement.Emit (ec);
172 Warning_DeadCodeFound (TrueStatement.loc);
173 if (FalseStatement != null)
174 return FalseStatement.Emit (ec);
178 EmitBoolExpression (ec, expr, false_target, false);
180 is_true_ret = TrueStatement.Emit (ec);
181 is_false_ret = is_true_ret;
183 if (FalseStatement != null){
184 bool branch_emitted = false;
186 end = ig.DefineLabel ();
188 ig.Emit (OpCodes.Br, end);
189 branch_emitted = true;
192 ig.MarkLabel (false_target);
193 is_false_ret = FalseStatement.Emit (ec);
198 ig.MarkLabel (false_target);
199 is_false_ret = false;
202 return is_true_ret && is_false_ret;
206 public class Do : Statement {
207 public Expression expr;
208 public readonly Statement EmbeddedStatement;
210 public Do (Statement statement, Expression boolExpr, Location l)
213 EmbeddedStatement = statement;
217 public override bool Resolve (EmitContext ec)
219 expr = ResolveBoolean (ec, expr, loc);
223 return EmbeddedStatement.Resolve (ec);
226 public override bool Emit (EmitContext ec)
228 ILGenerator ig = ec.ig;
229 Label loop = ig.DefineLabel ();
230 Label old_begin = ec.LoopBegin;
231 Label old_end = ec.LoopEnd;
232 bool old_inloop = ec.InLoop;
233 bool old_breaks = ec.Breaks;
235 ec.LoopBegin = ig.DefineLabel ();
236 ec.LoopEnd = ig.DefineLabel ();
241 EmbeddedStatement.Emit (ec);
242 bool breaks = ec.Breaks;
243 ig.MarkLabel (ec.LoopBegin);
246 // Dead code elimination
248 if (expr is BoolConstant){
249 bool res = ((BoolConstant) expr).Value;
252 ec.ig.Emit (OpCodes.Br, loop);
254 EmitBoolExpression (ec, expr, loop, true);
256 ig.MarkLabel (ec.LoopEnd);
258 ec.LoopBegin = old_begin;
259 ec.LoopEnd = old_end;
260 ec.InLoop = old_inloop;
261 ec.Breaks = old_breaks;
264 // Inform whether we are infinite or not
266 if (expr is BoolConstant){
267 BoolConstant bc = (BoolConstant) expr;
269 if (bc.Value == true)
270 return breaks == false;
277 public class While : Statement {
278 public Expression expr;
279 public readonly Statement Statement;
281 public While (Expression boolExpr, Statement statement, Location l)
283 this.expr = boolExpr;
284 Statement = statement;
288 public override bool Resolve (EmitContext ec)
290 expr = ResolveBoolean (ec, expr, loc);
294 return Statement.Resolve (ec);
297 public override bool Emit (EmitContext ec)
299 ILGenerator ig = ec.ig;
300 Label old_begin = ec.LoopBegin;
301 Label old_end = ec.LoopEnd;
302 bool old_inloop = ec.InLoop;
303 bool old_breaks = ec.Breaks;
304 Label while_loop = ig.DefineLabel ();
307 ec.LoopBegin = ig.DefineLabel ();
308 ec.LoopEnd = ig.DefineLabel ();
311 ig.Emit (OpCodes.Br, ec.LoopBegin);
312 ig.MarkLabel (while_loop);
315 // Inform whether we are infinite or not
317 if (expr is BoolConstant){
318 BoolConstant bc = (BoolConstant) expr;
320 ig.MarkLabel (ec.LoopBegin);
321 if (bc.Value == false){
322 Warning_DeadCodeFound (Statement.loc);
330 ig.Emit (OpCodes.Br, ec.LoopBegin);
333 // Inform that we are infinite (ie, `we return'), only
334 // if we do not `break' inside the code.
336 ret = breaks == false;
338 ig.MarkLabel (ec.LoopEnd);
342 ig.MarkLabel (ec.LoopBegin);
344 EmitBoolExpression (ec, expr, while_loop, true);
345 ig.MarkLabel (ec.LoopEnd);
350 ec.LoopBegin = old_begin;
351 ec.LoopEnd = old_end;
352 ec.InLoop = old_inloop;
353 ec.Breaks = old_breaks;
359 public class For : Statement {
361 readonly Statement InitStatement;
362 readonly Statement Increment;
363 readonly Statement Statement;
365 public For (Statement initStatement,
371 InitStatement = initStatement;
373 Increment = increment;
374 Statement = statement;
378 public override bool Resolve (EmitContext ec)
383 Test = ResolveBoolean (ec, Test, loc);
388 if (InitStatement != null){
389 if (!InitStatement.Resolve (ec))
393 if (Increment != null){
394 if (!Increment.Resolve (ec))
398 return Statement.Resolve (ec) && ok;
401 public override bool Emit (EmitContext ec)
403 ILGenerator ig = ec.ig;
404 Label old_begin = ec.LoopBegin;
405 Label old_end = ec.LoopEnd;
406 bool old_inloop = ec.InLoop;
407 bool old_breaks = ec.Breaks;
408 Label loop = ig.DefineLabel ();
409 Label test = ig.DefineLabel ();
411 if (InitStatement != null)
412 if (! (InitStatement is EmptyStatement))
413 InitStatement.Emit (ec);
415 ec.LoopBegin = ig.DefineLabel ();
416 ec.LoopEnd = ig.DefineLabel ();
419 ig.Emit (OpCodes.Br, test);
423 bool breaks = ec.Breaks;
425 ig.MarkLabel (ec.LoopBegin);
426 if (!(Increment is EmptyStatement))
431 // If test is null, there is no test, and we are just
435 EmitBoolExpression (ec, Test, ec.LoopEnd, false);
436 ig.Emit (OpCodes.Br, loop);
437 ig.MarkLabel (ec.LoopEnd);
439 ec.LoopBegin = old_begin;
440 ec.LoopEnd = old_end;
441 ec.InLoop = old_inloop;
442 ec.Breaks = old_breaks;
445 // Inform whether we are infinite or not
448 if (Test is BoolConstant){
449 BoolConstant bc = (BoolConstant) Test;
452 return breaks == false;
460 public class StatementExpression : Statement {
463 public StatementExpression (ExpressionStatement expr, Location l)
469 public override bool Resolve (EmitContext ec)
471 expr = (Expression) expr.Resolve (ec);
475 public override bool Emit (EmitContext ec)
477 ILGenerator ig = ec.ig;
479 if (expr is ExpressionStatement)
480 ((ExpressionStatement) expr).EmitStatement (ec);
483 ig.Emit (OpCodes.Pop);
489 public override string ToString ()
491 return "StatementExpression (" + expr + ")";
496 /// Implements the return statement
498 public class Return : Statement {
499 public Expression Expr;
501 public Return (Expression expr, Location l)
507 public override bool Resolve (EmitContext ec)
510 Expr = Expr.Resolve (ec);
517 public override bool Emit (EmitContext ec)
520 Report.Error (157,loc,"Control can not leave the body of the finally block");
524 if (ec.ReturnType == null){
526 Report.Error (127, loc, "Return with a value not allowed here");
531 Report.Error (126, loc, "An object of type `" +
532 TypeManager.CSharpName (ec.ReturnType) + "' is " +
533 "expected for the return statement");
537 if (Expr.Type != ec.ReturnType)
538 Expr = Expression.ConvertImplicitRequired (
539 ec, Expr, ec.ReturnType, loc);
546 if (ec.InTry || ec.InCatch)
547 ec.ig.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
550 if (ec.InTry || ec.InCatch)
551 ec.ig.Emit (OpCodes.Leave, ec.ReturnLabel);
553 ec.ig.Emit (OpCodes.Ret);
559 public class Goto : Statement {
563 public override bool Resolve (EmitContext ec)
568 public Goto (Block parent_block, string label, Location l)
570 block = parent_block;
575 public string Target {
581 public override bool Emit (EmitContext ec)
583 LabeledStatement label = block.LookupLabel (target);
587 // Maybe we should catch this before?
591 "No such label `" + target + "' in this scope");
594 Label l = label.LabelTarget (ec);
595 ec.ig.Emit (OpCodes.Br, l);
601 public class LabeledStatement : Statement {
606 public LabeledStatement (string label_name)
608 this.label_name = label_name;
611 public Label LabelTarget (EmitContext ec)
615 label = ec.ig.DefineLabel ();
621 public override bool Emit (EmitContext ec)
624 ec.ig.MarkLabel (label);
632 /// `goto default' statement
634 public class GotoDefault : Statement {
636 public GotoDefault (Location l)
641 public override bool Emit (EmitContext ec)
643 if (ec.Switch == null){
644 Report.Error (153, loc, "goto default is only valid in a switch statement");
648 if (!ec.Switch.GotDefault){
649 Report.Error (159, loc, "No default target on switch statement");
652 ec.ig.Emit (OpCodes.Br, ec.Switch.DefaultTarget);
658 /// `goto case' statement
660 public class GotoCase : Statement {
663 public GotoCase (Expression e, Location l)
669 public override bool Emit (EmitContext ec)
671 if (ec.Switch == null){
672 Report.Error (153, loc, "goto case is only valid in a switch statement");
676 expr = expr.Resolve (ec);
680 if (!(expr is Constant)){
681 Report.Error (159, loc, "Target expression for goto case is not constant");
685 object val = Expression.ConvertIntLiteral (
686 (Constant) expr, ec.Switch.SwitchType, loc);
691 SwitchLabel sl = (SwitchLabel) ec.Switch.Elements [val];
696 "No such label 'case " + val + "': for the goto case");
699 ec.ig.Emit (OpCodes.Br, sl.ILLabelCode);
704 public class Throw : Statement {
707 public Throw (Expression expr, Location l)
713 public override bool Resolve (EmitContext ec)
716 expr = expr.Resolve (ec);
723 public override bool Emit (EmitContext ec)
727 ec.ig.Emit (OpCodes.Rethrow);
731 "A throw statement with no argument is only " +
732 "allowed in a catch clause");
739 ec.ig.Emit (OpCodes.Throw);
745 public class Break : Statement {
747 public Break (Location l)
752 public override bool Emit (EmitContext ec)
754 ILGenerator ig = ec.ig;
756 if (ec.InLoop == false && ec.Switch == null){
757 Report.Error (139, loc, "No enclosing loop or switch to continue to");
762 if (ec.InTry || ec.InCatch)
763 ig.Emit (OpCodes.Leave, ec.LoopEnd);
765 ig.Emit (OpCodes.Br, ec.LoopEnd);
771 public class Continue : Statement {
773 public Continue (Location l)
778 public override bool Emit (EmitContext ec)
780 Label begin = ec.LoopBegin;
783 Report.Error (139, loc, "No enclosing loop to continue to");
788 // UGH: Non trivial. This Br might cross a try/catch boundary
792 // try { ... } catch { continue; }
796 // try {} catch { while () { continue; }}
798 ec.ig.Emit (OpCodes.Br, begin);
803 public class VariableInfo {
804 public readonly string Type;
805 public LocalBuilder LocalBuilder;
806 public Type VariableType;
807 public readonly Location Location;
810 public bool Assigned;
811 public bool ReadOnly;
813 public VariableInfo (string type, Location l)
820 public void MakePinned ()
822 TypeManager.MakePinned (LocalBuilder);
827 /// Block represents a C# block.
831 /// This class is used in a number of places: either to represent
832 /// explicit blocks that the programmer places or implicit blocks.
834 /// Implicit blocks are used as labels or to introduce variable
837 public class Block : Statement {
838 public readonly Block Parent;
839 public readonly bool Implicit;
840 public readonly Location StartLocation;
841 public Location EndLocation;
844 // The statements in this block
846 ArrayList statements;
849 // An array of Blocks. We keep track of children just
850 // to generate the local variable declarations.
852 // Statements and child statements are handled through the
858 // Labels. (label, block) pairs.
863 // Keeps track of (name, type) pairs
868 // Keeps track of constants
872 // Maps variable names to ILGenerator.LocalBuilders
874 Hashtable local_builders;
882 public Block (Block parent)
883 : this (parent, false, Location.Null, Location.Null)
886 public Block (Block parent, bool implicit_block)
887 : this (parent, implicit_block, Location.Null, Location.Null)
890 public Block (Block parent, Location start, Location end)
891 : this (parent, false, start, end)
894 public Block (Block parent, bool implicit_block, Location start, Location end)
897 parent.AddChild (this);
899 this.Parent = parent;
900 this.Implicit = implicit_block;
901 this.StartLocation = start;
902 this.EndLocation = end;
905 statements = new ArrayList ();
914 void AddChild (Block b)
916 if (children == null)
917 children = new ArrayList ();
922 public void SetEndLocation (Location loc)
928 /// Adds a label to the current block.
932 /// false if the name already exists in this block. true
936 public bool AddLabel (string name, LabeledStatement target)
939 labels = new Hashtable ();
940 if (labels.Contains (name))
943 labels.Add (name, target);
947 public LabeledStatement LookupLabel (string name)
950 if (labels.Contains (name))
951 return ((LabeledStatement) labels [name]);
955 return Parent.LookupLabel (name);
960 public VariableInfo AddVariable (string type, string name, Parameters pars, Location l)
962 if (variables == null)
963 variables = new Hashtable ();
965 if (GetVariableType (name) != null)
970 Parameter p = pars.GetParameterByName (name, out idx);
975 VariableInfo vi = new VariableInfo (type, l);
977 variables.Add (name, vi);
979 // Console.WriteLine ("Adding {0} to {1}", name, ID);
983 public bool AddConstant (string type, string name, Expression value, Parameters pars, Location l)
985 if (AddVariable (type, name, pars, l) == null)
988 if (constants == null)
989 constants = new Hashtable ();
991 constants.Add (name, value);
995 public Hashtable Variables {
1001 public VariableInfo GetVariableInfo (string name)
1003 if (variables != null) {
1005 temp = variables [name];
1008 return (VariableInfo) temp;
1013 return Parent.GetVariableInfo (name);
1018 public string GetVariableType (string name)
1020 VariableInfo vi = GetVariableInfo (name);
1028 public Expression GetConstantExpression (string name)
1030 if (constants != null) {
1032 temp = constants [name];
1035 return (Expression) temp;
1039 return Parent.GetConstantExpression (name);
1045 /// True if the variable named @name has been defined
1048 public bool IsVariableDefined (string name)
1050 // Console.WriteLine ("Looking up {0} in {1}", name, ID);
1051 if (variables != null) {
1052 if (variables.Contains (name))
1057 return Parent.IsVariableDefined (name);
1063 /// True if the variable named @name is a constant
1065 public bool IsConstant (string name)
1067 Expression e = null;
1069 e = GetConstantExpression (name);
1075 /// Use to fetch the statement associated with this label
1077 public Statement this [string name] {
1079 return (Statement) labels [name];
1084 /// A list of labels that were not used within this block
1086 public string [] GetUnreferenced ()
1088 // FIXME: Implement me
1092 public void AddStatement (Statement s)
1110 /// Emits the variable declarations and labels.
1113 /// tc: is our typecontainer (to resolve type references)
1114 /// ig: is the code generator:
1115 /// toplevel: the toplevel block. This is used for checking
1116 /// that no two labels with the same name are used.
1118 public void EmitMeta (EmitContext ec, Block toplevel)
1120 DeclSpace ds = ec.DeclSpace;
1121 ILGenerator ig = ec.ig;
1124 // Process this block variables
1126 if (variables != null){
1127 local_builders = new Hashtable ();
1129 foreach (DictionaryEntry de in variables){
1130 string name = (string) de.Key;
1131 VariableInfo vi = (VariableInfo) de.Value;
1134 t = RootContext.LookupType (ds, vi.Type, false, vi.Location);
1138 vi.VariableType = t;
1139 vi.LocalBuilder = ig.DeclareLocal (t);
1141 if (CodeGen.SymbolWriter != null)
1142 vi.LocalBuilder.SetLocalSymInfo (name);
1144 if (constants == null)
1147 Expression cv = (Expression) constants [name];
1151 Expression e = cv.Resolve (ec);
1155 if (!(e is Constant)){
1156 Report.Error (133, vi.Location,
1157 "The expression being assigned to `" +
1158 name + "' must be constant (" + e + ")");
1162 constants.Remove (name);
1163 constants.Add (name, e);
1168 // Now, handle the children
1170 if (children != null){
1171 foreach (Block b in children)
1172 b.EmitMeta (ec, toplevel);
1176 public void UsageWarning ()
1180 if (variables != null){
1181 foreach (DictionaryEntry de in variables){
1182 VariableInfo vi = (VariableInfo) de.Value;
1187 name = (string) de.Key;
1191 219, vi.Location, "The variable `" + name +
1192 "' is assigned but its value is never used");
1195 168, vi.Location, "The variable `" +
1197 "' is declared but never used");
1202 if (children != null)
1203 foreach (Block b in children)
1207 public override bool Resolve (EmitContext ec)
1209 Block prev_block = ec.CurrentBlock;
1211 ec.CurrentBlock = this;
1212 foreach (Statement s in statements){
1213 if (s.Resolve (ec) == false){
1214 ec.CurrentBlock = prev_block;
1219 ec.CurrentBlock = prev_block;
1223 public override bool Emit (EmitContext ec)
1225 bool is_ret = false;
1226 Block prev_block = ec.CurrentBlock;
1228 ec.CurrentBlock = this;
1230 if (CodeGen.SymbolWriter != null) {
1231 ec.Mark (StartLocation);
1233 foreach (Statement s in statements) {
1236 is_ret = s.Emit (ec);
1239 ec.Mark (EndLocation);
1241 foreach (Statement s in statements)
1242 is_ret = s.Emit (ec);
1245 ec.CurrentBlock = prev_block;
1250 public class SwitchLabel {
1253 public Location loc;
1254 public Label ILLabel;
1255 public Label ILLabelCode;
1258 // if expr == null, then it is the default case.
1260 public SwitchLabel (Expression expr, Location l)
1266 public Expression Label {
1272 public object Converted {
1279 // Resolves the expression, reduces it to a literal if possible
1280 // and then converts it to the requested type.
1282 public bool ResolveAndReduce (EmitContext ec, Type required_type)
1284 ILLabel = ec.ig.DefineLabel ();
1285 ILLabelCode = ec.ig.DefineLabel ();
1290 Expression e = label.Resolve (ec);
1295 if (!(e is Constant)){
1296 Console.WriteLine ("Value is: " + label);
1297 Report.Error (150, loc, "A constant value is expected");
1301 if (e is StringConstant || e is NullLiteral){
1302 if (required_type == TypeManager.string_type){
1304 ILLabel = ec.ig.DefineLabel ();
1309 converted = Expression.ConvertIntLiteral ((Constant) e, required_type, loc);
1310 if (converted == null)
1317 public class SwitchSection {
1318 // An array of SwitchLabels.
1319 public readonly ArrayList Labels;
1320 public readonly Block Block;
1322 public SwitchSection (ArrayList labels, Block block)
1329 public class Switch : Statement {
1330 public readonly ArrayList Sections;
1331 public Expression Expr;
1334 /// Maps constants whose type type SwitchType to their SwitchLabels.
1336 public Hashtable Elements;
1339 /// The governing switch type
1341 public Type SwitchType;
1347 Label default_target;
1350 // The types allowed to be implicitly cast from
1351 // on the governing type
1353 static Type [] allowed_types;
1355 public Switch (Expression e, ArrayList sects, Location l)
1362 public bool GotDefault {
1368 public Label DefaultTarget {
1370 return default_target;
1375 // Determines the governing type for a switch. The returned
1376 // expression might be the expression from the switch, or an
1377 // expression that includes any potential conversions to the
1378 // integral types or to string.
1380 Expression SwitchGoverningType (EmitContext ec, Type t)
1382 if (t == TypeManager.int32_type ||
1383 t == TypeManager.uint32_type ||
1384 t == TypeManager.char_type ||
1385 t == TypeManager.byte_type ||
1386 t == TypeManager.sbyte_type ||
1387 t == TypeManager.ushort_type ||
1388 t == TypeManager.short_type ||
1389 t == TypeManager.uint64_type ||
1390 t == TypeManager.int64_type ||
1391 t == TypeManager.string_type ||
1392 t == TypeManager.bool_type ||
1393 t.IsSubclassOf (TypeManager.enum_type))
1396 if (allowed_types == null){
1397 allowed_types = new Type [] {
1398 TypeManager.sbyte_type,
1399 TypeManager.byte_type,
1400 TypeManager.short_type,
1401 TypeManager.ushort_type,
1402 TypeManager.int32_type,
1403 TypeManager.uint32_type,
1404 TypeManager.int64_type,
1405 TypeManager.uint64_type,
1406 TypeManager.char_type,
1407 TypeManager.bool_type,
1408 TypeManager.string_type
1413 // Try to find a *user* defined implicit conversion.
1415 // If there is no implicit conversion, or if there are multiple
1416 // conversions, we have to report an error
1418 Expression converted = null;
1419 foreach (Type tt in allowed_types){
1422 e = Expression.ImplicitUserConversion (ec, Expr, tt, loc);
1426 if (converted != null){
1427 Report.Error (-12, loc, "More than one conversion to an integral " +
1428 " type exists for type `" +
1429 TypeManager.CSharpName (Expr.Type)+"'");
1437 void error152 (string n)
1440 152, "The label `" + n + ":' " +
1441 "is already present on this switch statement");
1445 // Performs the basic sanity checks on the switch statement
1446 // (looks for duplicate keys and non-constant expressions).
1448 // It also returns a hashtable with the keys that we will later
1449 // use to compute the switch tables
1451 bool CheckSwitch (EmitContext ec)
1455 Elements = new Hashtable ();
1457 got_default = false;
1459 if (TypeManager.IsEnumType (SwitchType)){
1460 compare_type = TypeManager.EnumToUnderlying (SwitchType);
1462 compare_type = SwitchType;
1464 foreach (SwitchSection ss in Sections){
1465 foreach (SwitchLabel sl in ss.Labels){
1466 if (!sl.ResolveAndReduce (ec, SwitchType)){
1471 if (sl.Label == null){
1473 error152 ("default");
1480 object key = sl.Converted;
1482 if (key is Constant)
1483 key = ((Constant) key).GetValue ();
1486 key = NullLiteral.Null;
1488 string lname = null;
1489 if (compare_type == TypeManager.uint64_type){
1490 ulong v = (ulong) key;
1492 if (Elements.Contains (v))
1493 lname = v.ToString ();
1495 Elements.Add (v, sl);
1496 } else if (compare_type == TypeManager.int64_type){
1497 long v = (long) key;
1499 if (Elements.Contains (v))
1500 lname = v.ToString ();
1502 Elements.Add (v, sl);
1503 } else if (compare_type == TypeManager.uint32_type){
1504 uint v = (uint) key;
1506 if (Elements.Contains (v))
1507 lname = v.ToString ();
1509 Elements.Add (v, sl);
1510 } else if (compare_type == TypeManager.char_type){
1511 char v = (char) key;
1513 if (Elements.Contains (v))
1514 lname = v.ToString ();
1516 Elements.Add (v, sl);
1517 } else if (compare_type == TypeManager.byte_type){
1518 byte v = (byte) key;
1520 if (Elements.Contains (v))
1521 lname = v.ToString ();
1523 Elements.Add (v, sl);
1524 } else if (compare_type == TypeManager.sbyte_type){
1525 sbyte v = (sbyte) key;
1527 if (Elements.Contains (v))
1528 lname = v.ToString ();
1530 Elements.Add (v, sl);
1531 } else if (compare_type == TypeManager.short_type){
1532 short v = (short) key;
1534 if (Elements.Contains (v))
1535 lname = v.ToString ();
1537 Elements.Add (v, sl);
1538 } else if (compare_type == TypeManager.ushort_type){
1539 ushort v = (ushort) key;
1541 if (Elements.Contains (v))
1542 lname = v.ToString ();
1544 Elements.Add (v, sl);
1545 } else if (compare_type == TypeManager.string_type){
1546 if (key is NullLiteral){
1547 if (Elements.Contains (NullLiteral.Null))
1550 Elements.Add (NullLiteral.Null, null);
1552 string s = (string) key;
1554 if (Elements.Contains (s))
1557 Elements.Add (s, sl);
1559 } else if (compare_type == TypeManager.int32_type) {
1562 if (Elements.Contains (v))
1563 lname = v.ToString ();
1565 Elements.Add (v, sl);
1566 } else if (compare_type == TypeManager.bool_type) {
1567 bool v = (bool) key;
1569 if (Elements.Contains (v))
1570 lname = v.ToString ();
1572 Elements.Add (v, sl);
1576 throw new Exception ("Unknown switch type!" +
1577 SwitchType + " " + compare_type);
1581 error152 ("case + " + lname);
1592 void EmitObjectInteger (ILGenerator ig, object k)
1595 IntConstant.EmitInt (ig, (int) k);
1596 else if (k is Constant) {
1597 EmitObjectInteger (ig, ((Constant) k).GetValue ());
1600 IntConstant.EmitInt (ig, unchecked ((int) (uint) k));
1603 if ((long) k >= int.MinValue && (long) k <= int.MaxValue)
1605 IntConstant.EmitInt (ig, (int) (long) k);
1606 ig.Emit (OpCodes.Conv_I8);
1609 LongConstant.EmitLong (ig, (long) k);
1611 else if (k is ulong)
1613 if ((ulong) k < (1L<<32))
1615 IntConstant.EmitInt (ig, (int) (long) k);
1616 ig.Emit (OpCodes.Conv_U8);
1620 LongConstant.EmitLong (ig, unchecked ((long) (ulong) k));
1624 IntConstant.EmitInt (ig, (int) ((char) k));
1625 else if (k is sbyte)
1626 IntConstant.EmitInt (ig, (int) ((sbyte) k));
1628 IntConstant.EmitInt (ig, (int) ((byte) k));
1629 else if (k is short)
1630 IntConstant.EmitInt (ig, (int) ((short) k));
1631 else if (k is ushort)
1632 IntConstant.EmitInt (ig, (int) ((ushort) k));
1634 IntConstant.EmitInt (ig, ((bool) k) ? 1 : 0);
1636 throw new Exception ("Unhandled case");
1639 // structure used to hold blocks of keys while calculating table switch
1640 class KeyBlock : IComparable
1642 public KeyBlock (long _nFirst)
1644 nFirst = nLast = _nFirst;
1648 public ArrayList rgKeys = null;
1651 get { return (int) (nLast - nFirst + 1); }
1653 public static long TotalLength (KeyBlock kbFirst, KeyBlock kbLast)
1655 return kbLast.nLast - kbFirst.nFirst + 1;
1657 public int CompareTo (object obj)
1659 KeyBlock kb = (KeyBlock) obj;
1660 int nLength = Length;
1661 int nLengthOther = kb.Length;
1662 if (nLengthOther == nLength)
1663 return (int) (kb.nFirst - nFirst);
1664 return nLength - nLengthOther;
1669 /// This method emits code for a lookup-based switch statement (non-string)
1670 /// Basically it groups the cases into blocks that are at least half full,
1671 /// and then spits out individual lookup opcodes for each block.
1672 /// It emits the longest blocks first, and short blocks are just
1673 /// handled with direct compares.
1675 /// <param name="ec"></param>
1676 /// <param name="val"></param>
1677 /// <returns></returns>
1678 bool TableSwitchEmit (EmitContext ec, LocalBuilder val)
1680 int cElements = Elements.Count;
1681 object [] rgKeys = new object [cElements];
1682 Elements.Keys.CopyTo (rgKeys, 0);
1683 Array.Sort (rgKeys);
1685 // initialize the block list with one element per key
1686 ArrayList rgKeyBlocks = new ArrayList ();
1687 foreach (object key in rgKeys)
1688 rgKeyBlocks.Add (new KeyBlock (Convert.ToInt64 (key)));
1691 // iteratively merge the blocks while they are at least half full
1692 // there's probably a really cool way to do this with a tree...
1693 while (rgKeyBlocks.Count > 1)
1695 ArrayList rgKeyBlocksNew = new ArrayList ();
1696 kbCurr = (KeyBlock) rgKeyBlocks [0];
1697 for (int ikb = 1; ikb < rgKeyBlocks.Count; ikb++)
1699 KeyBlock kb = (KeyBlock) rgKeyBlocks [ikb];
1700 if ((kbCurr.Length + kb.Length) * 2 >= KeyBlock.TotalLength (kbCurr, kb))
1703 kbCurr.nLast = kb.nLast;
1707 // start a new block
1708 rgKeyBlocksNew.Add (kbCurr);
1712 rgKeyBlocksNew.Add (kbCurr);
1713 if (rgKeyBlocks.Count == rgKeyBlocksNew.Count)
1715 rgKeyBlocks = rgKeyBlocksNew;
1718 // initialize the key lists
1719 foreach (KeyBlock kb in rgKeyBlocks)
1720 kb.rgKeys = new ArrayList ();
1722 // fill the key lists
1724 if (rgKeyBlocks.Count > 0) {
1725 kbCurr = (KeyBlock) rgKeyBlocks [0];
1726 foreach (object key in rgKeys)
1728 bool fNextBlock = (key is UInt64) ? (ulong) key > (ulong) kbCurr.nLast : Convert.ToInt64 (key) > kbCurr.nLast;
1730 kbCurr = (KeyBlock) rgKeyBlocks [++iBlockCurr];
1731 kbCurr.rgKeys.Add (key);
1735 // sort the blocks so we can tackle the largest ones first
1736 rgKeyBlocks.Sort ();
1738 // okay now we can start...
1739 ILGenerator ig = ec.ig;
1740 Label lblEnd = ig.DefineLabel (); // at the end ;-)
1741 Label lblDefault = ig.DefineLabel ();
1743 Type typeKeys = null;
1744 if (rgKeys.Length > 0)
1745 typeKeys = rgKeys [0].GetType (); // used for conversions
1747 for (int iBlock = rgKeyBlocks.Count - 1; iBlock >= 0; --iBlock)
1749 KeyBlock kb = ((KeyBlock) rgKeyBlocks [iBlock]);
1750 lblDefault = (iBlock == 0) ? DefaultTarget : ig.DefineLabel ();
1753 foreach (object key in kb.rgKeys)
1755 ig.Emit (OpCodes.Ldloc, val);
1756 EmitObjectInteger (ig, key);
1757 SwitchLabel sl = (SwitchLabel) Elements [key];
1758 ig.Emit (OpCodes.Beq, sl.ILLabel);
1763 // TODO: if all the keys in the block are the same and there are
1764 // no gaps/defaults then just use a range-check.
1765 if (SwitchType == TypeManager.int64_type ||
1766 SwitchType == TypeManager.uint64_type)
1768 // TODO: optimize constant/I4 cases
1770 // check block range (could be > 2^31)
1771 ig.Emit (OpCodes.Ldloc, val);
1772 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
1773 ig.Emit (OpCodes.Blt, lblDefault);
1774 ig.Emit (OpCodes.Ldloc, val);
1775 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
1776 ig.Emit (OpCodes.Bgt, lblDefault);
1779 ig.Emit (OpCodes.Ldloc, val);
1782 EmitObjectInteger (ig, Convert.ChangeType (kb.nFirst, typeKeys));
1783 ig.Emit (OpCodes.Sub);
1785 ig.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
1790 ig.Emit (OpCodes.Ldloc, val);
1791 int nFirst = (int) kb.nFirst;
1794 IntConstant.EmitInt (ig, nFirst);
1795 ig.Emit (OpCodes.Sub);
1797 else if (nFirst < 0)
1799 IntConstant.EmitInt (ig, -nFirst);
1800 ig.Emit (OpCodes.Add);
1804 // first, build the list of labels for the switch
1806 int cJumps = kb.Length;
1807 Label [] rgLabels = new Label [cJumps];
1808 for (int iJump = 0; iJump < cJumps; iJump++)
1810 object key = kb.rgKeys [iKey];
1811 if (Convert.ToInt64 (key) == kb.nFirst + iJump)
1813 SwitchLabel sl = (SwitchLabel) Elements [key];
1814 rgLabels [iJump] = sl.ILLabel;
1818 rgLabels [iJump] = lblDefault;
1820 // emit the switch opcode
1821 ig.Emit (OpCodes.Switch, rgLabels);
1824 // mark the default for this block
1826 ig.MarkLabel (lblDefault);
1829 // TODO: find the default case and emit it here,
1830 // to prevent having to do the following jump.
1831 // make sure to mark other labels in the default section
1833 // the last default just goes to the end
1834 ig.Emit (OpCodes.Br, lblDefault);
1836 // now emit the code for the sections
1837 bool fFoundDefault = false;
1838 bool fAllReturn = true;
1839 foreach (SwitchSection ss in Sections)
1841 foreach (SwitchLabel sl in ss.Labels)
1843 ig.MarkLabel (sl.ILLabel);
1844 ig.MarkLabel (sl.ILLabelCode);
1845 if (sl.Label == null)
1847 ig.MarkLabel (lblDefault);
1848 fFoundDefault = true;
1851 fAllReturn &= ss.Block.Emit (ec);
1852 //ig.Emit (OpCodes.Br, lblEnd);
1856 ig.MarkLabel (lblDefault);
1857 ig.MarkLabel (lblEnd);
1862 // This simple emit switch works, but does not take advantage of the
1864 // TODO: remove non-string logic from here
1865 // TODO: binary search strings?
1867 bool SimpleSwitchEmit (EmitContext ec, LocalBuilder val)
1869 ILGenerator ig = ec.ig;
1870 Label end_of_switch = ig.DefineLabel ();
1871 Label next_test = ig.DefineLabel ();
1872 Label null_target = ig.DefineLabel ();
1873 bool default_found = false;
1874 bool first_test = true;
1875 bool pending_goto_end = false;
1876 bool all_return = true;
1877 bool is_string = false;
1881 // Special processing for strings: we cant compare
1884 if (SwitchType == TypeManager.string_type){
1885 ig.Emit (OpCodes.Ldloc, val);
1888 if (Elements.Contains (NullLiteral.Null)){
1889 ig.Emit (OpCodes.Brfalse, null_target);
1891 ig.Emit (OpCodes.Brfalse, default_target);
1893 ig.Emit (OpCodes.Ldloc, val);
1894 ig.Emit (OpCodes.Call, TypeManager.string_isinterneted_string);
1895 ig.Emit (OpCodes.Stloc, val);
1898 SwitchSection last_section;
1899 last_section = (SwitchSection) Sections [Sections.Count-1];
1901 foreach (SwitchSection ss in Sections){
1902 Label sec_begin = ig.DefineLabel ();
1904 if (pending_goto_end)
1905 ig.Emit (OpCodes.Br, end_of_switch);
1907 int label_count = ss.Labels.Count;
1909 foreach (SwitchLabel sl in ss.Labels){
1910 ig.MarkLabel (sl.ILLabel);
1913 ig.MarkLabel (next_test);
1914 next_test = ig.DefineLabel ();
1917 // If we are the default target
1919 if (sl.Label == null){
1920 ig.MarkLabel (default_target);
1921 default_found = true;
1923 object lit = sl.Converted;
1925 if (lit is NullLiteral){
1927 if (label_count == 1)
1928 ig.Emit (OpCodes.Br, next_test);
1933 StringConstant str = (StringConstant) lit;
1935 ig.Emit (OpCodes.Ldloc, val);
1936 ig.Emit (OpCodes.Ldstr, str.Value);
1937 if (label_count == 1)
1938 ig.Emit (OpCodes.Bne_Un, next_test);
1940 ig.Emit (OpCodes.Beq, sec_begin);
1942 ig.Emit (OpCodes.Ldloc, val);
1943 EmitObjectInteger (ig, lit);
1944 ig.Emit (OpCodes.Ceq);
1945 if (label_count == 1)
1946 ig.Emit (OpCodes.Brfalse, next_test);
1948 ig.Emit (OpCodes.Brtrue, sec_begin);
1952 if (label_count != 1 && ss != last_section)
1953 ig.Emit (OpCodes.Br, next_test);
1956 ig.MarkLabel (null_target);
1957 ig.MarkLabel (sec_begin);
1958 foreach (SwitchLabel sl in ss.Labels)
\r
1959 ig.MarkLabel (sl.ILLabelCode);
1960 if (ss.Block.Emit (ec))
1961 pending_goto_end = false;
1964 pending_goto_end = true;
1968 if (!default_found){
1969 ig.MarkLabel (default_target);
1972 ig.MarkLabel (next_test);
1973 ig.MarkLabel (end_of_switch);
1978 public override bool Resolve (EmitContext ec)
1980 foreach (SwitchSection ss in Sections){
1981 if (ss.Block.Resolve (ec) != true)
1988 public override bool Emit (EmitContext ec)
1990 Expr = Expr.Resolve (ec);
1994 Expression new_expr = SwitchGoverningType (ec, Expr.Type);
1995 if (new_expr == null){
1996 Report.Error (151, loc, "An integer type or string was expected for switch");
2001 SwitchType = new_expr.Type;
2003 if (!CheckSwitch (ec))
2006 // Store variable for comparission purposes
2007 LocalBuilder value = ec.ig.DeclareLocal (SwitchType);
2009 ec.ig.Emit (OpCodes.Stloc, value);
2011 ILGenerator ig = ec.ig;
2013 default_target = ig.DefineLabel ();
2016 // Setup the codegen context
2018 Label old_end = ec.LoopEnd;
2019 Switch old_switch = ec.Switch;
2021 ec.LoopEnd = ig.DefineLabel ();
2026 if (SwitchType == TypeManager.string_type)
2027 all_return = SimpleSwitchEmit (ec, value);
2029 all_return = TableSwitchEmit (ec, value);
2031 // Restore context state.
2032 ig.MarkLabel (ec.LoopEnd);
2035 // Restore the previous context
2037 ec.LoopEnd = old_end;
2038 ec.Switch = old_switch;
2044 public class Lock : Statement {
2046 Statement Statement;
2048 public Lock (Expression expr, Statement stmt, Location l)
2055 public override bool Resolve (EmitContext ec)
2057 expr = expr.Resolve (ec);
2058 return Statement.Resolve (ec) && expr != null;
2061 public override bool Emit (EmitContext ec)
2063 Type type = expr.Type;
2066 if (type.IsValueType){
2067 Report.Error (185, loc, "lock statement requires the expression to be " +
2068 " a reference type (type is: `" +
2069 TypeManager.CSharpName (type) + "'");
2073 ILGenerator ig = ec.ig;
2074 LocalBuilder temp = ig.DeclareLocal (type);
2077 ig.Emit (OpCodes.Dup);
2078 ig.Emit (OpCodes.Stloc, temp);
2079 ig.Emit (OpCodes.Call, TypeManager.void_monitor_enter_object);
2082 Label end = ig.BeginExceptionBlock ();
2083 bool old_in_try = ec.InTry;
2085 Label finish = ig.DefineLabel ();
2086 val = Statement.Emit (ec);
2087 ec.InTry = old_in_try;
2088 // ig.Emit (OpCodes.Leave, finish);
2090 ig.MarkLabel (finish);
2093 ig.BeginFinallyBlock ();
2094 ig.Emit (OpCodes.Ldloc, temp);
2095 ig.Emit (OpCodes.Call, TypeManager.void_monitor_exit_object);
2096 ig.EndExceptionBlock ();
2102 public class Unchecked : Statement {
2103 public readonly Block Block;
2105 public Unchecked (Block b)
2110 public override bool Resolve (EmitContext ec)
2112 return Block.Resolve (ec);
2115 public override bool Emit (EmitContext ec)
2117 bool previous_state = ec.CheckState;
2118 bool previous_state_const = ec.ConstantCheckState;
2121 ec.CheckState = false;
2122 ec.ConstantCheckState = false;
2123 val = Block.Emit (ec);
2124 ec.CheckState = previous_state;
2125 ec.ConstantCheckState = previous_state_const;
2131 public class Checked : Statement {
2132 public readonly Block Block;
2134 public Checked (Block b)
2139 public override bool Resolve (EmitContext ec)
2141 bool previous_state = ec.CheckState;
2142 bool previous_state_const = ec.ConstantCheckState;
2144 ec.CheckState = true;
2145 ec.ConstantCheckState = true;
2146 bool ret = Block.Resolve (ec);
2147 ec.CheckState = previous_state;
2148 ec.ConstantCheckState = previous_state_const;
2153 public override bool Emit (EmitContext ec)
2155 bool previous_state = ec.CheckState;
2156 bool previous_state_const = ec.ConstantCheckState;
2159 ec.CheckState = true;
2160 ec.ConstantCheckState = true;
2161 val = Block.Emit (ec);
2162 ec.CheckState = previous_state;
2163 ec.ConstantCheckState = previous_state_const;
2169 public class Unsafe : Statement {
2170 public readonly Block Block;
2172 public Unsafe (Block b)
2177 public override bool Resolve (EmitContext ec)
2179 return Block.Resolve (ec);
2182 public override bool Emit (EmitContext ec)
2184 bool previous_state = ec.InUnsafe;
2188 val = Block.Emit (ec);
2189 ec.InUnsafe = previous_state;
2198 public class Fixed : Statement {
2200 ArrayList declarators;
2201 Statement statement;
2203 public Fixed (string type, ArrayList decls, Statement stmt, Location l)
2206 declarators = decls;
2211 public override bool Resolve (EmitContext ec)
2213 return statement.Resolve (ec);
2216 public override bool Emit (EmitContext ec)
2218 ILGenerator ig = ec.ig;
2221 t = RootContext.LookupType (ec.DeclSpace, type, false, loc);
2225 bool is_ret = false;
2227 foreach (Pair p in declarators){
2228 VariableInfo vi = (VariableInfo) p.First;
2229 Expression e = (Expression) p.Second;
2232 // The rules for the possible declarators are pretty wise,
2233 // but the production on the grammar is more concise.
2235 // So we have to enforce these rules here.
2237 // We do not resolve before doing the case 1 test,
2238 // because the grammar is explicit in that the token &
2239 // is present, so we need to test for this particular case.
2243 // Case 1: & object.
2245 if (e is Unary && ((Unary) e).Oper == Unary.Operator.AddressOf){
2246 Expression child = ((Unary) e).Expr;
2249 if (child is ParameterReference || child is LocalVariableReference){
2252 "No need to use fixed statement for parameters or " +
2253 "local variable declarations (address is already " +
2262 child = ((Unary) e).Expr;
2264 if (!TypeManager.VerifyUnManaged (child.Type, loc))
2268 // Store pointer in pinned location
2271 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2273 is_ret = statement.Emit (ec);
2275 // Clear the pinned variable.
2276 ig.Emit (OpCodes.Ldc_I4_0);
2277 ig.Emit (OpCodes.Conv_U);
2278 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2290 if (e.Type.IsArray){
2291 Type array_type = e.Type.GetElementType ();
2295 // Provided that array_type is unmanaged,
2297 if (!TypeManager.VerifyUnManaged (array_type, loc))
2301 // and T* is implicitly convertible to the
2302 // pointer type given in the fixed statement.
2304 ArrayPtr array_ptr = new ArrayPtr (e);
2306 Expression converted = Expression.ConvertImplicitRequired (
2307 ec, array_ptr, vi.VariableType, loc);
2308 if (converted == null)
2312 // Store pointer in pinned location
2314 converted.Emit (ec);
2316 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2318 is_ret = statement.Emit (ec);
2320 // Clear the pinned variable.
2321 ig.Emit (OpCodes.Ldc_I4_0);
2322 ig.Emit (OpCodes.Conv_U);
2323 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2331 if (e.Type == TypeManager.string_type){
2332 LocalBuilder pinned_string = ig.DeclareLocal (TypeManager.string_type);
2333 TypeManager.MakePinned (pinned_string);
2336 ig.Emit (OpCodes.Stloc, pinned_string);
2338 Expression sptr = new StringPtr (pinned_string);
2339 Expression converted = Expression.ConvertImplicitRequired (
2340 ec, sptr, vi.VariableType, loc);
2342 if (converted == null)
2345 converted.Emit (ec);
2346 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2348 is_ret = statement.Emit (ec);
2350 // Clear the pinned variable
2351 ig.Emit (OpCodes.Ldnull);
2352 ig.Emit (OpCodes.Stloc, pinned_string);
2360 public class Catch {
2361 public readonly string Type;
2362 public readonly string Name;
2363 public readonly Block Block;
2364 public readonly Location Location;
2366 public Catch (string type, string name, Block block, Location l)
2375 public class Try : Statement {
2376 public readonly Block Fini, Block;
2377 public readonly ArrayList Specific;
2378 public readonly Catch General;
2381 // specific, general and fini might all be null.
2383 public Try (Block block, ArrayList specific, Catch general, Block fini)
2385 if (specific == null && general == null){
2386 Console.WriteLine ("CIR.Try: Either specific or general have to be non-null");
2390 this.Specific = specific;
2391 this.General = general;
2395 public override bool Resolve (EmitContext ec)
2399 if (General != null)
2400 if (!General.Block.Resolve (ec))
2403 foreach (Catch c in Specific){
2404 if (!c.Block.Resolve (ec))
2408 if (!Block.Resolve (ec))
2412 if (!Fini.Resolve (ec))
2418 public override bool Emit (EmitContext ec)
2420 ILGenerator ig = ec.ig;
2422 Label finish = ig.DefineLabel ();;
2425 end = ig.BeginExceptionBlock ();
2426 bool old_in_try = ec.InTry;
2428 returns = Block.Emit (ec);
2429 ec.InTry = old_in_try;
2432 // System.Reflection.Emit provides this automatically:
2433 // ig.Emit (OpCodes.Leave, finish);
2435 bool old_in_catch = ec.InCatch;
2437 DeclSpace ds = ec.DeclSpace;
2439 foreach (Catch c in Specific){
2440 Type catch_type = RootContext.LookupType (ds, c.Type, false, c.Location);
2443 if (catch_type == null)
2446 ig.BeginCatchBlock (catch_type);
2448 if (c.Name != null){
2449 vi = c.Block.GetVariableInfo (c.Name);
2451 Console.WriteLine ("This should not happen! variable does not exist in this block");
2452 Environment.Exit (0);
2455 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2457 ig.Emit (OpCodes.Pop);
2459 if (!c.Block.Emit (ec))
2463 if (General != null){
2464 ig.BeginCatchBlock (TypeManager.object_type);
2465 ig.Emit (OpCodes.Pop);
2466 if (!General.Block.Emit (ec))
2469 ec.InCatch = old_in_catch;
2471 ig.MarkLabel (finish);
2473 ig.BeginFinallyBlock ();
2474 bool old_in_finally = ec.InFinally;
2475 ec.InFinally = true;
2477 ec.InFinally = old_in_finally;
2480 ig.EndExceptionBlock ();
2483 // FIXME: Is this correct?
2484 // Replace with `returns' and check test-18, maybe we can
2485 // perform an optimization here.
2492 // FIXME: We still do not support the expression variant of the using
2495 public class Using : Statement {
2496 object expression_or_block;
2497 Statement Statement;
2499 public Using (object expression_or_block, Statement stmt, Location l)
2501 this.expression_or_block = expression_or_block;
2507 // Emits the code for the case of using using a local variable declaration.
2509 bool EmitLocalVariableDecls (EmitContext ec, string type_name, ArrayList var_list)
2511 ILGenerator ig = ec.ig;
2512 Expression [] converted_vars;
2513 bool need_conv = false;
2514 Type type = RootContext.LookupType (ec.DeclSpace, type_name, false, loc);
2521 // The type must be an IDisposable or an implicit conversion
2524 converted_vars = new Expression [var_list.Count];
2525 if (!TypeManager.ImplementsInterface (type, TypeManager.idisposable_type)){
2526 foreach (DictionaryEntry e in var_list){
2527 Expression var = (Expression) e.Key;
2529 var = var.Resolve (ec);
2533 converted_vars [i] = Expression.ConvertImplicit (
2534 ec, var, TypeManager.idisposable_type, loc);
2536 if (converted_vars [i] == null)
2544 bool old_in_try = ec.InTry;
2547 foreach (DictionaryEntry e in var_list){
2548 LocalVariableReference var = (LocalVariableReference) e.Key;
2549 Expression expr = (Expression) e.Value;
2552 a = new Assign (var, expr, loc);
2555 converted_vars [i] = var;
2561 ((ExpressionStatement) a).EmitStatement (ec);
2563 ig.BeginExceptionBlock ();
2568 Statement.Emit (ec);
2569 ec.InTry = old_in_try;
2571 bool old_in_finally = ec.InFinally;
2572 ec.InFinally = true;
2573 var_list.Reverse ();
2574 foreach (DictionaryEntry e in var_list){
2575 LocalVariableReference var = (LocalVariableReference) e.Key;
2576 Label skip = ig.DefineLabel ();
2579 ig.BeginFinallyBlock ();
2582 ig.Emit (OpCodes.Brfalse, skip);
2583 converted_vars [i].Emit (ec);
2584 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2585 ig.MarkLabel (skip);
2586 ig.EndExceptionBlock ();
2588 ec.InFinally = old_in_finally;
2593 bool EmitExpression (EmitContext ec, Expression expr)
2595 Type expr_type = expr.Type;
2596 Expression conv = null;
2598 if (!TypeManager.ImplementsInterface (expr_type, TypeManager.idisposable_type)){
2599 conv = Expression.ConvertImplicit (
2600 ec, expr, TypeManager.idisposable_type, loc);
2607 // Make a copy of the expression and operate on that.
2609 ILGenerator ig = ec.ig;
2610 LocalBuilder local_copy = ig.DeclareLocal (expr_type);
2615 ig.Emit (OpCodes.Stloc, local_copy);
2617 bool old_in_try = ec.InTry;
2619 ig.BeginExceptionBlock ();
2620 Statement.Emit (ec);
2621 ec.InTry = old_in_try;
2623 Label skip = ig.DefineLabel ();
2624 bool old_in_finally = ec.InFinally;
2625 ig.BeginFinallyBlock ();
2626 ig.Emit (OpCodes.Ldloc, local_copy);
2627 ig.Emit (OpCodes.Brfalse, skip);
2628 ig.Emit (OpCodes.Ldloc, local_copy);
2629 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2630 ig.MarkLabel (skip);
2631 ec.InFinally = old_in_finally;
2632 ig.EndExceptionBlock ();
2637 public override bool Resolve (EmitContext ec)
2639 return Statement.Resolve (ec);
2642 public override bool Emit (EmitContext ec)
2644 if (expression_or_block is DictionaryEntry){
2645 string t = (string) ((DictionaryEntry) expression_or_block).Key;
2646 ArrayList var_list = (ArrayList)((DictionaryEntry)expression_or_block).Value;
2648 return EmitLocalVariableDecls (ec, t, var_list);
2649 } if (expression_or_block is Expression){
2650 Expression e = (Expression) expression_or_block;
2656 return EmitExpression (ec, e);
2663 /// Implementation of the foreach C# statement
2665 public class Foreach : Statement {
2667 LocalVariableReference variable;
2669 Statement statement;
2671 public Foreach (string type, LocalVariableReference var, Expression expr,
2672 Statement stmt, Location l)
2675 this.variable = var;
2681 public override bool Resolve (EmitContext ec)
2683 expr = expr.Resolve (ec);
2684 return statement.Resolve (ec) && expr != null;
2688 // Retrieves a `public bool MoveNext ()' method from the Type `t'
2690 static MethodInfo FetchMethodMoveNext (Type t)
2692 MemberInfo [] move_next_list;
2694 move_next_list = TypeContainer.FindMembers (
2695 t, MemberTypes.Method,
2696 BindingFlags.Public | BindingFlags.Instance,
2697 Type.FilterName, "MoveNext");
2698 if (move_next_list == null || move_next_list.Length == 0)
2701 foreach (MemberInfo m in move_next_list){
2702 MethodInfo mi = (MethodInfo) m;
2705 args = TypeManager.GetArgumentTypes (mi);
2706 if (args != null && args.Length == 0){
2707 if (mi.ReturnType == TypeManager.bool_type)
2715 // Retrieves a `public T get_Current ()' method from the Type `t'
2717 static MethodInfo FetchMethodGetCurrent (Type t)
2719 MemberInfo [] move_next_list;
2721 move_next_list = TypeContainer.FindMembers (
2722 t, MemberTypes.Method,
2723 BindingFlags.Public | BindingFlags.Instance,
2724 Type.FilterName, "get_Current");
2725 if (move_next_list == null || move_next_list.Length == 0)
2728 foreach (MemberInfo m in move_next_list){
2729 MethodInfo mi = (MethodInfo) m;
2732 args = TypeManager.GetArgumentTypes (mi);
2733 if (args != null && args.Length == 0)
2740 // This struct records the helper methods used by the Foreach construct
2742 class ForeachHelperMethods {
2743 public EmitContext ec;
2744 public MethodInfo get_enumerator;
2745 public MethodInfo move_next;
2746 public MethodInfo get_current;
2748 public ForeachHelperMethods (EmitContext ec)
2754 static bool GetEnumeratorFilter (MemberInfo m, object criteria)
2759 if (!(m is MethodInfo))
2762 if (m.Name != "GetEnumerator")
2765 MethodInfo mi = (MethodInfo) m;
2766 Type [] args = TypeManager.GetArgumentTypes (mi);
2768 if (args.Length != 0)
2771 ForeachHelperMethods hm = (ForeachHelperMethods) criteria;
2772 EmitContext ec = hm.ec;
2775 // Check whether GetEnumerator is accessible to us
2777 MethodAttributes prot = mi.Attributes & MethodAttributes.MemberAccessMask;
2779 Type declaring = mi.DeclaringType;
2780 if (prot == MethodAttributes.Private){
2781 if (declaring != ec.ContainerType)
2783 } else if (prot == MethodAttributes.FamANDAssem){
2784 // If from a different assembly, false
2785 if (!(mi is MethodBuilder))
2788 // Are we being invoked from the same class, or from a derived method?
2790 if (ec.ContainerType != declaring){
2791 if (!ec.ContainerType.IsSubclassOf (declaring))
2794 } else if (prot == MethodAttributes.FamORAssem){
2795 if (!(mi is MethodBuilder ||
2796 ec.ContainerType == declaring ||
2797 ec.ContainerType.IsSubclassOf (declaring)))
2799 } if (prot == MethodAttributes.Family){
2800 if (!(ec.ContainerType == declaring ||
2801 ec.ContainerType.IsSubclassOf (declaring)))
2806 // Ok, we can access it, now make sure that we can do something
2807 // with this `GetEnumerator'
2809 if (mi.ReturnType == TypeManager.ienumerator_type ||
2810 TypeManager.ienumerator_type.IsAssignableFrom (mi.ReturnType)){
2811 hm.move_next = TypeManager.bool_movenext_void;
2812 hm.get_current = TypeManager.object_getcurrent_void;
2817 // Ok, so they dont return an IEnumerable, we will have to
2818 // find if they support the GetEnumerator pattern.
2820 Type return_type = mi.ReturnType;
2822 hm.move_next = FetchMethodMoveNext (return_type);
2823 if (hm.move_next == null)
2825 hm.get_current = FetchMethodGetCurrent (return_type);
2826 if (hm.get_current == null)
2833 /// This filter is used to find the GetEnumerator method
2834 /// on which IEnumerator operates
2836 static MemberFilter FilterEnumerator;
2840 FilterEnumerator = new MemberFilter (GetEnumeratorFilter);
2843 void error1579 (Type t)
2845 Report.Error (1579, loc,
2846 "foreach statement cannot operate on variables of type `" +
2847 t.FullName + "' because that class does not provide a " +
2848 " GetEnumerator method or it is inaccessible");
2851 static bool TryType (Type t, ForeachHelperMethods hm)
2855 mi = TypeContainer.FindMembers (t, MemberTypes.Method,
2856 BindingFlags.Public | BindingFlags.NonPublic |
2857 BindingFlags.Instance,
2858 FilterEnumerator, hm);
2860 if (mi == null || mi.Length == 0)
2863 hm.get_enumerator = (MethodInfo) mi [0];
2868 // Looks for a usable GetEnumerator in the Type, and if found returns
2869 // the three methods that participate: GetEnumerator, MoveNext and get_Current
2871 ForeachHelperMethods ProbeCollectionType (EmitContext ec, Type t)
2873 ForeachHelperMethods hm = new ForeachHelperMethods (ec);
2875 if (TryType (t, hm))
2879 // Now try to find the method in the interfaces
2882 Type [] ifaces = t.GetInterfaces ();
2884 foreach (Type i in ifaces){
2885 if (TryType (i, hm))
2890 // Since TypeBuilder.GetInterfaces only returns the interface
2891 // types for this type, we have to keep looping, but once
2892 // we hit a non-TypeBuilder (ie, a Type), then we know we are
2893 // done, because it returns all the types
2895 if ((t is TypeBuilder))
2905 // FIXME: possible optimization.
2906 // We might be able to avoid creating `empty' if the type is the sam
2908 bool EmitCollectionForeach (EmitContext ec, Type var_type, ForeachHelperMethods hm)
2910 ILGenerator ig = ec.ig;
2911 LocalBuilder enumerator, disposable;
2912 Expression empty = new EmptyExpression ();
2916 // FIXME: maybe we can apply the same trick we do in the
2917 // array handling to avoid creating empty and conv in some cases.
2919 // Although it is not as important in this case, as the type
2920 // will not likely be object (what the enumerator will return).
2922 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
2926 enumerator = ig.DeclareLocal (TypeManager.ienumerator_type);
2927 disposable = ig.DeclareLocal (TypeManager.idisposable_type);
2930 // Instantiate the enumerator
2932 if (expr.Type.IsValueType){
2933 if (expr is IMemoryLocation){
2934 IMemoryLocation ml = (IMemoryLocation) expr;
2936 ml.AddressOf (ec, AddressOp.Load);
2938 throw new Exception ("Expr " + expr + " of type " + expr.Type +
2939 " does not implement IMemoryLocation");
2940 ig.Emit (OpCodes.Call, hm.get_enumerator);
2943 ig.Emit (OpCodes.Callvirt, hm.get_enumerator);
2945 ig.Emit (OpCodes.Stloc, enumerator);
2948 // Protect the code in a try/finalize block, so that
2949 // if the beast implement IDisposable, we get rid of it
2951 Label l = ig.BeginExceptionBlock ();
2952 bool old_in_try = ec.InTry;
2955 Label end_try = ig.DefineLabel ();
2957 ig.MarkLabel (ec.LoopBegin);
2958 ig.Emit (OpCodes.Ldloc, enumerator);
2959 ig.Emit (OpCodes.Callvirt, hm.move_next);
2960 ig.Emit (OpCodes.Brfalse, end_try);
2961 ig.Emit (OpCodes.Ldloc, enumerator);
2962 ig.Emit (OpCodes.Callvirt, hm.get_current);
2963 variable.EmitAssign (ec, conv);
2964 statement.Emit (ec);
2965 ig.Emit (OpCodes.Br, ec.LoopBegin);
2966 ig.MarkLabel (end_try);
2967 ec.InTry = old_in_try;
2969 // The runtime provides this for us.
2970 // ig.Emit (OpCodes.Leave, end);
2973 // Now the finally block
2975 Label end_finally = ig.DefineLabel ();
2976 bool old_in_finally = ec.InFinally;
2977 ec.InFinally = true;
2978 ig.BeginFinallyBlock ();
2980 ig.Emit (OpCodes.Ldloc, enumerator);
2981 ig.Emit (OpCodes.Isinst, TypeManager.idisposable_type);
2982 ig.Emit (OpCodes.Stloc, disposable);
2983 ig.Emit (OpCodes.Ldloc, disposable);
2984 ig.Emit (OpCodes.Brfalse, end_finally);
2985 ig.Emit (OpCodes.Ldloc, disposable);
2986 ig.Emit (OpCodes.Callvirt, TypeManager.void_dispose_void);
2987 ig.MarkLabel (end_finally);
2988 ec.InFinally = old_in_finally;
2990 // The runtime generates this anyways.
2991 // ig.Emit (OpCodes.Endfinally);
2993 ig.EndExceptionBlock ();
2995 ig.MarkLabel (ec.LoopEnd);
3000 // FIXME: possible optimization.
3001 // We might be able to avoid creating `empty' if the type is the sam
3003 bool EmitArrayForeach (EmitContext ec, Type var_type)
3005 Type array_type = expr.Type;
3006 Type element_type = array_type.GetElementType ();
3007 Expression conv = null;
3008 Expression empty = new EmptyExpression (element_type);
3010 conv = Expression.ConvertExplicit (ec, empty, var_type, loc);
3014 int rank = array_type.GetArrayRank ();
3015 ILGenerator ig = ec.ig;
3017 LocalBuilder copy = ig.DeclareLocal (array_type);
3020 // Make our copy of the array
3023 ig.Emit (OpCodes.Stloc, copy);
3026 LocalBuilder counter = ig.DeclareLocal (TypeManager.int32_type);
3030 ig.Emit (OpCodes.Ldc_I4_0);
3031 ig.Emit (OpCodes.Stloc, counter);
3032 test = ig.DefineLabel ();
3033 ig.Emit (OpCodes.Br, test);
3035 loop = ig.DefineLabel ();
3036 ig.MarkLabel (loop);
3038 ig.Emit (OpCodes.Ldloc, copy);
3039 ig.Emit (OpCodes.Ldloc, counter);
3040 ArrayAccess.EmitLoadOpcode (ig, var_type);
3042 variable.EmitAssign (ec, conv);
3044 statement.Emit (ec);
3046 ig.MarkLabel (ec.LoopBegin);
3047 ig.Emit (OpCodes.Ldloc, counter);
3048 ig.Emit (OpCodes.Ldc_I4_1);
3049 ig.Emit (OpCodes.Add);
3050 ig.Emit (OpCodes.Stloc, counter);
3052 ig.MarkLabel (test);
3053 ig.Emit (OpCodes.Ldloc, counter);
3054 ig.Emit (OpCodes.Ldloc, copy);
3055 ig.Emit (OpCodes.Ldlen);
3056 ig.Emit (OpCodes.Conv_I4);
3057 ig.Emit (OpCodes.Blt, loop);
3059 LocalBuilder [] dim_len = new LocalBuilder [rank];
3060 LocalBuilder [] dim_count = new LocalBuilder [rank];
3061 Label [] loop = new Label [rank];
3062 Label [] test = new Label [rank];
3065 for (dim = 0; dim < rank; dim++){
3066 dim_len [dim] = ig.DeclareLocal (TypeManager.int32_type);
3067 dim_count [dim] = ig.DeclareLocal (TypeManager.int32_type);
3068 test [dim] = ig.DefineLabel ();
3069 loop [dim] = ig.DefineLabel ();
3072 for (dim = 0; dim < rank; dim++){
3073 ig.Emit (OpCodes.Ldloc, copy);
3074 IntLiteral.EmitInt (ig, dim);
3075 ig.Emit (OpCodes.Callvirt, TypeManager.int_getlength_int);
3076 ig.Emit (OpCodes.Stloc, dim_len [dim]);
3079 for (dim = 0; dim < rank; dim++){
3080 ig.Emit (OpCodes.Ldc_I4_0);
3081 ig.Emit (OpCodes.Stloc, dim_count [dim]);
3082 ig.Emit (OpCodes.Br, test [dim]);
3083 ig.MarkLabel (loop [dim]);
3086 ig.Emit (OpCodes.Ldloc, copy);
3087 for (dim = 0; dim < rank; dim++)
3088 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
3091 // FIXME: Maybe we can cache the computation of `get'?
3093 Type [] args = new Type [rank];
3096 for (int i = 0; i < rank; i++)
3097 args [i] = TypeManager.int32_type;
3099 ModuleBuilder mb = CodeGen.ModuleBuilder;
3100 get = mb.GetArrayMethod (
3102 CallingConventions.HasThis| CallingConventions.Standard,
3104 ig.Emit (OpCodes.Call, get);
3105 variable.EmitAssign (ec, conv);
3106 statement.Emit (ec);
3107 ig.MarkLabel (ec.LoopBegin);
3108 for (dim = rank - 1; dim >= 0; dim--){
3109 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
3110 ig.Emit (OpCodes.Ldc_I4_1);
3111 ig.Emit (OpCodes.Add);
3112 ig.Emit (OpCodes.Stloc, dim_count [dim]);
3114 ig.MarkLabel (test [dim]);
3115 ig.Emit (OpCodes.Ldloc, dim_count [dim]);
3116 ig.Emit (OpCodes.Ldloc, dim_len [dim]);
3117 ig.Emit (OpCodes.Blt, loop [dim]);
3120 ig.MarkLabel (ec.LoopEnd);
3125 public override bool Emit (EmitContext ec)
3130 var_type = RootContext.LookupType (ec.DeclSpace, type, false, loc);
3131 if (var_type == null)
3135 // We need an instance variable. Not sure this is the best
3136 // way of doing this.
3138 // FIXME: When we implement propertyaccess, will those turn
3139 // out to return values in ExprClass? I think they should.
3141 if (!(expr.eclass == ExprClass.Variable || expr.eclass == ExprClass.Value ||
3142 expr.eclass == ExprClass.PropertyAccess)){
3143 error1579 (expr.Type);
3147 ILGenerator ig = ec.ig;
3149 Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
3150 bool old_inloop = ec.InLoop;
3151 ec.LoopBegin = ig.DefineLabel ();
3152 ec.LoopEnd = ig.DefineLabel ();
3155 if (expr.Type.IsArray)
3156 ret_val = EmitArrayForeach (ec, var_type);
3158 ForeachHelperMethods hm;
3160 hm = ProbeCollectionType (ec, expr.Type);
3162 error1579 (expr.Type);
3166 ret_val = EmitCollectionForeach (ec, var_type, hm);
3169 ec.LoopBegin = old_begin;
3170 ec.LoopEnd = old_end;
3171 ec.InLoop = old_inloop;