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;
195 public ThisInitializer (HoistedThis hoisted_this)
197 this.hoisted_this = hoisted_this;
200 protected override void DoEmit (EmitContext ec)
202 hoisted_this.EmitAssign (ec, new CompilerGeneratedThis (ec.CurrentType, loc), false, false);
205 protected override void CloneTo (CloneContext clonectx, Statement target)
212 public readonly int ID;
214 public readonly ExplicitBlock OriginalSourceBlock;
216 // A list of StoreyFieldPair with local field keeping parent storey instance
217 List<StoreyFieldPair> used_parent_storeys;
218 List<ExplicitBlock> children_references;
220 // A list of hoisted parameters
221 protected List<HoistedParameter> hoisted_params;
222 protected List<HoistedVariable> hoisted_locals;
225 protected HoistedThis hoisted_this;
227 // Local variable which holds this storey instance
228 public Expression Instance;
230 bool initialize_hoisted_this;
232 public AnonymousMethodStorey (ExplicitBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
233 : base (parent, MakeMemberName (host, name, parent.Module.CounterAnonymousContainers, tparams, block.StartLocation),
236 OriginalSourceBlock = block;
237 ID = parent.Module.CounterAnonymousContainers++;
240 public void AddCapturedThisField (EmitContext ec)
242 TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
243 Field f = AddCompilerGeneratedField ("$this", type_expr);
244 hoisted_this = new HoistedThis (this, f);
246 initialize_hoisted_this = true;
249 public Field AddCapturedVariable (string name, TypeSpec type)
251 CheckMembersDefined ();
253 FullNamedExpression field_type = new TypeExpression (type, Location);
254 if (!spec.IsGenericOrParentIsGeneric)
255 return AddCompilerGeneratedField (name, field_type);
257 const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
258 Field f = new HoistedField (this, field_type, mod, name, null, Location);
263 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
265 return AddCompilerGeneratedField (name, type, false);
268 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type, bool privateAccess)
270 Modifiers mod = Modifiers.COMPILER_GENERATED | (privateAccess ? Modifiers.PRIVATE : Modifiers.INTERNAL);
271 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
277 // Creates a link between hoisted variable block and the anonymous method storey
279 // An anonymous method can reference variables from any outer block, but they are
280 // hoisted in their own ExplicitBlock. When more than one block is referenced we
281 // need to create another link between those variable storeys
283 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
285 if (children_references == null)
286 children_references = new List<ExplicitBlock> ();
288 if (!children_references.Contains (block))
289 children_references.Add (block);
292 public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
294 CheckMembersDefined ();
296 if (used_parent_storeys == null)
297 used_parent_storeys = new List<StoreyFieldPair> ();
298 else if (used_parent_storeys.Exists (i => i.Storey == storey))
301 TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
302 Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
303 used_parent_storeys.Add (new StoreyFieldPair (storey, f));
306 public void CaptureLocalVariable (ResolveContext ec, LocalVariable localVariable)
308 if (this is StateMachine) {
309 if (ec.CurrentBlock.ParametersBlock != localVariable.Block.ParametersBlock)
310 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
312 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
315 var hoisted = localVariable.HoistedVariant;
316 if (hoisted != null && hoisted.Storey != this && hoisted.Storey.Kind == MemberKind.Struct) {
317 // TODO: It's too late the field is defined in HoistedLocalVariable ctor
318 hoisted.Storey.hoisted_locals.Remove (hoisted);
322 if (hoisted == null) {
323 hoisted = new HoistedLocalVariable (this, localVariable, GetVariableMangledName (localVariable));
324 localVariable.HoistedVariant = hoisted;
326 if (hoisted_locals == null)
327 hoisted_locals = new List<HoistedVariable> ();
329 hoisted_locals.Add (hoisted);
332 if (ec.CurrentBlock.Explicit != localVariable.Block.Explicit)
333 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
336 public void CaptureParameter (ResolveContext ec, ParametersBlock.ParameterInfo parameterInfo, ParameterReference parameterReference)
338 if (!(this is StateMachine)) {
339 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
342 var hoisted = parameterInfo.Parameter.HoistedVariant;
343 if (hoisted == null) {
344 var storey = parameterInfo.Block.StateMachine ?? this;
345 var hp = new HoistedParameter (storey, parameterReference);
347 parameterInfo.Parameter.HoistedVariant = hoisted;
349 if (storey.hoisted_params == null)
350 storey.hoisted_params = new List<HoistedParameter> (2);
352 storey.hoisted_params.Add (hp);
356 // Register link between current block and parameter storey. It will
357 // be used when setting up storey definition to deploy storey reference
358 // when parameters are used from multiple blocks
360 if (ec.CurrentBlock.Explicit != parameterInfo.Block) {
361 hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
365 TypeExpr CreateStoreyTypeExpression (EmitContext ec)
368 // Create an instance of storey type
370 TypeExpr storey_type_expr;
371 if (CurrentTypeParameters != null) {
373 // Use current method type parameter (MVAR) for top level storey only. All
374 // nested storeys use class type parameter (VAR)
376 var tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
377 ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
378 ec.CurrentTypeParameters;
380 TypeArguments targs = new TypeArguments ();
383 // Use type parameter name instead of resolved type parameter
384 // specification to resolve to correctly nested type parameters
386 for (int i = 0; i < tparams.Count; ++i)
387 targs.Add (new SimpleName (tparams [i].Name, Location)); // new TypeParameterExpr (tparams[i], Location));
389 storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
391 storey_type_expr = new TypeExpression (CurrentType, Location);
394 return storey_type_expr;
397 public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
399 Parent = parentStorey;
400 spec.IsGeneric = false;
401 spec.DeclaringType = parentStorey.CurrentType;
402 MemberName.TypeParameters = null;
405 protected override bool DoResolveTypeParameters ()
407 // Although any storey can have type parameters they are all clones of method type
408 // parameters therefore have to mutate MVAR references in any of cloned constraints
409 if (CurrentTypeParameters != null) {
410 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
411 var spec = CurrentTypeParameters[i].Type;
412 spec.BaseType = mutator.Mutate (spec.BaseType);
413 if (spec.InterfacesDefined != null) {
414 var mutated = new TypeSpec[spec.InterfacesDefined.Length];
415 for (int ii = 0; ii < mutated.Length; ++ii) {
416 mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
419 spec.InterfacesDefined = mutated;
422 if (spec.TypeArguments != null) {
423 spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
429 // Update parent cache as we most likely passed the point
430 // where the cache was constructed
432 Parent.CurrentType.MemberCache.AddMember (this.spec);
438 // Initializes all hoisted variables
440 public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
442 // There can be only one instance variable for each storey type
443 if (Instance != null)
444 throw new InternalErrorException ();
447 // Create an instance of this storey
449 ResolveContext rc = new ResolveContext (ec.MemberContext);
450 rc.CurrentBlock = block;
452 var storey_type_expr = CreateStoreyTypeExpression (ec);
453 var source = new New (storey_type_expr, null, Location).Resolve (rc);
456 // When the current context is async (or iterator) lift local storey
457 // instantiation to the currect storey
459 if (ec.CurrentAnonymousMethod is StateMachineInitializer) {
461 // Unfortunately, normal capture mechanism could not be used because we are
462 // too late in the pipeline and standart assign cannot be used either due to
463 // recursive nature of GetStoreyInstanceExpression
465 var field = ec.CurrentAnonymousMethod.Storey.AddCompilerGeneratedField (
466 LocalVariable.GetCompilerGeneratedName (block), storey_type_expr, true);
471 var fexpr = new FieldExpr (field, Location);
472 fexpr.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location);
473 fexpr.EmitAssign (ec, source, false, false);
476 var local = TemporaryVariableReference.Create (source.Type, block, Location);
477 if (source.Type.IsStruct) {
478 local.LocalInfo.CreateBuilder (ec);
480 local.EmitAssign (ec, source);
486 EmitHoistedFieldsInitialization (rc, ec);
488 // TODO: Implement properly
489 //SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
492 void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
495 // Initialize all storey reference fields by using local or hoisted variables
497 if (used_parent_storeys != null) {
498 foreach (StoreyFieldPair sf in used_parent_storeys) {
500 // Get instance expression of storey field
502 Expression instace_expr = GetStoreyInstanceExpression (ec);
503 var fs = sf.Field.Spec;
504 if (TypeManager.IsGenericType (instace_expr.Type))
505 fs = MemberCache.GetMember (instace_expr.Type, fs);
507 FieldExpr f_set_expr = new FieldExpr (fs, Location);
508 f_set_expr.InstanceExpression = instace_expr;
510 // TODO: CompilerAssign expression
511 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
512 if (a.Resolve (rc) != null)
513 a.EmitStatement (ec);
518 // Initialize hoisted `this' only once, everywhere else will be
519 // referenced indirectly
521 if (initialize_hoisted_this) {
522 rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
526 // Setting currect anonymous method to null blocks any further variable hoisting
528 AnonymousExpression ae = ec.CurrentAnonymousMethod;
529 ec.CurrentAnonymousMethod = null;
531 if (hoisted_params != null) {
532 EmitHoistedParameters (ec, hoisted_params);
535 ec.CurrentAnonymousMethod = ae;
538 protected virtual void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
540 foreach (HoistedParameter hp in hoisted) {
541 hp.EmitHoistingAssignment (ec);
546 // Returns a field which holds referenced storey instance
548 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
550 if (used_parent_storeys == null)
553 foreach (StoreyFieldPair sf in used_parent_storeys) {
554 if (sf.Storey == storey)
562 // Creates storey instance expression regardless of currect IP
564 public Expression GetStoreyInstanceExpression (EmitContext ec)
566 AnonymousExpression am = ec.CurrentAnonymousMethod;
569 // Access from original block -> storey
575 // Access from anonymous method implemented as a static -> storey
577 if (am.Storey == null)
580 Field f = am.Storey.GetReferencedStoreyField (this);
582 if (am.Storey == this) {
584 // Access from inside of same storey (S -> S)
586 return new CompilerGeneratedThis (CurrentType, Location);
590 // External field access
596 // Storey was cached to local field
598 FieldExpr f_ind = new FieldExpr (f, Location);
599 f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
603 protected virtual string GetVariableMangledName (LocalVariable local_info)
606 // No need to mangle anonymous method hoisted variables cause they
607 // are hoisted in their own scopes
609 return local_info.Name;
612 public HoistedThis HoistedThis {
617 hoisted_this = value;
621 public IList<ExplicitBlock> ReferencesFromChildrenBlock {
622 get { return children_references; }
626 public abstract class HoistedVariable
629 // Hoisted version of variable references used in expression
630 // tree has to be delayed until we know its location. The variable
631 // doesn't know its location until all stories are calculated
633 class ExpressionTreeVariableReference : Expression
635 readonly HoistedVariable hv;
637 public ExpressionTreeVariableReference (HoistedVariable hv)
642 public override bool ContainsEmitWithAwait ()
647 public override Expression CreateExpressionTree (ResolveContext ec)
649 return hv.CreateExpressionTree ();
652 protected override Expression DoResolve (ResolveContext ec)
654 eclass = ExprClass.Value;
655 type = ec.Module.PredefinedTypes.Expression.Resolve ();
659 public override void Emit (EmitContext ec)
661 ResolveContext rc = new ResolveContext (ec.MemberContext);
662 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc);
663 // This should never fail
670 protected readonly AnonymousMethodStorey storey;
671 protected Field field;
672 Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
673 FieldExpr cached_outer_access;
675 protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
676 : this (storey, storey.AddCapturedVariable (name, type))
680 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
682 this.storey = storey;
686 public AnonymousMethodStorey Storey {
692 public void AddressOf (EmitContext ec, AddressOp mode)
694 GetFieldExpression (ec).AddressOf (ec, mode);
697 public Expression CreateExpressionTree ()
699 return new ExpressionTreeVariableReference (this);
702 public void Emit (EmitContext ec)
704 GetFieldExpression (ec).Emit (ec);
707 public Expression EmitToField (EmitContext ec)
709 return GetFieldExpression (ec);
713 // Creates field access expression for hoisted variable
715 protected virtual FieldExpr GetFieldExpression (EmitContext ec)
717 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
718 if (cached_outer_access != null)
719 return cached_outer_access;
722 // When setting top-level hoisted variable in generic storey
723 // change storey generic types to method generic types (VAR -> MVAR)
725 if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
726 var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
727 cached_outer_access = new FieldExpr (fs, field.Location);
729 cached_outer_access = new FieldExpr (field, field.Location);
732 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
733 return cached_outer_access;
736 FieldExpr inner_access;
737 if (cached_inner_access != null) {
738 if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
742 cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
745 if (inner_access == null) {
746 if (field.Parent.IsGenericOrParentIsGeneric) {
747 var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
748 inner_access = new FieldExpr (fs, field.Location);
750 inner_access = new FieldExpr (field, field.Location);
753 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
754 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
760 public void Emit (EmitContext ec, bool leave_copy)
762 GetFieldExpression (ec).Emit (ec, leave_copy);
765 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
767 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
771 public class HoistedParameter : HoistedVariable
773 sealed class HoistedFieldAssign : Assign
775 public HoistedFieldAssign (Expression target, Expression source)
776 : base (target, source, source.Location)
780 protected override Expression ResolveConversions (ResolveContext ec)
783 // Implicit conversion check fails for hoisted type arguments
784 // as they are of different types (!!0 x !0)
790 readonly ParameterReference parameter;
792 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
793 : base (scope, par.Name, par.Type)
795 this.parameter = par;
798 public HoistedParameter (HoistedParameter hp, string name)
799 : base (hp.storey, name, hp.parameter.Type)
801 this.parameter = hp.parameter;
810 public void EmitHoistingAssignment (EmitContext ec)
813 // Remove hoisted redirection to emit assignment from original parameter
815 HoistedVariable temp = parameter.Parameter.HoistedVariant;
816 parameter.Parameter.HoistedVariant = null;
818 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
819 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
820 a.EmitStatement (ec);
822 parameter.Parameter.HoistedVariant = temp;
826 class HoistedLocalVariable : HoistedVariable
828 public HoistedLocalVariable (AnonymousMethodStorey storey, LocalVariable local, string name)
829 : base (storey, name, local.Type)
834 public class HoistedThis : HoistedVariable
836 public HoistedThis (AnonymousMethodStorey storey, Field field)
837 : base (storey, field)
849 // Anonymous method expression as created by parser
851 public class AnonymousMethodExpression : Expression
854 // Special conversion for nested expression tree lambdas
856 class Quote : ShimExpression
858 public Quote (Expression expr)
863 public override Expression CreateExpressionTree (ResolveContext ec)
865 var args = new Arguments (1);
866 args.Add (new Argument (expr.CreateExpressionTree (ec)));
867 return CreateExpressionFactoryCall (ec, "Quote", args);
870 protected override Expression DoResolve (ResolveContext rc)
872 expr = expr.Resolve (rc);
876 eclass = expr.eclass;
882 readonly Dictionary<TypeSpec, Expression> compatibles;
884 public ParametersBlock Block;
886 public AnonymousMethodExpression (Location loc)
889 this.compatibles = new Dictionary<TypeSpec, Expression> ();
894 public override string ExprClassName {
896 return "anonymous method";
900 public virtual bool HasExplicitParameters {
902 return Parameters != ParametersCompiled.Undefined;
906 public ParametersCompiled Parameters {
908 return Block.Parameters;
915 // Returns true if the body of lambda expression can be implicitly
916 // converted to the delegate of type `delegate_type'
918 public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
920 using (ec.With (ResolveContext.Options.InferReturnType, false)) {
921 using (ec.Set (ResolveContext.Options.ProbingMode)) {
922 return Compatible (ec, delegate_type) != null;
927 TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
929 if (delegate_type.IsDelegate)
930 return delegate_type;
932 if (delegate_type.IsExpressionTreeType) {
933 delegate_type = delegate_type.TypeArguments [0];
934 if (delegate_type.IsDelegate)
935 return delegate_type;
937 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
938 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
942 ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
943 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
947 protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
949 if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
952 if (!ec.IsInProbingMode)
953 ec.Report.Error (1661, loc,
954 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
955 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
960 protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
962 if (Parameters.Count != invoke_pd.Count) {
966 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
967 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
971 bool has_implicit_parameters = !HasExplicitParameters;
974 for (int i = 0; i < Parameters.Count; ++i) {
975 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
976 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
980 if (p_mod == Parameter.Modifier.NONE)
981 ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
982 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
984 ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
985 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
989 if (has_implicit_parameters)
992 TypeSpec type = invoke_pd.Types [i];
994 // We assume that generic parameters are always inflated
995 if (TypeManager.IsGenericParameter (type))
998 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
1001 if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
1005 ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
1007 TypeManager.CSharpName (Parameters.Types [i]),
1008 TypeManager.CSharpName (invoke_pd.Types [i]));
1017 // Infers type arguments based on explicit arguments
1019 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
1021 if (!HasExplicitParameters)
1024 if (!delegate_type.IsDelegate) {
1025 if (!delegate_type.IsExpressionTreeType)
1028 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
1029 if (!delegate_type.IsDelegate)
1033 AParametersCollection d_params = Delegate.GetParameters (delegate_type);
1034 if (d_params.Count != Parameters.Count)
1037 for (int i = 0; i < Parameters.Count; ++i) {
1038 if (type_inference.ExactInference (Parameters.Types[i], d_params.Types[i]) == 0)
1045 public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1048 AnonymousExpression am;
1050 if (compatibles.TryGetValue (delegate_type, out expr)) {
1051 am = expr as AnonymousExpression;
1052 return am == null ? null : am.ReturnType;
1055 using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
1056 var body = CompatibleMethodBody (ec, tic, null, delegate_type);
1058 am = body.Compatible (ec, body);
1067 // compatibles.Add (delegate_type, am);
1068 return am.ReturnType;
1071 public override bool ContainsEmitWithAwait ()
1077 // Returns AnonymousMethod container if this anonymous method
1078 // expression can be implicitly converted to the delegate type `delegate_type'
1080 public Expression Compatible (ResolveContext ec, TypeSpec type)
1083 if (compatibles.TryGetValue (type, out am))
1086 TypeSpec delegate_type = CompatibleChecks (ec, type);
1087 if (delegate_type == null)
1091 // At this point its the first time we know the return type that is
1092 // needed for the anonymous method. We create the method here.
1095 var invoke_mb = Delegate.GetInvokeMethod (delegate_type);
1096 TypeSpec return_type = invoke_mb.ReturnType;
1099 // Second: the return type of the delegate must be compatible with
1100 // the anonymous type. Instead of doing a pass to examine the block
1101 // we satisfy the rule by setting the return type on the EmitContext
1102 // to be the delegate type return type.
1105 var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1109 bool etree_conversion = delegate_type != type;
1112 if (etree_conversion) {
1113 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1115 // Nested expression tree lambda use same scope as parent
1116 // lambda, this also means no variable capturing between this
1119 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1122 // Quote nested expression tree
1125 am = new Quote (am);
1127 int errors = ec.Report.Errors;
1129 if (Block.IsAsync) {
1130 ec.Report.Error (1989, loc, "Async lambda expressions cannot be converted to expression trees");
1133 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1134 am = body.Compatible (ec);
1138 // Rewrite expressions into expression tree when targeting Expression<T>
1140 if (am != null && errors == ec.Report.Errors)
1141 am = CreateExpressionTree (ec, delegate_type);
1144 am = body.Compatible (ec);
1146 } catch (CompletionResult) {
1148 } catch (FatalException) {
1150 } catch (Exception e) {
1151 throw new InternalErrorException (e, loc);
1154 if (!ec.IsInProbingMode) {
1155 compatibles.Add (type, am ?? EmptyExpression.Null);
1161 protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
1163 return CreateExpressionTree (ec);
1166 public override Expression CreateExpressionTree (ResolveContext ec)
1168 ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1172 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1174 var delegate_parameters = Delegate.GetParameters (delegate_type);
1176 if (Parameters == ParametersCompiled.Undefined) {
1178 // We provide a set of inaccessible parameters
1180 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1182 for (int i = 0; i < delegate_parameters.Count; i++) {
1183 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1184 if ((i_mod & Parameter.Modifier.OUT) != 0) {
1185 if (!ec.IsInProbingMode) {
1186 ec.Report.Error (1688, loc,
1187 "Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
1188 delegate_type.GetSignatureForError ());
1193 fixedpars[i] = new Parameter (
1194 new TypeExpression (delegate_parameters.Types [i], loc), null,
1195 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1198 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1201 if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1208 protected override Expression DoResolve (ResolveContext ec)
1210 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1211 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1216 // Set class type, set type
1219 eclass = ExprClass.Value;
1222 // This hack means `The type is not accessible
1223 // anywhere', we depend on special conversion
1226 type = InternalType.AnonymousMethod;
1228 if (!DoResolveParameters (ec))
1232 // FIXME: The emitted code isn't very careful about reachability
1233 // so, ensure we have a 'ret' at the end
1234 BlockContext bc = ec as BlockContext;
1235 if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1236 bc.NeedReturnLabel ();
1241 protected virtual bool DoResolveParameters (ResolveContext rc)
1243 return Parameters.Resolve (rc);
1246 public override void Emit (EmitContext ec)
1248 // nothing, as we only exist to not do anything.
1251 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1253 ec.Report.Error (1686, loc,
1254 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
1258 public override string GetSignatureForError ()
1260 return ExprClassName;
1263 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
1265 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1269 ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
1272 var rt = return_type;
1273 if (rt != null && rt.Kind != MemberKind.Void && rt != ec.Module.PredefinedTypes.Task.TypeSpec && !rt.IsGenericTask) {
1274 ec.Report.Error (4010, loc, "Cannot convert async {0} to delegate type `{1}'",
1275 GetSignatureForError (), delegate_type.GetSignatureForError ());
1280 b = b.ConvertToAsyncTask (ec, ec.CurrentMemberDefinition.Parent.PartialContainer, p, return_type, loc);
1283 return CompatibleMethodFactory (return_type ?? InternalType.Arglist, delegate_type, p, b);
1286 protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
1288 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1291 protected override void CloneTo (CloneContext clonectx, Expression t)
1293 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1295 target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
1298 public override object Accept (StructuralVisitor visitor)
1300 return visitor.Visit (this);
1305 // Abstract expression for any block which requires variables hoisting
1307 public abstract class AnonymousExpression : ExpressionStatement
1309 protected class AnonymousMethodMethod : Method
1311 public readonly AnonymousExpression AnonymousMethod;
1312 public readonly AnonymousMethodStorey Storey;
1314 public AnonymousMethodMethod (TypeDefinition parent, AnonymousExpression am, AnonymousMethodStorey storey,
1315 TypeExpr return_type,
1316 Modifiers mod, MemberName name,
1317 ParametersCompiled parameters)
1318 : base (parent, return_type, mod | Modifiers.COMPILER_GENERATED,
1319 name, parameters, null)
1321 this.AnonymousMethod = am;
1322 this.Storey = storey;
1324 Parent.PartialContainer.Members.Add (this);
1325 Block = new ToplevelBlock (am.block, parameters);
1328 public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
1330 EmitContext ec = new EmitContext (this, ig, ReturnType, sourceMethod);
1331 ec.CurrentAnonymousMethod = AnonymousMethod;
1335 protected override void DefineTypeParameters ()
1337 // Type parameters were cloned
1340 protected override bool ResolveMemberType ()
1342 if (!base.ResolveMemberType ())
1345 if (Storey != null && Storey.Mutator != null) {
1346 if (!parameters.IsEmpty) {
1347 var mutated = Storey.Mutator.Mutate (parameters.Types);
1348 if (mutated != parameters.Types)
1349 parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
1352 member_type = Storey.Mutator.Mutate (member_type);
1358 public override void Emit ()
1360 if (MethodBuilder == null) {
1368 protected ParametersBlock block;
1370 public TypeSpec ReturnType;
1372 protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
1374 this.ReturnType = return_type;
1379 public abstract string ContainerType { get; }
1380 public abstract bool IsIterator { get; }
1381 public abstract AnonymousMethodStorey Storey { get; }
1384 // The block that makes up the body for the anonymous method
1386 public ParametersBlock Block {
1392 public AnonymousExpression Compatible (ResolveContext ec)
1394 return Compatible (ec, this);
1397 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1402 // TODO: Implement clone
1403 BlockContext aec = new BlockContext (ec, block, ReturnType);
1404 aec.CurrentAnonymousMethod = ae;
1406 ResolveContext.Options flags = 0;
1408 var am = this as AnonymousMethodBody;
1410 if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
1411 am.ReturnTypeInference = new TypeInferenceContext ();
1414 if (ec.IsInProbingMode)
1415 flags |= ResolveContext.Options.ProbingMode;
1417 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
1418 flags |= ResolveContext.Options.FieldInitializerScope;
1420 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion))
1421 flags |= ResolveContext.Options.ExpressionTreeConversion;
1425 var errors = ec.Report.Errors;
1427 bool res = Block.Resolve (ec.CurrentBranching, aec, null);
1429 if (am != null && am.ReturnTypeInference != null) {
1430 am.ReturnTypeInference.FixAllTypes (ec);
1431 ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
1432 am.ReturnTypeInference = null;
1435 // If e is synchronous the inferred return type is T
1436 // If e is asynchronous the inferred return type is Task<T>
1438 if (block.IsAsync && ReturnType != null) {
1439 ReturnType = ec.Module.PredefinedTypes.TaskGeneric.TypeSpec.MakeGenericType (ec, new [] { ReturnType });
1443 if (res && errors != ec.Report.Errors)
1446 return res ? this : null;
1449 public override bool ContainsEmitWithAwait ()
1454 public void SetHasThisAccess ()
1456 ExplicitBlock b = block;
1458 if (b.HasCapturedThis)
1461 b.HasCapturedThis = true;
1462 b = b.Parent == null ? null : b.Parent.Explicit;
1463 } while (b != null);
1467 public class AnonymousMethodBody : AnonymousExpression
1469 protected readonly ParametersCompiled parameters;
1470 AnonymousMethodStorey storey;
1472 AnonymousMethodMethod method;
1475 TypeInferenceContext return_inference;
1477 public AnonymousMethodBody (ParametersCompiled parameters,
1478 ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
1480 : base (block, return_type, loc)
1482 this.type = delegate_type;
1483 this.parameters = parameters;
1488 public override string ContainerType {
1489 get { return "anonymous method"; }
1492 public override bool IsIterator {
1498 public ParametersCompiled Parameters {
1504 public TypeInferenceContext ReturnTypeInference {
1506 return return_inference;
1509 return_inference = value;
1513 public override AnonymousMethodStorey Storey {
1514 get { return storey; }
1519 public override Expression CreateExpressionTree (ResolveContext ec)
1521 ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1525 bool Define (ResolveContext ec)
1527 if (!Block.Resolved && Compatible (ec) == null)
1530 if (block_name == null) {
1531 MemberCore mc = (MemberCore) ec.MemberContext;
1532 block_name = mc.MemberName.Basename;
1539 // Creates a host for the anonymous method
1541 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1544 // Anonymous method body can be converted to
1546 // 1, an instance method in current scope when only `this' is hoisted
1547 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1548 // 3, an instance method in compiler generated storey when any hoisted variable exists
1551 Modifiers modifiers;
1552 TypeDefinition parent = null;
1554 var src_block = Block.Original.Explicit;
1555 if (src_block.HasCapturedVariable || src_block.HasCapturedThis) {
1556 parent = storey = FindBestMethodStorey ();
1558 if (storey == null) {
1559 var sm = src_block.ParametersBlock.TopBlock.StateMachine;
1562 // Remove hoisted this demand when simple instance method is enough
1564 if (src_block.HasCapturedThis) {
1565 src_block.ParametersBlock.TopBlock.RemoveThisReferenceFromChildrenBlock (src_block);
1568 // Special case where parent class is used to emit instance method
1569 // because currect storey is of value type (async host) and we don't
1570 // want to create another childer storey to host this reference only
1572 if (sm != null && sm.Kind == MemberKind.Struct)
1573 parent = sm.Parent.PartialContainer;
1577 // For iterators we can host everything in one class
1579 if (sm is IteratorStorey)
1580 parent = storey = sm;
1583 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1585 if (ec.CurrentAnonymousMethod != null)
1586 parent = storey = ec.CurrentAnonymousMethod.Storey;
1588 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1592 parent = ec.CurrentTypeDefinition.Parent.PartialContainer;
1594 string name = CompilerGeneratedContainer.MakeName (parent != storey ? block_name : null,
1595 "m", null, ec.Module.CounterAnonymousMethods++);
1597 MemberName member_name;
1598 if (storey == null && ec.CurrentTypeParameters != null) {
1600 var hoisted_tparams = ec.CurrentTypeParameters;
1601 var type_params = new TypeParameters (hoisted_tparams.Count);
1602 for (int i = 0; i < hoisted_tparams.Count; ++i) {
1603 type_params.Add (hoisted_tparams[i].CreateHoistedCopy (null));
1606 member_name = new MemberName (name, type_params, Location);
1608 member_name = new MemberName (name, Location);
1611 return new AnonymousMethodMethod (parent,
1612 this, storey, new TypeExpression (ReturnType, Location), modifiers,
1613 member_name, parameters);
1616 protected override Expression DoResolve (ResolveContext ec)
1621 eclass = ExprClass.Value;
1625 public override void Emit (EmitContext ec)
1628 // Use same anonymous method implementation for scenarios where same
1629 // code is used from multiple blocks, e.g. field initializers
1631 if (method == null) {
1633 // Delay an anonymous method definition to avoid emitting unused code
1634 // for unreachable blocks or expression trees
1636 method = DoCreateMethodHost (ec);
1640 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1641 if (is_static && am_cache == null) {
1643 // Creates a field cache to store delegate instance if it's not generic
1645 if (!method.MemberName.IsGeneric) {
1646 var parent = method.Parent.PartialContainer;
1647 int id = parent.AnonymousMethodsCounter++;
1648 var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
1650 am_cache = new Field (parent, new TypeExpression (cache_type, loc),
1651 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1652 new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "am$cache", id), loc), null);
1654 parent.AddField (am_cache);
1656 // TODO: Implement caching of generated generic static methods
1660 // Some extra class is needed to capture variable generic type
1661 // arguments. Maybe we could re-use anonymous types, with a unique
1662 // anonymous method id, but they are quite heavy.
1664 // Consider : "() => typeof(T);"
1666 // We need something like
1667 // static class Wrap<Tn, Tm, DelegateType> {
1668 // public static DelegateType cache;
1671 // We then specialize local variable to capture all generic parameters
1672 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1677 Label l_initialized = ec.DefineLabel ();
1679 if (am_cache != null) {
1680 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1681 ec.Emit (OpCodes.Brtrue_S, l_initialized);
1685 // Load method delegate implementation
1690 } else if (storey != null) {
1691 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1699 // Special case for value type storey where this is not lifted but
1700 // droped off to parent class
1702 for (var b = Block.Parent; b != null; b = b.Parent) {
1703 if (b.ParametersBlock.StateMachine != null) {
1704 ec.Emit (OpCodes.Ldfld, b.ParametersBlock.StateMachine.HoistedThis.Field.Spec);
1710 var delegate_method = method.Spec;
1711 if (storey != null && storey.MemberName.IsGeneric) {
1712 TypeSpec t = storey.Instance.Type;
1715 // Mutate anonymous method instance type if we are in nested
1716 // hoisted generic anonymous method storey
1718 if (ec.IsAnonymousStoreyMutateRequired) {
1719 t = storey.Mutator.Mutate (t);
1722 ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
1724 if (delegate_method.IsGeneric)
1725 delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, method.TypeParameters);
1727 ec.Emit (OpCodes.Ldftn, delegate_method);
1730 var constructor_method = Delegate.GetConstructor (type);
1731 ec.Emit (OpCodes.Newobj, constructor_method);
1733 if (am_cache != null) {
1734 ec.Emit (OpCodes.Stsfld, am_cache.Spec);
1735 ec.MarkLabel (l_initialized);
1736 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1740 public override void EmitStatement (EmitContext ec)
1742 throw new NotImplementedException ();
1746 // Look for the best storey for this anonymous method
1748 AnonymousMethodStorey FindBestMethodStorey ()
1751 // Use the nearest parent block which has a storey
1753 for (Block b = Block.Parent; b != null; b = b.Parent) {
1754 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1762 public override string GetSignatureForError ()
1764 return TypeManager.CSharpName (type);
1769 // Anonymous type container
1771 public class AnonymousTypeClass : CompilerGeneratedContainer
1773 public const string ClassNamePrefix = "<>__AnonType";
1774 public const string SignatureForError = "anonymous type";
1776 readonly IList<AnonymousTypeParameter> parameters;
1778 private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
1779 : base (parent, name, parent.Evaluator != null ? Modifiers.PUBLIC : Modifiers.INTERNAL)
1781 this.parameters = parameters;
1784 public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
1786 string name = ClassNamePrefix + parent.Module.CounterAnonymousTypes++;
1788 ParametersCompiled all_parameters;
1789 TypeParameters tparams = null;
1790 SimpleName[] t_args;
1792 if (parameters.Count == 0) {
1793 all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
1796 t_args = new SimpleName[parameters.Count];
1797 tparams = new TypeParameters ();
1798 Parameter[] ctor_params = new Parameter[parameters.Count];
1799 for (int i = 0; i < parameters.Count; ++i) {
1800 AnonymousTypeParameter p = parameters[i];
1801 for (int ii = 0; ii < i; ++ii) {
1802 if (parameters[ii].Name == p.Name) {
1803 parent.Compiler.Report.Error (833, parameters[ii].Location,
1804 "`{0}': An anonymous type cannot have multiple properties with the same name",
1807 p = new AnonymousTypeParameter (null, "$" + i.ToString (), p.Location);
1813 t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1814 tparams.Add (new TypeParameter (i, new MemberName (t_args[i].Name, p.Location), null, null, Variance.None));
1815 ctor_params[i] = new Parameter (t_args[i], p.Name, Parameter.Modifier.NONE, null, p.Location);
1818 all_parameters = new ParametersCompiled (ctor_params);
1822 // Create generic anonymous type host with generic arguments
1823 // named upon properties names
1825 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.Module, new MemberName (name, tparams, loc), parameters, loc);
1827 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1828 null, all_parameters, loc);
1829 c.Block = new ToplevelBlock (parent.Module.Compiler, c.ParameterInfo, loc);
1832 // Create fields and constructor body with field initialization
1835 for (int i = 0; i < parameters.Count; ++i) {
1836 AnonymousTypeParameter p = parameters [i];
1838 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY | Modifiers.DEBUGGER_HIDDEN,
1839 new MemberName ("<" + p.Name + ">", p.Location), null);
1841 if (!a_type.AddField (f)) {
1846 c.Block.AddStatement (new StatementExpression (
1847 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1848 c.Block.GetParameterReference (i, p.Location))));
1850 ToplevelBlock get_block = new ToplevelBlock (parent.Module.Compiler, p.Location);
1851 get_block.AddStatement (new Return (
1852 new MemberAccess (new This (p.Location), f.Name), p.Location));
1854 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1855 new MemberName (p.Name, p.Location), null);
1856 prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
1857 prop.Get.Block = get_block;
1858 a_type.AddMember (prop);
1864 a_type.AddConstructor (c);
1868 protected override bool DoDefineMembers ()
1870 if (!base.DoDefineMembers ())
1873 Location loc = Location;
1875 var equals_parameters = ParametersCompiled.CreateFullyResolved (
1876 new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc), Compiler.BuiltinTypes.Object);
1878 Method equals = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
1879 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1880 equals_parameters, null);
1882 equals_parameters[0].Resolve (equals, 0);
1884 Method tostring = new Method (this, new TypeExpression (Compiler.BuiltinTypes.String, loc),
1885 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1886 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1888 ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
1890 TypeExpr current_type;
1891 if (CurrentTypeParameters != null) {
1892 var targs = new TypeArguments ();
1893 for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
1894 targs.Add (new TypeParameterExpr (CurrentTypeParameters[i], Location));
1897 current_type = new GenericTypeExpr (Definition, targs, loc);
1899 current_type = new TypeExpression (Definition, loc);
1902 var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
1903 equals_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_other.Type, loc), li_other));
1904 var other_variable = new LocalVariableReference (li_other, loc);
1906 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1907 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1909 Expression rs_equals = null;
1910 Expression string_concat = new StringConstant (Compiler.BuiltinTypes, "{", loc);
1911 Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
1912 for (int i = 0; i < parameters.Count; ++i) {
1913 var p = parameters [i];
1914 var f = (Field) Members [i * 2];
1916 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1917 system_collections_generic, "EqualityComparer",
1918 new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
1921 Arguments arguments_equal = new Arguments (2);
1922 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1923 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1925 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1926 "Equals", loc), arguments_equal);
1928 Arguments arguments_hashcode = new Arguments (1);
1929 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1930 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1931 "GetHashCode", loc), arguments_hashcode);
1933 IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);
1934 rs_hashcode = new Binary (Binary.Operator.Multiply,
1935 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode, loc),
1938 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
1939 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc), loc)),
1940 new Invocation (new MemberAccess (
1941 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1942 new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
1944 if (rs_equals == null) {
1945 rs_equals = field_equal;
1946 string_concat = new Binary (Binary.Operator.Addition,
1948 new Binary (Binary.Operator.Addition,
1949 new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
1957 // Implementation of ToString () body using string concatenation
1959 string_concat = new Binary (Binary.Operator.Addition,
1960 new Binary (Binary.Operator.Addition,
1962 new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc),
1967 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal, loc);
1970 string_concat = new Binary (Binary.Operator.Addition,
1972 new StringConstant (Compiler.BuiltinTypes, " }", loc),
1976 // Equals (object obj) override
1978 var other_variable_assign = new TemporaryVariableReference (li_other, loc);
1979 equals_block.AddStatement (new StatementExpression (
1980 new SimpleAssign (other_variable_assign,
1981 new As (equals_block.GetParameterReference (0, loc),
1982 current_type, loc), loc)));
1984 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc), loc);
1985 if (rs_equals != null)
1986 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals, loc);
1987 equals_block.AddStatement (new Return (equals_test, loc));
1989 equals.Block = equals_block;
1991 Members.Add (equals);
1994 // GetHashCode () override
1996 Method hashcode = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Int, loc),
1997 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1998 new MemberName ("GetHashCode", loc),
1999 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
2002 // Modified FNV with good avalanche behavior and uniform
2003 // distribution with larger hash sizes.
2005 // const int FNV_prime = 16777619;
2006 // int hash = (int) 2166136261;
2007 // foreach (int d in data)
2008 // hash = (hash ^ d) * FNV_prime;
2009 // hash += hash << 13;
2010 // hash ^= hash >> 7;
2011 // hash += hash << 3;
2012 // hash ^= hash >> 17;
2013 // hash += hash << 5;
2015 ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
2016 Block hashcode_block = new Block (hashcode_top, loc, loc);
2017 hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
2019 var li_hash = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Int, hashcode_top, loc);
2020 hashcode_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_hash.Type, loc), li_hash));
2021 LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
2022 hashcode_block.AddStatement (new StatementExpression (
2023 new SimpleAssign (hash_variable_assign, rs_hashcode)));
2025 var hash_variable = new LocalVariableReference (li_hash, loc);
2026 hashcode_block.AddStatement (new StatementExpression (
2027 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2028 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc), loc), loc)));
2029 hashcode_block.AddStatement (new StatementExpression (
2030 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2031 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc), loc), loc)));
2032 hashcode_block.AddStatement (new StatementExpression (
2033 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2034 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc), loc), loc)));
2035 hashcode_block.AddStatement (new StatementExpression (
2036 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
2037 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc), loc), loc)));
2038 hashcode_block.AddStatement (new StatementExpression (
2039 new CompoundAssign (Binary.Operator.Addition, hash_variable,
2040 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc), loc), loc)));
2042 hashcode_block.AddStatement (new Return (hash_variable, loc));
2043 hashcode.Block = hashcode_top;
2045 Members.Add (hashcode);
2048 // ToString () override
2051 ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
2052 tostring_block.AddStatement (new Return (string_concat, loc));
2053 tostring.Block = tostring_block;
2055 Members.Add (tostring);
2060 public override string GetSignatureForError ()
2062 return SignatureForError;
2065 public override CompilationSourceFile GetCompilationSourceFile ()
2070 public IList<AnonymousTypeParameter> Parameters {