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 for (int i = 0; i < type_params.Length; ++i) {
84 type_params[i] = tparams[i].CreateHoistedCopy (this, spec);
91 public TypeParameterMutator Mutator {
102 public HoistedStoreyClass GetGenericStorey ()
104 DeclSpace storey = this;
105 while (storey != null && storey.CurrentTypeParameters == null)
106 storey = storey.Parent;
108 return storey as HoistedStoreyClass;
114 // Anonymous method storey is created when an anonymous method uses
115 // variable or parameter from outer scope. They are then hoisted to
116 // anonymous method storey (captured)
118 public class AnonymousMethodStorey : HoistedStoreyClass
120 struct StoreyFieldPair
122 public readonly AnonymousMethodStorey Storey;
123 public readonly Field Field;
125 public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
127 this.Storey = storey;
133 // Needed to delay hoisted _this_ initialization. When an anonymous
134 // method is used inside ctor and _this_ is hoisted, base ctor has to
135 // be called first, otherwise _this_ will be initialized with
136 // uninitialized value.
138 sealed class ThisInitializer : Statement
140 readonly HoistedThis hoisted_this;
142 public ThisInitializer (HoistedThis hoisted_this)
144 this.hoisted_this = hoisted_this;
147 protected override void DoEmit (EmitContext ec)
149 hoisted_this.EmitHoistingAssignment (ec);
152 protected override void CloneTo (CloneContext clonectx, Statement target)
159 public readonly int ID;
160 static int unique_id;
162 public readonly Block OriginalSourceBlock;
164 // A list of StoreyFieldPair with local field keeping parent storey instance
165 List<StoreyFieldPair> used_parent_storeys;
166 List<ExplicitBlock> children_references;
168 // A list of hoisted parameters
169 protected List<HoistedParameter> hoisted_params;
170 protected List<HoistedVariable> hoisted_locals;
173 protected HoistedThis hoisted_this;
175 // Local variable which holds this storey instance
176 public LocalTemporary Instance;
178 public AnonymousMethodStorey (Block block, TypeContainer parent, MemberBase host, TypeParameter[] tparams, string name)
179 : base (parent, MakeMemberName (host, name, unique_id, tparams, block.StartLocation),
180 tparams, Modifiers.SEALED)
183 OriginalSourceBlock = block;
187 public void AddCapturedThisField (EmitContext ec)
189 TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
190 Field f = AddCompilerGeneratedField ("<>f__this", type_expr);
192 hoisted_this = new HoistedThis (this, f);
194 // Inflated type instance has to be updated manually
195 if (Instance.Type is InflatedTypeSpec) {
196 var inflator = new TypeParameterInflator (Instance.Type, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
197 Instance.Type.MemberCache.AddMember (f.Spec.InflateMember (inflator));
199 inflator = new TypeParameterInflator (f.Parent.CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
200 f.Parent.CurrentType.MemberCache.AddMember (f.Spec.InflateMember (inflator));
204 public Field AddCapturedVariable (string name, TypeSpec type)
206 CheckMembersDefined ();
208 FullNamedExpression field_type = new TypeExpression (type, Location);
210 return AddCompilerGeneratedField (name, field_type);
212 const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
213 Field f = new HoistedField (this, field_type, mod, name, null, Location);
218 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
220 const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
221 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
227 // Creates a link between hoisted variable block and the anonymous method storey
229 // An anonymous method can reference variables from any outer block, but they are
230 // hoisted in their own ExplicitBlock. When more than one block is referenced we
231 // need to create another link between those variable storeys
233 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
235 if (children_references == null)
236 children_references = new List<ExplicitBlock> ();
238 if (!children_references.Contains (block))
239 children_references.Add (block);
242 public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
244 CheckMembersDefined ();
246 if (used_parent_storeys == null)
247 used_parent_storeys = new List<StoreyFieldPair> ();
248 else if (used_parent_storeys.Exists (i => i.Storey == storey))
251 TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
252 Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
253 used_parent_storeys.Add (new StoreyFieldPair (storey, f));
256 public void CaptureLocalVariable (ResolveContext ec, LocalVariable local_info)
258 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
259 if (ec.CurrentBlock.Explicit != local_info.Block.Explicit)
260 AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
262 if (local_info.HoistedVariant != null)
265 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
266 local_info.HoistedVariant = var;
268 if (hoisted_locals == null)
269 hoisted_locals = new List<HoistedVariable> ();
271 hoisted_locals.Add (var);
274 public void CaptureParameter (ResolveContext ec, ParameterReference param_ref)
276 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
277 AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
279 if (param_ref.GetHoistedVariable (ec) != null)
282 if (hoisted_params == null)
283 hoisted_params = new List<HoistedParameter> (2);
285 var expr = new HoistedParameter (this, param_ref);
286 param_ref.Parameter.HoistedVariant = expr;
287 hoisted_params.Add (expr);
290 TypeExpr CreateStoreyTypeExpression (EmitContext ec)
293 // Create an instance of storey type
295 TypeExpr storey_type_expr;
296 if (CurrentTypeParameters != null) {
298 // Use current method type parameter (MVAR) for top level storey only. All
299 // nested storeys use class type parameter (VAR)
301 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
302 ec.CurrentAnonymousMethod.Storey.TypeParameters :
303 ec.CurrentTypeParameters;
305 TypeArguments targs = new TypeArguments ();
308 // Use type parameter name instead of resolved type parameter
309 // specification to resolve to correctly nested type parameters
311 for (int i = 0; i < tparams.Length; ++i)
312 targs.Add (new SimpleName (tparams [i].Name, Location)); // new TypeParameterExpr (tparams[i], Location));
314 storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
316 storey_type_expr = new TypeExpression (CurrentType, Location);
319 return storey_type_expr;
322 public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
324 Parent = parentStorey;
326 spec.IsGeneric = false;
327 spec.DeclaringType = parentStorey.CurrentType;
328 MemberName.TypeArguments = null;
331 protected override bool DoResolveTypeParameters ()
333 // Although any storey can have type parameters they are all clones of method type
334 // parameters therefore have to mutate MVAR references in any of cloned constraints
335 if (type_params != null) {
336 for (int i = 0; i < type_params.Length; ++i) {
337 var spec = type_params[i].Type;
338 spec.BaseType = mutator.Mutate (spec.BaseType);
339 if (spec.InterfacesDefined != null) {
340 var mutated = new TypeSpec[spec.InterfacesDefined.Length];
341 for (int ii = 0; ii < mutated.Length; ++ii) {
342 mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
345 spec.InterfacesDefined = mutated;
348 if (spec.TypeArguments != null) {
349 spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
358 // Initializes all hoisted variables
360 public void EmitStoreyInstantiation (EmitContext ec)
362 // There can be only one instance variable for each storey type
363 if (Instance != null)
364 throw new InternalErrorException ();
366 SymbolWriter.OpenCompilerGeneratedBlock (ec);
369 // Create an instance of a storey
371 var storey_type_expr = CreateStoreyTypeExpression (ec);
373 ResolveContext rc = new ResolveContext (ec.MemberContext);
374 Expression e = new New (storey_type_expr, null, Location).Resolve (rc);
377 Instance = new LocalTemporary (storey_type_expr.Type);
380 EmitHoistedFieldsInitialization (ec);
382 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
383 SymbolWriter.CloseCompilerGeneratedBlock (ec);
386 void EmitHoistedFieldsInitialization (EmitContext ec)
389 // Initialize all storey reference fields by using local or hoisted variables
391 if (used_parent_storeys != null) {
392 var rc = new ResolveContext (ec.MemberContext);
394 foreach (StoreyFieldPair sf in used_parent_storeys) {
396 // Get instance expression of storey field
398 Expression instace_expr = GetStoreyInstanceExpression (ec);
399 var fs = sf.Field.Spec;
400 if (TypeManager.IsGenericType (instace_expr.Type))
401 fs = MemberCache.GetMember (instace_expr.Type, fs);
403 FieldExpr f_set_expr = new FieldExpr (fs, Location);
404 f_set_expr.InstanceExpression = instace_expr;
406 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
407 if (a.Resolve (rc) != null)
408 a.EmitStatement (ec);
413 // Define hoisted `this' in top-level storey only
415 if (OriginalSourceBlock.Explicit.HasCapturedThis && !(Parent is AnonymousMethodStorey)) {
416 AddCapturedThisField (ec);
417 OriginalSourceBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
421 // Setting currect anonymous method to null blocks any further variable hoisting
423 AnonymousExpression ae = ec.CurrentAnonymousMethod;
424 ec.CurrentAnonymousMethod = null;
426 if (hoisted_params != null) {
427 EmitHoistedParameters (ec, hoisted_params);
430 ec.CurrentAnonymousMethod = ae;
433 protected virtual void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
435 foreach (HoistedParameter hp in hoisted) {
436 hp.EmitHoistingAssignment (ec);
440 public override void EmitType ()
442 SymbolWriter.DefineAnonymousScope (ID);
444 if (hoisted_this != null)
445 hoisted_this.EmitSymbolInfo ();
447 if (hoisted_locals != null) {
448 foreach (HoistedVariable local in hoisted_locals)
449 local.EmitSymbolInfo ();
452 if (hoisted_params != null) {
453 foreach (HoistedParameter param in hoisted_params)
454 param.EmitSymbolInfo ();
457 if (used_parent_storeys != null) {
458 foreach (StoreyFieldPair sf in used_parent_storeys) {
459 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
467 // Returns a field which holds referenced storey instance
469 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
471 if (used_parent_storeys == null)
474 foreach (StoreyFieldPair sf in used_parent_storeys) {
475 if (sf.Storey == storey)
483 // Creates storey instance expression regardless of currect IP
485 public Expression GetStoreyInstanceExpression (EmitContext ec)
487 AnonymousExpression am = ec.CurrentAnonymousMethod;
490 // Access from original block -> storey
496 // Access from anonymous method implemented as a static -> storey
498 if (am.Storey == null)
501 Field f = am.Storey.GetReferencedStoreyField (this);
503 if (am.Storey == this) {
505 // Access inside of same storey (S -> S)
507 return new CompilerGeneratedThis (CurrentType, Location);
510 // External field access
516 // Storey was cached to local field
518 FieldExpr f_ind = new FieldExpr (f, Location);
519 f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
523 protected virtual string GetVariableMangledName (LocalVariable local_info)
526 // No need to mangle anonymous method hoisted variables cause they
527 // are hoisted in their own scopes
529 return local_info.Name;
532 public HoistedThis HoistedThis {
533 get { return hoisted_this; }
536 public IList<ExplicitBlock> ReferencesFromChildrenBlock {
537 get { return children_references; }
540 public static void Reset ()
546 public abstract class HoistedVariable
549 // Hoisted version of variable references used in expression
550 // tree has to be delayed until we know its location. The variable
551 // doesn't know its location until all stories are calculated
553 class ExpressionTreeVariableReference : Expression
555 readonly HoistedVariable hv;
557 public ExpressionTreeVariableReference (HoistedVariable hv)
562 public override Expression CreateExpressionTree (ResolveContext ec)
564 throw new NotSupportedException ("ET");
567 protected override Expression DoResolve (ResolveContext ec)
569 eclass = ExprClass.Value;
570 type = TypeManager.expression_type_expr.Type;
574 public override void Emit (EmitContext ec)
576 ResolveContext rc = new ResolveContext (ec.MemberContext);
577 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc);
578 // This should never fail
585 protected readonly AnonymousMethodStorey storey;
586 protected Field field;
587 Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
588 FieldExpr cached_outer_access;
590 protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
591 : this (storey, storey.AddCapturedVariable (name, type))
595 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
597 this.storey = storey;
601 public void AddressOf (EmitContext ec, AddressOp mode)
603 GetFieldExpression (ec).AddressOf (ec, mode);
606 public Expression CreateExpressionTree ()
608 return new ExpressionTreeVariableReference (this);
611 public void Emit (EmitContext ec)
613 GetFieldExpression (ec).Emit (ec);
617 // Creates field access expression for hoisted variable
619 protected virtual FieldExpr GetFieldExpression (EmitContext ec)
621 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
622 if (cached_outer_access != null)
623 return cached_outer_access;
626 // When setting top-level hoisted variable in generic storey
627 // change storey generic types to method generic types (VAR -> MVAR)
629 if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
630 var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
631 cached_outer_access = new FieldExpr (fs, field.Location);
633 cached_outer_access = new FieldExpr (field, field.Location);
636 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
637 return cached_outer_access;
640 FieldExpr inner_access;
641 if (cached_inner_access != null) {
642 if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
646 cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
649 if (inner_access == null) {
650 if (field.Parent.IsGeneric) {
651 var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
652 inner_access = new FieldExpr (fs, field.Location);
654 inner_access = new FieldExpr (field, field.Location);
657 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
658 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
664 public abstract void EmitSymbolInfo ();
666 public void Emit (EmitContext ec, bool leave_copy)
668 GetFieldExpression (ec).Emit (ec, leave_copy);
671 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
673 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
677 public class HoistedParameter : HoistedVariable
679 sealed class HoistedFieldAssign : Assign
681 public HoistedFieldAssign (Expression target, Expression source)
682 : base (target, source, source.Location)
686 protected override Expression ResolveConversions (ResolveContext ec)
689 // Implicit conversion check fails for hoisted type arguments
690 // as they are of different types (!!0 x !0)
696 readonly ParameterReference parameter;
698 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
699 : base (scope, par.Name, par.Type)
701 this.parameter = par;
704 public HoistedParameter (HoistedParameter hp, string name)
705 : base (hp.storey, name, hp.parameter.Type)
707 this.parameter = hp.parameter;
710 public void EmitHoistingAssignment (EmitContext ec)
713 // Remove hoisted redirection to emit assignment from original parameter
715 HoistedVariable temp = parameter.Parameter.HoistedVariant;
716 parameter.Parameter.HoistedVariant = null;
718 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
719 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
720 a.EmitStatement (ec);
722 parameter.Parameter.HoistedVariant = temp;
725 public override void EmitSymbolInfo ()
727 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
731 get { return field; }
735 class HoistedLocalVariable : HoistedVariable
737 readonly string name;
739 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalVariable local, string name)
740 : base (scope, name, local.Type)
742 this.name = local.Name;
745 public override void EmitSymbolInfo ()
747 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
751 public class HoistedThis : HoistedVariable
753 public HoistedThis (AnonymousMethodStorey storey, Field field)
754 : base (storey, field)
758 public void EmitHoistingAssignment (EmitContext ec)
760 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), new CompilerGeneratedThis (ec.CurrentType, field.Location));
761 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
762 a.EmitStatement (ec);
765 public override void EmitSymbolInfo ()
767 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
771 get { return field; }
776 // Anonymous method expression as created by parser
778 public class AnonymousMethodExpression : Expression
781 // Special conversion for nested expression tree lambdas
783 class Quote : ShimExpression
785 public Quote (Expression expr)
790 public override Expression CreateExpressionTree (ResolveContext ec)
792 var args = new Arguments (1);
793 args.Add (new Argument (expr.CreateExpressionTree (ec)));
794 return CreateExpressionFactoryCall (ec, "Quote", args);
797 protected override Expression DoResolve (ResolveContext rc)
799 expr = expr.Resolve (rc);
803 eclass = expr.eclass;
809 Dictionary<TypeSpec, Expression> compatibles;
810 public ParametersBlock Block;
812 public AnonymousMethodExpression (Location loc)
815 this.compatibles = new Dictionary<TypeSpec, Expression> ();
818 public override string ExprClassName {
820 return "anonymous method";
824 public virtual bool HasExplicitParameters {
826 return Parameters != ParametersCompiled.Undefined;
830 public ParametersCompiled Parameters {
831 get { return Block.Parameters; }
835 // Returns true if the body of lambda expression can be implicitly
836 // converted to the delegate of type `delegate_type'
838 public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
840 using (ec.With (ResolveContext.Options.InferReturnType, false)) {
841 using (ec.Set (ResolveContext.Options.ProbingMode)) {
842 return Compatible (ec, delegate_type) != null;
847 TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
849 if (delegate_type.IsDelegate)
850 return delegate_type;
852 if (delegate_type.IsGeneric && delegate_type.GetDefinition () == TypeManager.expression_type) {
853 delegate_type = delegate_type.TypeArguments [0];
854 if (delegate_type.IsDelegate)
855 return delegate_type;
857 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
858 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
862 ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
863 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
867 protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
869 if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
872 if (!ec.IsInProbingMode)
873 ec.Report.Error (1661, loc,
874 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
875 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
880 protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
882 if (Parameters.Count != invoke_pd.Count) {
886 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
887 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
891 bool has_implicit_parameters = !HasExplicitParameters;
894 for (int i = 0; i < Parameters.Count; ++i) {
895 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
896 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
900 if (p_mod == Parameter.Modifier.NONE)
901 ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
902 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
904 ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
905 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
909 if (has_implicit_parameters)
912 TypeSpec type = invoke_pd.Types [i];
914 // We assume that generic parameters are always inflated
915 if (TypeManager.IsGenericParameter (type))
918 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
921 if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
925 ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
927 TypeManager.CSharpName (Parameters.Types [i]),
928 TypeManager.CSharpName (invoke_pd.Types [i]));
937 // Infers type arguments based on explicit arguments
939 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
941 if (!HasExplicitParameters)
944 if (!delegate_type.IsDelegate) {
945 if (delegate_type.GetDefinition () != TypeManager.expression_type)
948 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
949 if (!delegate_type.IsDelegate)
953 AParametersCollection d_params = Delegate.GetParameters (ec.Compiler, delegate_type);
954 if (d_params.Count != Parameters.Count)
957 for (int i = 0; i < Parameters.Count; ++i) {
958 TypeSpec itype = d_params.Types [i];
959 if (!TypeManager.IsGenericParameter (itype)) {
960 if (!TypeManager.HasElementType (itype))
963 if (!TypeManager.IsGenericParameter (TypeManager.GetElementType (itype)))
966 type_inference.ExactInference (Parameters.Types [i], itype);
971 public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
974 AnonymousExpression am;
976 if (compatibles.TryGetValue (delegate_type, out expr)) {
977 am = expr as AnonymousExpression;
978 return am == null ? null : am.ReturnType;
981 using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
982 am = CompatibleMethodBody (ec, tic, InternalType.Arglist, delegate_type);
984 am = am.Compatible (ec);
990 // compatibles.Add (delegate_type, am);
991 return am.ReturnType;
995 // Returns AnonymousMethod container if this anonymous method
996 // expression can be implicitly converted to the delegate type `delegate_type'
998 public Expression Compatible (ResolveContext ec, TypeSpec type)
1001 if (compatibles.TryGetValue (type, out am))
1004 TypeSpec delegate_type = CompatibleChecks (ec, type);
1005 if (delegate_type == null)
1009 // At this point its the first time we know the return type that is
1010 // needed for the anonymous method. We create the method here.
1013 var invoke_mb = Delegate.GetInvokeMethod (ec.Compiler, delegate_type);
1014 TypeSpec return_type = invoke_mb.ReturnType;
1017 // Second: the return type of the delegate must be compatible with
1018 // the anonymous type. Instead of doing a pass to examine the block
1019 // we satisfy the rule by setting the return type on the EmitContext
1020 // to be the delegate type return type.
1023 var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1027 bool etree_conversion = delegate_type != type;
1030 if (etree_conversion) {
1031 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1033 // Nested expression tree lambda use same scope as parent
1034 // lambda, this also means no variable capturing between this
1037 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1040 // Quote nested expression tree
1043 am = new Quote (am);
1045 int errors = ec.Report.Errors;
1047 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1048 am = body.Compatible (ec);
1052 // Rewrite expressions into expression tree when targeting Expression<T>
1054 if (am != null && errors == ec.Report.Errors)
1055 am = CreateExpressionTree (ec, delegate_type);
1058 am = body.Compatible (ec);
1060 } catch (CompletionResult) {
1062 } catch (Exception e) {
1063 throw new InternalErrorException (e, loc);
1066 if (!ec.IsInProbingMode) {
1067 compatibles.Add (type, am ?? EmptyExpression.Null);
1073 protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
1075 return CreateExpressionTree (ec);
1078 public override Expression CreateExpressionTree (ResolveContext ec)
1080 ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1084 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1086 var delegate_parameters = Delegate.GetParameters (ec.Compiler, delegate_type);
1088 if (Parameters == ParametersCompiled.Undefined) {
1090 // We provide a set of inaccessible parameters
1092 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1094 for (int i = 0; i < delegate_parameters.Count; i++) {
1095 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1096 if (i_mod == Parameter.Modifier.OUT) {
1097 if (!ec.IsInProbingMode) {
1098 ec.Report.Error (1688, loc,
1099 "Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
1100 delegate_type.GetSignatureForError ());
1105 fixedpars[i] = new Parameter (
1106 new TypeExpression (delegate_parameters.Types [i], loc), null,
1107 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1110 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1113 if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1120 protected override Expression DoResolve (ResolveContext ec)
1122 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1123 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1128 // Set class type, set type
1131 eclass = ExprClass.Value;
1134 // This hack means `The type is not accessible
1135 // anywhere', we depend on special conversion
1138 type = InternalType.AnonymousMethod;
1140 if (!DoResolveParameters (ec))
1143 // FIXME: The emitted code isn't very careful about reachability
1144 // so, ensure we have a 'ret' at the end
1145 BlockContext bc = ec as BlockContext;
1146 if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1147 bc.NeedReturnLabel ();
1152 protected virtual bool DoResolveParameters (ResolveContext rc)
1154 return Parameters.Resolve (rc);
1157 public override void Emit (EmitContext ec)
1159 // nothing, as we only exist to not do anything.
1162 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1164 ec.Report.Error (1686, loc,
1165 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1169 public override string GetSignatureForError ()
1171 return ExprClassName;
1174 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
1176 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1180 ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
1182 return CompatibleMethodFactory (return_type, delegate_type, p, b);
1186 protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
1188 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1191 protected override void CloneTo (CloneContext clonectx, Expression t)
1193 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1195 target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
1200 // Abstract expression for any block which requires variables hoisting
1202 public abstract class AnonymousExpression : Expression
1204 protected class AnonymousMethodMethod : Method
1206 public readonly AnonymousExpression AnonymousMethod;
1207 public readonly AnonymousMethodStorey Storey;
1208 readonly string RealName;
1210 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1211 GenericMethod generic, TypeExpr return_type,
1212 Modifiers mod, string real_name, MemberName name,
1213 ParametersCompiled parameters)
1214 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1215 name, parameters, null)
1217 this.AnonymousMethod = am;
1218 this.Storey = storey;
1219 this.RealName = real_name;
1221 Parent.PartialContainer.AddMethod (this);
1222 Block = new ToplevelBlock (am.block, parameters);
1225 public override EmitContext CreateEmitContext (ILGenerator ig)
1227 EmitContext ec = new EmitContext (this, ig, ReturnType);
1228 ec.CurrentAnonymousMethod = AnonymousMethod;
1229 if (AnonymousMethod.return_label != null) {
1230 ec.HasReturnLabel = true;
1231 ec.ReturnLabel = (Label) AnonymousMethod.return_label;
1237 protected override void DefineTypeParameters ()
1239 // Type parameters were cloned
1242 protected override bool ResolveMemberType ()
1244 if (!base.ResolveMemberType ())
1247 if (Storey != null && Storey.Mutator != null) {
1248 if (!parameters.IsEmpty) {
1249 var mutated = Storey.Mutator.Mutate (parameters.Types);
1250 if (mutated != parameters.Types)
1251 parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
1254 member_type = Storey.Mutator.Mutate (member_type);
1260 public override void Emit ()
1262 if (MethodBuilder == null) {
1269 public override void EmitExtraSymbolInfo (SourceMethod source)
1271 source.SetRealMethodName (RealName);
1275 protected ParametersBlock block;
1277 public TypeSpec ReturnType;
1279 object return_label;
1281 protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
1283 this.ReturnType = return_type;
1288 public abstract string ContainerType { get; }
1289 public abstract bool IsIterator { get; }
1290 public abstract AnonymousMethodStorey Storey { get; }
1292 public AnonymousExpression Compatible (ResolveContext ec)
1294 return Compatible (ec, this);
1297 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1302 // TODO: Implement clone
1303 BlockContext aec = new BlockContext (ec, block, ReturnType);
1304 aec.CurrentAnonymousMethod = ae;
1306 ResolveContext.FlagsHandle? aec_dispose = null;
1307 ResolveContext.Options flags = 0;
1309 var am = this as AnonymousMethodBody;
1311 if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
1312 am.ReturnTypeInference = new TypeInferenceContext ();
1315 if (ec.IsInProbingMode)
1316 flags |= ResolveContext.Options.ProbingMode;
1318 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
1319 flags |= ResolveContext.Options.FieldInitializerScope;
1321 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion))
1322 flags |= ResolveContext.Options.ExpressionTreeConversion;
1324 // HACK: Flag with 0 cannot be set
1326 aec_dispose = aec.Set (flags);
1328 var errors = ec.Report.Errors;
1330 bool res = Block.Resolve (ec.CurrentBranching, aec, null);
1332 if (aec.HasReturnLabel)
1333 return_label = aec.ReturnLabel;
1335 if (am != null && am.ReturnTypeInference != null) {
1336 am.ReturnTypeInference.FixAllTypes (ec);
1337 ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
1338 am.ReturnTypeInference = null;
1341 if (aec_dispose != null) {
1342 aec_dispose.Value.Dispose ();
1345 if (res && errors != ec.Report.Errors)
1348 return res ? this : null;
1351 public void SetHasThisAccess ()
1353 ExplicitBlock b = block;
1355 if (b.HasCapturedThis)
1358 b.HasCapturedThis = true;
1359 b = b.Parent == null ? null : b.Parent.Explicit;
1360 } while (b != null);
1364 // The block that makes up the body for the anonymous method
1366 public ParametersBlock Block {
1374 public class AnonymousMethodBody : AnonymousExpression
1376 protected readonly ParametersCompiled parameters;
1377 AnonymousMethodStorey storey;
1379 AnonymousMethodMethod method;
1382 TypeInferenceContext return_inference;
1384 static int unique_id;
1386 public AnonymousMethodBody (ParametersCompiled parameters,
1387 ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
1389 : base (block, return_type, loc)
1391 this.type = delegate_type;
1392 this.parameters = parameters;
1397 public override string ContainerType {
1398 get { return "anonymous method"; }
1401 public override bool IsIterator {
1402 get { return false; }
1405 public TypeInferenceContext ReturnTypeInference {
1407 return return_inference;
1410 return_inference = value;
1414 public override AnonymousMethodStorey Storey {
1415 get { return storey; }
1420 public override Expression CreateExpressionTree (ResolveContext ec)
1422 ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1426 bool Define (ResolveContext ec)
1428 if (!Block.Resolved && Compatible (ec) == null)
1431 if (block_name == null) {
1432 MemberCore mc = (MemberCore) ec.MemberContext;
1433 block_name = mc.MemberName.Basename;
1440 // Creates a host for the anonymous method
1442 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1445 // Anonymous method body can be converted to
1447 // 1, an instance method in current scope when only `this' is hoisted
1448 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1449 // 3, an instance method in compiler generated storey when any hoisted variable exists
1452 Modifiers modifiers;
1453 if (Block.HasCapturedVariable || Block.HasCapturedThis) {
1454 storey = FindBestMethodStorey ();
1455 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1457 if (ec.CurrentAnonymousMethod != null)
1458 storey = ec.CurrentAnonymousMethod.Storey;
1460 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1463 TypeContainer parent = storey != null ? storey : ec.CurrentTypeDefinition.Parent.PartialContainer;
1465 MemberCore mc = ec.MemberContext as MemberCore;
1466 string name = CompilerGeneratedClass.MakeName (parent != storey ? block_name : null,
1467 "m", null, unique_id++);
1469 MemberName member_name;
1470 GenericMethod generic_method;
1471 if (storey == null && mc.MemberName.TypeArguments != null) {
1472 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1474 var hoisted_tparams = ec.CurrentTypeParameters;
1475 var type_params = new TypeParameter[hoisted_tparams.Length];
1476 for (int i = 0; i < type_params.Length; ++i) {
1477 type_params[i] = hoisted_tparams[i].CreateHoistedCopy (null, null);
1480 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name, type_params,
1481 new TypeExpression (ReturnType, Location), parameters);
1483 member_name = new MemberName (name, Location);
1484 generic_method = null;
1487 string real_name = String.Format (
1488 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1489 parameters.GetSignatureForError ());
1491 return new AnonymousMethodMethod (parent,
1492 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1493 real_name, member_name, parameters);
1496 protected override Expression DoResolve (ResolveContext ec)
1501 eclass = ExprClass.Value;
1505 public override void Emit (EmitContext ec)
1508 // Use same anonymous method implementation for scenarios where same
1509 // code is used from multiple blocks, e.g. field initializers
1511 if (method == null) {
1513 // Delay an anonymous method definition to avoid emitting unused code
1514 // for unreachable blocks or expression trees
1516 method = DoCreateMethodHost (ec);
1520 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1521 if (is_static && am_cache == null) {
1523 // Creates a field cache to store delegate instance if it's not generic
1525 if (!method.MemberName.IsGeneric) {
1526 TypeContainer parent = method.Parent.PartialContainer;
1527 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1528 var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
1530 am_cache = new Field (parent, new TypeExpression (cache_type, loc),
1531 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1532 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1534 parent.AddField (am_cache);
1536 // TODO: Implement caching of generated generic static methods
1540 // Some extra class is needed to capture variable generic type
1541 // arguments. Maybe we could re-use anonymous types, with a unique
1542 // anonymous method id, but they are quite heavy.
1544 // Consider : "() => typeof(T);"
1546 // We need something like
1547 // static class Wrap<Tn, Tm, DelegateType> {
1548 // public static DelegateType cache;
1551 // We then specialize local variable to capture all generic parameters
1552 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1557 Label l_initialized = ec.DefineLabel ();
1559 if (am_cache != null) {
1560 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1561 ec.Emit (OpCodes.Brtrue_S, l_initialized);
1565 // Load method delegate implementation
1569 ec.Emit (OpCodes.Ldnull);
1570 } else if (storey != null) {
1571 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1575 ec.Emit (OpCodes.Ldarg_0);
1578 var delegate_method = method.Spec;
1579 if (storey != null && storey.MemberName.IsGeneric) {
1580 TypeSpec t = storey.Instance.Type;
1583 // Mutate anonymous method instance type if we are in nested
1584 // hoisted generic anonymous method storey
1586 if (ec.CurrentAnonymousMethod != null &&
1587 ec.CurrentAnonymousMethod.Storey != null &&
1588 ec.CurrentAnonymousMethod.Storey.Mutator != null) {
1589 t = storey.Mutator.Mutate (t);
1592 ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
1594 ec.Emit (OpCodes.Ldftn, delegate_method);
1597 var constructor_method = Delegate.GetConstructor (ec.MemberContext.Compiler, ec.CurrentType, type);
1598 ec.Emit (OpCodes.Newobj, constructor_method);
1600 if (am_cache != null) {
1601 ec.Emit (OpCodes.Stsfld, am_cache.Spec);
1602 ec.MarkLabel (l_initialized);
1603 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1608 // Look for the best storey for this anonymous method
1610 AnonymousMethodStorey FindBestMethodStorey ()
1613 // Use the nearest parent block which has a storey
1615 for (Block b = Block.Parent; b != null; b = b.Parent) {
1616 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1624 public override string GetSignatureForError ()
1626 return TypeManager.CSharpName (type);
1629 public static void Reset ()
1636 // Anonymous type container
1638 public class AnonymousTypeClass : CompilerGeneratedClass
1640 // TODO: Merge with AnonymousTypeParameter
1641 public class GeneratedParameter : Parameter
1643 public GeneratedParameter (FullNamedExpression type, AnonymousTypeParameter p)
1644 : base (type, p.Name, Modifier.NONE, null, p.Location)
1649 static int types_counter;
1650 public const string ClassNamePrefix = "<>__AnonType";
1651 public const string SignatureForError = "anonymous type";
1653 readonly IList<AnonymousTypeParameter> parameters;
1655 private AnonymousTypeClass (DeclSpace parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
1656 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1658 this.parameters = parameters;
1661 public static AnonymousTypeClass Create (CompilerContext ctx, TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
1663 string name = ClassNamePrefix + types_counter++;
1665 ParametersCompiled all_parameters;
1666 TypeParameterName[] t_params;
1667 SimpleName[] t_args;
1669 if (parameters.Count == 0) {
1670 all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
1671 t_params = new TypeParameterName[0];
1674 t_args = new SimpleName[parameters.Count];
1675 t_params = new TypeParameterName[parameters.Count];
1676 Parameter[] ctor_params = new Parameter[parameters.Count];
1677 for (int i = 0; i < parameters.Count; ++i) {
1678 AnonymousTypeParameter p = parameters[i];
1680 t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1681 t_params[i] = new TypeParameterName (t_args[i].Name, null, p.Location);
1682 ctor_params[i] = new GeneratedParameter (t_args[i], p);
1685 all_parameters = new ParametersCompiled (ctor_params);
1689 // Create generic anonymous type host with generic arguments
1690 // named upon properties names
1692 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1693 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1695 if (parameters.Count > 0)
1696 a_type.SetParameterInfo (null);
1698 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1699 null, all_parameters, null, loc);
1700 c.Block = new ToplevelBlock (ctx, c.ParameterInfo, loc);
1703 // Create fields and contructor body with field initialization
1706 for (int i = 0; i < parameters.Count; ++i) {
1707 AnonymousTypeParameter p = parameters [i];
1709 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1710 new MemberName ("<" + p.Name + ">", p.Location), null);
1712 if (!a_type.AddField (f)) {
1717 c.Block.AddStatement (new StatementExpression (
1718 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1719 c.Block.GetParameterReference (i, p.Location))));
1721 ToplevelBlock get_block = new ToplevelBlock (ctx, p.Location);
1722 get_block.AddStatement (new Return (
1723 new MemberAccess (new This (p.Location), f.Name), p.Location));
1725 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1726 new MemberName (p.Name, p.Location), null);
1727 prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
1728 prop.Get.Block = get_block;
1729 a_type.AddProperty (prop);
1735 a_type.AddConstructor (c);
1739 public static void Reset ()
1744 protected override bool AddToContainer (MemberCore symbol, string name)
1746 MemberCore mc = GetDefinition (name);
1749 defined_names.Add (name, symbol);
1753 Report.SymbolRelatedToPreviousError (mc);
1757 protected override bool DoDefineMembers ()
1759 if (!base.DoDefineMembers ())
1762 Location loc = Location;
1764 var equals_parameters = ParametersCompiled.CreateFullyResolved (
1765 new Parameter (new TypeExpression (TypeManager.object_type, loc), "obj", 0, null, loc), TypeManager.object_type);
1767 Method equals = new Method (this, null, new TypeExpression (TypeManager.bool_type, loc),
1768 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1769 equals_parameters, null);
1771 equals_parameters[0].Resolve (equals, 0);
1773 Method tostring = new Method (this, null, new TypeExpression (TypeManager.string_type, loc),
1774 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1775 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1777 ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
1779 TypeExpr current_type;
1780 if (type_params != null) {
1781 var targs = new TypeArguments ();
1782 foreach (var type_param in type_params)
1783 targs.Add (new TypeParameterExpr (type_param, type_param.Location));
1785 current_type = new GenericTypeExpr (Definition, targs, loc);
1787 current_type = new TypeExpression (Definition, loc);
1790 var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
1791 equals_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_other.Type, loc), li_other));
1792 var other_variable = new LocalVariableReference (li_other, loc);
1794 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1795 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1797 Expression rs_equals = null;
1798 Expression string_concat = new StringConstant ("{", loc);
1799 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1800 for (int i = 0; i < parameters.Count; ++i) {
1801 var p = parameters [i];
1804 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1805 system_collections_generic, "EqualityComparer",
1806 new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
1809 Arguments arguments_equal = new Arguments (2);
1810 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1811 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1813 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1814 "Equals", loc), arguments_equal);
1816 Arguments arguments_hashcode = new Arguments (1);
1817 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1818 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1819 "GetHashCode", loc), arguments_hashcode);
1821 IntConstant FNV_prime = new IntConstant (16777619, loc);
1822 rs_hashcode = new Binary (Binary.Operator.Multiply,
1823 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode, loc),
1826 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
1827 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc), loc)),
1828 new Invocation (new MemberAccess (
1829 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1830 new StringConstant (string.Empty, loc), loc);
1832 if (rs_equals == null) {
1833 rs_equals = field_equal;
1834 string_concat = new Binary (Binary.Operator.Addition,
1836 new Binary (Binary.Operator.Addition,
1837 new StringConstant (" " + p.Name + " = ", loc),
1845 // Implementation of ToString () body using string concatenation
1847 string_concat = new Binary (Binary.Operator.Addition,
1848 new Binary (Binary.Operator.Addition,
1850 new StringConstant (", " + p.Name + " = ", loc),
1855 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal, loc);
1858 string_concat = new Binary (Binary.Operator.Addition,
1860 new StringConstant (" }", loc),
1864 // Equals (object obj) override
1866 var other_variable_assign = new TemporaryVariableReference (li_other, loc);
1867 equals_block.AddStatement (new StatementExpression (
1868 new SimpleAssign (other_variable_assign,
1869 new As (equals_block.GetParameterReference (0, loc),
1870 current_type, loc), loc)));
1872 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc), loc);
1873 if (rs_equals != null)
1874 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals, loc);
1875 equals_block.AddStatement (new Return (equals_test, loc));
1877 equals.Block = equals_block;
1882 // GetHashCode () override
1884 Method hashcode = new Method (this, null, new TypeExpression (TypeManager.int32_type, loc),
1885 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1886 new MemberName ("GetHashCode", loc),
1887 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1890 // Modified FNV with good avalanche behavior and uniform
1891 // distribution with larger hash sizes.
1893 // const int FNV_prime = 16777619;
1894 // int hash = (int) 2166136261;
1895 // foreach (int d in data)
1896 // hash = (hash ^ d) * FNV_prime;
1897 // hash += hash << 13;
1898 // hash ^= hash >> 7;
1899 // hash += hash << 3;
1900 // hash ^= hash >> 17;
1901 // hash += hash << 5;
1903 ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
1904 Block hashcode_block = new Block (hashcode_top, loc, loc);
1905 hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
1907 var li_hash = LocalVariable.CreateCompilerGenerated (TypeManager.int32_type, hashcode_top, loc);
1908 hashcode_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_hash.Type, loc), li_hash));
1909 LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
1910 hashcode_block.AddStatement (new StatementExpression (
1911 new SimpleAssign (hash_variable_assign, rs_hashcode)));
1913 var hash_variable = new LocalVariableReference (li_hash, loc);
1914 hashcode_block.AddStatement (new StatementExpression (
1915 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1916 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc), loc), loc)));
1917 hashcode_block.AddStatement (new StatementExpression (
1918 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1919 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc), loc), loc)));
1920 hashcode_block.AddStatement (new StatementExpression (
1921 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1922 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc), loc), loc)));
1923 hashcode_block.AddStatement (new StatementExpression (
1924 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1925 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc), loc), loc)));
1926 hashcode_block.AddStatement (new StatementExpression (
1927 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1928 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc), loc), loc)));
1930 hashcode_block.AddStatement (new Return (hash_variable, loc));
1931 hashcode.Block = hashcode_top;
1933 AddMethod (hashcode);
1936 // ToString () override
1939 ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
1940 tostring_block.AddStatement (new Return (string_concat, loc));
1941 tostring.Block = tostring_block;
1943 AddMethod (tostring);
1948 public override string GetSignatureForError ()
1950 return SignatureForError;
1953 public IList<AnonymousTypeParameter> Parameters {