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, ExplicitBlock block)
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 rc.CurrentBlock = block;
375 Expression e = new New (storey_type_expr, null, Location).Resolve (rc);
378 Instance = new LocalTemporary (storey_type_expr.Type);
381 EmitHoistedFieldsInitialization (rc, ec);
383 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
384 SymbolWriter.CloseCompilerGeneratedBlock (ec);
387 void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
390 // Initialize all storey reference fields by using local or hoisted variables
392 if (used_parent_storeys != null) {
393 foreach (StoreyFieldPair sf in used_parent_storeys) {
395 // Get instance expression of storey field
397 Expression instace_expr = GetStoreyInstanceExpression (ec);
398 var fs = sf.Field.Spec;
399 if (TypeManager.IsGenericType (instace_expr.Type))
400 fs = MemberCache.GetMember (instace_expr.Type, fs);
402 FieldExpr f_set_expr = new FieldExpr (fs, Location);
403 f_set_expr.InstanceExpression = instace_expr;
405 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
406 if (a.Resolve (rc) != null)
407 a.EmitStatement (ec);
412 // Define hoisted `this' in top-level storey only
414 if (OriginalSourceBlock.Explicit.HasCapturedThis && !(Parent is AnonymousMethodStorey)) {
415 AddCapturedThisField (ec);
416 rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
420 // Setting currect anonymous method to null blocks any further variable hoisting
422 AnonymousExpression ae = ec.CurrentAnonymousMethod;
423 ec.CurrentAnonymousMethod = null;
425 if (hoisted_params != null) {
426 EmitHoistedParameters (ec, hoisted_params);
429 ec.CurrentAnonymousMethod = ae;
432 protected virtual void EmitHoistedParameters (EmitContext ec, IList<HoistedParameter> hoisted)
434 foreach (HoistedParameter hp in hoisted) {
435 hp.EmitHoistingAssignment (ec);
439 public override void EmitType ()
441 SymbolWriter.DefineAnonymousScope (ID);
443 if (hoisted_this != null)
444 hoisted_this.EmitSymbolInfo ();
446 if (hoisted_locals != null) {
447 foreach (HoistedVariable local in hoisted_locals)
448 local.EmitSymbolInfo ();
451 if (hoisted_params != null) {
452 foreach (HoistedParameter param in hoisted_params)
453 param.EmitSymbolInfo ();
456 if (used_parent_storeys != null) {
457 foreach (StoreyFieldPair sf in used_parent_storeys) {
458 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
466 // Returns a field which holds referenced storey instance
468 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
470 if (used_parent_storeys == null)
473 foreach (StoreyFieldPair sf in used_parent_storeys) {
474 if (sf.Storey == storey)
482 // Creates storey instance expression regardless of currect IP
484 public Expression GetStoreyInstanceExpression (EmitContext ec)
486 AnonymousExpression am = ec.CurrentAnonymousMethod;
489 // Access from original block -> storey
495 // Access from anonymous method implemented as a static -> storey
497 if (am.Storey == null)
500 Field f = am.Storey.GetReferencedStoreyField (this);
502 if (am.Storey == this) {
504 // Access inside of same storey (S -> S)
506 return new CompilerGeneratedThis (CurrentType, Location);
509 // External field access
515 // Storey was cached to local field
517 FieldExpr f_ind = new FieldExpr (f, Location);
518 f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
522 protected virtual string GetVariableMangledName (LocalVariable local_info)
525 // No need to mangle anonymous method hoisted variables cause they
526 // are hoisted in their own scopes
528 return local_info.Name;
531 public HoistedThis HoistedThis {
532 get { return hoisted_this; }
535 public IList<ExplicitBlock> ReferencesFromChildrenBlock {
536 get { return children_references; }
539 public static void Reset ()
545 public abstract class HoistedVariable
548 // Hoisted version of variable references used in expression
549 // tree has to be delayed until we know its location. The variable
550 // doesn't know its location until all stories are calculated
552 class ExpressionTreeVariableReference : Expression
554 readonly HoistedVariable hv;
556 public ExpressionTreeVariableReference (HoistedVariable hv)
561 public override Expression CreateExpressionTree (ResolveContext ec)
563 throw new NotSupportedException ("ET");
566 protected override Expression DoResolve (ResolveContext ec)
568 eclass = ExprClass.Value;
569 type = TypeManager.expression_type_expr.Type;
573 public override void Emit (EmitContext ec)
575 ResolveContext rc = new ResolveContext (ec.MemberContext);
576 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc);
577 // This should never fail
584 protected readonly AnonymousMethodStorey storey;
585 protected Field field;
586 Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
587 FieldExpr cached_outer_access;
589 protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
590 : this (storey, storey.AddCapturedVariable (name, type))
594 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
596 this.storey = storey;
600 public void AddressOf (EmitContext ec, AddressOp mode)
602 GetFieldExpression (ec).AddressOf (ec, mode);
605 public Expression CreateExpressionTree ()
607 return new ExpressionTreeVariableReference (this);
610 public void Emit (EmitContext ec)
612 GetFieldExpression (ec).Emit (ec);
616 // Creates field access expression for hoisted variable
618 protected virtual FieldExpr GetFieldExpression (EmitContext ec)
620 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
621 if (cached_outer_access != null)
622 return cached_outer_access;
625 // When setting top-level hoisted variable in generic storey
626 // change storey generic types to method generic types (VAR -> MVAR)
628 if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
629 var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
630 cached_outer_access = new FieldExpr (fs, field.Location);
632 cached_outer_access = new FieldExpr (field, field.Location);
635 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
636 return cached_outer_access;
639 FieldExpr inner_access;
640 if (cached_inner_access != null) {
641 if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
645 cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
648 if (inner_access == null) {
649 if (field.Parent.IsGeneric) {
650 var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
651 inner_access = new FieldExpr (fs, field.Location);
653 inner_access = new FieldExpr (field, field.Location);
656 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
657 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
663 public abstract void EmitSymbolInfo ();
665 public void Emit (EmitContext ec, bool leave_copy)
667 GetFieldExpression (ec).Emit (ec, leave_copy);
670 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
672 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
676 public class HoistedParameter : HoistedVariable
678 sealed class HoistedFieldAssign : Assign
680 public HoistedFieldAssign (Expression target, Expression source)
681 : base (target, source, source.Location)
685 protected override Expression ResolveConversions (ResolveContext ec)
688 // Implicit conversion check fails for hoisted type arguments
689 // as they are of different types (!!0 x !0)
695 readonly ParameterReference parameter;
697 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
698 : base (scope, par.Name, par.Type)
700 this.parameter = par;
703 public HoistedParameter (HoistedParameter hp, string name)
704 : base (hp.storey, name, hp.parameter.Type)
706 this.parameter = hp.parameter;
709 public void EmitHoistingAssignment (EmitContext ec)
712 // Remove hoisted redirection to emit assignment from original parameter
714 HoistedVariable temp = parameter.Parameter.HoistedVariant;
715 parameter.Parameter.HoistedVariant = null;
717 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
718 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
719 a.EmitStatement (ec);
721 parameter.Parameter.HoistedVariant = temp;
724 public override void EmitSymbolInfo ()
726 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
730 get { return field; }
734 class HoistedLocalVariable : HoistedVariable
736 readonly string name;
738 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalVariable local, string name)
739 : base (scope, name, local.Type)
741 this.name = local.Name;
744 public override void EmitSymbolInfo ()
746 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
750 public class HoistedThis : HoistedVariable
752 public HoistedThis (AnonymousMethodStorey storey, Field field)
753 : base (storey, field)
757 public void EmitHoistingAssignment (EmitContext ec)
759 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), new CompilerGeneratedThis (ec.CurrentType, field.Location));
760 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
761 a.EmitStatement (ec);
764 public override void EmitSymbolInfo ()
766 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
770 get { return field; }
775 // Anonymous method expression as created by parser
777 public class AnonymousMethodExpression : Expression
780 // Special conversion for nested expression tree lambdas
782 class Quote : ShimExpression
784 public Quote (Expression expr)
789 public override Expression CreateExpressionTree (ResolveContext ec)
791 var args = new Arguments (1);
792 args.Add (new Argument (expr.CreateExpressionTree (ec)));
793 return CreateExpressionFactoryCall (ec, "Quote", args);
796 protected override Expression DoResolve (ResolveContext rc)
798 expr = expr.Resolve (rc);
802 eclass = expr.eclass;
808 Dictionary<TypeSpec, Expression> compatibles;
809 public ParametersBlock Block;
811 public AnonymousMethodExpression (Location loc)
814 this.compatibles = new Dictionary<TypeSpec, Expression> ();
817 public override string ExprClassName {
819 return "anonymous method";
823 public virtual bool HasExplicitParameters {
825 return Parameters != ParametersCompiled.Undefined;
829 public ParametersCompiled Parameters {
830 get { return Block.Parameters; }
834 // Returns true if the body of lambda expression can be implicitly
835 // converted to the delegate of type `delegate_type'
837 public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
839 using (ec.With (ResolveContext.Options.InferReturnType, false)) {
840 using (ec.Set (ResolveContext.Options.ProbingMode)) {
841 return Compatible (ec, delegate_type) != null;
846 TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
848 if (delegate_type.IsDelegate)
849 return delegate_type;
851 if (delegate_type.IsGeneric && delegate_type.GetDefinition () == TypeManager.expression_type) {
852 delegate_type = delegate_type.TypeArguments [0];
853 if (delegate_type.IsDelegate)
854 return delegate_type;
856 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
857 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
861 ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
862 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
866 protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
868 if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
871 if (!ec.IsInProbingMode)
872 ec.Report.Error (1661, loc,
873 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
874 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
879 protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
881 if (Parameters.Count != invoke_pd.Count) {
885 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
886 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
890 bool has_implicit_parameters = !HasExplicitParameters;
893 for (int i = 0; i < Parameters.Count; ++i) {
894 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
895 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
899 if (p_mod == Parameter.Modifier.NONE)
900 ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
901 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
903 ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
904 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
908 if (has_implicit_parameters)
911 TypeSpec type = invoke_pd.Types [i];
913 // We assume that generic parameters are always inflated
914 if (TypeManager.IsGenericParameter (type))
917 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
920 if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
924 ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
926 TypeManager.CSharpName (Parameters.Types [i]),
927 TypeManager.CSharpName (invoke_pd.Types [i]));
936 // Infers type arguments based on explicit arguments
938 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
940 if (!HasExplicitParameters)
943 if (!delegate_type.IsDelegate) {
944 if (delegate_type.GetDefinition () != TypeManager.expression_type)
947 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
948 if (!delegate_type.IsDelegate)
952 AParametersCollection d_params = Delegate.GetParameters (ec.Compiler, delegate_type);
953 if (d_params.Count != Parameters.Count)
956 for (int i = 0; i < Parameters.Count; ++i) {
957 TypeSpec itype = d_params.Types [i];
958 if (!TypeManager.IsGenericParameter (itype)) {
959 if (!TypeManager.HasElementType (itype))
962 if (!TypeManager.IsGenericParameter (TypeManager.GetElementType (itype)))
965 type_inference.ExactInference (Parameters.Types [i], itype);
970 public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
973 AnonymousExpression am;
975 if (compatibles.TryGetValue (delegate_type, out expr)) {
976 am = expr as AnonymousExpression;
977 return am == null ? null : am.ReturnType;
980 using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
981 am = CompatibleMethodBody (ec, tic, InternalType.Arglist, delegate_type);
983 am = am.Compatible (ec);
989 // compatibles.Add (delegate_type, am);
990 return am.ReturnType;
994 // Returns AnonymousMethod container if this anonymous method
995 // expression can be implicitly converted to the delegate type `delegate_type'
997 public Expression Compatible (ResolveContext ec, TypeSpec type)
1000 if (compatibles.TryGetValue (type, out am))
1003 TypeSpec delegate_type = CompatibleChecks (ec, type);
1004 if (delegate_type == null)
1008 // At this point its the first time we know the return type that is
1009 // needed for the anonymous method. We create the method here.
1012 var invoke_mb = Delegate.GetInvokeMethod (ec.Compiler, delegate_type);
1013 TypeSpec return_type = invoke_mb.ReturnType;
1016 // Second: the return type of the delegate must be compatible with
1017 // the anonymous type. Instead of doing a pass to examine the block
1018 // we satisfy the rule by setting the return type on the EmitContext
1019 // to be the delegate type return type.
1022 var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
1026 bool etree_conversion = delegate_type != type;
1029 if (etree_conversion) {
1030 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
1032 // Nested expression tree lambda use same scope as parent
1033 // lambda, this also means no variable capturing between this
1036 am = body.Compatible (ec, ec.CurrentAnonymousMethod);
1039 // Quote nested expression tree
1042 am = new Quote (am);
1044 int errors = ec.Report.Errors;
1046 using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
1047 am = body.Compatible (ec);
1051 // Rewrite expressions into expression tree when targeting Expression<T>
1053 if (am != null && errors == ec.Report.Errors)
1054 am = CreateExpressionTree (ec, delegate_type);
1057 am = body.Compatible (ec);
1059 } catch (CompletionResult) {
1061 } catch (Exception e) {
1062 throw new InternalErrorException (e, loc);
1065 if (!ec.IsInProbingMode) {
1066 compatibles.Add (type, am ?? EmptyExpression.Null);
1072 protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
1074 return CreateExpressionTree (ec);
1077 public override Expression CreateExpressionTree (ResolveContext ec)
1079 ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1083 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
1085 var delegate_parameters = Delegate.GetParameters (ec.Compiler, delegate_type);
1087 if (Parameters == ParametersCompiled.Undefined) {
1089 // We provide a set of inaccessible parameters
1091 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1093 for (int i = 0; i < delegate_parameters.Count; i++) {
1094 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1095 if (i_mod == Parameter.Modifier.OUT) {
1096 if (!ec.IsInProbingMode) {
1097 ec.Report.Error (1688, loc,
1098 "Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
1099 delegate_type.GetSignatureForError ());
1104 fixedpars[i] = new Parameter (
1105 new TypeExpression (delegate_parameters.Types [i], loc), null,
1106 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1109 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1112 if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1119 protected override Expression DoResolve (ResolveContext ec)
1121 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1122 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1127 // Set class type, set type
1130 eclass = ExprClass.Value;
1133 // This hack means `The type is not accessible
1134 // anywhere', we depend on special conversion
1137 type = InternalType.AnonymousMethod;
1139 if (!DoResolveParameters (ec))
1142 // FIXME: The emitted code isn't very careful about reachability
1143 // so, ensure we have a 'ret' at the end
1144 BlockContext bc = ec as BlockContext;
1145 if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1146 bc.NeedReturnLabel ();
1151 protected virtual bool DoResolveParameters (ResolveContext rc)
1153 return Parameters.Resolve (rc);
1156 public override void Emit (EmitContext ec)
1158 // nothing, as we only exist to not do anything.
1161 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1163 ec.Report.Error (1686, loc,
1164 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1168 public override string GetSignatureForError ()
1170 return ExprClassName;
1173 AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
1175 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1179 ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
1181 return CompatibleMethodFactory (return_type, delegate_type, p, b);
1185 protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
1187 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1190 protected override void CloneTo (CloneContext clonectx, Expression t)
1192 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1194 target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
1199 // Abstract expression for any block which requires variables hoisting
1201 public abstract class AnonymousExpression : Expression
1203 protected class AnonymousMethodMethod : Method
1205 public readonly AnonymousExpression AnonymousMethod;
1206 public readonly AnonymousMethodStorey Storey;
1207 readonly string RealName;
1209 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1210 GenericMethod generic, TypeExpr return_type,
1211 Modifiers mod, string real_name, MemberName name,
1212 ParametersCompiled parameters)
1213 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1214 name, parameters, null)
1216 this.AnonymousMethod = am;
1217 this.Storey = storey;
1218 this.RealName = real_name;
1220 Parent.PartialContainer.AddMethod (this);
1221 Block = new ToplevelBlock (am.block, parameters);
1224 public override EmitContext CreateEmitContext (ILGenerator ig)
1226 EmitContext ec = new EmitContext (this, ig, ReturnType);
1227 ec.CurrentAnonymousMethod = AnonymousMethod;
1228 if (AnonymousMethod.return_label != null) {
1229 ec.HasReturnLabel = true;
1230 ec.ReturnLabel = (Label) AnonymousMethod.return_label;
1236 protected override void DefineTypeParameters ()
1238 // Type parameters were cloned
1241 protected override bool ResolveMemberType ()
1243 if (!base.ResolveMemberType ())
1246 if (Storey != null && Storey.Mutator != null) {
1247 if (!parameters.IsEmpty) {
1248 var mutated = Storey.Mutator.Mutate (parameters.Types);
1249 if (mutated != parameters.Types)
1250 parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
1253 member_type = Storey.Mutator.Mutate (member_type);
1259 public override void Emit ()
1261 if (MethodBuilder == null) {
1268 public override void EmitExtraSymbolInfo (SourceMethod source)
1270 source.SetRealMethodName (RealName);
1274 protected ParametersBlock block;
1276 public TypeSpec ReturnType;
1278 object return_label;
1280 protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
1282 this.ReturnType = return_type;
1287 public abstract string ContainerType { get; }
1288 public abstract bool IsIterator { get; }
1289 public abstract AnonymousMethodStorey Storey { get; }
1291 public AnonymousExpression Compatible (ResolveContext ec)
1293 return Compatible (ec, this);
1296 public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
1301 // TODO: Implement clone
1302 BlockContext aec = new BlockContext (ec, block, ReturnType);
1303 aec.CurrentAnonymousMethod = ae;
1305 ResolveContext.Options flags = 0;
1307 var am = this as AnonymousMethodBody;
1309 if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
1310 am.ReturnTypeInference = new TypeInferenceContext ();
1313 if (ec.IsInProbingMode)
1314 flags |= ResolveContext.Options.ProbingMode;
1316 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
1317 flags |= ResolveContext.Options.FieldInitializerScope;
1319 if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion))
1320 flags |= ResolveContext.Options.ExpressionTreeConversion;
1324 var errors = ec.Report.Errors;
1326 bool res = Block.Resolve (ec.CurrentBranching, aec, null);
1328 if (aec.HasReturnLabel)
1329 return_label = aec.ReturnLabel;
1331 if (am != null && am.ReturnTypeInference != null) {
1332 am.ReturnTypeInference.FixAllTypes (ec);
1333 ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
1334 am.ReturnTypeInference = null;
1337 if (res && errors != ec.Report.Errors)
1340 return res ? this : null;
1343 public void SetHasThisAccess ()
1345 ExplicitBlock b = block;
1347 if (b.HasCapturedThis)
1350 b.HasCapturedThis = true;
1351 b = b.Parent == null ? null : b.Parent.Explicit;
1352 } while (b != null);
1356 // The block that makes up the body for the anonymous method
1358 public ParametersBlock Block {
1366 public class AnonymousMethodBody : AnonymousExpression
1368 protected readonly ParametersCompiled parameters;
1369 AnonymousMethodStorey storey;
1371 AnonymousMethodMethod method;
1374 TypeInferenceContext return_inference;
1376 static int unique_id;
1378 public AnonymousMethodBody (ParametersCompiled parameters,
1379 ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
1381 : base (block, return_type, loc)
1383 this.type = delegate_type;
1384 this.parameters = parameters;
1389 public override string ContainerType {
1390 get { return "anonymous method"; }
1393 public override bool IsIterator {
1394 get { return false; }
1397 public TypeInferenceContext ReturnTypeInference {
1399 return return_inference;
1402 return_inference = value;
1406 public override AnonymousMethodStorey Storey {
1407 get { return storey; }
1412 public override Expression CreateExpressionTree (ResolveContext ec)
1414 ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1418 bool Define (ResolveContext ec)
1420 if (!Block.Resolved && Compatible (ec) == null)
1423 if (block_name == null) {
1424 MemberCore mc = (MemberCore) ec.MemberContext;
1425 block_name = mc.MemberName.Basename;
1432 // Creates a host for the anonymous method
1434 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1437 // Anonymous method body can be converted to
1439 // 1, an instance method in current scope when only `this' is hoisted
1440 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1441 // 3, an instance method in compiler generated storey when any hoisted variable exists
1444 Modifiers modifiers;
1445 if (Block.HasCapturedVariable || Block.HasCapturedThis) {
1446 storey = FindBestMethodStorey ();
1447 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1449 if (ec.CurrentAnonymousMethod != null)
1450 storey = ec.CurrentAnonymousMethod.Storey;
1452 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1455 TypeContainer parent = storey != null ? storey : ec.CurrentTypeDefinition.Parent.PartialContainer;
1457 MemberCore mc = ec.MemberContext as MemberCore;
1458 string name = CompilerGeneratedClass.MakeName (parent != storey ? block_name : null,
1459 "m", null, unique_id++);
1461 MemberName member_name;
1462 GenericMethod generic_method;
1463 if (storey == null && mc.MemberName.TypeArguments != null) {
1464 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1466 var hoisted_tparams = ec.CurrentTypeParameters;
1467 var type_params = new TypeParameter[hoisted_tparams.Length];
1468 for (int i = 0; i < type_params.Length; ++i) {
1469 type_params[i] = hoisted_tparams[i].CreateHoistedCopy (null, null);
1472 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name, type_params,
1473 new TypeExpression (ReturnType, Location), parameters);
1475 member_name = new MemberName (name, Location);
1476 generic_method = null;
1479 string real_name = String.Format (
1480 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1481 parameters.GetSignatureForError ());
1483 return new AnonymousMethodMethod (parent,
1484 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1485 real_name, member_name, parameters);
1488 protected override Expression DoResolve (ResolveContext ec)
1493 eclass = ExprClass.Value;
1497 public override void Emit (EmitContext ec)
1500 // Use same anonymous method implementation for scenarios where same
1501 // code is used from multiple blocks, e.g. field initializers
1503 if (method == null) {
1505 // Delay an anonymous method definition to avoid emitting unused code
1506 // for unreachable blocks or expression trees
1508 method = DoCreateMethodHost (ec);
1512 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1513 if (is_static && am_cache == null) {
1515 // Creates a field cache to store delegate instance if it's not generic
1517 if (!method.MemberName.IsGeneric) {
1518 TypeContainer parent = method.Parent.PartialContainer;
1519 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1520 var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
1522 am_cache = new Field (parent, new TypeExpression (cache_type, loc),
1523 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1524 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1526 parent.AddField (am_cache);
1528 // TODO: Implement caching of generated generic static methods
1532 // Some extra class is needed to capture variable generic type
1533 // arguments. Maybe we could re-use anonymous types, with a unique
1534 // anonymous method id, but they are quite heavy.
1536 // Consider : "() => typeof(T);"
1538 // We need something like
1539 // static class Wrap<Tn, Tm, DelegateType> {
1540 // public static DelegateType cache;
1543 // We then specialize local variable to capture all generic parameters
1544 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1549 Label l_initialized = ec.DefineLabel ();
1551 if (am_cache != null) {
1552 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1553 ec.Emit (OpCodes.Brtrue_S, l_initialized);
1557 // Load method delegate implementation
1561 ec.Emit (OpCodes.Ldnull);
1562 } else if (storey != null) {
1563 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1567 ec.Emit (OpCodes.Ldarg_0);
1570 var delegate_method = method.Spec;
1571 if (storey != null && storey.MemberName.IsGeneric) {
1572 TypeSpec t = storey.Instance.Type;
1575 // Mutate anonymous method instance type if we are in nested
1576 // hoisted generic anonymous method storey
1578 if (ec.CurrentAnonymousMethod != null &&
1579 ec.CurrentAnonymousMethod.Storey != null &&
1580 ec.CurrentAnonymousMethod.Storey.Mutator != null) {
1581 t = storey.Mutator.Mutate (t);
1584 ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
1586 ec.Emit (OpCodes.Ldftn, delegate_method);
1589 var constructor_method = Delegate.GetConstructor (ec.MemberContext.Compiler, ec.CurrentType, type);
1590 ec.Emit (OpCodes.Newobj, constructor_method);
1592 if (am_cache != null) {
1593 ec.Emit (OpCodes.Stsfld, am_cache.Spec);
1594 ec.MarkLabel (l_initialized);
1595 ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
1600 // Look for the best storey for this anonymous method
1602 AnonymousMethodStorey FindBestMethodStorey ()
1605 // Use the nearest parent block which has a storey
1607 for (Block b = Block.Parent; b != null; b = b.Parent) {
1608 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1616 public override string GetSignatureForError ()
1618 return TypeManager.CSharpName (type);
1621 public static void Reset ()
1628 // Anonymous type container
1630 public class AnonymousTypeClass : CompilerGeneratedClass
1632 // TODO: Merge with AnonymousTypeParameter
1633 public class GeneratedParameter : Parameter
1635 public GeneratedParameter (FullNamedExpression type, AnonymousTypeParameter p)
1636 : base (type, p.Name, Modifier.NONE, null, p.Location)
1641 static int types_counter;
1642 public const string ClassNamePrefix = "<>__AnonType";
1643 public const string SignatureForError = "anonymous type";
1645 readonly IList<AnonymousTypeParameter> parameters;
1647 private AnonymousTypeClass (DeclSpace parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
1648 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1650 this.parameters = parameters;
1653 public static AnonymousTypeClass Create (CompilerContext ctx, TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
1655 string name = ClassNamePrefix + types_counter++;
1657 ParametersCompiled all_parameters;
1658 TypeParameterName[] t_params;
1659 SimpleName[] t_args;
1661 if (parameters.Count == 0) {
1662 all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
1663 t_params = new TypeParameterName[0];
1666 t_args = new SimpleName[parameters.Count];
1667 t_params = new TypeParameterName[parameters.Count];
1668 Parameter[] ctor_params = new Parameter[parameters.Count];
1669 for (int i = 0; i < parameters.Count; ++i) {
1670 AnonymousTypeParameter p = parameters[i];
1672 t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1673 t_params[i] = new TypeParameterName (t_args[i].Name, null, p.Location);
1674 ctor_params[i] = new GeneratedParameter (t_args[i], p);
1677 all_parameters = new ParametersCompiled (ctor_params);
1681 // Create generic anonymous type host with generic arguments
1682 // named upon properties names
1684 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1685 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1687 if (parameters.Count > 0)
1688 a_type.SetParameterInfo (null);
1690 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1691 null, all_parameters, null, loc);
1692 c.Block = new ToplevelBlock (ctx, c.ParameterInfo, loc);
1695 // Create fields and contructor body with field initialization
1698 for (int i = 0; i < parameters.Count; ++i) {
1699 AnonymousTypeParameter p = parameters [i];
1701 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1702 new MemberName ("<" + p.Name + ">", p.Location), null);
1704 if (!a_type.AddField (f)) {
1709 c.Block.AddStatement (new StatementExpression (
1710 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1711 c.Block.GetParameterReference (i, p.Location))));
1713 ToplevelBlock get_block = new ToplevelBlock (ctx, p.Location);
1714 get_block.AddStatement (new Return (
1715 new MemberAccess (new This (p.Location), f.Name), p.Location));
1717 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1718 new MemberName (p.Name, p.Location), null);
1719 prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
1720 prop.Get.Block = get_block;
1721 a_type.AddProperty (prop);
1727 a_type.AddConstructor (c);
1731 public static void Reset ()
1736 protected override bool AddToContainer (MemberCore symbol, string name)
1738 MemberCore mc = GetDefinition (name);
1741 defined_names.Add (name, symbol);
1745 Report.SymbolRelatedToPreviousError (mc);
1749 protected override bool DoDefineMembers ()
1751 if (!base.DoDefineMembers ())
1754 Location loc = Location;
1756 var equals_parameters = ParametersCompiled.CreateFullyResolved (
1757 new Parameter (new TypeExpression (TypeManager.object_type, loc), "obj", 0, null, loc), TypeManager.object_type);
1759 Method equals = new Method (this, null, new TypeExpression (TypeManager.bool_type, loc),
1760 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1761 equals_parameters, null);
1763 equals_parameters[0].Resolve (equals, 0);
1765 Method tostring = new Method (this, null, new TypeExpression (TypeManager.string_type, loc),
1766 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1767 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1769 ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
1771 TypeExpr current_type;
1772 if (type_params != null) {
1773 var targs = new TypeArguments ();
1774 foreach (var type_param in type_params)
1775 targs.Add (new TypeParameterExpr (type_param, type_param.Location));
1777 current_type = new GenericTypeExpr (Definition, targs, loc);
1779 current_type = new TypeExpression (Definition, loc);
1782 var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
1783 equals_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_other.Type, loc), li_other));
1784 var other_variable = new LocalVariableReference (li_other, loc);
1786 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1787 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1789 Expression rs_equals = null;
1790 Expression string_concat = new StringConstant ("{", loc);
1791 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1792 for (int i = 0; i < parameters.Count; ++i) {
1793 var p = parameters [i];
1796 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1797 system_collections_generic, "EqualityComparer",
1798 new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
1801 Arguments arguments_equal = new Arguments (2);
1802 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1803 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1805 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1806 "Equals", loc), arguments_equal);
1808 Arguments arguments_hashcode = new Arguments (1);
1809 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1810 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1811 "GetHashCode", loc), arguments_hashcode);
1813 IntConstant FNV_prime = new IntConstant (16777619, loc);
1814 rs_hashcode = new Binary (Binary.Operator.Multiply,
1815 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode, loc),
1818 Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
1819 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc), loc)),
1820 new Invocation (new MemberAccess (
1821 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1822 new StringConstant (string.Empty, loc), loc);
1824 if (rs_equals == null) {
1825 rs_equals = field_equal;
1826 string_concat = new Binary (Binary.Operator.Addition,
1828 new Binary (Binary.Operator.Addition,
1829 new StringConstant (" " + p.Name + " = ", loc),
1837 // Implementation of ToString () body using string concatenation
1839 string_concat = new Binary (Binary.Operator.Addition,
1840 new Binary (Binary.Operator.Addition,
1842 new StringConstant (", " + p.Name + " = ", loc),
1847 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal, loc);
1850 string_concat = new Binary (Binary.Operator.Addition,
1852 new StringConstant (" }", loc),
1856 // Equals (object obj) override
1858 var other_variable_assign = new TemporaryVariableReference (li_other, loc);
1859 equals_block.AddStatement (new StatementExpression (
1860 new SimpleAssign (other_variable_assign,
1861 new As (equals_block.GetParameterReference (0, loc),
1862 current_type, loc), loc)));
1864 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc), loc);
1865 if (rs_equals != null)
1866 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals, loc);
1867 equals_block.AddStatement (new Return (equals_test, loc));
1869 equals.Block = equals_block;
1874 // GetHashCode () override
1876 Method hashcode = new Method (this, null, new TypeExpression (TypeManager.int32_type, loc),
1877 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1878 new MemberName ("GetHashCode", loc),
1879 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1882 // Modified FNV with good avalanche behavior and uniform
1883 // distribution with larger hash sizes.
1885 // const int FNV_prime = 16777619;
1886 // int hash = (int) 2166136261;
1887 // foreach (int d in data)
1888 // hash = (hash ^ d) * FNV_prime;
1889 // hash += hash << 13;
1890 // hash ^= hash >> 7;
1891 // hash += hash << 3;
1892 // hash ^= hash >> 17;
1893 // hash += hash << 5;
1895 ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
1896 Block hashcode_block = new Block (hashcode_top, loc, loc);
1897 hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
1899 var li_hash = LocalVariable.CreateCompilerGenerated (TypeManager.int32_type, hashcode_top, loc);
1900 hashcode_block.AddStatement (new BlockVariableDeclaration (new TypeExpression (li_hash.Type, loc), li_hash));
1901 LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
1902 hashcode_block.AddStatement (new StatementExpression (
1903 new SimpleAssign (hash_variable_assign, rs_hashcode)));
1905 var hash_variable = new LocalVariableReference (li_hash, loc);
1906 hashcode_block.AddStatement (new StatementExpression (
1907 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1908 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc), loc), loc)));
1909 hashcode_block.AddStatement (new StatementExpression (
1910 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1911 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc), loc), loc)));
1912 hashcode_block.AddStatement (new StatementExpression (
1913 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1914 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc), loc), loc)));
1915 hashcode_block.AddStatement (new StatementExpression (
1916 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1917 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc), loc), loc)));
1918 hashcode_block.AddStatement (new StatementExpression (
1919 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1920 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc), loc), loc)));
1922 hashcode_block.AddStatement (new Return (hash_variable, loc));
1923 hashcode.Block = hashcode_top;
1925 AddMethod (hashcode);
1928 // ToString () override
1931 ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
1932 tostring_block.AddStatement (new Return (string_concat, loc));
1933 tostring.Block = tostring_block;
1935 AddMethod (tostring);
1940 public override string GetSignatureForError ()
1942 return SignatureForError;
1945 public IList<AnonymousTypeParameter> Parameters {