// Dual licensed under the terms of the MIT X11 or GNU GPL
// Copyright 2003 Ximian, Inc.
// Copyright 2003-2008 Novell, Inc.
-//
-
-// TODO:
-// Flow analysis for Yield.
+// Copyright 2011 Xamarin Inc.
//
using System;
using System.Collections.Generic;
+using Mono.CompilerServices.SymbolWriter;
#if STATIC
using IKVM.Reflection.Emit;
loc = l;
}
+ public Expression Expr {
+ get { return this.expr; }
+ }
+
protected override void CloneTo (CloneContext clonectx, Statement t)
{
var target = (YieldStatement<T>) t;
machine_initializer = bc.CurrentAnonymousMethod as T;
if (!bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
- unwind_protect = bc.CurrentBranching.AddResumePoint (this, out resume_pc);
+ unwind_protect = bc.CurrentBranching.AddResumePoint (this, this, out resume_pc);
return true;
}
return true;
}
+
+ public override object Accept (StructuralVisitor visitor)
+ {
+ return visitor.Visit (this);
+ }
}
public class YieldBreak : ExitStatement
{
iterator.EmitYieldBreak (ec, unwind_protect);
}
+
+ public override object Accept (StructuralVisitor visitor)
+ {
+ return visitor.Visit (this);
+ }
}
public abstract class StateMachine : AnonymousMethodStorey
}
Field pc_field;
- int local_name_idx;
StateMachineMethod method;
+ int local_name_idx;
- protected StateMachine (Block block, TypeContainer parent, MemberBase host, TypeParameter[] tparams, string name)
- : base (block, parent, host, tparams, name)
+ protected StateMachine (ParametersBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
+ : base (block, parent, host, tparams, name, kind)
{
}
throw new InternalErrorException ();
this.method = method;
- AddMethod (method);
+ Members.Add (method);
}
protected override bool 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");
}
}
for (int i = 0; i < host.hoisted_params.Count; ++i) {
HoistedParameter hp = host.hoisted_params [i];
- HoistedParameter hp_cp = host.hoisted_params_copy [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);
}
}
- public GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
+ GetEnumeratorMethod (IteratorStorey host, FullNamedExpression returnType, MemberName name)
: base (host, null, returnType, Modifiers.DEBUGGER_HIDDEN, name)
{
- Block.AddStatement (new GetEnumeratorStatement (host, this));
+ }
+
+ 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;
}
}
: base (host, null, new TypeExpression (host.Compiler.BuiltinTypes.Void, host.Location), Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
new MemberName ("Dispose", host.Location))
{
- host.AddMethod (this);
+ host.Members.Add (this);
Block.AddStatement (new DisposeMethodStatement (host.Iterator));
+ Block.IsCompilerGenerated = true;
}
}
Field current_field;
Field disposing_field;
- TypeExpr enumerator_type;
- TypeExpr enumerable_type;
- TypeArguments generic_args;
- TypeExpr generic_enumerator_type;
- TypeExpr generic_enumerable_type;
+ TypeSpec generic_enumerator_type;
+ TypeSpec generic_enumerable_type;
public IteratorStorey (Iterator iterator)
: base (iterator.Container.ParametersBlock, iterator.Host,
- iterator.OriginalMethod as MemberBase, iterator.GenericMethod == null ? null : iterator.GenericMethod.CurrentTypeParameters, "Iterator")
+ iterator.OriginalMethod as MemberBase, iterator.OriginalMethod.CurrentTypeParameters, "Iterator", MemberKind.Class)
{
this.Iterator = iterator;
}
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;
mtype = Mutator.Mutate (mtype);
iterator_type_expr = new TypeExpression (mtype, Location);
- generic_args = new TypeArguments (iterator_type_expr);
- var list = new List<FullNamedExpression> ();
+ var ifaces = new List<TypeSpec> (5);
if (Iterator.IsEnumerable) {
- enumerable_type = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
- list.Add (enumerable_type);
+ ifaces.Add (Compiler.BuiltinTypes.IEnumerable);
if (Module.PredefinedTypes.IEnumerableGeneric.Define ()) {
- generic_enumerable_type = new GenericTypeExpr (Module.PredefinedTypes.IEnumerableGeneric.TypeSpec, generic_args, Location);
- list.Add (generic_enumerable_type);
+ generic_enumerable_type = Module.PredefinedTypes.IEnumerableGeneric.TypeSpec.MakeGenericType (Module, new[] { mtype });
+ ifaces.Add (generic_enumerable_type);
}
}
- enumerator_type = new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location);
- list.Add (enumerator_type);
-
- list.Add (new TypeExpression (Compiler.BuiltinTypes.IDisposable, Location));
+ ifaces.Add (Compiler.BuiltinTypes.IEnumerator);
+ ifaces.Add (Compiler.BuiltinTypes.IDisposable);
var ienumerator_generic = Module.PredefinedTypes.IEnumeratorGeneric;
if (ienumerator_generic.Define ()) {
- generic_enumerator_type = new GenericTypeExpr (ienumerator_generic.TypeSpec, generic_args, Location);
- list.Add (generic_enumerator_type);
+ generic_enumerator_type = ienumerator_generic.TypeSpec.MakeGenericType (Module, new [] { mtype });
+ ifaces.Add (generic_enumerator_type);
}
- type_bases = list;
+ base_class = null;
- return base.ResolveBaseTypes (out base_class);
+ 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 (hoisted_params != null) {
+ 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
//
- // TODO: Do it for assigned/modified parameters only
- //
hoisted_params_copy = new List<HoistedParameter> (hoisted_params.Count);
foreach (HoistedParameter hp in hoisted_params) {
- hoisted_params_copy.Add (new HoistedParameter (hp, "<$>" + hp.Field.Name));
+
+ //
+ // 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);
}
}
Define_Reset ();
if (Iterator.IsEnumerable) {
- MemberName name = new MemberName (QualifiedAliasMember.GlobalAlias, "System", null, Location);
- name = new MemberName (name, "Collections", Location);
- name = new MemberName (name, "IEnumerable", Location);
- name = new MemberName (name, "GetEnumerator", Location);
+ FullNamedExpression explicit_iface = new TypeExpression (Compiler.BuiltinTypes.IEnumerable, Location);
+ var name = new MemberName ("GetEnumerator", null, explicit_iface, Location.Null);
if (generic_enumerator_type != null) {
- Method get_enumerator = new StateMachineMethod (this, null, enumerator_type, 0, name);
-
- name = new MemberName (name.Left.Left, "Generic", Location);
- name = new MemberName (name, "IEnumerable", generic_args, Location);
- name = new MemberName (name, "GetEnumerator", Location);
- Method gget_enumerator = new GetEnumeratorMethod (this, generic_enumerator_type, name);
+ 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
//
- get_enumerator.Block.AddStatement (
- new Return (new Invocation (new DynamicMethodGroupExpr (gget_enumerator, Location), null), Location));
+ 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);
- AddMethod (get_enumerator);
- AddMethod (gget_enumerator);
+ Members.Add (get_enumerator);
+ Members.Add (gget_enumerator);
} else {
- AddMethod (new GetEnumeratorMethod (this, enumerator_type, name));
+ Members.Add (GetEnumeratorMethod.Create (this, new TypeExpression (Compiler.BuiltinTypes.IEnumerator, Location), name));
}
}
void Define_Current (bool is_generic)
{
TypeExpr type;
-
- MemberName name = new MemberName (QualifiedAliasMember.GlobalAlias, "System", null, Location);
- name = new MemberName (name, "Collections", Location);
+ FullNamedExpression explicit_iface;
if (is_generic) {
- name = new MemberName (name, "Generic", Location);
- name = new MemberName (name, "IEnumerator", generic_args, Location);
+ explicit_iface = new TypeExpression (generic_enumerator_type, Location);
type = iterator_type_expr;
} else {
- name = new MemberName (name, "IEnumerator");
+ explicit_iface = new TypeExpression (Module.Compiler.BuiltinTypes.IEnumerator, Location);
type = new TypeExpression (Compiler.BuiltinTypes.Object, Location);
}
- name = new MemberName (name, "Current", Location);
+ var name = new MemberName ("Current", null, explicit_iface, Location);
- ToplevelBlock get_block = new ToplevelBlock (Compiler, 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, name, null);
- current.Get = new Property.GetMethod (current, 0, null, 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;
- AddProperty (current);
+ Members.Add (current);
}
void Define_Reset ()
{
Method reset = new Method (
- this, null, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
- Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
+ this, new TypeExpression (Compiler.BuiltinTypes.Void, Location),
+ Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN | Modifiers.COMPILER_GENERATED,
new MemberName ("Reset", Location),
ParametersCompiled.EmptyReadOnlyParameters, null);
- AddMethod (reset);
+ Members.Add (reset);
- reset.Block = new ToplevelBlock (Compiler, Location);
+ reset.Block = new ToplevelBlock (Compiler, Location) {
+ IsCompilerGenerated = true
+ };
TypeSpec ex_type = Module.PredefinedTypes.NotSupportedException.Resolve ();
if (ex_type == null)
reset.Block.AddStatement (new Throw (new New (new TypeExpression (ex_type, Location), null, Location), Location));
}
- protected override void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
+ protected override void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
{
base.EmitHoistedParameters (ec, hoisted);
- base.EmitHoistedParameters (ec, hoisted_params_copy);
+ if (hoisted_params_copy != null)
+ base.EmitHoistedParameters (ec, hoisted_params_copy);
}
}
readonly StateMachineInitializer expr;
public StateMachineMethod (StateMachine host, StateMachineInitializer expr, FullNamedExpression returnType, Modifiers mod, MemberName name)
- : base (host, null, returnType, mod | Modifiers.COMPILER_GENERATED,
+ : base (host, returnType, mod | Modifiers.COMPILER_GENERATED,
name, ParametersCompiled.EmptyReadOnlyParameters, null)
{
this.expr = expr;
- Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
+ Block = new ToplevelBlock (host.Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
}
- public override EmitContext CreateEmitContext (ILGenerator ig)
+ public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
{
- EmitContext ec = new EmitContext (this, ig, MemberType);
+ EmitContext ec = new EmitContext (this, ig, MemberType, sourceMethod);
ec.CurrentAnonymousMethod = expr;
if (expr is AsyncInitializer)
{
state_machine.EmitMoveNext (ec);
}
+
+ public override void Emit (EmitContext ec)
+ {
+ // Don't create sequence point
+ DoEmit (ec);
+ }
}
- public readonly TypeContainer Host;
+ public readonly TypeDefinition Host;
protected StateMachine storey;
//
protected LocalBuilder current_pc;
protected List<ResumableStatement> resume_points;
- protected StateMachineInitializer (ParametersBlock block, TypeContainer host, TypeSpec returnType)
+ protected StateMachineInitializer (ParametersBlock block, TypeDefinition host, TypeSpec returnType)
: base (block, returnType, block.StartLocation)
{
this.Host = host;
protected override Expression DoResolve (ResolveContext ec)
{
- storey = (StateMachine) block.Parent.ParametersBlock.AnonymousMethodStorey;
-
var ctx = CreateBlockContext (ec);
Block.Resolve (ctx);
public override void Emit (EmitContext ec)
{
//
- // Load Iterator storey instance
+ // Load state machine instance
//
storey.Instance.Emit (ec);
}
- void EmitMoveNext_NoResumePoints (EmitContext ec, Block original_block)
+ void EmitMoveNext_NoResumePoints (EmitContext ec)
{
ec.EmitThis ();
ec.Emit (OpCodes.Ldfld, storey.PC.Spec);
iterator_body_end = ec.DefineLabel ();
- SymbolWriter.StartIteratorBody (ec);
- original_block.Emit (ec);
- SymbolWriter.EndIteratorBody (ec);
+ block.EmitEmbedded (ec);
ec.MarkLabel (iterator_body_end);
move_next_error = ec.DefineLabel ();
if (resume_points == null) {
- EmitMoveNext_NoResumePoints (ec, block);
+ EmitMoveNext_NoResumePoints (ec);
return;
}
if (async_init != null)
ec.BeginExceptionBlock ();
- SymbolWriter.StartIteratorDispatcher (ec);
ec.Emit (OpCodes.Ldloc, current_pc);
ec.Emit (OpCodes.Switch, labels);
ec.Emit (async_init != null ? OpCodes.Leave : OpCodes.Br, move_next_error);
- SymbolWriter.EndIteratorDispatcher (ec);
ec.MarkLabel (labels[0]);
iterator_body_end = ec.DefineLabel ();
- SymbolWriter.StartIteratorBody (ec);
- block.Emit (ec);
- SymbolWriter.EndIteratorBody (ec);
-
- SymbolWriter.StartIteratorDispatcher (ec);
+ block.EmitEmbedded (ec);
ec.MarkLabel (iterator_body_end);
ec.EndExceptionBlock ();
}
+ ec.Mark (Block.Original.EndLocation);
ec.EmitThis ();
ec.EmitInt ((int) IteratorStorey.State.After);
ec.Emit (OpCodes.Stfld, storey.PC.Spec);
ec.EmitInt (1);
ec.Emit (OpCodes.Ret);
}
-
- SymbolWriter.EndIteratorDispatcher (ec);
}
protected virtual void EmitMoveNextEpilogue (EmitContext ec)
ec.Emit (OpCodes.Stloc, skip_finally);
}
}
+
+ public void SetStateMachine (StateMachine stateMachine)
+ {
+ this.storey = stateMachine;
+ }
}
//
- // Iterators are implemented as hidden anonymous block
+ // 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, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
+ 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.type = method.ReturnType;
}
- public Block Container {
- get { return OriginalMethod.Block; }
- }
+ #region Properties
- public GenericMethod GenericMethod {
- get { return OriginalMethod.GenericMethod; }
+ public ToplevelBlock Container {
+ get { return OriginalMethod.Block; }
}
public override string ContainerType {
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 void EmitDispose (EmitContext ec)
{
+ if (resume_points == null)
+ return;
+
Label end = ec.DefineLabel ();
Label[] labels = null;
- int n_resume_points = resume_points == null ? 0 : resume_points.Count;
- for (int i = 0; i < n_resume_points; ++i) {
+ 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)
return bc;
}
- public static void CreateIterator (IMethodData method, TypeContainer parent, Modifiers modifiers)
+ public static void CreateIterator (IMethodData method, TypeDefinition parent, Modifiers modifiers)
{
bool is_enumerable;
TypeSpec iterator_type;
"The body of `{0}' cannot be an iterator block " +
"because `{1}' is not an iterator interface type",
method.GetSignatureForError (),
- TypeManager.CSharpName (ret));
+ ret.GetSignatureForError ());
return;
}
for (int i = 0; i < parameters.Count; i++) {
Parameter p = parameters [i];
Parameter.Modifier mod = p.ModFlags;
- if ((mod & Parameter.Modifier.ISBYREF) != 0) {
+ if ((mod & Parameter.Modifier.RefOutMask) != 0) {
parent.Compiler.Report.Error (1623, p.Location,
"Iterators cannot have ref or out parameters");
return;
parent.Compiler.Report.Error (1629, method.Location, "Unsafe code may not appear in iterators");
}
- method.Block.WrapIntoIterator (method, parent, iterator_type, is_enumerable);
+ 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)