2 // anonymous.cs: Support for anonymous methods and types
5 // Miguel de Icaza (miguel@ximain.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2011 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
14 using System.Collections.Generic;
15 using Mono.CompilerServices.SymbolWriter;
16 using System.Diagnostics;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using System.Reflection;
23 using System.Reflection.Emit;
26 namespace Mono.CSharp {
28 public abstract class CompilerGeneratedContainer : ClassOrStruct
30 protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod)
31 : this (parent, name, mod, MemberKind.Class)
35 protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod, MemberKind kind)
36 : base (parent, name, null, kind)
38 Debug.Assert ((mod & Modifiers.AccessibilityMask) != 0);
40 ModFlags = mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED;
41 spec = new TypeSpec (Kind, null, this, null, ModFlags);
44 protected void CheckMembersDefined ()
46 if (HasMembersDefined)
47 throw new InternalErrorException ("Helper class already defined!");
50 protected override bool DoDefineMembers ()
52 if (Kind == MemberKind.Class && !IsStatic && !PartialContainer.HasInstanceConstructor) {
53 DefineDefaultConstructor (false);
56 return base.DoDefineMembers ();
59 protected static MemberName MakeMemberName (MemberBase host, string name, int unique_id, TypeParameters tparams, Location loc)
61 string host_name = host == null ? null : host is InterfaceMemberBase ? ((InterfaceMemberBase)host).GetFullName (host.MemberName) : host.MemberName.Name;
62 string tname = MakeName (host_name, "c", name, unique_id);
63 TypeParameters args = null;
64 if (tparams != null) {
65 args = new TypeParameters (tparams.Count);
67 // Type parameters will be filled later when we have TypeContainer
68 // instance, for now we need only correct arity to create valid name
69 for (int i = 0; i < tparams.Count; ++i)
70 args.Add ((TypeParameter) null);
73 return new MemberName (tname, args, loc);
76 public static string MakeName (string host, string typePrefix, string name, int id)
78 return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
81 protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
83 base_type = Compiler.BuiltinTypes.Object;
90 public class HoistedStoreyClass : CompilerGeneratedContainer
92 public sealed class HoistedField : Field
94 public HoistedField (HoistedStoreyClass parent, FullNamedExpression type, Modifiers mod, string name,
95 Attributes attrs, Location loc)
96 : base (parent, type, mod, new MemberName (name, loc), attrs)
100 protected override bool ResolveMemberType ()
102 if (!base.ResolveMemberType ())
105 HoistedStoreyClass parent = ((HoistedStoreyClass) Parent).GetGenericStorey ();
106 if (parent != null && parent.Mutator != null)
107 member_type = parent.Mutator.Mutate (MemberType);
113 protected TypeParameterMutator mutator;
115 public HoistedStoreyClass (TypeDefinition parent, MemberName name, TypeParameters tparams, Modifiers mods, MemberKind kind)
116 : base (parent, name, mods | Modifiers.PRIVATE, kind)
119 if (tparams != null) {
120 var type_params = name.TypeParameters;
121 var src = new TypeParameterSpec[tparams.Count];
122 var dst = new TypeParameterSpec[tparams.Count];
124 for (int i = 0; i < tparams.Count; ++i) {
125 type_params[i] = tparams[i].CreateHoistedCopy (spec);
127 src[i] = tparams[i].Type;
128 dst[i] = type_params[i].Type;
131 // A copy is not enough, inflate any type parameter constraints
132 // using a new type parameters
133 var inflator = new TypeParameterInflator (this, null, src, dst);
134 for (int i = 0; i < tparams.Count; ++i) {
135 src[i].InflateConstraints (inflator, dst[i]);
138 mutator = new TypeParameterMutator (tparams, type_params);
144 public TypeParameterMutator Mutator {
155 public HoistedStoreyClass GetGenericStorey ()
157 TypeContainer storey = this;
158 while (storey != null && storey.CurrentTypeParameters == null)
159 storey = storey.Parent;
161 return storey as HoistedStoreyClass;
167 // Anonymous method storey is created when an anonymous method uses
168 // variable or parameter from outer scope. They are then hoisted to
169 // anonymous method storey (captured)
171 public class AnonymousMethodStorey : HoistedStoreyClass
173 struct StoreyFieldPair
175 public readonly AnonymousMethodStorey Storey;
176 public readonly Field Field;
178 public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
180 this.Storey = storey;
186 // Needed to delay hoisted _this_ initialization. When an anonymous
187 // method is used inside ctor and _this_ is hoisted, base ctor has to
188 // be called first, otherwise _this_ will be initialized with
189 // uninitialized value.
191 sealed class ThisInitializer : Statement
193 readonly HoistedThis hoisted_this;
194 readonly AnonymousMethodStorey parent;
196 public ThisInitializer (HoistedThis hoisted_this, AnonymousMethodStorey parent)
198 this.hoisted_this = hoisted_this;
199 this.parent = parent;
202 protected override void DoEmit (EmitContext ec)
207 source = new CompilerGeneratedThis (ec.CurrentType, loc);
209 source = new FieldExpr (parent.HoistedThis.Field, Location.Null) {
210 InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location.Null)
214 hoisted_this.EmitAssign (ec, source, false, false);
217 protected override void CloneTo (CloneContext clonectx, Statement target)
224 public readonly int ID;
226 public readonly ExplicitBlock OriginalSourceBlock;
228 // A list of StoreyFieldPair with local field keeping parent storey instance
229 List<StoreyFieldPair> used_parent_storeys;
230 List<ExplicitBlock> children_references;
232 // A list of hoisted parameters
233 protected List<HoistedParameter> hoisted_params;
234 List<HoistedParameter> hoisted_local_params;
235 protected List<HoistedVariable> hoisted_locals;
238 protected HoistedThis hoisted_this;
240 // Local variable which holds this storey instance
241 public Expression Instance;
243 bool initialize_hoisted_this;
244 AnonymousMethodStorey hoisted_this_parent;
246 public AnonymousMethodStorey (ExplicitBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
247 : base (parent, MakeMemberName (host, name, parent.PartialContainer.CounterAnonymousContainers, tparams, block.StartLocation),
250 OriginalSourceBlock = block;
251 ID = parent.PartialContainer.CounterAnonymousContainers++;
254 public void AddCapturedThisField (EmitContext ec, AnonymousMethodStorey parent)
256 TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
257 Field f = AddCompilerGeneratedField ("$this", type_expr);
258 hoisted_this = new HoistedThis (this, f);
260 initialize_hoisted_this = true;
261 hoisted_this_parent = parent;
264 public Field AddCapturedVariable (string name, TypeSpec type)
266 CheckMembersDefined ();
268 FullNamedExpression field_type = new TypeExpression (type, Location);
269 if (!spec.IsGenericOrParentIsGeneric)
270 return AddCompilerGeneratedField (name, field_type);
272 const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
273 Field f = new HoistedField (this, field_type, mod, name, null, Location);
278 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
280 return AddCompilerGeneratedField (name, type, false);
283 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type, bool privateAccess)
285 Modifiers mod = Modifiers.COMPILER_GENERATED | (privateAccess ? Modifiers.PRIVATE : Modifiers.INTERNAL);
286 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
292 // Creates a link between hoisted variable block and the anonymous method storey
294 // An anonymous method can reference variables from any outer block, but they are
295 // hoisted in their own ExplicitBlock. When more than one block is referenced we
296 // need to create another link between those variable storeys
298 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
300 if (children_references == null)
301 children_references = new List<ExplicitBlock> ();
303 if (!children_references.Contains (block))
304 children_references.Add (block);
307 public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
309 CheckMembersDefined ();
311 if (used_parent_storeys == null)
312 used_parent_storeys = new List<StoreyFieldPair> ();
313 else if (used_parent_storeys.Exists (i => i.Storey == storey))
316 TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
317 Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
318 used_parent_storeys.Add (new StoreyFieldPair (storey, f));
321 public void CaptureLocalVariable (ResolveContext ec, LocalVariable localVariable)
323 if (this is StateMachine) {
324 if (ec.CurrentBlock.ParametersBlock != localVariable.Block.ParametersBlock)
325 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
327 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
330 var hoisted = localVariable.HoistedVariant;
331 if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
333 // Variable is already hoisted but we need it in storey which can be shared
335 hoisted.Storey.hoisted_locals.Remove (hoisted);
336 hoisted.Storey.Members.Remove (hoisted.Field);
340 if (hoisted == null) {
341 hoisted = new HoistedLocalVariable (this, localVariable, GetVariableMangledName (localVariable));
342 localVariable.HoistedVariant = hoisted;
344 if (hoisted_locals == null)
345 hoisted_locals = new List<HoistedVariable> ();
347 hoisted_locals.Add (hoisted);
350 if (ec.CurrentBlock.Explicit != localVariable.Block.Explicit && !(hoisted.Storey is StateMachine))
351 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
354 public void CaptureParameter (ResolveContext ec, ParametersBlock.ParameterInfo parameterInfo, ParameterReference parameterReference)
356 if (!(this is StateMachine)) {
357 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
360 var hoisted = parameterInfo.Parameter.HoistedVariant;
362 if (parameterInfo.Block.StateMachine != null) {
364 // Another storey in same block exists but state machine does not
365 // have parameter captured. We need to add it there as well to
366 // proxy parameter value correctly.
368 if (hoisted == null && parameterInfo.Block.StateMachine != this) {
369 var storey = parameterInfo.Block.StateMachine;
371 hoisted = new HoistedParameter (storey, parameterReference);
372 parameterInfo.Parameter.HoistedVariant = hoisted;
374 if (storey.hoisted_params == null)
375 storey.hoisted_params = new List<HoistedParameter> ();
377 storey.hoisted_params.Add (hoisted);
381 // Lift captured parameter from value type storey to reference type one. Otherwise
382 // any side effects would be done on a copy
384 if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
385 if (hoisted_local_params == null)
386 hoisted_local_params = new List<HoistedParameter> ();
388 hoisted_local_params.Add (hoisted);
393 if (hoisted == null) {
394 hoisted = new HoistedParameter (this, parameterReference);
395 parameterInfo.Parameter.HoistedVariant = hoisted;
397 if (hoisted_params == null)
398 hoisted_params = new List<HoistedParameter> ();
400 hoisted_params.Add (hoisted);
404 // Register link between current block and parameter storey. It will
405 // be used when setting up storey definition to deploy storey reference
406 // when parameters are used from multiple blocks
408 if (ec.CurrentBlock.Explicit != parameterInfo.Block) {
409 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
413 TypeExpr CreateStoreyTypeExpression (EmitContext ec)
416 // Create an instance of storey type
418 TypeExpr storey_type_expr;
419 if (CurrentTypeParameters != null) {
421 // Use current method type parameter (MVAR) for top level storey only. All
422 // nested storeys use class type parameter (VAR)
424 var tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
425 ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
426 ec.CurrentTypeParameters;
428 TypeArguments targs = new TypeArguments ();
431 // Use type parameter name instead of resolved type parameter
432 // specification to resolve to correctly nested type parameters
434 for (int i = 0; i < tparams.Count; ++i)
435 targs.Add (new SimpleName (tparams [i].Name, Location)); // new TypeParameterExpr (tparams[i], Location));
437 storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
439 storey_type_expr = new TypeExpression (CurrentType, Location);
442 return storey_type_expr;
445 public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
447 Parent = parentStorey;
448 spec.IsGeneric = false;
449 spec.DeclaringType = parentStorey.CurrentType;
450 MemberName.TypeParameters = null;
453 protected override bool DoResolveTypeParameters ()
455 // Although any storey can have type parameters they are all clones of method type
456 // parameters therefore have to mutate MVAR references in any of cloned constraints
457 if (CurrentTypeParameters != null) {
458 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
459 var spec = CurrentTypeParameters[i].Type;
460 spec.BaseType = mutator.Mutate (spec.BaseType);
461 if (spec.InterfacesDefined != null) {
462 var mutated = new TypeSpec[spec.InterfacesDefined.Length];
463 for (int ii = 0; ii < mutated.Length; ++ii) {
464 mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
467 spec.InterfacesDefined = mutated;
470 if (spec.TypeArguments != null) {
471 spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
477 // Update parent cache as we most likely passed the point
478 // where the cache was constructed
480 Parent.CurrentType.MemberCache.AddMember (this.spec);
486 // Initializes all hoisted variables
488 public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
490 // There can be only one instance variable for each storey type
491 if (Instance != null)
492 throw new InternalErrorException ();
495 // Create an instance of this storey
497 ResolveContext rc = new ResolveContext (ec.MemberContext);
498 rc.CurrentBlock = block;
500 var storey_type_expr = CreateStoreyTypeExpression (ec);
501 var source = new New (storey_type_expr, null, Location).Resolve (rc);
504 // When the current context is async (or iterator) lift local storey
505 // instantiation to the currect storey
507 if (ec.CurrentAnonymousMethod is StateMachineInitializer && (block.HasYield || block.HasAwait)) {
509 // Unfortunately, normal capture mechanism could not be used because we are
510 // too late in the pipeline and standart assign cannot be used either due to
511 // recursive nature of GetStoreyInstanceExpression
513 var field = ec.CurrentAnonymousMethod.Storey.AddCompilerGeneratedField (
514 LocalVariable.GetCompilerGeneratedName (block), storey_type_expr, true);
519 var fexpr = new FieldExpr (field, Location);
520 fexpr.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location);
521 fexpr.EmitAssign (ec, source, false, false);
524 var local = TemporaryVariableReference.Create (source.Type, block, Location);
525 if (source.Type.IsStruct) {
526 local.LocalInfo.CreateBuilder (ec);
528 local.EmitAssign (ec, source);
534 EmitHoistedFieldsInitialization (rc, ec);
536 // TODO: Implement properly
537 //SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
540 void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
543 // Initialize all storey reference fields by using local or hoisted variables
545 if (used_parent_storeys != null) {
546 foreach (StoreyFieldPair sf in used_parent_storeys) {
548 // Get instance expression of storey field
550 Expression instace_expr = GetStoreyInstanceExpression (ec);
551 var fs = sf.Field.Spec;
552 if (TypeManager.IsGenericType (instace_expr.Type))
553 fs = MemberCache.GetMember (instace_expr.Type, fs);
555 FieldExpr f_set_expr = new FieldExpr (fs, Location);
556 f_set_expr.InstanceExpression = instace_expr;
558 // TODO: CompilerAssign expression
559 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
560 if (a.Resolve (rc) != null)
561 a.EmitStatement (ec);
566 // Initialize hoisted `this' only once, everywhere else will be
567 // referenced indirectly
569 if (initialize_hoisted_this) {
570 rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this, hoisted_this_parent));
574 // Setting currect anonymous method to null blocks any further variable hoisting
576 AnonymousExpression ae = ec.CurrentAnonymousMethod;
577 ec.CurrentAnonymousMethod = null;
579 if (hoisted_params != null) {
580 EmitHoistedParameters (ec, hoisted_params);
583 ec.CurrentAnonymousMethod = ae;
586 protected virtual void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
588 foreach (HoistedParameter hp in hoisted) {
593 // Parameters could be proxied via local fields for value type storey
595 if (hoisted_local_params != null) {
596 var local_param = hoisted_local_params.Find (l => l.Parameter.Parameter == hp.Parameter.Parameter);
597 var source = new FieldExpr (local_param.Field, Location);
598 source.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
599 hp.EmitAssign (ec, source, false, false);
603 hp.EmitHoistingAssignment (ec);
608 // Returns a field which holds referenced storey instance
610 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
612 if (used_parent_storeys == null)
615 foreach (StoreyFieldPair sf in used_parent_storeys) {
616 if (sf.Storey == storey)
624 // Creates storey instance expression regardless of currect IP
626 public Expression GetStoreyInstanceExpression (EmitContext ec)
628 AnonymousExpression am = ec.CurrentAnonymousMethod;
631 // Access from original block -> storey
637 // Access from anonymous method implemented as a static -> storey
639 if (am.Storey == null)
642 Field f = am.Storey.GetReferencedStoreyField (this);
644 if (am.Storey == this) {
646 // Access from inside of same storey (S -> S)
648 return new CompilerGeneratedThis (CurrentType, Location);
652 // External field access
658 // Storey was cached to local field
660 FieldExpr f_ind = new FieldExpr (f, Location);
661 f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
665 protected virtual string GetVariableMangledName (LocalVariable local_info)
668 // No need to mangle anonymous method hoisted variables cause they
669 // are hoisted in their own scopes
671 return local_info.Name;
674 public HoistedThis HoistedThis {
679 hoisted_this = value;
683 public IList<ExplicitBlock> ReferencesFromChildrenBlock {
684 get { return children_references; }
688 public abstract class HoistedVariable
691 // Hoisted version of variable references used in expression
692 // tree has to be delayed until we know its location. The variable
693 // doesn't know its location until all stories are calculated
695 class ExpressionTreeVariableReference : Expression
697 readonly HoistedVariable hv;
699 public ExpressionTreeVariableReference (HoistedVariable hv)
704 public override bool ContainsEmitWithAwait ()
709 public override Expression CreateExpressionTree (ResolveContext ec)
711 return hv.CreateExpressionTree ();
714 protected override Expression DoResolve (ResolveContext ec)
716 eclass = ExprClass.Value;
717 type = ec.Module.PredefinedTypes.Expression.Resolve ();
721 public override void Emit (EmitContext ec)
723 ResolveContext rc = new ResolveContext (ec.MemberContext);
724 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc, false);
725 // This should never fail
732 protected readonly AnonymousMethodStorey storey;
733 protected Field field;
734 Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
735 FieldExpr cached_outer_access;
737 protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
738 : this (storey, storey.AddCapturedVariable (name, type))
742 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
744 this.storey = storey;
754 public AnonymousMethodStorey Storey {
760 public void AddressOf (EmitContext ec, AddressOp mode)
762 GetFieldExpression (ec).AddressOf (ec, mode);
765 public Expression CreateExpressionTree ()
767 return new ExpressionTreeVariableReference (this);
770 public void Emit (EmitContext ec)
772 GetFieldExpression (ec).Emit (ec);
775 public Expression EmitToField (EmitContext ec)
777 return GetFieldExpression (ec);
781 // Creates field access expression for hoisted variable
783 protected virtual FieldExpr GetFieldExpression (EmitContext ec)
785 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
786 if (cached_outer_access != null)
787 return cached_outer_access;
790 // When setting top-level hoisted variable in generic storey
791 // change storey generic types to method generic types (VAR -> MVAR)
793 if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
794 var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
795 cached_outer_access = new FieldExpr (fs, field.Location);
797 cached_outer_access = new FieldExpr (field, field.Location);
800 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
801 return cached_outer_access;
804 FieldExpr inner_access;
805 if (cached_inner_access != null) {
806 if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
810 cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
813 if (inner_access == null) {
814 if (field.Parent.IsGenericOrParentIsGeneric) {
815 var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
816 inner_access = new FieldExpr (fs, field.Location);
818 inner_access = new FieldExpr (field, field.Location);
821 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
822 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
828 public void Emit (EmitContext ec, bool leave_copy)
830 GetFieldExpression (ec).Emit (ec, leave_copy);
833 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
835 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
839 public class HoistedParameter : HoistedVariable
841 sealed class HoistedFieldAssign : CompilerAssign
843 public HoistedFieldAssign (Expression target, Expression source)
844 : base (target, source, target.Location)
848 protected override Expression ResolveConversions (ResolveContext ec)
851 // Implicit conversion check fails for hoisted type arguments
852 // as they are of different types (!!0 x !0)
858 readonly ParameterReference parameter;
860 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
861 : base (scope, par.Name, par.Type)
863 this.parameter = par;
866 public HoistedParameter (HoistedParameter hp, string name)
867 : base (hp.storey, name, hp.parameter.Type)
869 this.parameter = hp.parameter;
874 public bool IsAssigned { get; set; }
876 public ParameterReference Parameter {
884 public void EmitHoistingAssignment (EmitContext ec)
887 // Remove hoisted redirection to emit assignment from original parameter
889 var temp = parameter.Parameter.HoistedVariant;
890 parameter.Parameter.HoistedVariant = null;
892 var a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
893 a.EmitStatement (ec);
895 parameter.Parameter.HoistedVariant = temp;
899 class HoistedLocalVariable : HoistedVariable
901 public HoistedLocalVariable (AnonymousMethodStorey storey, LocalVariable local, string name)
902 : base (storey, name, local.Type)
907 public class HoistedThis : HoistedVariable
909 public HoistedThis (AnonymousMethodStorey storey, Field field)
910 : base (storey, field)
916 // Anonymous method expression as created by parser
918 public class AnonymousMethodExpression : Expression
921 // Special conversion for nested expression tree lambdas
923 class Quote : ShimExpression
925 public Quote (Expression expr)
930 public override Expression CreateExpressionTree (ResolveContext ec)
932 var args = new Arguments (1);
933 args.Add (new Argument (expr.CreateExpressionTree (ec)));
934 return CreateExpressionFactoryCall (ec, "Quote", args);
937 protected override Expression DoResolve (ResolveContext rc)
939 expr = expr.Resolve (rc);
943 eclass = expr.eclass;
949 readonly Dictionary<TypeSpec, Expression> compatibles;
951 public ParametersBlock Block;
953 public AnonymousMethodExpression (Location loc)
956 this.compatibles = new Dictionary<TypeSpec, Expression> ();
961 public override string ExprClassName {
963 return "anonymous method";
967 public virtual bool HasExplicitParameters {
969 return Parameters != ParametersCompiled.Undefined;
973 public override bool IsSideEffectFree {
979 public ParametersCompiled Parameters {
981 return Block.Parameters;
985 public ReportPrinter TypeInferenceReportPrinter {
992 // Returns true if the body of lambda expression can be implicitly
993 // converted to the delegate of type `delegate_type'
995 public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
997 using (ec.With (ResolveContext.Options.InferReturnType, false)) {
998 using (ec.Set (ResolveContext.Options.ProbingMode)) {
999 var prev = ec.Report.SetPrinter (TypeInferenceReportPrinter ?? new NullReportPrinter ());
1001 var res = Compatible (ec, delegate_type) != null;
1003 ec.Report.SetPrinter (prev);
1010 TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
1012 if (delegate_type.IsDelegate)
1013 return delegate_type;
1015 if (delegate_type.IsExpressionTreeType) {
1016 delegate_type = delegate_type.TypeArguments [0];
1017 if (delegate_type.IsDelegate)
1018 return delegate_type;
1020 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
1021 GetSignatureForError (), delegate_type.GetSignatureForError ());
1025 ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
1026 GetSignatureForError (), delegate_type.GetSignatureForError ());
1030 protected bool VerifyExplicitParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type, AParametersCollection parameters)
1032 if (VerifyParameterCompatibility (ec, tic, delegate_type, parameters, ec.IsInProbingMode))
1035 if (!ec.IsInProbingMode)
1036 ec.Report.Error (1661, loc,
1037 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
1038 GetSignatureForError (), delegate_type.GetSignatureForError ());
1043 protected bool VerifyParameterCompatibility (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
1045 if (Parameters.Count != invoke_pd.Count) {
1049 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
1050 delegate_type.GetSignatureForError (), Parameters.Count.ToString ());
1054 bool has_implicit_parameters = !HasExplicitParameters;
1057 for (int i = 0; i < Parameters.Count; ++i) {
1058 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
1059 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
1063 if (p_mod == Parameter.Modifier.NONE)
1064 ec.Report.Error (1677, Parameters[i].Location, "Parameter `{0}' should not be declared with the `{1}' keyword",
1065 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters [i].ModFlags));
1067 ec.Report.Error (1676, Parameters[i].Location, "Parameter `{0}' must be declared with the `{1}' keyword",
1068 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
1072 if (has_implicit_parameters)
1075 TypeSpec type = invoke_pd.Types [i];
1078 type = tic.InflateGenericArgument (ec, type);
1080 if (!TypeSpecComparer.IsEqual (type, Parameters.Types [i])) {
1084 ec.Report.Error (1678, Parameters [i].Location, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
1086 Parameters.Types [i].GetSignatureForError (),
1087 invoke_pd.Types [i].GetSignatureForError ());
1096 // Infers type arguments based on explicit arguments
1098 public bool ExplicitTypeInference (TypeInferenceContext type_inference, TypeSpec delegate_type)
1100 if (!HasExplicitParameters)
1103 if (!delegate_type.IsDelegate) {
1104 if (!delegate_type.IsExpressionTreeType)
1107 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
1108 if (!delegate_type.IsDelegate)
1112 AParametersCollection d_params = Delegate.GetParameters (delegate_type);
1113 if (d_params.Count != Parameters.Count)
1116 var ptypes = Parameters.Types;
1117 var dtypes = d_params.Types;
1118 for (int i = 0; i < Parameters.Count; ++i) {
1119 if (type_inference.ExactInference (ptypes[i], dtypes[i]) == 0) {
1121 // Continue when 0 (quick path) does not mean inference failure. Checking for
1122 // same type handles cases like int -> int
1124 if (ptypes[i] == dtypes[i])
1134 public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1137 AnonymousExpression am;
1139 if (compatibles.TryGetValue (delegate_type, out expr)) {
1140 am = expr as AnonymousExpression;
1141 return am == null ? null : am.ReturnType;
1144 using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
1146 if (TypeInferenceReportPrinter != null) {
1147 prev = ec.Report.SetPrinter (TypeInferenceReportPrinter);
1152 var body = CompatibleMethodBody (ec, tic, null, delegate_type);
1154 am = body.Compatible (ec, body);
1159 if (TypeInferenceReportPrinter != null) {
1160 ec.Report.SetPrinter (prev);
1167 // compatibles.Add (delegate_type, am);
1168 return am.ReturnType;
1171 public override bool ContainsEmitWithAwait ()
1177 // Returns AnonymousMethod container if this anonymous method
1178 // expression can be implicitly converted to the delegate type `delegate_type'
1180 public Expression Compatible (ResolveContext ec, TypeSpec type)
1183 if (compatibles.TryGetValue (type, out am))
1186 TypeSpec delegate_type = CompatibleChecks (ec, type);
1187 if (delegate_type == null)
1191 // At this point its the first time we know the return type that is
1192 // needed for the anonymous method. We create the method here.
1195 var invoke_mb = Delegate.GetInvokeMethod (delegate_type);
1196 TypeSpec return_type = invoke_mb.ReturnType;
1199 // Second: the return type of the delegate must be compatible with
1200 // the anonymous type. Instead of doing a pass to examine the block
1201 // we satisfy the rule by setting the return type on the EmitContext
1202 // to be the delegate type return type.
1205 var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1209 bool etree_conversion = delegate_type != type;
1212 if (etree_conversion) {
1213 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1215 // Nested expression tree lambda use same scope as parent
1216 // lambda, this also means no variable capturing between this
1219 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1222 // Quote nested expression tree
1225 am = new Quote (am);
1227 int errors = ec.Report.Errors;
1229 if (Block.IsAsync) {
1230 ec.Report.Error (1989, loc, "Async lambda expressions cannot be converted to expression trees");
1233 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1234 am = body.Compatible (ec);
1238 // Rewrite expressions into expression tree when targeting Expression<T>
1240 if (am != null && errors == ec.Report.Errors)
1241 am = CreateExpressionTree (ec, delegate_type);
1244 am = body.Compatible (ec);
1246 if (body.DirectMethodGroupConversion != null) {
1247 var errors_printer = new SessionReportPrinter ();
1248 var old = ec.Report.SetPrinter (errors_printer);
1249 var expr = new ImplicitDelegateCreation (delegate_type, body.DirectMethodGroupConversion, loc) {
1250 AllowSpecialMethodsInvocation = true
1252 ec.Report.SetPrinter (old);
1253 if (expr != null && errors_printer.ErrorsCount == 0)
1257 } catch (CompletionResult) {
1259 } catch (FatalException) {
1261 } catch (Exception e) {
1262 throw new InternalErrorException (e, loc);
1265 if (!ec.IsInProbingMode) {
1266 compatibles.Add (type, am ?? EmptyExpression.Null);
1272 protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
1274 return CreateExpressionTree (ec);
1277 public override Expression CreateExpressionTree (ResolveContext ec)
1279 ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1283 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1285 var delegate_parameters = Delegate.GetParameters (delegate_type);
1287 if (Parameters == ParametersCompiled.Undefined) {
1289 // We provide a set of inaccessible parameters
1291 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1293 for (int i = 0; i < delegate_parameters.Count; i++) {
1294 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1295 if ((i_mod & Parameter.Modifier.OUT) != 0) {
1296 if (!ec.IsInProbingMode) {
1297 ec.Report.Error (1688, loc,
1298 "Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
1299 delegate_type.GetSignatureForError ());
1304 fixedpars[i] = new Parameter (
1305 new TypeExpression (delegate_parameters.Types [i], loc), null,
1306 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1309 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1312 if (!VerifyExplicitParameters (ec, tic, delegate_type, delegate_parameters)) {
1319 protected override Expression DoResolve (ResolveContext ec)
1321 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1322 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1327 // Set class type, set type
1330 eclass = ExprClass.Value;
1333 // This hack means `The type is not accessible
1334 // anywhere', we depend on special conversion
1337 type = InternalType.AnonymousMethod;
1339 if (!DoResolveParameters (ec))
1343 // FIXME: The emitted code isn't very careful about reachability
1344 // so, ensure we have a 'ret' at the end
1345 BlockContext bc = ec as BlockContext;
1346 if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1347 bc.NeedReturnLabel ();
1352 protected virtual bool DoResolveParameters (ResolveContext rc)
1354 return Parameters.Resolve (rc);
1357 public override void Emit (EmitContext ec)
1359 // nothing, as we only exist to not do anything.
1362 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1364 ec.Report.Error (1686, loc,
1365 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
1369 public override string GetSignatureForError ()
1371 return ExprClassName;
1374 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
1376 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1380 ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
1383 var rt = return_type;
1384 if (rt != null && rt.Kind != MemberKind.Void && rt != ec.Module.PredefinedTypes.Task.TypeSpec && !rt.IsGenericTask) {
1385 ec.Report.Error (4010, loc, "Cannot convert async {0} to delegate type `{1}'",
1386 GetSignatureForError (), delegate_type.GetSignatureForError ());
1391 b = b.ConvertToAsyncTask (ec, ec.CurrentMemberDefinition.Parent.PartialContainer, p, return_type, delegate_type, loc);
1394 return CompatibleMethodFactory (return_type ?? InternalType.ErrorType, delegate_type, p, b);
1397 protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
1399 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1402 protected override void CloneTo (CloneContext clonectx, Expression t)
1404 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1406 target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
1409 public override object Accept (StructuralVisitor visitor)
1411 return visitor.Visit (this);
1416 // Abstract expression for any block which requires variables hoisting
1418 public abstract class AnonymousExpression : ExpressionStatement
1420 protected class AnonymousMethodMethod : Method
1422 public readonly AnonymousExpression AnonymousMethod;
1423 public readonly AnonymousMethodStorey Storey;
1425 public AnonymousMethodMethod (TypeDefinition parent, AnonymousExpression am, AnonymousMethodStorey storey,
1426 TypeExpr return_type,
1427 Modifiers mod, MemberName name,
1428 ParametersCompiled parameters)
1429 : base (parent, return_type, mod | Modifiers.COMPILER_GENERATED,
1430 name, parameters, null)
1432 this.AnonymousMethod = am;
1433 this.Storey = storey;
1435 Parent.PartialContainer.Members.Add (this);
1436 Block = new ToplevelBlock (am.block, parameters);
1439 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1441 EmitContext ec = new EmitContext (this, ig, ReturnType, sourceMethod);
1442 ec.CurrentAnonymousMethod = AnonymousMethod;
1446 protected override void DefineTypeParameters ()
1448 // Type parameters were cloned
1451 protected override bool ResolveMemberType ()
1453 if (!base.ResolveMemberType ())
1456 if (Storey != null && Storey.Mutator != null) {
1457 if (!parameters.IsEmpty) {
1458 var mutated = Storey.Mutator.Mutate (parameters.Types);
1459 if (mutated != parameters.Types)
1460 parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
1463 member_type = Storey.Mutator.Mutate (member_type);
1469 public override void Emit ()
1471 if (MethodBuilder == null) {
1479 protected readonly ParametersBlock block;
1481 public TypeSpec ReturnType;
1483 protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
1485 this.ReturnType = return_type;
1490 public abstract string ContainerType { get; }
1491 public abstract bool IsIterator { get; }
1492 public abstract AnonymousMethodStorey Storey { get; }
1495 // The block that makes up the body for the anonymous method
1497 public ParametersBlock Block {
1503 public AnonymousExpression Compatible (ResolveContext ec)
1505 return Compatible (ec, this);
1508 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1513 // TODO: Implement clone
1514 BlockContext aec = new BlockContext (ec, block, ReturnType);
1515 aec.CurrentAnonymousMethod = ae;
1517 var am = this as AnonymousMethodBody;
1519 if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
1520 am.ReturnTypeInference = new TypeInferenceContext ();
1523 var bc = ec as BlockContext;
1525 aec.FlowOffset = bc.FlowOffset;
1527 var errors = ec.Report.Errors;
1529 bool res = Block.Resolve (ec.CurrentBranching, aec, null);
1531 if (am != null && am.ReturnTypeInference != null) {
1532 am.ReturnTypeInference.FixAllTypes (ec);
1533 ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
1534 am.ReturnTypeInference = null;
1537 // If e is synchronous the inferred return type is T
1538 // If e is asynchronous and the body of F is either an expression classified as nothing
1539 // or a statement block where no return statements have expressions, the inferred return type is Task
1540 // If e is async and has an inferred result type T, the inferred return type is Task<T>
1542 if (block.IsAsync && ReturnType != null) {
1543 ReturnType = ReturnType.Kind == MemberKind.Void ?
1544 ec.Module.PredefinedTypes.Task.TypeSpec :
1545 ec.Module.PredefinedTypes.TaskGeneric.TypeSpec.MakeGenericType (ec, new [] { ReturnType });
1549 if (res && errors != ec.Report.Errors)
1552 return res ? this : null;
1555 public override bool ContainsEmitWithAwait ()
1560 public void SetHasThisAccess ()
1562 ExplicitBlock b = block;
1564 if (b.HasCapturedThis)
1567 b.HasCapturedThis = true;
1568 b = b.Parent == null ? null : b.Parent.Explicit;
1569 } while (b != null);
1573 public class AnonymousMethodBody : AnonymousExpression
1575 protected readonly ParametersCompiled parameters;
1576 AnonymousMethodStorey storey;
1578 AnonymousMethodMethod method;
1581 TypeInferenceContext return_inference;
1583 public AnonymousMethodBody (ParametersCompiled parameters,
1584 ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
1586 : base (block, return_type, loc)
1588 this.type = delegate_type;
1589 this.parameters = parameters;
1594 public override string ContainerType {
1595 get { return "anonymous method"; }
1599 // Method-group instance for lambdas which can be replaced with
1600 // simple method group call
1602 public MethodGroupExpr DirectMethodGroupConversion {
1606 public override bool IsIterator {
1612 public ParametersCompiled Parameters {
1618 public TypeInferenceContext ReturnTypeInference {
1620 return return_inference;
1623 return_inference = value;
1627 public override AnonymousMethodStorey Storey {
1635 public override Expression CreateExpressionTree (ResolveContext ec)
1637 ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1641 bool Define (ResolveContext ec)
1643 if (!Block.Resolved && Compatible (ec) == null)
1646 if (block_name == null) {
1647 MemberCore mc = (MemberCore) ec.MemberContext;
1648 block_name = mc.MemberName.Basename;
1655 // Creates a host for the anonymous method
1657 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1660 // Anonymous method body can be converted to
1662 // 1, an instance method in current scope when only `this' is hoisted
1663 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1664 // 3, an instance method in compiler generated storey when any hoisted variable exists
1667 Modifiers modifiers;
1668 TypeDefinition parent = null;
1670 var src_block = Block.Original.Explicit;
1671 if (src_block.HasCapturedVariable || src_block.HasCapturedThis) {
1672 parent = storey = FindBestMethodStorey ();
1674 if (storey == null) {
1675 var top_block = src_block.ParametersBlock.TopBlock;
1676 var sm = top_block.StateMachine;
1678 if (src_block.HasCapturedThis) {
1680 // Remove hoisted 'this' request when simple instance method is
1681 // enough. No hoisted variables only 'this' and don't need to
1682 // propagate this to value type state machine.
1684 StateMachine sm_parent;
1685 var pb = src_block.ParametersBlock;
1687 sm_parent = pb.StateMachine;
1688 pb = pb.Parent == null ? null : pb.Parent.ParametersBlock;
1689 } while (sm_parent == null && pb != null);
1691 if (sm_parent == null) {
1692 top_block.RemoveThisReferenceFromChildrenBlock (src_block);
1693 } else if (sm_parent.Kind == MemberKind.Struct) {
1695 // Special case where parent class is used to emit instance method
1696 // because currect storey is of value type (async host) and we cannot
1697 // use ldftn on non-boxed instances either to share mutated state
1699 parent = sm_parent.Parent.PartialContainer;
1700 } else if (sm is IteratorStorey) {
1702 // For iterators we can host everything in one class
1704 parent = storey = sm;
1709 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1711 if (ec.CurrentAnonymousMethod != null)
1712 parent = storey = ec.CurrentAnonymousMethod.Storey;
1714 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1718 parent = ec.CurrentTypeDefinition.Parent.PartialContainer;
1720 string name = CompilerGeneratedContainer.MakeName (parent != storey ? block_name : null,
1721 "m", null, parent.PartialContainer.CounterAnonymousMethods++);
1723 MemberName member_name;
1724 if (storey == null && ec.CurrentTypeParameters != null) {
1726 var hoisted_tparams = ec.CurrentTypeParameters;
1727 var type_params = new TypeParameters (hoisted_tparams.Count);
1728 for (int i = 0; i < hoisted_tparams.Count; ++i) {
1729 type_params.Add (hoisted_tparams[i].CreateHoistedCopy (null));
1732 member_name = new MemberName (name, type_params, Location);
1734 member_name = new MemberName (name, Location);
1737 return new AnonymousMethodMethod (parent,
1738 this, storey, new TypeExpression (ReturnType, Location), modifiers,
1739 member_name, parameters);
1742 protected override Expression DoResolve (ResolveContext ec)
1747 eclass = ExprClass.Value;
1751 public override void Emit (EmitContext ec)
1754 // Use same anonymous method implementation for scenarios where same
1755 // code is used from multiple blocks, e.g. field initializers
1757 if (method == null) {
1759 // Delay an anonymous method definition to avoid emitting unused code
1760 // for unreachable blocks or expression trees
1762 method = DoCreateMethodHost (ec);
1764 method.PrepareEmit ();
1767 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1768 if (is_static && am_cache == null) {
1770 // Creates a field cache to store delegate instance if it's not generic
1772 if (!method.MemberName.IsGeneric) {
1773 var parent = method.Parent.PartialContainer;
1774 int id = parent.AnonymousMethodsCounter++;
1775 var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
1777 am_cache = new Field (parent, new TypeExpression (cache_type, loc),
1778 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1779 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "am$cache", id), loc), null);
1781 parent.AddField (am_cache);
1783 // TODO: Implement caching of generated generic static methods
1787 // Some extra class is needed to capture variable generic type
1788 // arguments. Maybe we could re-use anonymous types, with a unique
1789 // anonymous method id, but they are quite heavy.
1791 // Consider : "() => typeof(T);"
1793 // We need something like
1794 // static class Wrap<Tn, Tm, DelegateType> {
1795 // public static DelegateType cache;
1798 // We then specialize local variable to capture all generic parameters
1799 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1804 Label l_initialized = ec.DefineLabel ();
1806 if (am_cache != null) {
1807 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1808 ec.Emit (OpCodes.Brtrue_S, l_initialized);
1812 // Load method delegate implementation
1817 } else if (storey != null) {
1818 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1826 // Special case for value type storey where this is not lifted but
1827 // droped off to parent class
1829 if (ec.CurrentAnonymousMethod != null && ec.AsyncTaskStorey != null)
1830 ec.Emit (OpCodes.Ldfld, ec.AsyncTaskStorey.HoistedThis.Field.Spec);
1833 var delegate_method = method.Spec;
1834 if (storey != null && storey.MemberName.IsGeneric) {
1835 TypeSpec t = storey.Instance.Type;
1838 // Mutate anonymous method instance type if we are in nested
1839 // hoisted generic anonymous method storey
1841 if (ec.IsAnonymousStoreyMutateRequired) {
1842 t = storey.Mutator.Mutate (t);
1845 ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
1847 if (delegate_method.IsGeneric)
1848 delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, method.TypeParameters);
1850 ec.Emit (OpCodes.Ldftn, delegate_method);
1853 var constructor_method = Delegate.GetConstructor (type);
1854 ec.Emit (OpCodes.Newobj, constructor_method);
1856 if (am_cache != null) {
1857 ec.Emit (OpCodes.Stsfld, am_cache.Spec);
1858 ec.MarkLabel (l_initialized);
1859 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1863 public override void EmitStatement (EmitContext ec)
1865 throw new NotImplementedException ();
1869 // Look for the best storey for this anonymous method
1871 AnonymousMethodStorey FindBestMethodStorey ()
1874 // Use the nearest parent block which has a storey
1876 for (Block b = Block.Parent; b != null; b = b.Parent) {
1877 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1885 public override string GetSignatureForError ()
1887 return type.GetSignatureForError ();
1892 // Anonymous type container
1894 public class AnonymousTypeClass : CompilerGeneratedContainer
1896 public const string ClassNamePrefix = "<>__AnonType";
1897 public const string SignatureForError = "anonymous type";
1899 readonly IList<AnonymousTypeParameter> parameters;
1901 private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
1902 : base (parent, name, parent.Evaluator != null ? Modifiers.PUBLIC : Modifiers.INTERNAL)
1904 this.parameters = parameters;
1907 public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
1909 string name = ClassNamePrefix + parent.Module.CounterAnonymousTypes++;
1911 ParametersCompiled all_parameters;
1912 TypeParameters tparams = null;
1913 SimpleName[] t_args;
1915 if (parameters.Count == 0) {
1916 all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
1919 t_args = new SimpleName[parameters.Count];
1920 tparams = new TypeParameters ();
1921 Parameter[] ctor_params = new Parameter[parameters.Count];
1922 for (int i = 0; i < parameters.Count; ++i) {
1923 AnonymousTypeParameter p = parameters[i];
1924 for (int ii = 0; ii < i; ++ii) {
1925 if (parameters[ii].Name == p.Name) {
1926 parent.Compiler.Report.Error (833, parameters[ii].Location,
1927 "`{0}': An anonymous type cannot have multiple properties with the same name",
1930 p = new AnonymousTypeParameter (null, "$" + i.ToString (), p.Location);
1936 t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1937 tparams.Add (new TypeParameter (i, new MemberName (t_args[i].Name, p.Location), null, null, Variance.None));
1938 ctor_params[i] = new Parameter (t_args[i], p.Name, Parameter.Modifier.NONE, null, p.Location);
1941 all_parameters = new ParametersCompiled (ctor_params);
1945 // Create generic anonymous type host with generic arguments
1946 // named upon properties names
1948 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.Module, new MemberName (name, tparams, loc), parameters, loc);
1950 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1951 null, all_parameters, loc);
1952 c.Block = new ToplevelBlock (parent.Module.Compiler, c.ParameterInfo, loc);
1955 // Create fields and constructor body with field initialization
1958 for (int i = 0; i < parameters.Count; ++i) {
1959 AnonymousTypeParameter p = parameters [i];
1961 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY | Modifiers.DEBUGGER_HIDDEN,
1962 new MemberName ("<" + p.Name + ">", p.Location), null);
1964 if (!a_type.AddField (f)) {
1969 c.Block.AddStatement (new StatementExpression (
1970 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1971 c.Block.GetParameterReference (i, p.Location))));
1973 ToplevelBlock get_block = new ToplevelBlock (parent.Module.Compiler, p.Location);
1974 get_block.AddStatement (new Return (
1975 new MemberAccess (new This (p.Location), f.Name), p.Location));
1977 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1978 new MemberName (p.Name, p.Location), null);
1979 prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
1980 prop.Get.Block = get_block;
1981 a_type.AddMember (prop);
1987 a_type.AddConstructor (c);
1991 protected override bool DoDefineMembers ()
1993 if (!base.DoDefineMembers ())
1996 Location loc = Location;
1998 var equals_parameters = ParametersCompiled.CreateFullyResolved (
1999 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc), Compiler.BuiltinTypes.Object);
2001 Method equals = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
2002 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
2003 equals_parameters, null);
2005 equals_parameters[0].Resolve (equals, 0);
2007 Method tostring = new Method (this, new TypeExpression (Compiler.BuiltinTypes.String, loc),
2008 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
2009 ParametersCompiled.EmptyReadOnlyParameters, null);
2011 ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
2013 TypeExpr current_type;
2014 if (CurrentTypeParameters != null) {
2015 var targs = new TypeArguments ();
2016 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
2017 targs.Add (new TypeParameterExpr (CurrentTypeParameters[i], Location));
2020 current_type = new GenericTypeExpr (Definition, targs, loc);
2022 current_type = new TypeExpression (Definition, loc);
2025 var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
2026 equals_block.AddStatement (new BlockVariable (new TypeExpression (li_other.Type, loc), li_other));
2027 var other_variable = new LocalVariableReference (li_other, loc);
2029 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
2030 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
2032 Expression rs_equals = null;
2033 Expression string_concat = new StringConstant (Compiler.BuiltinTypes, "{", loc);
2034 Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
2035 for (int i = 0; i < parameters.Count; ++i) {
2036 var p = parameters [i];
2037 var f = (Field) Members [i * 2];
2039 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
2040 system_collections_generic, "EqualityComparer",
2041 new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
2044 Arguments arguments_equal = new Arguments (2);
2045 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2046 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
2048 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
2049 "Equals", loc), arguments_equal);
2051 Arguments arguments_hashcode = new Arguments (1);
2052 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
2053 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
2054 "GetHashCode", loc), arguments_hashcode);
2056 IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);
2057 rs_hashcode = new Binary (Binary.Operator.Multiply,
2058 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
2061 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
2062 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc))),
2063 new Invocation (new MemberAccess (
2064 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
2065 new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
2067 if (rs_equals == null) {
2068 rs_equals = field_equal;
2069 string_concat = new Binary (Binary.Operator.Addition,
2071 new Binary (Binary.Operator.Addition,
2072 new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
2078 // Implementation of ToString () body using string concatenation
2080 string_concat = new Binary (Binary.Operator.Addition,
2081 new Binary (Binary.Operator.Addition,
2083 new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc)),
2086 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
2089 string_concat = new Binary (Binary.Operator.Addition,
2091 new StringConstant (Compiler.BuiltinTypes, " }", loc));
2094 // Equals (object obj) override
2096 var other_variable_assign = new TemporaryVariableReference (li_other, loc);
2097 equals_block.AddStatement (new StatementExpression (
2098 new SimpleAssign (other_variable_assign,
2099 new As (equals_block.GetParameterReference (0, loc),
2100 current_type, loc), loc)));
2102 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
2103 if (rs_equals != null)
2104 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
2105 equals_block.AddStatement (new Return (equals_test, loc));
2107 equals.Block = equals_block;
2109 equals.PrepareEmit ();
2110 Members.Add (equals);
2113 // GetHashCode () override
2115 Method hashcode = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Int, loc),
2116 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
2117 new MemberName ("GetHashCode", loc),
2118 ParametersCompiled.EmptyReadOnlyParameters, null);
2121 // Modified FNV with good avalanche behavior and uniform
2122 // distribution with larger hash sizes.
2124 // const int FNV_prime = 16777619;
2125 // int hash = (int) 2166136261;
2126 // foreach (int d in data)
2127 // hash = (hash ^ d) * FNV_prime;
2128 // hash += hash << 13;
2129 // hash ^= hash >> 7;
2130 // hash += hash << 3;
2131 // hash ^= hash >> 17;
2132 // hash += hash << 5;
2134 ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
2135 Block hashcode_block = new Block (hashcode_top, loc, loc);
2136 hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
2138 var li_hash = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Int, hashcode_top, loc);
2139 hashcode_block.AddStatement (new BlockVariable (new TypeExpression (li_hash.Type, loc), li_hash));
2140 LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
2141 hashcode_block.AddStatement (new StatementExpression (
2142 new SimpleAssign (hash_variable_assign, rs_hashcode)));
2144 var hash_variable = new LocalVariableReference (li_hash, loc);
2145 hashcode_block.AddStatement (new StatementExpression (
2146 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2147 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc)))));
2148 hashcode_block.AddStatement (new StatementExpression (
2149 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2150 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc)))));
2151 hashcode_block.AddStatement (new StatementExpression (
2152 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2153 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc)))));
2154 hashcode_block.AddStatement (new StatementExpression (
2155 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2156 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc)))));
2157 hashcode_block.AddStatement (new StatementExpression (
2158 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2159 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc)))));
2161 hashcode_block.AddStatement (new Return (hash_variable, loc));
2162 hashcode.Block = hashcode_top;
2164 hashcode.PrepareEmit ();
2165 Members.Add (hashcode);
2168 // ToString () override
2171 ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
2172 tostring_block.AddStatement (new Return (string_concat, loc));
2173 tostring.Block = tostring_block;
2175 tostring.PrepareEmit ();
2176 Members.Add (tostring);
2181 public override string GetSignatureForError ()
2183 return SignatureForError;
2186 public override CompilationSourceFile GetCompilationSourceFile ()
2191 public IList<AnonymousTypeParameter> Parameters {