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;
15 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
19 namespace Mono.CSharp {
21 public abstract class CompilerGeneratedClass : Class
23 public static string MakeName (string host, string typePrefix, string name, int id)
25 return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
28 protected CompilerGeneratedClass (DeclSpace parent, MemberName name, int mod)
29 : base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED, null)
33 protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic, MemberName name, int mod)
34 : this (parent, name, mod)
36 if (generic != null) {
37 ArrayList list = new ArrayList ();
38 foreach (TypeParameter tparam in generic.TypeParameters) {
39 if (tparam.Constraints != null)
40 list.Add (tparam.Constraints.Clone ());
42 SetParameterInfo (list);
46 protected void CheckMembersDefined ()
49 throw new InternalErrorException ("Helper class already defined!");
54 // Anonymous method storey is created when an anonymous method uses
55 // variable or parameter from outer scope. They are then hoisted to
56 // anonymous method storey (captured)
58 public class AnonymousMethodStorey : CompilerGeneratedClass
60 class StoreyFieldPair {
61 public AnonymousMethodStorey Storey;
64 public StoreyFieldPair (AnonymousMethodStorey storey)
69 public override int GetHashCode ()
71 return Storey.ID.GetHashCode ();
74 public override bool Equals (object obj)
76 return (AnonymousMethodStorey)obj == Storey;
80 class HoistedGenericField : Field
82 public HoistedGenericField (DeclSpace parent, FullNamedExpression type, int mod, string name,
83 Attributes attrs, Location loc)
84 : base (parent, type, mod, new MemberName (name, loc), attrs)
88 protected override bool ResolveMemberType ()
90 if (!base.ResolveMemberType ())
93 AnonymousMethodStorey parent = ((AnonymousMethodStorey) Parent).GetGenericStorey ();
95 member_type = parent.MutateType (member_type);
102 public readonly int ID;
103 static int unique_id;
105 public readonly Block OriginalSourceBlock;
107 // A list of StoreyFieldPair with local field keeping parent storey instance
108 ArrayList used_parent_storeys;
110 // A list of hoisted parameters
111 protected ArrayList hoisted_params;
112 protected ArrayList hoisted_locals;
115 protected HoistedThis hoisted_this;
117 // Local variable which holds this storey instance
118 public LocalTemporary Instance;
120 bool references_defined;
121 bool has_hoisted_variable;
124 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
125 : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE)
128 OriginalSourceBlock = block;
132 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
134 string host_name = host == null ? null : host.Name;
135 string tname = MakeName (host_name, "c", name, unique_id);
136 TypeArguments args = null;
137 if (generic != null) {
138 args = new TypeArguments ();
139 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
140 args.Add (new TypeParameterName (tparam.Name, null, loc));
143 return new MemberName (tname, args, loc);
146 public Field AddCapturedVariable (string name, Type type)
148 CheckMembersDefined ();
150 FullNamedExpression field_type = new TypeExpression (type, Location);
152 return AddCompilerGeneratedField (name, field_type);
154 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
155 Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
160 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
162 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
163 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
168 public void AddParentStoreyReference (AnonymousMethodStorey s)
170 CheckMembersDefined ();
172 if (used_parent_storeys == null)
173 used_parent_storeys = new ArrayList ();
174 else if (used_parent_storeys.IndexOf (s) != -1)
177 has_hoisted_variable = true;
178 used_parent_storeys.Add (new StoreyFieldPair (s));
181 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
183 if (local_info.HoistedVariableReference != null)
186 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
187 local_info.HoistedVariableReference = var;
188 has_hoisted_variable = true;
190 if (hoisted_locals == null)
191 hoisted_locals = new ArrayList ();
193 hoisted_locals.Add (var);
196 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
198 if (param_ref.HoistedVariable != null)
201 if (hoisted_params == null)
202 hoisted_params = new ArrayList (2);
204 HoistedVariable expr = new HoistedParameter (this, param_ref);
205 param_ref.Parameter.HoistedVariableReference = expr;
206 hoisted_params.Add (expr);
209 public HoistedThis CaptureThis (EmitContext ec, This t)
211 hoisted_this = new HoistedThis (this, t);
215 public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
217 Parent = parentStorey;
221 void DefineStoreyReferences ()
223 if (used_parent_storeys == null || references_defined)
226 references_defined = true;
229 // For each used variable from parent scope we allocate its local reference point
231 for (int i = 0; i < used_parent_storeys.Count; ++i) {
232 StoreyFieldPair sf = (StoreyFieldPair) used_parent_storeys [i];
233 AnonymousMethodStorey p_storey = sf.Storey;
234 TypeExpr type_expr = new TypeExpression (p_storey.TypeBuilder, Location);
236 sf.Field = AddCompilerGeneratedField ("<>f__ref$" + p_storey.ID, type_expr);
242 // Initializes all hoisted variables
244 public void EmitHoistedVariables (EmitContext ec)
246 // There can be only one instance variable for each storey type
247 if (Instance != null)
248 throw new InternalErrorException ();
251 // A storey with hoisted `this' is an instance method
253 if (!HasHoistedVariables) {
254 hoisted_this.RemoveHoisting ();
258 SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
260 DefineStoreyReferences ();
263 // Create an instance of storey type
265 Expression storey_type_expr;
268 // Use current method type parameter (MVAR) for top level storey only. All
269 // nested storeys use class type parameter (VAR)
271 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
272 ec.CurrentAnonymousMethod.Storey.TypeParameters :
273 ec.GenericDeclContainer.TypeParameters;
275 TypeArguments targs = new TypeArguments ();
277 if (tparams.Length < CountTypeParameters) {
278 TypeParameter[] parent_tparams = ec.DeclContainer.Parent.CurrentTypeParameters;
279 for (int i = 0; i < parent_tparams.Length; ++i)
280 targs.Add (new TypeParameterExpr (parent_tparams[i], Location));
283 for (int i = 0; i < tparams.Length; ++i)
284 targs.Add (new TypeParameterExpr (tparams[i], Location));
286 storey_type_expr = new GenericTypeExpr (TypeBuilder, targs, Location);
288 storey_type_expr = new TypeExpression (TypeBuilder, Location);
291 Expression e = new New (storey_type_expr, new ArrayList (0), Location).Resolve (ec);
294 Instance = new LocalTemporary (storey_type_expr.Type);
297 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
299 EmitHoistedFieldsInitialization (ec);
301 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
304 void EmitHoistedFieldsInitialization (EmitContext ec)
307 // Initialize all storey reference fields by using local or hoisted variables
309 if (used_parent_storeys != null) {
310 foreach (StoreyFieldPair sf in used_parent_storeys) {
312 // Setting local field
314 Expression instace_expr = GetStoreyInstanceExpression (ec);
315 FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
316 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
317 new FieldExpr (sf.Field.FieldBuilder, Location);
318 f_set_expr.InstanceExpression = instace_expr;
320 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
321 if (a.Resolve (ec) != null)
322 a.EmitStatement (ec);
327 // Setting currect anonymous method to null blocks any further variable hoisting
329 AnonymousExpression ae = ec.CurrentAnonymousMethod;
330 ec.CurrentAnonymousMethod = null;
332 if (hoisted_params != null) {
333 EmitHoistedParameters (ec, hoisted_params);
336 if (hoisted_this != null) {
337 hoisted_this.EmitHoistingAssignment (ec);
340 ec.CurrentAnonymousMethod = ae;
343 protected virtual void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
345 foreach (HoistedParameter hp in hoisted) {
346 hp.EmitHoistingAssignment (ec);
350 public override void EmitType ()
352 SymbolWriter.DefineAnonymousScope (ID);
354 if (hoisted_this != null)
355 hoisted_this.EmitSymbolInfo ();
357 if (hoisted_locals != null) {
358 foreach (HoistedVariable local in hoisted_locals)
359 local.EmitSymbolInfo ();
362 if (hoisted_params != null) {
363 foreach (HoistedParameter param in hoisted_params)
364 param.EmitSymbolInfo ();
367 DefineStoreyReferences ();
369 if (used_parent_storeys != null) {
370 foreach (StoreyFieldPair sf in used_parent_storeys) {
371 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
378 public AnonymousMethodStorey GetGenericStorey ()
380 DeclSpace storey = this;
381 while (storey != null && storey.CurrentTypeParameters.Length == 0)
382 storey = storey.Parent;
384 return storey as AnonymousMethodStorey;
388 // Returns a field which holds referenced storey instance
390 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
392 if (used_parent_storeys == null)
395 foreach (StoreyFieldPair sf in used_parent_storeys) {
396 if (sf.Storey == storey)
404 // Creates storey instance expression regardless of currect IP
406 public Expression GetStoreyInstanceExpression (EmitContext ec)
408 AnonymousExpression am = ec.CurrentAnonymousMethod;
411 // Access from original block -> storey
417 // Access from anonymous method implemented as a static -> storey
419 if (am.Storey == null)
422 Field f = am.Storey.GetReferencedStoreyField (this);
424 if (am.Storey == this) {
426 // Access inside of same storey (S -> S)
428 return new CompilerGeneratedThis (TypeBuilder, Location);
431 // External field access
437 // Storey was cached to local field
439 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
440 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
444 protected virtual string GetVariableMangledName (LocalInfo local_info)
447 // No need to mangle anonymous method hoisted variables cause they
448 // are hoisted in their own scopes
450 return local_info.Name;
454 // Returns true when at least one local variable or parameter is
455 // hoisted, or story is transitioned
457 public bool HasHoistedVariables {
459 return has_hoisted_variable || hoisted_params != null;
462 has_hoisted_variable = value;
466 public bool IsUndone {
467 get { return is_undone; }
471 // Mutate type dispatcher
473 public Type MutateType (Type type)
476 if (TypeManager.IsGenericType (type))
477 return MutateGenericType (type);
479 if (TypeManager.IsGenericParameter (type))
480 return MutateGenericArgument (type);
483 return MutateArrayType (type);
489 // Changes method type arguments (MVAR) to storey (VAR) type arguments
491 public MethodInfo MutateGenericMethod (MethodInfo method)
494 Type [] t_args = TypeManager.GetGenericArguments (method);
495 if (TypeManager.IsGenericType (method.DeclaringType)) {
496 Type t = MutateGenericType (method.DeclaringType);
497 if (t != method.DeclaringType) {
498 method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
499 if (method.Module == CodeGen.Module.Builder)
500 method = TypeBuilder.GetMethod (t, method);
502 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
506 if (t_args == null || t_args.Length == 0)
509 for (int i = 0; i < t_args.Length; ++i)
510 t_args [i] = MutateType (t_args [i]);
512 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
514 throw new NotSupportedException ();
518 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
521 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
522 Type t = MutateGenericType (ctor.DeclaringType);
523 if (t != ctor.DeclaringType) {
524 ctor = (ConstructorInfo) TypeManager.DropGenericMethodArguments (ctor);
525 if (ctor.Module == CodeGen.Module.Builder)
526 return TypeBuilder.GetConstructor (t, ctor);
528 return (ConstructorInfo) ConstructorInfo.GetMethodFromHandle (ctor.MethodHandle, t.TypeHandle);
535 public FieldInfo MutateField (FieldInfo field)
538 if (TypeManager.IsGenericType (field.DeclaringType)) {
539 Type t = MutateGenericType (field.DeclaringType);
540 if (t != field.DeclaringType) {
541 // TODO: It should throw on imported types
542 return TypeBuilder.GetField (t, field);
550 protected Type MutateArrayType (Type array)
552 int rank = array.GetArrayRank ();
553 Type element = TypeManager.GetElementType (array);
555 throw new NotImplementedException ();
557 if (TypeManager.IsGenericParameter (element)) {
558 element = MutateGenericArgument (element);
559 } else if (TypeManager.IsGenericType (element)) {
560 element = MutateGenericType (element);
565 return element.MakeArrayType (rank);
568 protected Type MutateGenericType (Type type)
570 Type [] t_args = TypeManager.GetTypeArguments (type);
571 if (t_args == null || t_args.Length == 0)
574 for (int i = 0; i < t_args.Length; ++i)
575 t_args [i] = MutateType (t_args [i]);
577 return type.GetGenericTypeDefinition ().MakeGenericType (t_args);
582 // Changes method generic argument (MVAR) to type generic argument (VAR)
584 public Type MutateGenericArgument (Type type)
586 foreach (TypeParameter tp in CurrentTypeParameters) {
587 if (tp.Name == type.Name) {
595 public static void Reset ()
603 if (hoisted_this != null)
604 hoisted_this.RemoveHoisting ();
608 public abstract class HoistedVariable
610 class ExpressionTreeProxy : Expression
612 readonly HoistedVariable hv;
614 public ExpressionTreeProxy (HoistedVariable hv)
619 public override Expression CreateExpressionTree (EmitContext ec)
621 throw new NotSupportedException ("ET");
624 public override Expression DoResolve (EmitContext ec)
626 eclass = ExprClass.Value;
627 type = TypeManager.expression_type_expr.Type;
631 public override void Emit (EmitContext ec)
633 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (ec);
634 // This should never fail
641 protected readonly AnonymousMethodStorey storey;
642 protected Field field;
643 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
644 FieldExpr cached_outer_access;
646 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
648 this.storey = storey;
650 this.field = storey.AddCapturedVariable (name, type);
653 public void AddressOf (EmitContext ec, AddressOp mode)
655 GetFieldExpression (ec).AddressOf (ec, mode);
658 public Expression CreateExpressionTree (EmitContext ec)
660 return new ExpressionTreeProxy (this);
663 public void Emit (EmitContext ec)
665 GetFieldExpression (ec).Emit (ec);
669 // Creates field access expression for hoisted variable
671 protected FieldExpr GetFieldExpression (EmitContext ec)
673 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
674 if (cached_outer_access != null)
675 return cached_outer_access;
678 // When setting top-level hoisted variable in generic storey
679 // change storey generic types to method generic types (VAR -> MVAR)
681 cached_outer_access = storey.MemberName.IsGeneric ?
682 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
683 new FieldExpr (field.FieldBuilder, field.Location);
685 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
686 cached_outer_access.Resolve (ec);
687 return cached_outer_access;
690 FieldExpr inner_access;
691 if (cached_inner_access != null) {
692 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
695 cached_inner_access = new Hashtable (4);
698 if (inner_access == null) {
699 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
700 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
701 inner_access.Resolve (ec);
702 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
708 public abstract void EmitSymbolInfo ();
710 public void Emit (EmitContext ec, bool leave_copy)
712 GetFieldExpression (ec).Emit (ec, leave_copy);
715 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
717 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
721 class HoistedParameter : HoistedVariable
723 sealed class HoistedFieldAssign : Assign
725 public HoistedFieldAssign (Expression target, Expression source)
726 : base (target, source, source.Location)
730 protected override Expression ResolveConversions (EmitContext ec)
733 // Implicit conversion check fails for hoisted type arguments
734 // as they are of different types (!!0 x !0)
740 readonly ParameterReference parameter;
742 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
743 : base (scope, par.Name, par.Type)
745 this.parameter = par;
748 public HoistedParameter (HoistedParameter hp, string name)
749 : base (hp.storey, name, hp.parameter.Type)
751 this.parameter = hp.parameter;
754 public void EmitHoistingAssignment (EmitContext ec)
757 // Remove hoisted redirection to emit assignment from original parameter
759 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
760 parameter.Parameter.HoistedVariableReference = null;
762 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
763 if (a.Resolve (ec) != null)
764 a.EmitStatement (ec);
766 parameter.Parameter.HoistedVariableReference = temp;
769 public override void EmitSymbolInfo ()
771 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
775 get { return field; }
779 class HoistedLocalVariable : HoistedVariable
781 readonly string name;
783 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
784 : base (scope, name, local.VariableType)
786 this.name = local.Name;
789 public override void EmitSymbolInfo ()
791 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
795 public class HoistedThis : HoistedVariable
797 readonly This this_reference;
799 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
800 : base (storey, "<>f__this", this_reference.Type)
802 this.this_reference = this_reference;
805 public void EmitHoistingAssignment (EmitContext ec)
807 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
808 if (a.Resolve (ec) != null)
809 a.EmitStatement (ec);
812 public override void EmitSymbolInfo ()
814 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
818 get { return field; }
821 public void RemoveHoisting ()
823 this_reference.RemoveHoisting ();
828 // Anonymous method expression as created by parser
830 public class AnonymousMethodExpression : Expression
832 ListDictionary compatibles;
833 public ToplevelBlock Block;
835 public AnonymousMethodExpression (Location loc)
838 this.compatibles = new ListDictionary ();
841 public override string ExprClassName {
843 return "anonymous method";
847 public virtual bool HasExplicitParameters {
849 return Parameters != Parameters.Undefined;
853 public Parameters Parameters {
854 get { return Block.Parameters; }
858 // Returns true if the body of lambda expression can be implicitly
859 // converted to the delegate of type `delegate_type'
861 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
863 using (ec.Set (EmitContext.Flags.ProbingMode)) {
864 return Compatible (ec, delegate_type) != null;
868 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
870 if (TypeManager.IsDelegateType (delegate_type))
871 return delegate_type;
874 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
875 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
876 if (TypeManager.IsDelegateType (delegate_type))
877 return delegate_type;
879 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
880 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
885 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
886 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
890 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
892 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
896 Report.Error (1661, loc,
897 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
898 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
903 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
905 if (Parameters.Count != invoke_pd.Count) {
909 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
910 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
914 bool has_implicit_parameters = !HasExplicitParameters;
917 for (int i = 0; i < Parameters.Count; ++i) {
918 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
919 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
923 if (p_mod == Parameter.Modifier.NONE)
924 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
925 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
927 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
928 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
932 if (has_implicit_parameters)
935 Type type = invoke_pd.Types [i];
937 // We assume that generic parameters are always inflated
938 if (TypeManager.IsGenericParameter (type))
941 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
944 if (invoke_pd.Types [i] != Parameters.Types [i]) {
948 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
950 TypeManager.CSharpName (Parameters.Types [i]),
951 TypeManager.CSharpName (invoke_pd.Types [i]));
960 // Infers type arguments based on explicit arguments
962 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
964 if (!HasExplicitParameters)
967 if (!TypeManager.IsDelegateType (delegate_type)) {
969 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
972 delegate_type = delegate_type.GetGenericArguments () [0];
973 if (!TypeManager.IsDelegateType (delegate_type))
980 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
981 if (d_params.Count != Parameters.Count)
984 for (int i = 0; i < Parameters.Count; ++i) {
985 Type itype = d_params.Types [i];
986 if (!TypeManager.IsGenericParameter (itype)) {
987 if (!TypeManager.HasElementType (itype))
990 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
993 type_inference.ExactInference (Parameters.Types [i], itype);
998 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1000 AnonymousMethodBody am;
1001 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
1002 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
1008 if (am.ReturnType == TypeManager.null_type)
1009 am.ReturnType = null;
1011 return am.ReturnType;
1015 // Returns AnonymousMethod container if this anonymous method
1016 // expression can be implicitly converted to the delegate type `delegate_type'
1018 public Expression Compatible (EmitContext ec, Type type)
1020 Expression am = (Expression) compatibles [type];
1024 Type delegate_type = CompatibleChecks (ec, type);
1025 if (delegate_type == null)
1029 // At this point its the first time we know the return type that is
1030 // needed for the anonymous method. We create the method here.
1033 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1034 ec.ContainerType, delegate_type);
1035 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1038 Type[] g_args = delegate_type.GetGenericArguments ();
1039 if (return_type.IsGenericParameter)
1040 return_type = g_args [return_type.GenericParameterPosition];
1044 // Second: the return type of the delegate must be compatible with
1045 // the anonymous type. Instead of doing a pass to examine the block
1046 // we satisfy the rule by setting the return type on the EmitContext
1047 // to be the delegate type return type.
1051 int errors = Report.Errors;
1052 am = CompatibleMethod (ec, null, return_type, delegate_type);
1053 if (am != null && delegate_type != type && errors == Report.Errors)
1054 am = CreateExpressionTree (ec, delegate_type);
1056 if (!ec.IsInProbingMode)
1057 compatibles.Add (type, am);
1060 } catch (Exception e) {
1061 throw new InternalErrorException (e, loc);
1065 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1067 return CreateExpressionTree (ec);
1070 public override Expression CreateExpressionTree (EmitContext ec)
1072 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1076 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1078 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1080 if (Parameters == Parameters.Undefined) {
1082 // We provide a set of inaccessible parameters
1084 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1086 for (int i = 0; i < delegate_parameters.Count; i++) {
1087 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1088 if (i_mod == Parameter.Modifier.OUT) {
1089 Report.Error (1688, loc, "Cannot convert anonymous " +
1090 "method block without a parameter list " +
1091 "to delegate type `{0}' because it has " +
1092 "one or more `out' parameters.",
1093 TypeManager.CSharpName (delegate_type));
1096 fixedpars[i] = new Parameter (
1098 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1101 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1104 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1111 public override Expression DoResolve (EmitContext ec)
1113 if (!ec.IsAnonymousMethodAllowed) {
1114 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1119 // Set class type, set type
1122 eclass = ExprClass.Value;
1125 // This hack means `The type is not accessible
1126 // anywhere', we depend on special conversion
1129 type = TypeManager.anonymous_method_type;
1131 if ((Parameters != null) && !Parameters.Resolve (ec))
1134 // FIXME: The emitted code isn't very careful about reachability
1135 // so, ensure we have a 'ret' at the end
1136 if (ec.CurrentBranching != null &&
1137 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1138 ec.NeedReturnLabel ();
1143 public override void Emit (EmitContext ec)
1145 // nothing, as we only exist to not do anything.
1148 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1150 Report.Error (1686, loc,
1151 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1155 public override string GetSignatureForError ()
1157 return ExprClassName;
1160 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1162 Parameters p = ResolveParameters (ec, tic, delegate_type);
1166 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1168 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1169 if (!anonymous.Compatible (ec))
1175 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1177 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1180 protected override void CloneTo (CloneContext clonectx, Expression t)
1182 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1184 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1189 // Abstract expression for any block which requires variables hoisting
1191 public abstract class AnonymousExpression : Expression
1193 protected class AnonymousMethodMethod : Method
1195 public readonly AnonymousExpression AnonymousMethod;
1196 public readonly AnonymousMethodStorey Storey;
1197 readonly string RealName;
1199 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1200 GenericMethod generic, TypeExpr return_type,
1201 int mod, string real_name, MemberName name,
1202 Parameters parameters)
1203 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1204 name, parameters, null)
1206 this.AnonymousMethod = am;
1207 this.Storey = storey;
1208 this.RealName = real_name;
1210 Parent.PartialContainer.AddMethod (this);
1214 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1216 EmitContext aec = AnonymousMethod.aec;
1218 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1222 protected override bool ResolveMemberType ()
1224 if (!base.ResolveMemberType ())
1227 if (Storey != null && Storey.IsGeneric && Storey.HasHoistedVariables) {
1228 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1229 if (gstorey != null) {
1230 if (!Parameters.IsEmpty) {
1231 Type [] ptypes = Parameters.Types;
1232 for (int i = 0; i < ptypes.Length; ++i)
1233 ptypes [i] = gstorey.MutateType (ptypes [i]);
1236 member_type = gstorey.MutateType (member_type);
1243 public override void Emit ()
1246 // Before emitting any code we have to change all MVAR references to VAR
1247 // when the method is of generic type and has hoisted variables
1249 if (Storey == Parent && Storey.IsGeneric) {
1250 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1251 if (gstorey != null) {
1252 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1253 block.MutateHoistedGenericType (gstorey);
1257 if (MethodBuilder == null) {
1264 public override void EmitExtraSymbolInfo (SourceMethod source)
1266 source.SetRealMethodName (RealName);
1271 // The block that makes up the body for the anonymous method
1273 protected readonly ToplevelBlock Block;
1275 public Type ReturnType;
1276 protected EmitContext aec;
1278 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1280 this.ReturnType = return_type;
1285 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1286 public abstract string ContainerType { get; }
1287 public abstract bool IsIterator { get; }
1288 public abstract AnonymousMethodStorey Storey { get; }
1290 public bool Compatible (EmitContext ec)
1292 // TODO: Implement clone
1293 aec = new EmitContext (
1294 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1295 Location, null, ReturnType,
1296 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1298 aec.CurrentAnonymousMethod = this;
1299 aec.IsStatic = ec.IsStatic;
1301 IDisposable aec_dispose = null;
1302 EmitContext.Flags flags = 0;
1303 if (ec.InferReturnType)
1304 flags |= EmitContext.Flags.InferReturnType;
1306 if (ec.IsInProbingMode)
1307 flags |= EmitContext.Flags.ProbingMode;
1309 if (ec.IsInFieldInitializer)
1310 flags |= EmitContext.Flags.InFieldInitializer;
1312 if (ec.IsInUnsafeScope)
1313 flags |= EmitContext.Flags.InUnsafe;
1315 // HACK: Flag with 0 cannot be set
1317 aec_dispose = aec.Set (flags);
1320 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1322 if (ec.InferReturnType)
1323 ReturnType = aec.ReturnType;
1325 if (aec_dispose != null) {
1326 aec_dispose.Dispose ();
1333 public class AnonymousMethodBody : AnonymousExpression
1335 ArrayList referenced_storeys;
1336 protected readonly Parameters parameters;
1337 AnonymousMethodStorey storey;
1339 AnonymousMethodMethod method;
1342 static int unique_id;
1344 public AnonymousMethodBody (Parameters parameters,
1345 ToplevelBlock block, Type return_type, Type delegate_type,
1347 : base (block, return_type, loc)
1349 this.type = delegate_type;
1350 this.parameters = parameters;
1353 public override string ContainerType {
1354 get { return "anonymous method"; }
1357 public override AnonymousMethodStorey Storey {
1358 get { return storey; }
1361 public override bool IsIterator {
1362 get { return false; }
1366 // Adds new storey reference to track out of scope variables
1368 public override void AddStoreyReference (AnonymousMethodStorey storey)
1370 if (referenced_storeys == null) {
1371 referenced_storeys = new ArrayList (2);
1373 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1379 referenced_storeys.Add (storey);
1382 public override Expression CreateExpressionTree (EmitContext ec)
1384 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1388 bool Define (EmitContext ec)
1390 if (aec == null && !Compatible (ec))
1393 if (referenced_storeys != null)
1394 ConnectReferencedStoreys ();
1399 void ConnectReferencedStoreys ()
1401 storey = FindBestMethodStorey ();
1403 foreach (AnonymousMethodStorey s in referenced_storeys) {
1405 // An anonymous method has to have an instance access when
1406 // children anonymous method requires access to parent storey
1407 // hoisted variables
1409 for (Block b = Block.Parent; b != s.OriginalSourceBlock; b = b.Parent)
1410 b.Toplevel.HasStoreyAccess = true;
1415 s.HasHoistedVariables = true;
1416 Block.Parent.Explicit.PropagateStoreyReference (s);
1421 // Creates a host for the anonymous method
1423 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1426 // Anonymous method body can be converted to
1428 // 1, an instance method in current scope when only `this' is hoisted
1429 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1430 // 3, an instance method in compiler generated storey when any hoisted variable exists
1434 if (referenced_storeys != null || Block.HasStoreyAccess) {
1435 if (storey == null || storey.IsUndone)
1436 storey = FindBestMethodStorey ();
1438 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1440 if (ec.CurrentAnonymousMethod != null)
1441 storey = ec.CurrentAnonymousMethod.Storey;
1443 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1446 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1448 MemberCore mc = ec.ResolveContext as MemberCore;
1449 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1450 "m", null, unique_id++);
1452 MemberName member_name;
1453 GenericMethod generic_method;
1454 if (storey == null && mc.MemberName.IsGeneric) {
1455 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1457 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1458 new TypeExpression (ReturnType, Location), parameters);
1460 ArrayList list = new ArrayList ();
1461 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1462 if (tparam.Constraints != null)
1463 list.Add (tparam.Constraints.Clone ());
1465 generic_method.SetParameterInfo (list);
1467 member_name = new MemberName (name, Location);
1468 generic_method = null;
1471 string real_name = String.Format (
1472 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1473 parameters.GetSignatureForError ());
1475 return new AnonymousMethodMethod (parent,
1476 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1477 real_name, member_name, parameters);
1480 public override Expression DoResolve (EmitContext ec)
1482 if (eclass == ExprClass.Invalid) {
1487 eclass = ExprClass.Value;
1491 public override void Emit (EmitContext ec)
1494 // Use same anonymous method implementation for scenarios where same
1495 // code is used from multiple blocks, e.g. field initializers
1497 if (method == null) {
1499 // Delay an anonymous method definition to avoid emitting unused code
1500 // for unreachable blocks or expression trees
1502 method = DoCreateMethodHost (ec);
1506 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1507 if (is_static && am_cache == null) {
1509 // Creates a field cache to store delegate instance if it's not generic
1511 if (!method.MemberName.IsGeneric) {
1512 TypeContainer parent = method.Parent.PartialContainer;
1513 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1514 am_cache = new Field (parent, new TypeExpression (type, loc),
1515 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1516 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1518 parent.AddField (am_cache);
1520 // TODO: Implement caching of generated generic static methods
1524 // Some extra class is needed to capture variable generic type
1525 // arguments. Maybe we could re-use anonymous types, with a unique
1526 // anonymous method id, but they are quite heavy.
1528 // Consider : "() => typeof(T);"
1530 // We need something like
1531 // static class Wrap<Tn, Tm, DelegateType> {
1532 // public static DelegateType cache;
1535 // We then specialize local variable to capture all generic parameters
1536 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1541 ILGenerator ig = ec.ig;
1542 Label l_initialized = ig.DefineLabel ();
1544 if (am_cache != null) {
1545 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1546 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1550 // Load method delegate implementation
1554 ig.Emit (OpCodes.Ldnull);
1555 } else if (storey != null) {
1556 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1560 ig.Emit (OpCodes.Ldarg_0);
1563 MethodInfo delegate_method = method.MethodBuilder;
1565 if (storey != null && storey.MemberName.IsGeneric) {
1566 Type t = storey.Instance.Type;
1569 // Mutate anonymous method instance type if we are in nested
1570 // hoisted generic anonymous method storey
1572 if (ec.CurrentAnonymousMethod != null &&
1573 ec.CurrentAnonymousMethod.Storey != null &&
1574 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1575 t = storey.GetGenericStorey ().MutateType (t);
1578 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1581 ig.Emit (OpCodes.Ldftn, delegate_method);
1583 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1585 if (type.IsGenericType && type is TypeBuilder)
1586 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1588 ig.Emit (OpCodes.Newobj, constructor_method);
1590 if (am_cache != null) {
1591 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1592 ig.MarkLabel (l_initialized);
1593 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1598 // Look for the best storey for this anonymous method
1600 AnonymousMethodStorey FindBestMethodStorey ()
1603 // Use the nearest parent block which has a storey
1605 for (Block b = Block.Parent; b != null; b = b.Parent) {
1606 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1614 public override string GetSignatureForError ()
1616 return TypeManager.CSharpName (type);
1619 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1621 type = storey.MutateType (type);
1624 public static void Reset ()
1631 // Anonymous type container
1633 public class AnonymousTypeClass : CompilerGeneratedClass
1635 static int types_counter;
1636 public const string ClassNamePrefix = "<>__AnonType";
1637 public const string SignatureForError = "anonymous type";
1639 readonly ArrayList parameters;
1641 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1642 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1644 this.parameters = parameters;
1647 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1649 if (RootContext.Version <= LanguageVersion.ISO_2)
1650 Report.FeatureIsNotAvailable (loc, "anonymous types");
1652 string name = ClassNamePrefix + types_counter++;
1654 SimpleName [] t_args = new SimpleName [parameters.Count];
1655 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1656 Parameter [] ctor_params = new Parameter [parameters.Count];
1657 for (int i = 0; i < parameters.Count; ++i) {
1658 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1660 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1661 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1662 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1666 // Create generic anonymous type host with generic arguments
1667 // named upon properties names
1669 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1670 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1672 if (parameters.Count > 0)
1673 a_type.SetParameterInfo (null);
1675 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1676 null, new Parameters (ctor_params), null, loc);
1677 c.Block = new ToplevelBlock (c.Parameters, loc);
1680 // Create fields and contructor body with field initialization
1683 for (int i = 0; i < parameters.Count; ++i) {
1684 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1686 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1687 new MemberName ("<" + p.Name + ">", p.Location), null);
1689 if (!a_type.AddField (f)) {
1691 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1696 c.Block.AddStatement (new StatementExpression (
1697 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1698 c.Block.GetParameterReference (p.Name, p.Location))));
1700 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1701 get_block.AddStatement (new Return (
1702 new MemberAccess (new This (p.Location), f.Name), p.Location));
1703 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1704 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1705 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1706 a_type.AddProperty (prop);
1712 a_type.AddConstructor (c);
1716 public static void Reset ()
1721 protected override bool AddToContainer (MemberCore symbol, string name)
1723 MemberCore mc = (MemberCore) defined_names [name];
1726 defined_names.Add (name, symbol);
1730 Report.SymbolRelatedToPreviousError (mc);
1734 void DefineOverrides ()
1736 Location loc = Location;
1738 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1739 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1740 Mono.CSharp.Parameters.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1742 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1743 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1744 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1746 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1747 TypeExpr current_type;
1749 current_type = new GenericTypeExpr (this, loc);
1751 current_type = new TypeExpression (TypeBuilder, loc);
1753 equals_block.AddVariable (current_type, "other", loc);
1754 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1756 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1757 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1759 Expression rs_equals = null;
1760 Expression string_concat = new StringConstant ("<empty type>", loc);
1761 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1762 for (int i = 0; i < parameters.Count; ++i) {
1763 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1764 Field f = (Field) Fields [i];
1766 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1767 system_collections_generic, "EqualityComparer",
1768 new TypeArguments (new SimpleName (TypeParameters [i].Name, loc)), loc),
1771 ArrayList arguments_equal = new ArrayList (2);
1772 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1773 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1775 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1776 "Equals", loc), arguments_equal);
1778 ArrayList arguments_hashcode = new ArrayList (1);
1779 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1780 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1781 "GetHashCode", loc), arguments_hashcode);
1783 IntConstant FNV_prime = new IntConstant (16777619, loc);
1784 rs_hashcode = new Binary (Binary.Operator.Multiply,
1785 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1788 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1789 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1790 new Invocation (new MemberAccess (
1791 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1792 new StringConstant ("<null>", loc));
1794 if (rs_equals == null) {
1795 rs_equals = field_equal;
1796 string_concat = new Binary (Binary.Operator.Addition,
1797 new StringConstant (p.Name + " = ", loc),
1803 // Implementation of ToString () body using string concatenation
1805 string_concat = new Binary (Binary.Operator.Addition,
1806 new Binary (Binary.Operator.Addition,
1808 new StringConstant (", " + p.Name + " = ", loc)),
1811 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1815 // Equals (object obj) override
1817 equals_block.AddStatement (new StatementExpression (
1818 new SimpleAssign (other_variable,
1819 new As (equals_block.GetParameterReference ("obj", loc),
1820 current_type, loc), loc)));
1822 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1823 if (rs_equals != null)
1824 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1825 equals_block.AddStatement (new Return (equals_test, loc));
1827 equals.Block = equals_block;
1832 // GetHashCode () override
1834 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1835 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1836 new MemberName ("GetHashCode", loc),
1837 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1840 // Modified FNV with good avalanche behavior and uniform
1841 // distribution with larger hash sizes.
1843 // const int FNV_prime = 16777619;
1844 // int hash = (int) 2166136261;
1845 // foreach (int d in data)
1846 // hash = (hash ^ d) * FNV_prime;
1847 // hash += hash << 13;
1848 // hash ^= hash >> 7;
1849 // hash += hash << 3;
1850 // hash ^= hash >> 17;
1851 // hash += hash << 5;
1853 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1854 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1855 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1856 hashcode_block.AddStatement (new StatementExpression (
1857 new SimpleAssign (hash_variable, rs_hashcode)));
1859 hashcode_block.AddStatement (new StatementExpression (
1860 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1861 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1862 hashcode_block.AddStatement (new StatementExpression (
1863 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1864 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1865 hashcode_block.AddStatement (new StatementExpression (
1866 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1867 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1868 hashcode_block.AddStatement (new StatementExpression (
1869 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1870 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1871 hashcode_block.AddStatement (new StatementExpression (
1872 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1873 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1875 hashcode_block.AddStatement (new Return (hash_variable, loc));
1876 hashcode.Block = hashcode_block;
1878 AddMethod (hashcode);
1881 // ToString () override
1884 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1885 tostring_block.AddStatement (new Return (string_concat, loc));
1886 tostring.Block = tostring_block;
1888 AddMethod (tostring);
1891 public override bool Define ()
1893 if (!base.Define ())
1900 public override string GetSignatureForError ()
1902 return SignatureForError;
1905 public ArrayList Parameters {