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 public readonly Parameters Parameters;
833 ListDictionary compatibles;
834 public ToplevelBlock Block;
836 public AnonymousMethodExpression (Parameters parameters, Location loc)
838 this.Parameters = parameters;
840 this.compatibles = new ListDictionary ();
843 public override string ExprClassName {
845 return "anonymous method";
849 public virtual bool HasExplicitParameters {
851 return Parameters != null;
856 // Returns true if the body of lambda expression can be implicitly
857 // converted to the delegate of type `delegate_type'
859 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
861 using (ec.Set (EmitContext.Flags.ProbingMode)) {
862 return Compatible (ec, delegate_type) != null;
866 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
868 if (TypeManager.IsDelegateType (delegate_type))
869 return delegate_type;
872 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
873 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
874 if (TypeManager.IsDelegateType (delegate_type))
875 return delegate_type;
877 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
878 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
883 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
884 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
888 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
890 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
894 Report.Error (1661, loc,
895 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
896 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
901 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
903 if (Parameters.Count != invoke_pd.Count) {
907 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
908 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
912 bool has_implicit_parameters = !HasExplicitParameters;
915 for (int i = 0; i < Parameters.Count; ++i) {
916 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
917 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
921 if (p_mod == Parameter.Modifier.NONE)
922 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
923 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
925 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
926 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
930 if (has_implicit_parameters)
933 Type type = invoke_pd.Types [i];
935 // We assume that generic parameters are always inflated
936 if (TypeManager.IsGenericParameter (type))
939 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
942 if (invoke_pd.Types [i] != Parameters.Types [i]) {
946 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
948 TypeManager.CSharpName (Parameters.Types [i]),
949 TypeManager.CSharpName (invoke_pd.Types [i]));
958 // Infers type arguments based on explicit arguments
960 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
962 if (!HasExplicitParameters)
965 if (!TypeManager.IsDelegateType (delegate_type)) {
967 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
970 delegate_type = delegate_type.GetGenericArguments () [0];
971 if (!TypeManager.IsDelegateType (delegate_type))
978 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
979 if (d_params.Count != Parameters.Count)
982 for (int i = 0; i < Parameters.Count; ++i) {
983 Type itype = d_params.Types [i];
984 if (!TypeManager.IsGenericParameter (itype)) {
985 if (!TypeManager.HasElementType (itype))
988 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
991 type_inference.ExactInference (Parameters.Types [i], itype);
996 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
998 AnonymousMethodBody am;
999 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
1000 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
1006 if (am.ReturnType == TypeManager.null_type)
1007 am.ReturnType = null;
1009 return am.ReturnType;
1013 // Returns AnonymousMethod container if this anonymous method
1014 // expression can be implicitly converted to the delegate type `delegate_type'
1016 public Expression Compatible (EmitContext ec, Type type)
1018 Expression am = (Expression) compatibles [type];
1022 Type delegate_type = CompatibleChecks (ec, type);
1023 if (delegate_type == null)
1027 // At this point its the first time we know the return type that is
1028 // needed for the anonymous method. We create the method here.
1031 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1032 ec.ContainerType, delegate_type);
1033 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1036 Type[] g_args = delegate_type.GetGenericArguments ();
1037 if (return_type.IsGenericParameter)
1038 return_type = g_args [return_type.GenericParameterPosition];
1042 // Second: the return type of the delegate must be compatible with
1043 // the anonymous type. Instead of doing a pass to examine the block
1044 // we satisfy the rule by setting the return type on the EmitContext
1045 // to be the delegate type return type.
1049 int errors = Report.Errors;
1050 am = CompatibleMethod (ec, null, return_type, delegate_type);
1051 if (am != null && delegate_type != type && errors == Report.Errors)
1052 am = CreateExpressionTree (ec, delegate_type);
1054 if (!ec.IsInProbingMode)
1055 compatibles.Add (type, am);
1058 } catch (Exception e) {
1059 throw new InternalErrorException (e, loc);
1063 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1065 return CreateExpressionTree (ec);
1068 public override Expression CreateExpressionTree (EmitContext ec)
1070 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1074 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1076 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1078 if (Parameters == null) {
1080 // We provide a set of inaccessible parameters
1082 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1084 for (int i = 0; i < delegate_parameters.Count; i++) {
1085 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1086 if (i_mod == Parameter.Modifier.OUT) {
1087 Report.Error (1688, loc, "Cannot convert anonymous " +
1088 "method block without a parameter list " +
1089 "to delegate type `{0}' because it has " +
1090 "one or more `out' parameters.",
1091 TypeManager.CSharpName (delegate_type));
1094 fixedpars[i] = new Parameter (
1096 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1099 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1102 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1109 public override Expression DoResolve (EmitContext ec)
1111 if (!ec.IsAnonymousMethodAllowed) {
1112 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1117 // Set class type, set type
1120 eclass = ExprClass.Value;
1123 // This hack means `The type is not accessible
1124 // anywhere', we depend on special conversion
1127 type = TypeManager.anonymous_method_type;
1129 if ((Parameters != null) && !Parameters.Resolve (ec))
1132 // FIXME: The emitted code isn't very careful about reachability
1133 // so, ensure we have a 'ret' at the end
1134 if (ec.CurrentBranching != null &&
1135 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1136 ec.NeedReturnLabel ();
1141 public override void Emit (EmitContext ec)
1143 // nothing, as we only exist to not do anything.
1146 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1148 Report.Error (1686, loc,
1149 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1153 public override string GetSignatureForError ()
1155 return ExprClassName;
1158 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1160 Parameters p = ResolveParameters (ec, tic, delegate_type);
1164 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1166 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1167 if (!anonymous.Compatible (ec))
1173 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1175 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1178 protected override void CloneTo (CloneContext clonectx, Expression t)
1180 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1182 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1187 // Abstract expression for any block which requires variables hoisting
1189 public abstract class AnonymousExpression : Expression
1191 protected class AnonymousMethodMethod : Method
1193 public readonly AnonymousExpression AnonymousMethod;
1194 public readonly AnonymousMethodStorey Storey;
1195 readonly string RealName;
1197 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1198 GenericMethod generic, TypeExpr return_type,
1199 int mod, string real_name, MemberName name,
1200 Parameters parameters)
1201 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1202 name, parameters, null)
1204 this.AnonymousMethod = am;
1205 this.Storey = storey;
1206 this.RealName = real_name;
1208 Parent.PartialContainer.AddMethod (this);
1212 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1214 EmitContext aec = AnonymousMethod.aec;
1216 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1220 protected override bool ResolveMemberType ()
1222 if (!base.ResolveMemberType ())
1225 if (Storey != null && Storey.IsGeneric && Storey.HasHoistedVariables) {
1226 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1227 if (gstorey != null) {
1228 if (!Parameters.IsEmpty) {
1229 Type [] ptypes = Parameters.Types;
1230 for (int i = 0; i < ptypes.Length; ++i)
1231 ptypes [i] = gstorey.MutateType (ptypes [i]);
1234 member_type = gstorey.MutateType (member_type);
1241 public override void Emit ()
1244 // Before emitting any code we have to change all MVAR references to VAR
1245 // when the method is of generic type and has hoisted variables
1247 if (Storey == Parent && Storey.IsGeneric) {
1248 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1249 if (gstorey != null) {
1250 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1251 block.MutateHoistedGenericType (gstorey);
1255 if (MethodBuilder == null) {
1262 public override void EmitExtraSymbolInfo (SourceMethod source)
1264 source.SetRealMethodName (RealName);
1269 // The block that makes up the body for the anonymous method
1271 protected readonly ToplevelBlock Block;
1273 public Type ReturnType;
1274 protected EmitContext aec;
1276 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1278 this.ReturnType = return_type;
1283 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1284 public abstract string ContainerType { get; }
1285 public abstract bool IsIterator { get; }
1286 public abstract AnonymousMethodStorey Storey { get; }
1288 public bool Compatible (EmitContext ec)
1290 // TODO: Implement clone
1291 aec = new EmitContext (
1292 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1293 Location, null, ReturnType,
1294 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1296 aec.CurrentAnonymousMethod = this;
1297 aec.IsStatic = ec.IsStatic;
1299 IDisposable aec_dispose = null;
1300 EmitContext.Flags flags = 0;
1301 if (ec.InferReturnType)
1302 flags |= EmitContext.Flags.InferReturnType;
1304 if (ec.IsInProbingMode)
1305 flags |= EmitContext.Flags.ProbingMode;
1307 if (ec.IsInFieldInitializer)
1308 flags |= EmitContext.Flags.InFieldInitializer;
1310 if (ec.IsInUnsafeScope)
1311 flags |= EmitContext.Flags.InUnsafe;
1313 // HACK: Flag with 0 cannot be set
1315 aec_dispose = aec.Set (flags);
1318 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1320 if (ec.InferReturnType)
1321 ReturnType = aec.ReturnType;
1323 if (aec_dispose != null) {
1324 aec_dispose.Dispose ();
1331 public class AnonymousMethodBody : AnonymousExpression
1333 ArrayList referenced_storeys;
1334 protected readonly Parameters parameters;
1335 AnonymousMethodStorey storey;
1337 AnonymousMethodMethod method;
1340 static int unique_id;
1342 public AnonymousMethodBody (Parameters parameters,
1343 ToplevelBlock block, Type return_type, Type delegate_type,
1345 : base (block, return_type, loc)
1347 this.type = delegate_type;
1348 this.parameters = parameters;
1351 public override string ContainerType {
1352 get { return "anonymous method"; }
1355 public override AnonymousMethodStorey Storey {
1356 get { return storey; }
1359 public override bool IsIterator {
1360 get { return false; }
1364 // Adds new storey reference to track out of scope variables
1366 public override void AddStoreyReference (AnonymousMethodStorey storey)
1368 if (referenced_storeys == null) {
1369 referenced_storeys = new ArrayList (2);
1371 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1377 referenced_storeys.Add (storey);
1380 public override Expression CreateExpressionTree (EmitContext ec)
1382 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1386 bool Define (EmitContext ec)
1388 if (aec == null && !Compatible (ec))
1391 if (referenced_storeys != null)
1392 ConnectReferencedStoreys ();
1397 void ConnectReferencedStoreys ()
1399 storey = FindBestMethodStorey ();
1401 foreach (AnonymousMethodStorey s in referenced_storeys) {
1403 // An anonymous method has to have an instance access when
1404 // children anonymous method requires access to parent storey
1405 // hoisted variables
1407 for (Block b = Block.Parent; b != s.OriginalSourceBlock; b = b.Parent)
1408 b.Toplevel.HasStoreyAccess = true;
1413 s.HasHoistedVariables = true;
1414 Block.Parent.Explicit.PropagateStoreyReference (s);
1419 // Creates a host for the anonymous method
1421 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1424 // Anonymous method body can be converted to
1426 // 1, an instance method in current scope when only `this' is hoisted
1427 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1428 // 3, an instance method in compiler generated storey when any hoisted variable exists
1432 if (referenced_storeys != null || Block.HasStoreyAccess) {
1433 if (storey == null || storey.IsUndone)
1434 storey = FindBestMethodStorey ();
1436 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1438 if (ec.CurrentAnonymousMethod != null)
1439 storey = ec.CurrentAnonymousMethod.Storey;
1441 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1444 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1446 MemberCore mc = ec.ResolveContext as MemberCore;
1447 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1448 "m", null, unique_id++);
1450 MemberName member_name;
1451 GenericMethod generic_method;
1452 if (storey == null && mc.MemberName.IsGeneric) {
1453 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1455 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1456 new TypeExpression (ReturnType, Location), parameters);
1458 ArrayList list = new ArrayList ();
1459 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1460 if (tparam.Constraints != null)
1461 list.Add (tparam.Constraints.Clone ());
1463 generic_method.SetParameterInfo (list);
1465 member_name = new MemberName (name, Location);
1466 generic_method = null;
1469 string real_name = String.Format (
1470 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1471 parameters.GetSignatureForError ());
1473 return new AnonymousMethodMethod (parent,
1474 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1475 real_name, member_name, parameters);
1478 public override Expression DoResolve (EmitContext ec)
1480 if (eclass == ExprClass.Invalid) {
1485 eclass = ExprClass.Value;
1489 public override void Emit (EmitContext ec)
1492 // Use same anonymous method implementation for scenarios where same
1493 // code is used from multiple blocks, e.g. field initializers
1495 if (method == null) {
1497 // Delay an anonymous method definition to avoid emitting unused code
1498 // for unreachable blocks or expression trees
1500 method = DoCreateMethodHost (ec);
1504 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1505 if (is_static && am_cache == null) {
1507 // Creates a field cache to store delegate instance if it's not generic
1509 if (!method.MemberName.IsGeneric) {
1510 TypeContainer parent = method.Parent.PartialContainer;
1511 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1512 am_cache = new Field (parent, new TypeExpression (type, loc),
1513 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1514 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1516 parent.AddField (am_cache);
1518 // TODO: Implement caching of generated generic static methods
1522 // Some extra class is needed to capture variable generic type
1523 // arguments. Maybe we could re-use anonymous types, with a unique
1524 // anonymous method id, but they are quite heavy.
1526 // Consider : "() => typeof(T);"
1528 // We need something like
1529 // static class Wrap<Tn, Tm, DelegateType> {
1530 // public static DelegateType cache;
1533 // We then specialize local variable to capture all generic parameters
1534 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1539 ILGenerator ig = ec.ig;
1540 Label l_initialized = ig.DefineLabel ();
1542 if (am_cache != null) {
1543 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1544 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1548 // Load method delegate implementation
1552 ig.Emit (OpCodes.Ldnull);
1553 } else if (storey != null) {
1554 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1558 ig.Emit (OpCodes.Ldarg_0);
1561 MethodInfo delegate_method = method.MethodBuilder;
1563 if (storey != null && storey.MemberName.IsGeneric) {
1564 Type t = storey.Instance.Type;
1567 // Mutate anonymous method instance type if we are in nested
1568 // hoisted generic anonymous method storey
1570 if (ec.CurrentAnonymousMethod != null &&
1571 ec.CurrentAnonymousMethod.Storey != null &&
1572 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1573 t = storey.GetGenericStorey ().MutateType (t);
1576 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1579 ig.Emit (OpCodes.Ldftn, delegate_method);
1581 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1583 if (type.IsGenericType && type is TypeBuilder)
1584 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1586 ig.Emit (OpCodes.Newobj, constructor_method);
1588 if (am_cache != null) {
1589 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1590 ig.MarkLabel (l_initialized);
1591 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1596 // Look for the best storey for this anonymous method
1598 AnonymousMethodStorey FindBestMethodStorey ()
1601 // Use the nearest parent block which has a storey
1603 for (Block b = Block.Parent; b != null; b = b.Parent) {
1604 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1612 public override string GetSignatureForError ()
1614 return TypeManager.CSharpName (type);
1617 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1619 type = storey.MutateType (type);
1622 public static void Reset ()
1629 // Anonymous type container
1631 public class AnonymousTypeClass : CompilerGeneratedClass
1633 static int types_counter;
1634 public const string ClassNamePrefix = "<>__AnonType";
1635 public const string SignatureForError = "anonymous type";
1637 readonly ArrayList parameters;
1639 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1640 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1642 this.parameters = parameters;
1645 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1647 if (RootContext.Version <= LanguageVersion.ISO_2)
1648 Report.FeatureIsNotAvailable (loc, "anonymous types");
1650 string name = ClassNamePrefix + types_counter++;
1652 SimpleName [] t_args = new SimpleName [parameters.Count];
1653 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1654 Parameter [] ctor_params = new Parameter [parameters.Count];
1655 for (int i = 0; i < parameters.Count; ++i) {
1656 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1658 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1659 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1660 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1664 // Create generic anonymous type host with generic arguments
1665 // named upon properties names
1667 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1668 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1670 if (parameters.Count > 0)
1671 a_type.SetParameterInfo (null);
1673 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1674 null, new Parameters (ctor_params), null, loc);
1675 c.Block = new ToplevelBlock (c.Parameters, loc);
1678 // Create fields and contructor body with field initialization
1681 for (int i = 0; i < parameters.Count; ++i) {
1682 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1684 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1685 new MemberName ("<" + p.Name + ">", p.Location), null);
1687 if (!a_type.AddField (f)) {
1689 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1694 c.Block.AddStatement (new StatementExpression (
1695 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1696 c.Block.GetParameterReference (p.Name, p.Location))));
1698 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1699 get_block.AddStatement (new Return (
1700 new MemberAccess (new This (p.Location), f.Name), p.Location));
1701 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1702 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1703 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1704 a_type.AddProperty (prop);
1710 a_type.AddConstructor (c);
1714 public static void Reset ()
1719 protected override bool AddToContainer (MemberCore symbol, string name)
1721 MemberCore mc = (MemberCore) defined_names [name];
1724 defined_names.Add (name, symbol);
1728 Report.SymbolRelatedToPreviousError (mc);
1732 void DefineOverrides ()
1734 Location loc = Location;
1736 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1737 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1738 Mono.CSharp.Parameters.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1740 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1741 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1742 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1744 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1745 TypeExpr current_type;
1747 current_type = new GenericTypeExpr (this, loc);
1749 current_type = new TypeExpression (TypeBuilder, loc);
1751 equals_block.AddVariable (current_type, "other", loc);
1752 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1754 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1755 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1757 Expression rs_equals = null;
1758 Expression string_concat = new StringConstant ("<empty type>", loc);
1759 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1760 for (int i = 0; i < parameters.Count; ++i) {
1761 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1762 Field f = (Field) Fields [i];
1764 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1765 system_collections_generic, "EqualityComparer",
1766 new TypeArguments (new SimpleName (TypeParameters [i].Name, loc)), loc),
1769 ArrayList arguments_equal = new ArrayList (2);
1770 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1771 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1773 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1774 "Equals", loc), arguments_equal);
1776 ArrayList arguments_hashcode = new ArrayList (1);
1777 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1778 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1779 "GetHashCode", loc), arguments_hashcode);
1781 IntConstant FNV_prime = new IntConstant (16777619, loc);
1782 rs_hashcode = new Binary (Binary.Operator.Multiply,
1783 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1786 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1787 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1788 new Invocation (new MemberAccess (
1789 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1790 new StringConstant ("<null>", loc));
1792 if (rs_equals == null) {
1793 rs_equals = field_equal;
1794 string_concat = new Binary (Binary.Operator.Addition,
1795 new StringConstant (p.Name + " = ", loc),
1801 // Implementation of ToString () body using string concatenation
1803 string_concat = new Binary (Binary.Operator.Addition,
1804 new Binary (Binary.Operator.Addition,
1806 new StringConstant (", " + p.Name + " = ", loc)),
1809 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1813 // Equals (object obj) override
1815 equals_block.AddStatement (new StatementExpression (
1816 new SimpleAssign (other_variable,
1817 new As (equals_block.GetParameterReference ("obj", loc),
1818 current_type, loc), loc)));
1820 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1821 if (rs_equals != null)
1822 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1823 equals_block.AddStatement (new Return (equals_test, loc));
1825 equals.Block = equals_block;
1830 // GetHashCode () override
1832 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1833 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1834 new MemberName ("GetHashCode", loc),
1835 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1838 // Modified FNV with good avalanche behavior and uniform
1839 // distribution with larger hash sizes.
1841 // const int FNV_prime = 16777619;
1842 // int hash = (int) 2166136261;
1843 // foreach (int d in data)
1844 // hash = (hash ^ d) * FNV_prime;
1845 // hash += hash << 13;
1846 // hash ^= hash >> 7;
1847 // hash += hash << 3;
1848 // hash ^= hash >> 17;
1849 // hash += hash << 5;
1851 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1852 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1853 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1854 hashcode_block.AddStatement (new StatementExpression (
1855 new SimpleAssign (hash_variable, rs_hashcode)));
1857 hashcode_block.AddStatement (new StatementExpression (
1858 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1859 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1860 hashcode_block.AddStatement (new StatementExpression (
1861 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1862 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1863 hashcode_block.AddStatement (new StatementExpression (
1864 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1865 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1866 hashcode_block.AddStatement (new StatementExpression (
1867 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1868 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1869 hashcode_block.AddStatement (new StatementExpression (
1870 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1871 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1873 hashcode_block.AddStatement (new Return (hash_variable, loc));
1874 hashcode.Block = hashcode_block;
1876 AddMethod (hashcode);
1879 // ToString () override
1882 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1883 tostring_block.AddStatement (new Return (string_concat, loc));
1884 tostring.Block = tostring_block;
1886 AddMethod (tostring);
1889 public override bool Define ()
1891 if (!base.Define ())
1898 public override string GetSignatureForError ()
1900 return SignatureForError;
1903 public ArrayList Parameters {