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-2008 Novell, Inc.
14 using System.Collections.Generic;
15 using System.Reflection;
16 using System.Reflection.Emit;
18 namespace Mono.CSharp {
20 public abstract class CompilerGeneratedClass : Class
22 protected CompilerGeneratedClass (DeclSpace parent, MemberName name, Modifiers mod)
23 : base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED, null)
27 protected void CheckMembersDefined ()
29 if (HasMembersDefined)
30 throw new InternalErrorException ("Helper class already defined!");
33 protected static MemberName MakeMemberName (MemberBase host, string name, int unique_id, TypeParameter[] tparams, Location loc)
35 string host_name = host == null ? null : host.Name;
36 string tname = MakeName (host_name, "c", name, unique_id);
37 TypeArguments args = null;
38 if (tparams != null) {
39 args = new TypeArguments ();
40 foreach (TypeParameter tparam in tparams)
41 args.Add (new TypeParameterName (tparam.Name, null, loc));
44 return new MemberName (tname, args, loc);
47 public static string MakeName (string host, string typePrefix, string name, int id)
49 return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
53 public class HoistedStoreyClass : CompilerGeneratedClass
55 public sealed class HoistedField : Field
57 public HoistedField (HoistedStoreyClass parent, FullNamedExpression type, Modifiers mod, string name,
58 Attributes attrs, Location loc)
59 : base (parent, type, mod, new MemberName (name, loc), attrs)
63 protected override bool ResolveMemberType ()
65 if (!base.ResolveMemberType ())
68 HoistedStoreyClass parent = ((HoistedStoreyClass) Parent).GetGenericStorey ();
69 if (parent != null && parent.Mutator != null)
70 member_type = parent.Mutator.Mutate (MemberType);
76 protected TypeParameterMutator mutator;
78 public HoistedStoreyClass (DeclSpace parent, MemberName name, TypeParameter[] tparams, Modifiers mod)
79 : base (parent, name, mod | Modifiers.PRIVATE)
81 if (tparams != null) {
82 type_params = new TypeParameter[tparams.Length];
83 var src = new TypeParameterSpec[tparams.Length];
84 var dst = new TypeParameterSpec[tparams.Length];
86 for (int i = 0; i < type_params.Length; ++i) {
87 type_params[i] = tparams[i].CreateHoistedCopy (this, spec);
89 src[i] = tparams[i].Type;
90 dst[i] = type_params[i].Type;
93 // A copy is not enough, inflate any type parameter constraints
94 // using a new type parameters
95 var inflator = new TypeParameterInflator (null, src, dst);
96 for (int i = 0; i < type_params.Length; ++i) {
97 src[i].InflateConstraints (inflator, dst[i]);
104 public TypeParameterMutator Mutator {
115 public HoistedStoreyClass GetGenericStorey ()
117 DeclSpace storey = this;
118 while (storey != null && storey.CurrentTypeParameters == null)
119 storey = storey.Parent;
121 return storey as HoistedStoreyClass;
127 // Anonymous method storey is created when an anonymous method uses
128 // variable or parameter from outer scope. They are then hoisted to
129 // anonymous method storey (captured)
131 public class AnonymousMethodStorey : HoistedStoreyClass
133 struct StoreyFieldPair
135 public readonly AnonymousMethodStorey Storey;
136 public readonly Field Field;
138 public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
140 this.Storey = storey;
146 // Needed to delay hoisted _this_ initialization. When an anonymous
147 // method is used inside ctor and _this_ is hoisted, base ctor has to
148 // be called first, otherwise _this_ will be initialized with
149 // uninitialized value.
151 sealed class ThisInitializer : Statement
153 readonly HoistedThis hoisted_this;
155 public ThisInitializer (HoistedThis hoisted_this)
157 this.hoisted_this = hoisted_this;
160 protected override void DoEmit (EmitContext ec)
162 hoisted_this.EmitHoistingAssignment (ec);
165 protected override void CloneTo (CloneContext clonectx, Statement target)
172 public readonly int ID;
173 static int unique_id;
175 public readonly Block OriginalSourceBlock;
177 // A list of StoreyFieldPair with local field keeping parent storey instance
178 List<StoreyFieldPair> used_parent_storeys;
179 List<ExplicitBlock> children_references;
181 // A list of hoisted parameters
182 protected List<HoistedParameter> hoisted_params;
183 protected List<HoistedVariable> hoisted_locals;
186 protected HoistedThis hoisted_this;
188 // Local variable which holds this storey instance
189 public LocalTemporary Instance;
191 public AnonymousMethodStorey (Block block, TypeContainer parent, MemberBase host, TypeParameter[] tparams, string name)
192 : base (parent, MakeMemberName (host, name, unique_id, tparams, block.StartLocation),
193 tparams, Modifiers.SEALED)
196 OriginalSourceBlock = block;
200 public void AddCapturedThisField (EmitContext ec)
202 TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
203 Field f = AddCompilerGeneratedField ("<>f__this", type_expr);
205 hoisted_this = new HoistedThis (this, f);
207 // Inflated type instance has to be updated manually
208 if (Instance.Type is InflatedTypeSpec) {
209 var inflator = new TypeParameterInflator (Instance.Type, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
210 Instance.Type.MemberCache.AddMember (f.Spec.InflateMember (inflator));
212 inflator = new TypeParameterInflator (f.Parent.CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
213 f.Parent.CurrentType.MemberCache.AddMember (f.Spec.InflateMember (inflator));
217 public Field AddCapturedVariable (string name, TypeSpec type)
219 CheckMembersDefined ();
221 FullNamedExpression field_type = new TypeExpression (type, Location);
223 return AddCompilerGeneratedField (name, field_type);
225 const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
226 Field f = new HoistedField (this, field_type, mod, name, null, Location);
231 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
233 const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
234 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
240 // Creates a link between hoisted variable block and the anonymous method storey
242 // An anonymous method can reference variables from any outer block, but they are
243 // hoisted in their own ExplicitBlock. When more than one block is referenced we
244 // need to create another link between those variable storeys
246 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
248 if (children_references == null)
249 children_references = new List<ExplicitBlock> ();
251 if (!children_references.Contains (block))
252 children_references.Add (block);
255 public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
257 CheckMembersDefined ();
259 if (used_parent_storeys == null)
260 used_parent_storeys = new List<StoreyFieldPair> ();
261 else if (used_parent_storeys.Exists (i => i.Storey == storey))
264 TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
265 Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
266 used_parent_storeys.Add (new StoreyFieldPair (storey, f));
269 public void CaptureLocalVariable (ResolveContext ec, LocalVariable local_info)
271 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
272 if (ec.CurrentBlock.Explicit != local_info.Block.Explicit)
273 AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
275 if (local_info.HoistedVariant != null)
278 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
279 local_info.HoistedVariant = var;
281 if (hoisted_locals == null)
282 hoisted_locals = new List<HoistedVariable> ();
284 hoisted_locals.Add (var);
287 public void CaptureParameter (ResolveContext ec, ParameterReference param_ref)
289 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
290 AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
292 if (param_ref.GetHoistedVariable (ec) != null)
295 if (hoisted_params == null)
296 hoisted_params = new List<HoistedParameter> (2);
298 var expr = new HoistedParameter (this, param_ref);
299 param_ref.Parameter.HoistedVariant = expr;
300 hoisted_params.Add (expr);
303 TypeExpr CreateStoreyTypeExpression (EmitContext ec)
306 // Create an instance of storey type
308 TypeExpr storey_type_expr;
309 if (CurrentTypeParameters != null) {
311 // Use current method type parameter (MVAR) for top level storey only. All
312 // nested storeys use class type parameter (VAR)
314 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
315 ec.CurrentAnonymousMethod.Storey.TypeParameters :
316 ec.CurrentTypeParameters;
318 TypeArguments targs = new TypeArguments ();
321 // Use type parameter name instead of resolved type parameter
322 // specification to resolve to correctly nested type parameters
324 for (int i = 0; i < tparams.Length; ++i)
325 targs.Add (new SimpleName (tparams [i].Name, Location)); // new TypeParameterExpr (tparams[i], Location));
327 storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
329 storey_type_expr = new TypeExpression (CurrentType, Location);
332 return storey_type_expr;
335 public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
337 Parent = parentStorey;
339 spec.IsGeneric = false;
340 spec.DeclaringType = parentStorey.CurrentType;
341 MemberName.TypeArguments = null;
344 protected override bool DoResolveTypeParameters ()
346 // Although any storey can have type parameters they are all clones of method type
347 // parameters therefore have to mutate MVAR references in any of cloned constraints
348 if (type_params != null) {
349 for (int i = 0; i < type_params.Length; ++i) {
350 var spec = type_params[i].Type;
351 spec.BaseType = mutator.Mutate (spec.BaseType);
352 if (spec.InterfacesDefined != null) {
353 var mutated = new TypeSpec[spec.InterfacesDefined.Length];
354 for (int ii = 0; ii < mutated.Length; ++ii) {
355 mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
358 spec.InterfacesDefined = mutated;
361 if (spec.TypeArguments != null) {
362 spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
368 // Update parent cache as we most likely passed the point
369 // where the cache was constructed
371 Parent.CurrentType.MemberCache.AddMember (this.spec);
377 // Initializes all hoisted variables
379 public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
381 // There can be only one instance variable for each storey type
382 if (Instance != null)
383 throw new InternalErrorException ();
385 SymbolWriter.OpenCompilerGeneratedBlock (ec);
388 // Create an instance of a storey
390 var storey_type_expr = CreateStoreyTypeExpression (ec);
392 ResolveContext rc = new ResolveContext (ec.MemberContext);
393 rc.CurrentBlock = block;
394 Expression e = new New (storey_type_expr, null, Location).Resolve (rc);
397 Instance = new LocalTemporary (storey_type_expr.Type);
400 EmitHoistedFieldsInitialization (rc, ec);
402 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
403 SymbolWriter.CloseCompilerGeneratedBlock (ec);
406 void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
409 // Initialize all storey reference fields by using local or hoisted variables
411 if (used_parent_storeys != null) {
412 foreach (StoreyFieldPair sf in used_parent_storeys) {
414 // Get instance expression of storey field
416 Expression instace_expr = GetStoreyInstanceExpression (ec);
417 var fs = sf.Field.Spec;
418 if (TypeManager.IsGenericType (instace_expr.Type))
419 fs = MemberCache.GetMember (instace_expr.Type, fs);
421 FieldExpr f_set_expr = new FieldExpr (fs, Location);
422 f_set_expr.InstanceExpression = instace_expr;
424 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
425 if (a.Resolve (rc) != null)
426 a.EmitStatement (ec);
431 // Define hoisted `this' in top-level storey only
433 if (OriginalSourceBlock.Explicit.HasCapturedThis && !(Parent is AnonymousMethodStorey)) {
434 AddCapturedThisField (ec);
435 rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
439 // Setting currect anonymous method to null blocks any further variable hoisting
441 AnonymousExpression ae = ec.CurrentAnonymousMethod;
442 ec.CurrentAnonymousMethod = null;
444 if (hoisted_params != null) {
445 EmitHoistedParameters (ec, hoisted_params);
448 ec.CurrentAnonymousMethod = ae;
451 protected virtual void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
453 foreach (HoistedParameter hp in hoisted) {
454 hp.EmitHoistingAssignment (ec);
458 public override void EmitType ()
460 SymbolWriter.DefineAnonymousScope (ID);
462 if (hoisted_this != null)
463 hoisted_this.EmitSymbolInfo ();
465 if (hoisted_locals != null) {
466 foreach (HoistedVariable local in hoisted_locals)
467 local.EmitSymbolInfo ();
470 if (hoisted_params != null) {
471 foreach (HoistedParameter param in hoisted_params)
472 param.EmitSymbolInfo ();
475 if (used_parent_storeys != null) {
476 foreach (StoreyFieldPair sf in used_parent_storeys) {
477 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
485 // Returns a field which holds referenced storey instance
487 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
489 if (used_parent_storeys == null)
492 foreach (StoreyFieldPair sf in used_parent_storeys) {
493 if (sf.Storey == storey)
501 // Creates storey instance expression regardless of currect IP
503 public Expression GetStoreyInstanceExpression (EmitContext ec)
505 AnonymousExpression am = ec.CurrentAnonymousMethod;
508 // Access from original block -> storey
514 // Access from anonymous method implemented as a static -> storey
516 if (am.Storey == null)
519 Field f = am.Storey.GetReferencedStoreyField (this);
521 if (am.Storey == this) {
523 // Access inside of same storey (S -> S)
525 return new CompilerGeneratedThis (CurrentType, Location);
528 // External field access
534 // Storey was cached to local field
536 FieldExpr f_ind = new FieldExpr (f, Location);
537 f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
541 protected virtual string GetVariableMangledName (LocalVariable local_info)
544 // No need to mangle anonymous method hoisted variables cause they
545 // are hoisted in their own scopes
547 return local_info.Name;
550 public HoistedThis HoistedThis {
551 get { return hoisted_this; }
554 public IList<ExplicitBlock> ReferencesFromChildrenBlock {
555 get { return children_references; }
558 public static void Reset ()
564 public abstract class HoistedVariable
567 // Hoisted version of variable references used in expression
568 // tree has to be delayed until we know its location. The variable
569 // doesn't know its location until all stories are calculated
571 class ExpressionTreeVariableReference : Expression
573 readonly HoistedVariable hv;
575 public ExpressionTreeVariableReference (HoistedVariable hv)
580 public override Expression CreateExpressionTree (ResolveContext ec)
582 throw new NotSupportedException ("ET");
585 protected override Expression DoResolve (ResolveContext ec)
587 eclass = ExprClass.Value;
588 type = TypeManager.expression_type_expr.Type;
592 public override void Emit (EmitContext ec)
594 ResolveContext rc = new ResolveContext (ec.MemberContext);
595 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc);
596 // This should never fail
603 protected readonly AnonymousMethodStorey storey;
604 protected Field field;
605 Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
606 FieldExpr cached_outer_access;
608 protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
609 : this (storey, storey.AddCapturedVariable (name, type))
613 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
615 this.storey = storey;
619 public void AddressOf (EmitContext ec, AddressOp mode)
621 GetFieldExpression (ec).AddressOf (ec, mode);
624 public Expression CreateExpressionTree ()
626 return new ExpressionTreeVariableReference (this);
629 public void Emit (EmitContext ec)
631 GetFieldExpression (ec).Emit (ec);
635 // Creates field access expression for hoisted variable
637 protected virtual FieldExpr GetFieldExpression (EmitContext ec)
639 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
640 if (cached_outer_access != null)
641 return cached_outer_access;
644 // When setting top-level hoisted variable in generic storey
645 // change storey generic types to method generic types (VAR -> MVAR)
647 if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
648 var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
649 cached_outer_access = new FieldExpr (fs, field.Location);
651 cached_outer_access = new FieldExpr (field, field.Location);
654 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
655 return cached_outer_access;
658 FieldExpr inner_access;
659 if (cached_inner_access != null) {
660 if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
664 cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
667 if (inner_access == null) {
668 if (field.Parent.IsGeneric) {
669 var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
670 inner_access = new FieldExpr (fs, field.Location);
672 inner_access = new FieldExpr (field, field.Location);
675 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
676 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
682 public abstract void EmitSymbolInfo ();
684 public void Emit (EmitContext ec, bool leave_copy)
686 GetFieldExpression (ec).Emit (ec, leave_copy);
689 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
691 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
695 public class HoistedParameter : HoistedVariable
697 sealed class HoistedFieldAssign : Assign
699 public HoistedFieldAssign (Expression target, Expression source)
700 : base (target, source, source.Location)
704 protected override Expression ResolveConversions (ResolveContext ec)
707 // Implicit conversion check fails for hoisted type arguments
708 // as they are of different types (!!0 x !0)
714 readonly ParameterReference parameter;
716 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
717 : base (scope, par.Name, par.Type)
719 this.parameter = par;
722 public HoistedParameter (HoistedParameter hp, string name)
723 : base (hp.storey, name, hp.parameter.Type)
725 this.parameter = hp.parameter;
728 public void EmitHoistingAssignment (EmitContext ec)
731 // Remove hoisted redirection to emit assignment from original parameter
733 HoistedVariable temp = parameter.Parameter.HoistedVariant;
734 parameter.Parameter.HoistedVariant = null;
736 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
737 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
738 a.EmitStatement (ec);
740 parameter.Parameter.HoistedVariant = temp;
743 public override void EmitSymbolInfo ()
745 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
749 get { return field; }
753 class HoistedLocalVariable : HoistedVariable
755 readonly string name;
757 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalVariable local, string name)
758 : base (scope, name, local.Type)
760 this.name = local.Name;
763 public override void EmitSymbolInfo ()
765 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
769 public class HoistedThis : HoistedVariable
771 public HoistedThis (AnonymousMethodStorey storey, Field field)
772 : base (storey, field)
776 public void EmitHoistingAssignment (EmitContext ec)
778 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), new CompilerGeneratedThis (ec.CurrentType, field.Location));
779 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
780 a.EmitStatement (ec);
783 public override void EmitSymbolInfo ()
785 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
789 get { return field; }
794 // Anonymous method expression as created by parser
796 public class AnonymousMethodExpression : Expression
799 // Special conversion for nested expression tree lambdas
801 class Quote : ShimExpression
803 public Quote (Expression expr)
808 public override Expression CreateExpressionTree (ResolveContext ec)
810 var args = new Arguments (1);
811 args.Add (new Argument (expr.CreateExpressionTree (ec)));
812 return CreateExpressionFactoryCall (ec, "Quote", args);
815 protected override Expression DoResolve (ResolveContext rc)
817 expr = expr.Resolve (rc);
821 eclass = expr.eclass;
827 Dictionary<TypeSpec, Expression> compatibles;
828 public ParametersBlock Block;
830 public AnonymousMethodExpression (Location loc)
833 this.compatibles = new Dictionary<TypeSpec, Expression> ();
836 public override string ExprClassName {
838 return "anonymous method";
842 public virtual bool HasExplicitParameters {
844 return Parameters != ParametersCompiled.Undefined;
848 public ParametersCompiled Parameters {
849 get { return Block.Parameters; }
853 // Returns true if the body of lambda expression can be implicitly
854 // converted to the delegate of type `delegate_type'
856 public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
858 using (ec.With (ResolveContext.Options.InferReturnType, false)) {
859 using (ec.Set (ResolveContext.Options.ProbingMode)) {
860 return Compatible (ec, delegate_type) != null;
865 TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
867 if (delegate_type.IsDelegate)
868 return delegate_type;
870 if (delegate_type.IsGeneric && delegate_type.GetDefinition () == TypeManager.expression_type) {
871 delegate_type = delegate_type.TypeArguments [0];
872 if (delegate_type.IsDelegate)
873 return delegate_type;
875 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
876 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
880 ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
881 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
885 protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
887 if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
890 if (!ec.IsInProbingMode)
891 ec.Report.Error (1661, loc,
892 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
893 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
898 protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
900 if (Parameters.Count != invoke_pd.Count) {
904 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
905 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
909 bool has_implicit_parameters = !HasExplicitParameters;
912 for (int i = 0; i < Parameters.Count; ++i) {
913 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
914 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
918 if (p_mod == Parameter.Modifier.NONE)
919 ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
920 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
922 ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
923 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
927 if (has_implicit_parameters)
930 TypeSpec type = invoke_pd.Types [i];
932 // We assume that generic parameters are always inflated
933 if (TypeManager.IsGenericParameter (type))
936 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
939 if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
943 ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
945 TypeManager.CSharpName (Parameters.Types [i]),
946 TypeManager.CSharpName (invoke_pd.Types [i]));
955 // Infers type arguments based on explicit arguments
957 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
959 if (!HasExplicitParameters)
962 if (!delegate_type.IsDelegate) {
963 if (delegate_type.GetDefinition () != TypeManager.expression_type)
966 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
967 if (!delegate_type.IsDelegate)
971 AParametersCollection d_params = Delegate.GetParameters (ec.Compiler, delegate_type);
972 if (d_params.Count != Parameters.Count)
975 for (int i = 0; i < Parameters.Count; ++i) {
976 TypeSpec itype = d_params.Types [i];
977 if (!TypeManager.IsGenericParameter (itype)) {
978 if (!TypeManager.HasElementType (itype))
981 if (!TypeManager.IsGenericParameter (TypeManager.GetElementType (itype)))
984 type_inference.ExactInference (Parameters.Types [i], itype);
989 public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
992 AnonymousExpression am;
994 if (compatibles.TryGetValue (delegate_type, out expr)) {
995 am = expr as AnonymousExpression;
996 return am == null ? null : am.ReturnType;
999 using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
1000 am = CompatibleMethodBody (ec, tic, InternalType.Arglist, delegate_type);
1002 am = am.Compatible (ec);
1008 // compatibles.Add (delegate_type, am);
1009 return am.ReturnType;
1013 // Returns AnonymousMethod container if this anonymous method
1014 // expression can be implicitly converted to the delegate type `delegate_type'
1016 public Expression Compatible (ResolveContext ec, TypeSpec type)
1019 if (compatibles.TryGetValue (type, out am))
1022 TypeSpec delegate_type = CompatibleChecks (ec, type);
1023 if (delegate_type == null)
1027 // At this point its the first time we know the return type that is
1028 // needed for the anonymous method. We create the method here.
1031 var invoke_mb = Delegate.GetInvokeMethod (ec.Compiler, delegate_type);
1032 TypeSpec return_type = invoke_mb.ReturnType;
1035 // Second: the return type of the delegate must be compatible with
1036 // the anonymous type. Instead of doing a pass to examine the block
1037 // we satisfy the rule by setting the return type on the EmitContext
1038 // to be the delegate type return type.
1041 var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1045 bool etree_conversion = delegate_type != type;
1048 if (etree_conversion) {
1049 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1051 // Nested expression tree lambda use same scope as parent
1052 // lambda, this also means no variable capturing between this
1055 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1058 // Quote nested expression tree
1061 am = new Quote (am);
1063 int errors = ec.Report.Errors;
1065 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1066 am = body.Compatible (ec);
1070 // Rewrite expressions into expression tree when targeting Expression<T>
1072 if (am != null && errors == ec.Report.Errors)
1073 am = CreateExpressionTree (ec, delegate_type);
1076 am = body.Compatible (ec);
1078 } catch (CompletionResult) {
1080 } catch (Exception e) {
1081 throw new InternalErrorException (e, loc);
1084 if (!ec.IsInProbingMode) {
1085 compatibles.Add (type, am ?? EmptyExpression.Null);
1091 protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
1093 return CreateExpressionTree (ec);
1096 public override Expression CreateExpressionTree (ResolveContext ec)
1098 ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1102 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1104 var delegate_parameters = Delegate.GetParameters (ec.Compiler, delegate_type);
1106 if (Parameters == ParametersCompiled.Undefined) {
1108 // We provide a set of inaccessible parameters
1110 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1112 for (int i = 0; i < delegate_parameters.Count; i++) {
1113 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1114 if (i_mod == Parameter.Modifier.OUT) {
1115 if (!ec.IsInProbingMode) {
1116 ec.Report.Error (1688, loc,
1117 "Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
1118 delegate_type.GetSignatureForError ());
1123 fixedpars[i] = new Parameter (
1124 new TypeExpression (delegate_parameters.Types [i], loc), null,
1125 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1128 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1131 if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1138 protected override Expression DoResolve (ResolveContext ec)
1140 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1141 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1146 // Set class type, set type
1149 eclass = ExprClass.Value;
1152 // This hack means `The type is not accessible
1153 // anywhere', we depend on special conversion
1156 type = InternalType.AnonymousMethod;
1158 if (!DoResolveParameters (ec))
1161 // FIXME: The emitted code isn't very careful about reachability
1162 // so, ensure we have a 'ret' at the end
1163 BlockContext bc = ec as BlockContext;
1164 if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1165 bc.NeedReturnLabel ();
1170 protected virtual bool DoResolveParameters (ResolveContext rc)
1172 return Parameters.Resolve (rc);
1175 public override void Emit (EmitContext ec)
1177 // nothing, as we only exist to not do anything.
1180 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1182 ec.Report.Error (1686, loc,
1183 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1187 public override string GetSignatureForError ()
1189 return ExprClassName;
1192 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
1194 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1198 ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
1200 return CompatibleMethodFactory (return_type, delegate_type, p, b);
1204 protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
1206 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1209 protected override void CloneTo (CloneContext clonectx, Expression t)
1211 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1213 target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
1218 // Abstract expression for any block which requires variables hoisting
1220 public abstract class AnonymousExpression : Expression
1222 protected class AnonymousMethodMethod : Method
1224 public readonly AnonymousExpression AnonymousMethod;
1225 public readonly AnonymousMethodStorey Storey;
1226 readonly string RealName;
1228 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1229 GenericMethod generic, TypeExpr return_type,
1230 Modifiers mod, string real_name, MemberName name,
1231 ParametersCompiled parameters)
1232 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1233 name, parameters, null)
1235 this.AnonymousMethod = am;
1236 this.Storey = storey;
1237 this.RealName = real_name;
1239 Parent.PartialContainer.AddMethod (this);
1240 Block = new ToplevelBlock (am.block, parameters);
1243 public override EmitContext CreateEmitContext (ILGenerator ig)
1245 EmitContext ec = new EmitContext (this, ig, ReturnType);
1246 ec.CurrentAnonymousMethod = AnonymousMethod;
1247 if (AnonymousMethod.return_label != null) {
1248 ec.HasReturnLabel = true;
1249 ec.ReturnLabel = (Label) AnonymousMethod.return_label;
1255 protected override void DefineTypeParameters ()
1257 // Type parameters were cloned
1260 protected override bool ResolveMemberType ()
1262 if (!base.ResolveMemberType ())
1265 if (Storey != null && Storey.Mutator != null) {
1266 if (!parameters.IsEmpty) {
1267 var mutated = Storey.Mutator.Mutate (parameters.Types);
1268 if (mutated != parameters.Types)
1269 parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
1272 member_type = Storey.Mutator.Mutate (member_type);
1278 public override void Emit ()
1280 if (MethodBuilder == null) {
1287 public override void EmitExtraSymbolInfo (SourceMethod source)
1289 source.SetRealMethodName (RealName);
1293 protected ParametersBlock block;
1295 public TypeSpec ReturnType;
1297 object return_label;
1299 protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
1301 this.ReturnType = return_type;
1306 public abstract string ContainerType { get; }
1307 public abstract bool IsIterator { get; }
1308 public abstract AnonymousMethodStorey Storey { get; }
1310 public AnonymousExpression Compatible (ResolveContext ec)
1312 return Compatible (ec, this);
1315 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1320 // TODO: Implement clone
1321 BlockContext aec = new BlockContext (ec, block, ReturnType);
1322 aec.CurrentAnonymousMethod = ae;
1324 ResolveContext.Options flags = 0;
1326 var am = this as AnonymousMethodBody;
1328 if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
1329 am.ReturnTypeInference = new TypeInferenceContext ();
1332 if (ec.IsInProbingMode)
1333 flags |= ResolveContext.Options.ProbingMode;
1335 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
1336 flags |= ResolveContext.Options.FieldInitializerScope;
1338 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion))
1339 flags |= ResolveContext.Options.ExpressionTreeConversion;
1343 var errors = ec.Report.Errors;
1345 bool res = Block.Resolve (ec.CurrentBranching, aec, null);
1347 if (aec.HasReturnLabel)
1348 return_label = aec.ReturnLabel;
1350 if (am != null && am.ReturnTypeInference != null) {
1351 am.ReturnTypeInference.FixAllTypes (ec);
1352 ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
1353 am.ReturnTypeInference = null;
1356 if (res && errors != ec.Report.Errors)
1359 return res ? this : null;
1362 public void SetHasThisAccess ()
1364 ExplicitBlock b = block;
1366 if (b.HasCapturedThis)
1369 b.HasCapturedThis = true;
1370 b = b.Parent == null ? null : b.Parent.Explicit;
1371 } while (b != null);
1375 // The block that makes up the body for the anonymous method
1377 public ParametersBlock Block {
1385 public class AnonymousMethodBody : AnonymousExpression
1387 protected readonly ParametersCompiled parameters;
1388 AnonymousMethodStorey storey;
1390 AnonymousMethodMethod method;
1393 TypeInferenceContext return_inference;
1395 static int unique_id;
1397 public AnonymousMethodBody (ParametersCompiled parameters,
1398 ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
1400 : base (block, return_type, loc)
1402 this.type = delegate_type;
1403 this.parameters = parameters;
1408 public override string ContainerType {
1409 get { return "anonymous method"; }
1412 public override bool IsIterator {
1413 get { return false; }
1416 public TypeInferenceContext ReturnTypeInference {
1418 return return_inference;
1421 return_inference = value;
1425 public override AnonymousMethodStorey Storey {
1426 get { return storey; }
1431 public override Expression CreateExpressionTree (ResolveContext ec)
1433 ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1437 bool Define (ResolveContext ec)
1439 if (!Block.Resolved && Compatible (ec) == null)
1442 if (block_name == null) {
1443 MemberCore mc = (MemberCore) ec.MemberContext;
1444 block_name = mc.MemberName.Basename;
1451 // Creates a host for the anonymous method
1453 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1456 // Anonymous method body can be converted to
1458 // 1, an instance method in current scope when only `this' is hoisted
1459 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1460 // 3, an instance method in compiler generated storey when any hoisted variable exists
1463 Modifiers modifiers;
1464 if (Block.HasCapturedVariable || Block.HasCapturedThis) {
1465 storey = FindBestMethodStorey ();
1466 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1468 if (ec.CurrentAnonymousMethod != null)
1469 storey = ec.CurrentAnonymousMethod.Storey;
1471 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1474 TypeContainer parent = storey != null ? storey : ec.CurrentTypeDefinition.Parent.PartialContainer;
1476 MemberCore mc = ec.MemberContext as MemberCore;
1477 string name = CompilerGeneratedClass.MakeName (parent != storey ? block_name : null,
1478 "m", null, unique_id++);
1480 MemberName member_name;
1481 GenericMethod generic_method;
1482 if (storey == null && mc.MemberName.TypeArguments != null) {
1483 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1485 var hoisted_tparams = ec.CurrentTypeParameters;
1486 var type_params = new TypeParameter[hoisted_tparams.Length];
1487 for (int i = 0; i < type_params.Length; ++i) {
1488 type_params[i] = hoisted_tparams[i].CreateHoistedCopy (null, null);
1491 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name, type_params,
1492 new TypeExpression (ReturnType, Location), parameters);
1494 member_name = new MemberName (name, Location);
1495 generic_method = null;
1498 string real_name = String.Format (
1499 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1500 parameters.GetSignatureForError ());
1502 return new AnonymousMethodMethod (parent,
1503 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1504 real_name, member_name, parameters);
1507 protected override Expression DoResolve (ResolveContext ec)
1512 eclass = ExprClass.Value;
1516 public override void Emit (EmitContext ec)
1519 // Use same anonymous method implementation for scenarios where same
1520 // code is used from multiple blocks, e.g. field initializers
1522 if (method == null) {
1524 // Delay an anonymous method definition to avoid emitting unused code
1525 // for unreachable blocks or expression trees
1527 method = DoCreateMethodHost (ec);
1531 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1532 if (is_static && am_cache == null) {
1534 // Creates a field cache to store delegate instance if it's not generic
1536 if (!method.MemberName.IsGeneric) {
1537 TypeContainer parent = method.Parent.PartialContainer;
1538 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1539 var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
1541 am_cache = new Field (parent, new TypeExpression (cache_type, loc),
1542 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1543 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1545 parent.AddField (am_cache);
1547 // TODO: Implement caching of generated generic static methods
1551 // Some extra class is needed to capture variable generic type
1552 // arguments. Maybe we could re-use anonymous types, with a unique
1553 // anonymous method id, but they are quite heavy.
1555 // Consider : "() => typeof(T);"
1557 // We need something like
1558 // static class Wrap<Tn, Tm, DelegateType> {
1559 // public static DelegateType cache;
1562 // We then specialize local variable to capture all generic parameters
1563 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1568 Label l_initialized = ec.DefineLabel ();
1570 if (am_cache != null) {
1571 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1572 ec.Emit (OpCodes.Brtrue_S, l_initialized);
1576 // Load method delegate implementation
1580 ec.Emit (OpCodes.Ldnull);
1581 } else if (storey != null) {
1582 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1586 ec.Emit (OpCodes.Ldarg_0);
1589 var delegate_method = method.Spec;
1590 if (storey != null && storey.MemberName.IsGeneric) {
1591 TypeSpec t = storey.Instance.Type;
1594 // Mutate anonymous method instance type if we are in nested
1595 // hoisted generic anonymous method storey
1597 if (ec.CurrentAnonymousMethod != null &&
1598 ec.CurrentAnonymousMethod.Storey != null &&
1599 ec.CurrentAnonymousMethod.Storey.Mutator != null) {
1600 t = storey.Mutator.Mutate (t);
1603 ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
1605 if (delegate_method.IsGeneric)
1606 delegate_method = delegate_method.MakeGenericMethod (method.TypeParameters);
1608 ec.Emit (OpCodes.Ldftn, delegate_method);
1611 var constructor_method = Delegate.GetConstructor (ec.MemberContext.Compiler, ec.CurrentType, type);
1612 ec.Emit (OpCodes.Newobj, constructor_method);
1614 if (am_cache != null) {
1615 ec.Emit (OpCodes.Stsfld, am_cache.Spec);
1616 ec.MarkLabel (l_initialized);
1617 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1622 // Look for the best storey for this anonymous method
1624 AnonymousMethodStorey FindBestMethodStorey ()
1627 // Use the nearest parent block which has a storey
1629 for (Block b = Block.Parent; b != null; b = b.Parent) {
1630 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1638 public override string GetSignatureForError ()
1640 return TypeManager.CSharpName (type);
1643 public static void Reset ()
1650 // Anonymous type container
1652 public class AnonymousTypeClass : CompilerGeneratedClass
1654 // TODO: Merge with AnonymousTypeParameter
1655 public class GeneratedParameter : Parameter
1657 public GeneratedParameter (FullNamedExpression type, AnonymousTypeParameter p)
1658 : base (type, p.Name, Modifier.NONE, null, p.Location)
1663 static int types_counter;
1664 public const string ClassNamePrefix = "<>__AnonType";
1665 public const string SignatureForError = "anonymous type";
1667 readonly IList<AnonymousTypeParameter> parameters;
1669 private AnonymousTypeClass (DeclSpace parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
1670 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1672 this.parameters = parameters;
1675 public static AnonymousTypeClass Create (CompilerContext ctx, TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
1677 string name = ClassNamePrefix + types_counter++;
1679 ParametersCompiled all_parameters;
1680 TypeParameterName[] t_params;
1681 SimpleName[] t_args;
1683 if (parameters.Count == 0) {
1684 all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
1685 t_params = new TypeParameterName[0];
1688 t_args = new SimpleName[parameters.Count];
1689 t_params = new TypeParameterName[parameters.Count];
1690 Parameter[] ctor_params = new Parameter[parameters.Count];
1691 for (int i = 0; i < parameters.Count; ++i) {
1692 AnonymousTypeParameter p = parameters[i];
1694 t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1695 t_params[i] = new TypeParameterName (t_args[i].Name, null, p.Location);
1696 ctor_params[i] = new GeneratedParameter (t_args[i], p);
1699 all_parameters = new ParametersCompiled (ctor_params);
1703 // Create generic anonymous type host with generic arguments
1704 // named upon properties names
1706 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1707 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1709 if (parameters.Count > 0)
1710 a_type.SetParameterInfo (null);
1712 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1713 null, all_parameters, null, loc);
1714 c.Block = new ToplevelBlock (ctx, c.ParameterInfo, loc);
1717 // Create fields and contructor body with field initialization
1720 for (int i = 0; i < parameters.Count; ++i) {
1721 AnonymousTypeParameter p = parameters [i];
1723 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1724 new MemberName ("<" + p.Name + ">", p.Location), null);
1726 if (!a_type.AddField (f)) {
1731 c.Block.AddStatement (new StatementExpression (
1732 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1733 c.Block.GetParameterReference (i, p.Location))));
1735 ToplevelBlock get_block = new ToplevelBlock (ctx, p.Location);
1736 get_block.AddStatement (new Return (
1737 new MemberAccess (new This (p.Location), f.Name), p.Location));
1739 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1740 new MemberName (p.Name, p.Location), null);
1741 prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
1742 prop.Get.Block = get_block;
1743 a_type.AddProperty (prop);
1749 a_type.AddConstructor (c);
1753 public static void Reset ()
1758 protected override bool AddToContainer (MemberCore symbol, string name)
1760 MemberCore mc = GetDefinition (name);
1763 defined_names.Add (name, symbol);
1767 // A conflict between anonymous type members will be reported
1768 if (symbol is TypeParameter) {
1769 Report.SymbolRelatedToPreviousError (symbol);
1773 // Ignore other conflicts
1777 protected override bool DoDefineMembers ()
1779 if (!base.DoDefineMembers ())
1782 Location loc = Location;
1784 var equals_parameters = ParametersCompiled.CreateFullyResolved (
1785 new Parameter (new TypeExpression (TypeManager.object_type, loc), "obj", 0, null, loc), TypeManager.object_type);
1787 Method equals = new Method (this, null, new TypeExpression (TypeManager.bool_type, loc),
1788 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1789 equals_parameters, null);
1791 equals_parameters[0].Resolve (equals, 0);
1793 Method tostring = new Method (this, null, new TypeExpression (TypeManager.string_type, loc),
1794 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1795 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1797 ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
1799 TypeExpr current_type;
1800 if (type_params != null) {
1801 var targs = new TypeArguments ();
1802 foreach (var type_param in type_params)
1803 targs.Add (new TypeParameterExpr (type_param, type_param.Location));
1805 current_type = new GenericTypeExpr (Definition, targs, loc);
1807 current_type = new TypeExpression (Definition, loc);
1810 var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
1811 equals_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_other.Type, loc), li_other));
1812 var other_variable = new LocalVariableReference (li_other, loc);
1814 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1815 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1817 Expression rs_equals = null;
1818 Expression string_concat = new StringConstant ("{", loc);
1819 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1820 for (int i = 0; i < parameters.Count; ++i) {
1821 var p = parameters [i];
1824 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1825 system_collections_generic, "EqualityComparer",
1826 new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
1829 Arguments arguments_equal = new Arguments (2);
1830 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1831 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1833 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1834 "Equals", loc), arguments_equal);
1836 Arguments arguments_hashcode = new Arguments (1);
1837 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1838 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1839 "GetHashCode", loc), arguments_hashcode);
1841 IntConstant FNV_prime = new IntConstant (16777619, loc);
1842 rs_hashcode = new Binary (Binary.Operator.Multiply,
1843 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode, loc),
1846 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
1847 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc), loc)),
1848 new Invocation (new MemberAccess (
1849 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1850 new StringConstant (string.Empty, loc), loc);
1852 if (rs_equals == null) {
1853 rs_equals = field_equal;
1854 string_concat = new Binary (Binary.Operator.Addition,
1856 new Binary (Binary.Operator.Addition,
1857 new StringConstant (" " + p.Name + " = ", loc),
1865 // Implementation of ToString () body using string concatenation
1867 string_concat = new Binary (Binary.Operator.Addition,
1868 new Binary (Binary.Operator.Addition,
1870 new StringConstant (", " + p.Name + " = ", loc),
1875 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal, loc);
1878 string_concat = new Binary (Binary.Operator.Addition,
1880 new StringConstant (" }", loc),
1884 // Equals (object obj) override
1886 var other_variable_assign = new TemporaryVariableReference (li_other, loc);
1887 equals_block.AddStatement (new StatementExpression (
1888 new SimpleAssign (other_variable_assign,
1889 new As (equals_block.GetParameterReference (0, loc),
1890 current_type, loc), loc)));
1892 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc), loc);
1893 if (rs_equals != null)
1894 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals, loc);
1895 equals_block.AddStatement (new Return (equals_test, loc));
1897 equals.Block = equals_block;
1902 // GetHashCode () override
1904 Method hashcode = new Method (this, null, new TypeExpression (TypeManager.int32_type, loc),
1905 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1906 new MemberName ("GetHashCode", loc),
1907 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1910 // Modified FNV with good avalanche behavior and uniform
1911 // distribution with larger hash sizes.
1913 // const int FNV_prime = 16777619;
1914 // int hash = (int) 2166136261;
1915 // foreach (int d in data)
1916 // hash = (hash ^ d) * FNV_prime;
1917 // hash += hash << 13;
1918 // hash ^= hash >> 7;
1919 // hash += hash << 3;
1920 // hash ^= hash >> 17;
1921 // hash += hash << 5;
1923 ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
1924 Block hashcode_block = new Block (hashcode_top, loc, loc);
1925 hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
1927 var li_hash = LocalVariable.CreateCompilerGenerated (TypeManager.int32_type, hashcode_top, loc);
1928 hashcode_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_hash.Type, loc), li_hash));
1929 LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
1930 hashcode_block.AddStatement (new StatementExpression (
1931 new SimpleAssign (hash_variable_assign, rs_hashcode)));
1933 var hash_variable = new LocalVariableReference (li_hash, loc);
1934 hashcode_block.AddStatement (new StatementExpression (
1935 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1936 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc), loc), loc)));
1937 hashcode_block.AddStatement (new StatementExpression (
1938 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1939 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc), loc), loc)));
1940 hashcode_block.AddStatement (new StatementExpression (
1941 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1942 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc), loc), loc)));
1943 hashcode_block.AddStatement (new StatementExpression (
1944 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1945 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc), loc), loc)));
1946 hashcode_block.AddStatement (new StatementExpression (
1947 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1948 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc), loc), loc)));
1950 hashcode_block.AddStatement (new Return (hash_variable, loc));
1951 hashcode.Block = hashcode_top;
1953 AddMethod (hashcode);
1956 // ToString () override
1959 ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
1960 tostring_block.AddStatement (new Return (string_concat, loc));
1961 tostring.Block = tostring_block;
1963 AddMethod (tostring);
1968 public override string GetSignatureForError ()
1970 return SignatureForError;
1973 public IList<AnonymousTypeParameter> Parameters {