1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
|
//
// iterators.cs: Support for implementing iterators
//
// Author:
// Miguel de Icaza (miguel@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
// Copyright 2003 Ximian, Inc.
// Copyright 2003-2008 Novell, Inc.
// Copyright 2011 Xamarin Inc.
//
using System;
using System.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;
#if STATIC
using IKVM.Reflection.Emit;
#else
using System.Reflection.Emit;
#endif
namespace Mono.CSharp
{
public abstract class YieldStatement<T> : ResumableStatement where T : StateMachineInitializer
{
protected Expression expr;
protected bool unwind_protect;
protected T machine_initializer;
int resume_pc;
protected YieldStatement (Expression expr, Location l)
{
this.expr = expr;
loc = l;
}
public Expression Expr {
get { return this.expr; }
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
var target = (YieldStatement<T>) t;
target.expr = expr.Clone (clonectx);
}
protected override void DoEmit (EmitContext ec)
{
machine_initializer.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
}
public override bool Resolve (BlockContext bc)
{
expr = expr.Resolve (bc);
if (expr == null)
return false;
machine_initializer = bc.CurrentAnonymousMethod as T;
if (!bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
unwind_protect = bc.CurrentBranching.AddResumePoint (this, this, out resume_pc);
return true;
}
}
public class Yield : YieldStatement<Iterator>
{
public Yield (Expression expr, Location loc)
: base (expr, loc)
{
}
public static bool CheckContext (ResolveContext ec, Location loc)
{
if (!ec.CurrentAnonymousMethod.IsIterator) {
ec.Report.Error (1621, loc,
"The yield statement cannot be used inside anonymous method blocks");
return false;
}
return true;
}
public override bool Resolve (BlockContext bc)
{
if (!CheckContext (bc, loc))
return false;
if (!base.Resolve (bc))
return false;
var otype = bc.CurrentIterator.OriginalIteratorType;
if (expr.Type != otype) {
expr = Convert.ImplicitConversionRequired (bc, expr, otype, loc);
if (expr == null)
return false;
}
return true;
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class YieldBreak : ExitStatement
{
Iterator iterator;
public YieldBreak (Location l)
{
loc = l;
}
public override void Error_FinallyClause (Report Report)
{
Report.Error (1625, loc, "Cannot yield in the body of a finally clause");
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
protected override bool DoResolve (BlockContext ec)
{
iterator = ec.CurrentIterator;
return Yield.CheckContext (ec, loc);
}
protected override void DoEmit (EmitContext ec)
{
iterator.EmitYieldBreak (ec, unwind_protect);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public abstract class StateMachine : AnonymousMethodStorey
{
public enum State
{
Running = -3, // Used only in CurrentPC, never stored into $PC
Uninitialized = -2,
After = -1,
Start = 0
}
Field pc_field;
StateMachineMethod method;
int local_name_idx;
protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
: base (block, parent, host, tparams, name, kind)
{
}
#region Properties
public StateMachineMethod StateMachineMethod {
get {
return method;
}
}
public Field PC {
get {
return pc_field;
}
}
#endregion
public void AddEntryMethod (StateMachineMethod method)
{
if (this.method != null)
throw new InternalErrorException ();
this.method = method;
Members.Add (method);
}
protected override bool DoDefineMembers ()
{
pc_field = AddCompilerGeneratedField ("$PC", new TypeExpression (Compiler.BuiltinTypes.Int, Location));
return base.DoDefineMembers ();
}
protected override string GetVariableMangledName (LocalVariable local_info)
{
if (local_info.IsCompilerGenerated)
return base.GetVariableMangledName (local_info);
return "<" + local_info.Name + ">__" + local_name_idx++.ToString ("X");
}
}
class IteratorStorey : StateMachine
{
class GetEnumeratorMethod : StateMachineMethod
{
sealed class GetEnumeratorStatement : Statement
{
readonly IteratorStorey host;
readonly StateMachineMethod host_method;
Expression new_storey;
public GetEnumeratorStatement (IteratorStorey host, StateMachineMethod host_method)
{
this.host = host;
this.host_method = host_method;
loc = host_method.Location;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
public override bool Resolve (BlockContext ec)
{
TypeExpression storey_type_expr = new TypeExpression (host.Definition, loc);
List<Expression> init = null;
if (host.hoisted_this != null) {
init = new List<Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
HoistedThis ht = host.hoisted_this;
FieldExpr from = new FieldExpr (ht.Field, loc);
from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
init.Add (new ElementInitializer (ht.Field.Name, from, loc));
}
if (host.hoisted_params != null) {
if (init == null)
init = new List<Expression> (host.HoistedParameters.Count);
for (int i = 0; i < host.hoisted_params.Count; ++i) {
HoistedParameter hp = host.hoisted_params [i];
HoistedParameter hp_cp = host.hoisted_params_copy [i] ?? hp;
FieldExpr from = new FieldExpr (hp_cp.Field, loc);
from.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
init.Add (new ElementInitializer (hp.Field.Name, from, loc));
}
}
if (init != null) {
new_storey = new NewInitialize (storey_type_expr, null,
new CollectionOrObjectInitializers (init, loc), loc);
} else {
new_storey = new New (storey_type_expr, null, loc);
}
new_storey = new_storey.Resolve (ec);
if (new_storey != null)
new_storey = Convert.ImplicitConversionRequired (ec, new_storey, host_method.MemberType, loc);
ec.CurrentBranching.CurrentUsageVector.Goto ();
return true;
}
protected override void DoEmit (EmitContext ec)
{
Label label_init = ec.DefineLabel ();
ec.EmitThis ();
ec.Emit (OpCodes.Ldflda, host.PC.Spec);
ec.EmitInt ((int) State.Start);
ec.EmitInt ((int) State.Uninitialized);
var m = ec.Module.PredefinedMembers.InterlockedCompareExchange.Resolve (loc);
if (m != null)
ec.Emit (OpCodes.Call, m);
ec.EmitInt ((int) State.Uninitialized);
ec.Emit (OpCodes.Bne_Un_S, label_init);
ec.EmitThis ();
ec.Emit (OpCodes.Ret);
ec.MarkLabel (label_init);
new_storey.Emit (ec);
ec.Emit (OpCodes.Ret);
}
}
GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
: base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name)
{
}
public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name)
{
return Create (host, returnType, name, null);
}
public static GetEnumeratorMethod Create (IteratorStorey host, FullNamedExpression returnType, MemberName name, Statement statement)
{
var m = new GetEnumeratorMethod (host, returnType, name);
var stmt = statement ?? new GetEnumeratorStatement (host, m);
m.block.AddStatement (stmt);
m.block.IsCompilerGenerated = true;
return m;
}
}
class DisposeMethod : StateMachineMethod
{
sealed class DisposeMethodStatement : Statement
{
Iterator iterator;
public DisposeMethodStatement (Iterator iterator)
{
this.iterator = iterator;
this.loc = iterator.Location;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
public override bool Resolve (BlockContext ec)
{
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.CurrentAnonymousMethod = iterator;
iterator.EmitDispose (ec);
}
}
public DisposeMethod (IteratorStorey host)
: base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
new MemberName ("Dispose", host.Location))
{
host.Members.Add (this);
Block.AddStatement (new DisposeMethodStatement (host.Iterator));
Block.IsCompilerGenerated = true;
}
}
//
// Uses Method as method info
//
class DynamicMethodGroupExpr : MethodGroupExpr
{
readonly Method method;
public DynamicMethodGroupExpr (Method method, Location loc)
: base ((IList<MemberSpec>) null, null, loc)
{
this.method = method;
eclass = ExprClass.Unresolved;
}
protected override Expression DoResolve (ResolveContext ec)
{
Methods = new List<MemberSpec> (1) { method.Spec };
type = method.Parent.Definition;
InstanceExpression = new CompilerGeneratedThis (type, Location);
return base.DoResolve (ec);
}
}
class DynamicFieldExpr : FieldExpr
{
readonly Field field;
public DynamicFieldExpr (Field field, Location loc)
: base (loc)
{
this.field = field;
}
protected override Expression DoResolve (ResolveContext ec)
{
spec = field.Spec;
type = spec.MemberType;
InstanceExpression = new CompilerGeneratedThis (type, Location);
return base.DoResolve (ec);
}
}
public readonly Iterator Iterator;
List<HoistedParameter> hoisted_params_copy;
TypeExpr iterator_type_expr;
Field current_field;
Field disposing_field;
TypeSpec generic_enumerator_type;
TypeSpec generic_enumerable_type;
public IteratorStorey (Iterator iterator)
: base (iterator.Container.ParametersBlock, iterator.Host,
iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
{
this.Iterator = iterator;
}
public Field CurrentField {
get {
return current_field;
}
}
public Field DisposingField {
get {
return disposing_field;
}
}
public IList<HoistedParameter> HoistedParameters {
get { return hoisted_params; }
}
protected override Constructor DefineDefaultConstructor (bool is_static)
{
var ctor = base.DefineDefaultConstructor (is_static);
ctor.ModFlags |= Modifiers.DEBUGGER_HIDDEN;
return ctor;
}
protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
{
var mtype = Iterator.OriginalIteratorType;
if (Mutator != null)
mtype = Mutator.Mutate (mtype);
iterator_type_expr = new TypeExpression (mtype, Location);
var ifaces = new List<TypeSpec> (5);
if (Iterator.IsEnumerable) {
ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
ifaces.Add (generic_enumerable_type);
}
}
ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
ifaces.Add (Compiler.BuiltinTypes.IDisposable);
var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
if (ienumerator_generic.Define ()) {
generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
ifaces.Add (generic_enumerator_type);
}
base_class = null;
base_type = Compiler.BuiltinTypes.Object;
return ifaces.ToArray ();
}
protected override bool DoDefineMembers ()
{
current_field = AddCompilerGeneratedField ("$current", iterator_type_expr);
disposing_field = AddCompilerGeneratedField ("$disposing", new TypeExpression (Compiler.BuiltinTypes.Bool, Location));
if (Iterator.IsEnumerable && hoisted_params != null) {
//
// Iterators are independent, each GetEnumerator call has to
// create same enumerator therefore we have to keep original values
// around for re-initialization
//
hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
foreach (HoistedParameter hp in hoisted_params) {
//
// Don't create field copy for unmodified captured parameters
//
HoistedParameter hp_copy;
if (hp.IsAssigned) {
hp_copy = new HoistedParameter (hp, "<$>" + hp.Field.Name);
} else {
hp_copy = null;
}
hoisted_params_copy.Add (hp_copy);
}
}
if (generic_enumerator_type != null)
Define_Current (true);
Define_Current (false);
new DisposeMethod (this);
Define_Reset ();
if (Iterator.IsEnumerable) {
FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
if (generic_enumerator_type != null) {
explicit_iface = new TypeExpression (generic_enumerable_type, Location);
var gname = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
Method gget_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (generic_enumerator_type, Location), gname);
//
// Just call generic GetEnumerator implementation
//
var stmt = new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location);
Method get_enumerator = GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);
Members.Add (get_enumerator);
Members.Add (gget_enumerator);
} else {
Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
}
}
return base.DoDefineMembers ();
}
void Define_Current (bool is_generic)
{
TypeExpr type;
FullNamedExpression explicit_iface;
if (is_generic) {
explicit_iface = new TypeExpression (generic_enumerator_type, Location);
type = iterator_type_expr;
} else {
explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
}
var name = new MemberName ("Current", null, explicit_iface, Location);
ToplevelBlock get_block = new ToplevelBlock (Compiler, Location) {
IsCompilerGenerated = true
};
get_block.AddStatement (new Return (new DynamicFieldExpr (CurrentField, Location), Location));
Property current = new Property (this, type, Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED, name, null);
current.Get = new Property.GetMethod (current, Modifiers.COMPILER_GENERATED, null, Location);
current.Get.Block = get_block;
Members.Add (current);
}
void Define_Reset ()
{
Method reset = new Method (
this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
new MemberName ("Reset", Location),
ParametersCompiled.EmptyReadOnlyParameters, null);
Members.Add (reset);
reset.Block = new ToplevelBlock (Compiler, Location) {
IsCompilerGenerated = true
};
TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
if (ex_type == null)
return;
reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
}
protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
{
base.EmitHoistedParameters (ec, hoisted);
if (hoisted_params_copy != null)
base.EmitHoistedParameters (ec, hoisted_params_copy);
}
}
public class StateMachineMethod : Method
{
readonly StateMachineInitializer expr;
public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
: base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
name, ParametersCompiled.EmptyReadOnlyParameters, null)
{
this.expr = expr;
Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
}
public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
{
EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
ec.CurrentAnonymousMethod = expr;
if (expr is AsyncInitializer)
ec.With (BuilderContext.Options.AsyncBody, true);
return ec;
}
}
public abstract class StateMachineInitializer : AnonymousExpression
{
sealed class MoveNextBodyStatement : Statement
{
readonly StateMachineInitializer state_machine;
public MoveNextBodyStatement (StateMachineInitializer stateMachine)
{
this.state_machine = stateMachine;
this.loc = stateMachine.Location;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
public override bool Resolve (BlockContext ec)
{
return true;
}
protected override void DoEmit (EmitContext ec)
{
state_machine.EmitMoveNext (ec);
}
public override void Emit (EmitContext ec)
{
// Don't create sequence point
DoEmit (ec);
}
}
public readonly TypeDefinition Host;
protected StateMachine storey;
//
// The state as we generate the machine
//
Label move_next_ok;
Label iterator_body_end;
protected Label move_next_error;
LocalBuilder skip_finally;
protected LocalBuilder current_pc;
protected List<ResumableStatement> resume_points;
protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
: base (block, returnType, block.StartLocation)
{
this.Host = host;
}
#region Properties
public Label BodyEnd {
get {
return iterator_body_end;
}
}
public LocalBuilder CurrentPC
{
get {
return current_pc;
}
}
public LocalBuilder SkipFinally {
get {
return skip_finally;
}
}
public override AnonymousMethodStorey Storey {
get {
return storey;
}
}
#endregion
public int AddResumePoint (ResumableStatement stmt)
{
if (resume_points == null)
resume_points = new List<ResumableStatement> ();
resume_points.Add (stmt);
return resume_points.Count;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ("ET");
}
protected virtual BlockContext CreateBlockContext (ResolveContext rc)
{
var ctx = new BlockContext (rc, block, ((BlockContext) rc).ReturnType);
ctx.CurrentAnonymousMethod = this;
return ctx;
}
protected override Expression DoResolve (ResolveContext ec)
{
var ctx = CreateBlockContext (ec);
Block.Resolve (ctx);
//
// Explicit return is required for Task<T> state machine
//
var task_storey = storey as AsyncTaskStorey;
if (task_storey == null || (task_storey.ReturnType != null && !task_storey.ReturnType.IsGenericTask))
ctx.CurrentBranching.CurrentUsageVector.Goto ();
ctx.EndFlowBranching ();
if (!ec.IsInProbingMode) {
var move_next = new StateMachineMethod (storey, this, new TypeExpression (ReturnType, loc), Modifiers.PUBLIC, new MemberName ("MoveNext", loc));
move_next.Block.AddStatement (new MoveNextBodyStatement (this));
storey.AddEntryMethod (move_next);
}
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
//
// Load state machine instance
//
storey.Instance.Emit (ec);
}
void EmitMoveNext_NoResumePoints (EmitContext ec)
{
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
// We only care if the PC is zero (start executing) or non-zero (don't do anything)
ec.Emit (OpCodes.Brtrue, move_next_error);
iterator_body_end = ec.DefineLabel ();
block.EmitEmbedded (ec);
ec.MarkLabel (iterator_body_end);
EmitMoveNextEpilogue (ec);
ec.MarkLabel (move_next_error);
if (ReturnType.Kind != MemberKind.Void) {
ec.EmitInt (0);
ec.Emit (OpCodes.Ret);
}
}
void EmitMoveNext (EmitContext ec)
{
move_next_ok = ec.DefineLabel ();
move_next_error = ec.DefineLabel ();
if (resume_points == null) {
EmitMoveNext_NoResumePoints (ec);
return;
}
current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
ec.Emit (OpCodes.Stloc, current_pc);
// We're actually in state 'running', but this is as good a PC value as any if there's an abnormal exit
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
Label[] labels = new Label[1 + resume_points.Count];
labels[0] = ec.DefineLabel ();
bool need_skip_finally = false;
for (int i = 0; i < resume_points.Count; ++i) {
ResumableStatement s = resume_points[i];
need_skip_finally |= s is ExceptionStatement;
labels[i + 1] = s.PrepareForEmit (ec);
}
if (need_skip_finally) {
skip_finally = ec.GetTemporaryLocal (ec.BuiltinTypes.Bool);
ec.EmitInt (0);
ec.Emit (OpCodes.Stloc, skip_finally);
}
var async_init = this as AsyncInitializer;
if (async_init != null)
ec.BeginExceptionBlock ();
ec.Emit (OpCodes.Ldloc, current_pc);
ec.Emit (OpCodes.Switch, labels);
ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
ec.MarkLabel (labels[0]);
iterator_body_end = ec.DefineLabel ();
block.EmitEmbedded (ec);
ec.MarkLabel (iterator_body_end);
if (async_init != null) {
var catch_value = LocalVariable.CreateCompilerGenerated (ec.Module.Compiler.BuiltinTypes.Exception, block, Location);
ec.BeginCatchBlock (catch_value.Type);
catch_value.EmitAssign (ec);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
((AsyncTaskStorey) async_init.Storey).EmitSetException (ec, new LocalVariableReference (catch_value, Location));
ec.Emit (OpCodes.Leave, move_next_ok);
ec.EndExceptionBlock ();
}
ec.Mark (Block.Original.EndLocation);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
EmitMoveNextEpilogue (ec);
ec.MarkLabel (move_next_error);
if (ReturnType.Kind != MemberKind.Void) {
ec.EmitInt (0);
ec.Emit (OpCodes.Ret);
}
ec.MarkLabel (move_next_ok);
if (ReturnType.Kind != MemberKind.Void) {
ec.EmitInt (1);
ec.Emit (OpCodes.Ret);
}
}
protected virtual void EmitMoveNextEpilogue (EmitContext ec)
{
}
public void EmitLeave (EmitContext ec, bool unwind_protect)
{
// Return ok
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_ok);
}
//
// Called back from YieldStatement
//
public virtual void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
{
//
// Guard against being disposed meantime
//
Label disposed = ec.DefineLabel ();
var iterator = storey as IteratorStorey;
if (iterator != null) {
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, iterator.DisposingField.Spec);
ec.Emit (OpCodes.Brtrue_S, disposed);
}
//
// store resume program-counter
//
ec.EmitThis ();
ec.EmitInt (resume_pc);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
if (iterator != null) {
ec.MarkLabel (disposed);
}
// mark finally blocks as disabled
if (unwind_protect && skip_finally != null) {
ec.EmitInt (1);
ec.Emit (OpCodes.Stloc, skip_finally);
}
}
public void SetStateMachine (StateMachine stateMachine)
{
this.storey = stateMachine;
}
}
//
// Iterators are implemented as state machine blocks
//
public class Iterator : StateMachineInitializer
{
sealed class TryFinallyBlockProxyStatement : Statement
{
TryFinallyBlock block;
Iterator iterator;
public TryFinallyBlockProxyStatement (Iterator iterator, TryFinallyBlock block)
{
this.iterator = iterator;
this.block = block;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotSupportedException ();
}
protected override void DoEmit (EmitContext ec)
{
//
// Restore redirection for any captured variables
//
ec.CurrentAnonymousMethod = iterator;
using (ec.With (BuilderContext.Options.OmitDebugInfo, !ec.HasMethodSymbolBuilder)) {
block.EmitFinallyBody (ec);
}
}
}
public readonly IMethodData OriginalMethod;
public readonly bool IsEnumerable;
public readonly TypeSpec OriginalIteratorType;
int finally_hosts_counter;
public Iterator (ParametersBlock block, IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
: base (block, host, host.Compiler.BuiltinTypes.Bool)
{
this.OriginalMethod = method;
this.OriginalIteratorType = iterator_type;
this.IsEnumerable = is_enumerable;
this.type = method.ReturnType;
}
#region Properties
public ToplevelBlock Container {
get { return OriginalMethod.Block; }
}
public override string ContainerType {
get { return "iterator"; }
}
public override bool IsIterator {
get { return true; }
}
#endregion
public Method CreateFinallyHost (TryFinallyBlock block)
{
var method = new Method (storey, new TypeExpression (storey.Compiler.BuiltinTypes.Void, loc),
Modifiers.COMPILER_GENERATED, new MemberName (CompilerGeneratedContainer.MakeName (null, null, "Finally", finally_hosts_counter++), loc),
ParametersCompiled.EmptyReadOnlyParameters, null);
method.Block = new ToplevelBlock (method.Compiler, method.ParameterInfo, loc);
method.Block.IsCompilerGenerated = true;
method.Block.AddStatement (new TryFinallyBlockProxyStatement (this, block));
// Cannot it add to storey because it'd be emitted before nested
// anonoymous methods which could capture shared variable
return method;
}
public void EmitYieldBreak (EmitContext ec, bool unwind_protect)
{
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, move_next_error);
}
public override string GetSignatureForError ()
{
return OriginalMethod.GetSignatureForError ();
}
public override void Emit (EmitContext ec)
{
//
// Load Iterator storey instance
//
storey.Instance.Emit (ec);
//
// Initialize iterator PC when it's unitialized
//
if (IsEnumerable) {
ec.Emit (OpCodes.Dup);
ec.EmitInt ((int)IteratorStorey.State.Uninitialized);
var field = storey.PC.Spec;
if (storey.MemberName.IsGeneric) {
field = MemberCache.GetMember (Storey.Instance.Type, field);
}
ec.Emit (OpCodes.Stfld, field);
}
}
public void EmitDispose (EmitContext ec)
{
if (resume_points == null)
return;
Label end = ec.DefineLabel ();
Label[] labels = null;
for (int i = 0; i < resume_points.Count; ++i) {
ResumableStatement s = resume_points[i];
Label ret = s.PrepareForDispose (ec, end);
if (ret.Equals (end) && labels == null)
continue;
if (labels == null) {
labels = new Label[resume_points.Count + 1];
for (int j = 0; j <= i; ++j)
labels[j] = end;
}
labels[i + 1] = ret;
}
if (labels != null) {
current_pc = ec.GetTemporaryLocal (ec.BuiltinTypes.UInt);
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
ec.Emit (OpCodes.Stloc, current_pc);
}
ec.EmitThis ();
ec.EmitInt (1);
ec.Emit (OpCodes.Stfld, ((IteratorStorey) storey).DisposingField.Spec);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
if (labels != null) {
//SymbolWriter.StartIteratorDispatcher (ec.ig);
ec.Emit (OpCodes.Ldloc, current_pc);
ec.Emit (OpCodes.Switch, labels);
//SymbolWriter.EndIteratorDispatcher (ec.ig);
foreach (ResumableStatement s in resume_points)
s.EmitForDispose (ec, current_pc, end, true);
}
ec.MarkLabel (end);
}
public override void EmitStatement (EmitContext ec)
{
throw new NotImplementedException ();
}
public override void InjectYield (EmitContext ec, Expression expr, int resume_pc, bool unwind_protect, Label resume_point)
{
// Store the new value into current
var fe = new FieldExpr (((IteratorStorey) storey).CurrentField, loc);
fe.InstanceExpression = new CompilerGeneratedThis (storey.CurrentType, loc);
fe.EmitAssign (ec, expr, false, false);
base.InjectYield (ec, expr, resume_pc, unwind_protect, resume_point);
EmitLeave (ec, unwind_protect);
ec.MarkLabel (resume_point);
}
protected override BlockContext CreateBlockContext (ResolveContext rc)
{
var bc = base.CreateBlockContext (rc);
bc.StartFlowBranching (this, rc.CurrentBranching);
return bc;
}
public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
{
bool is_enumerable;
TypeSpec iterator_type;
TypeSpec ret = method.ReturnType;
if (ret == null)
return;
if (!CheckType (ret, parent, out iterator_type, out is_enumerable)) {
parent.Compiler.Report.Error (1624, method.Location,
"The body of `{0}' cannot be an iterator block " +
"because `{1}' is not an iterator interface type",
method.GetSignatureForError (),
ret.GetSignatureForError ());
return;
}
ParametersCompiled parameters = method.ParameterInfo;
for (int i = 0; i < parameters.Count; i++) {
Parameter p = parameters [i];
Parameter.Modifier mod = p.ModFlags;
if ((mod & Parameter.Modifier.RefOutMask) != 0) {
parent.Compiler.Report.Error (1623, p.Location,
"Iterators cannot have ref or out parameters");
return;
}
if (p is ArglistParameter) {
parent.Compiler.Report.Error (1636, method.Location,
"__arglist is not allowed in parameter list of iterators");
return;
}
if (parameters.Types [i].IsPointer) {
parent.Compiler.Report.Error (1637, p.Location,
"Iterators cannot have unsafe parameters or yield types");
return;
}
}
if ((modifiers & Modifiers.UNSAFE) != 0) {
parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
}
method.Block = method.Block.ConvertToIterator (method, parent, iterator_type, is_enumerable);
}
static bool CheckType (TypeSpec ret, TypeContainer parent, out TypeSpec original_iterator_type, out bool is_enumerable)
{
original_iterator_type = null;
is_enumerable = false;
if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerable) {
original_iterator_type = parent.Compiler.BuiltinTypes.Object;
is_enumerable = true;
return true;
}
if (ret.BuiltinType == BuiltinTypeSpec.Type.IEnumerator) {
original_iterator_type = parent.Compiler.BuiltinTypes.Object;
is_enumerable = false;
return true;
}
InflatedTypeSpec inflated = ret as InflatedTypeSpec;
if (inflated == null)
return false;
var member_definition = inflated.MemberDefinition;
PredefinedType ptype = parent.Module.PredefinedTypes.IEnumerableGeneric;
if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
original_iterator_type = inflated.TypeArguments[0];
is_enumerable = true;
return true;
}
ptype = parent.Module.PredefinedTypes.IEnumeratorGeneric;
if (ptype.Define () && ptype.TypeSpec.MemberDefinition == member_definition) {
original_iterator_type = inflated.TypeArguments[0];
is_enumerable = false;
return true;
}
return false;
}
}
}
|