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, name, attrs, loc)
88 public override bool Define ()
90 AnonymousMethodStorey parent = ((AnonymousMethodStorey) Parent).GetGenericStorey ();
92 type_name.Type = parent.MutateType (type_name.Type);
94 return base.Define ();
99 public readonly int ID;
100 static int unique_id;
102 public readonly Block OriginalSourceBlock;
104 // A list of StoreyFieldPair with local field keeping parent storey instance
105 ArrayList used_parent_storeys;
107 // A list of hoisted parameters
108 protected ArrayList hoisted_params;
111 protected HoistedThis hoisted_this;
113 // Local variable which holds this storey instance
114 public LocalTemporary Instance;
116 bool references_defined;
117 bool has_hoisted_variable;
119 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
120 : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE)
123 OriginalSourceBlock = block;
127 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
129 string host_name = host == null ? null : host.Name;
130 string tname = MakeName (host_name, "c", name, unique_id);
131 TypeArguments args = null;
132 if (generic != null) {
133 args = new TypeArguments (loc);
134 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
135 args.Add (new SimpleName (tparam.Name, loc));
138 return new MemberName (tname, args, loc);
141 public Field AddCapturedVariable (string name, Type type)
143 CheckMembersDefined ();
145 FullNamedExpression field_type = new TypeExpression (type, Location);
147 return AddCompilerGeneratedField (name, field_type);
149 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
150 Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
155 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
157 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
158 Field f = new Field (this, type, mod, name, null, Location);
163 public void AddParentStoreyReference (AnonymousMethodStorey s)
165 CheckMembersDefined ();
167 if (used_parent_storeys == null)
168 used_parent_storeys = new ArrayList ();
169 else if (used_parent_storeys.IndexOf (s) != -1)
172 has_hoisted_variable = true;
173 used_parent_storeys.Add (new StoreyFieldPair (s));
176 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
178 if (local_info.HoistedVariableReference != null)
181 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
182 local_info.HoistedVariableReference = var;
183 has_hoisted_variable = true;
186 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
188 if (param_ref.HoistedVariable != null)
191 if (hoisted_params == null)
192 hoisted_params = new ArrayList (2);
194 HoistedVariable expr = new HoistedParameter (this, param_ref);
195 param_ref.Parameter.HoistedVariableReference = expr;
196 hoisted_params.Add (expr);
199 public HoistedThis CaptureThis (EmitContext ec, This t)
201 hoisted_this = new HoistedThis (this, t);
205 public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
207 Parent = parentStorey;
211 void DefineStoreyReferences ()
213 if (used_parent_storeys == null || references_defined)
216 references_defined = true;
219 // For each used variable from parent scope we allocate its local reference point
221 for (int i = 0; i < used_parent_storeys.Count; ++i) {
222 StoreyFieldPair sf = (StoreyFieldPair) used_parent_storeys [i];
223 AnonymousMethodStorey p_storey = sf.Storey;
224 TypeExpr type_expr = new TypeExpression (p_storey.TypeBuilder, Location);
226 sf.Field = AddCompilerGeneratedField ("<>f__ref$" + p_storey.ID, type_expr);
232 // Initializes all hoisted variables
234 public void EmitHoistedVariables (EmitContext ec)
236 // There can be only one instance variable for each storey type
237 if (Instance != null)
238 throw new InternalErrorException ();
241 // A storey with hoisted `this' is an instance method
243 if (!HasHoistedVariables) {
244 hoisted_this.RemoveHoisting ();
248 SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
250 DefineStoreyReferences ();
253 // Create an instance of storey type
255 Expression storey_type_expr;
258 // Use current method type parameter (MVAR) for top level storey only. All
259 // nested storeys use class type parameter (VAR)
261 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
262 ec.CurrentAnonymousMethod.Storey.TypeParameters :
263 ec.GenericDeclContainer.TypeParameters;
265 if (tparams.Length != CountTypeParameters) {
266 TypeParameter [] full = new TypeParameter [CountTypeParameters];
267 DeclSpace parent = ec.DeclContainer.Parent;
268 parent.CurrentTypeParameters.CopyTo (full, 0);
269 tparams.CopyTo (full, parent.CountTypeParameters);
273 storey_type_expr = new ConstructedType (TypeBuilder, tparams, Location);
275 storey_type_expr = new TypeExpression (TypeBuilder, Location);
278 Expression e = new New (storey_type_expr, new ArrayList (0), Location).Resolve (ec);
281 Instance = new LocalTemporary (storey_type_expr.Type);
284 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
286 EmitHoistedFieldsInitialization (ec);
288 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
291 void EmitHoistedFieldsInitialization (EmitContext ec)
294 // Initialize all storey reference fields by using local or hoisted variables
296 if (used_parent_storeys != null) {
297 foreach (StoreyFieldPair sf in used_parent_storeys) {
299 // Setting local field
301 Expression instace_expr = GetStoreyInstanceExpression (ec);
302 FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
303 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
304 new FieldExpr (sf.Field.FieldBuilder, Location);
305 f_set_expr.InstanceExpression = instace_expr;
307 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
308 if (a.Resolve (ec) != null)
309 a.EmitStatement (ec);
314 // Setting currect anonymous method to null blocks any further variable hoisting
316 AnonymousExpression ae = ec.CurrentAnonymousMethod;
317 ec.CurrentAnonymousMethod = null;
319 if (hoisted_params != null) {
320 EmitHoistedParameters (ec, hoisted_params);
323 if (hoisted_this != null) {
324 hoisted_this.EmitHoistingAssignment (ec);
327 ec.CurrentAnonymousMethod = ae;
330 protected virtual void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
332 foreach (HoistedParameter hp in hoisted) {
333 hp.EmitHoistingAssignment (ec);
337 public override void EmitType ()
339 SymbolWriter.DefineAnonymousScope (ID);
341 if (hoisted_this != null)
342 hoisted_this.EmitSymbolInfo ();
344 foreach (LocalInfo li in OriginalSourceBlock.Variables.Values) {
345 HoistedVariable hv = li.HoistedVariableReference;
347 hv.EmitSymbolInfo ();
350 if (hoisted_params != null) {
351 foreach (HoistedParameter param in hoisted_params)
352 param.EmitSymbolInfo ();
355 DefineStoreyReferences ();
357 if (used_parent_storeys != null) {
358 foreach (StoreyFieldPair sf in used_parent_storeys) {
359 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
366 public AnonymousMethodStorey GetGenericStorey ()
368 DeclSpace storey = this;
369 while (storey != null && storey.CurrentTypeParameters.Length == 0)
370 storey = storey.Parent;
372 return storey as AnonymousMethodStorey;
376 // Returns a field which holds referenced storey instance
378 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
380 if (used_parent_storeys == null)
383 foreach (StoreyFieldPair sf in used_parent_storeys) {
384 if (sf.Storey == storey)
392 // Creates storey instance expression regardless of currect IP
394 public Expression GetStoreyInstanceExpression (EmitContext ec)
396 AnonymousExpression am = ec.CurrentAnonymousMethod;
399 // Access from original block -> storey
405 // Access from anonymous method implemented as a static -> storey
407 if (am.Storey == null)
410 Field f = am.Storey.GetReferencedStoreyField (this);
412 if (am.Storey == this) {
414 // Access inside of same storey (S -> S)
416 return new CompilerGeneratedThis (TypeBuilder, Location);
419 // External field access
425 // Storey was cached to local field
427 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
428 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
432 protected virtual string GetVariableMangledName (LocalInfo local_info)
435 // No need to mangle anonymous method hoisted variables cause they
436 // are hoisted in their own scopes
438 return local_info.Name;
442 // Returns true when at least one local variable or parameter is
443 // hoisted, or story is transitioned
445 public bool HasHoistedVariables {
447 return has_hoisted_variable || hoisted_params != null;
450 has_hoisted_variable = value;
455 // Mutate type dispatcher
457 public Type MutateType (Type type)
460 if (TypeManager.IsGenericType (type))
461 return MutateGenericType (type);
463 if (TypeManager.IsGenericParameter (type))
464 return MutateGenericArgument (type);
467 return MutateArrayType (type);
473 // Changes method type arguments (MVAR) to storey (VAR) type arguments
475 public MethodInfo MutateGenericMethod (MethodInfo method)
478 Type [] t_args = TypeManager.GetGenericArguments (method);
479 if (TypeManager.IsGenericType (method.DeclaringType)) {
480 Type t = MutateGenericType (method.DeclaringType);
481 if (t != method.DeclaringType) {
482 method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
483 if (method.Module == CodeGen.Module.Builder)
484 method = TypeBuilder.GetMethod (t, method);
486 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
490 if (t_args == null || t_args.Length == 0)
493 for (int i = 0; i < t_args.Length; ++i)
494 t_args [i] = MutateType (t_args [i]);
496 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
498 throw new NotSupportedException ();
502 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
505 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
506 Type t = MutateGenericType (ctor.DeclaringType);
507 if (t != ctor.DeclaringType) {
508 // TODO: It should throw on imported types
509 return TypeBuilder.GetConstructor (t, ctor);
516 public FieldInfo MutateField (FieldInfo field)
519 if (TypeManager.IsGenericType (field.DeclaringType)) {
520 Type t = MutateGenericType (field.DeclaringType);
521 if (t != field.DeclaringType) {
522 // TODO: It should throw on imported types
523 return TypeBuilder.GetField (t, field);
531 protected Type MutateArrayType (Type array)
533 int rank = array.GetArrayRank ();
534 Type element = TypeManager.GetElementType (array);
536 throw new NotImplementedException ();
538 if (TypeManager.IsGenericParameter (element)) {
539 element = MutateGenericArgument (element);
540 } else if (TypeManager.IsGenericType (element)) {
541 element = MutateGenericType (element);
546 return element.MakeArrayType (rank);
549 protected Type MutateGenericType (Type type)
551 Type [] t_args = TypeManager.GetTypeArguments (type);
552 if (t_args == null || t_args.Length == 0)
555 for (int i = 0; i < t_args.Length; ++i)
556 t_args [i] = MutateType (t_args [i]);
558 return type.GetGenericTypeDefinition ().MakeGenericType (t_args);
563 // Changes method generic argument (MVAR) to type generic argument (VAR)
565 public Type MutateGenericArgument (Type type)
567 foreach (TypeParameter tp in CurrentTypeParameters) {
568 if (tp.Name == type.Name) {
576 public static void Reset ()
583 if (hoisted_this != null)
584 hoisted_this.RemoveHoisting ();
588 public abstract class HoistedVariable
590 class ExpressionTreeProxy : Expression
592 readonly HoistedVariable hv;
594 public ExpressionTreeProxy (HoistedVariable hv)
599 public override Expression CreateExpressionTree (EmitContext ec)
601 throw new NotSupportedException ("ET");
604 public override Expression DoResolve (EmitContext ec)
606 eclass = ExprClass.Value;
607 type = TypeManager.expression_type_expr.Type;
611 public override void Emit (EmitContext ec)
613 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (ec);
614 // This should never fail
621 protected readonly AnonymousMethodStorey storey;
622 protected Field field;
623 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
625 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
627 this.storey = storey;
629 this.field = storey.AddCapturedVariable (name, type);
632 public void AddressOf (EmitContext ec, AddressOp mode)
634 GetFieldExpression (ec).AddressOf (ec, mode);
637 public Expression CreateExpressionTree (EmitContext ec)
639 return new ExpressionTreeProxy (this);
642 public void Emit (EmitContext ec)
644 GetFieldExpression (ec).Emit (ec);
648 // Creates field access expression for hoisted variable
650 protected FieldExpr GetFieldExpression (EmitContext ec)
652 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
654 // When setting top-level hoisted variable in generic storey
655 // change storey generic types to method generic types (VAR -> MVAR)
657 FieldExpr outer_access = storey.MemberName.IsGeneric ?
658 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
659 new FieldExpr (field.FieldBuilder, field.Location);
661 outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
662 outer_access.Resolve (ec);
666 FieldExpr inner_access;
667 if (cached_inner_access != null) {
668 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
671 cached_inner_access = new Hashtable (4);
674 if (inner_access == null) {
675 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
676 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
677 inner_access.Resolve (ec);
678 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
684 public abstract void EmitSymbolInfo ();
686 public void Emit (EmitContext ec, bool leave_copy)
688 GetFieldExpression (ec).Emit (ec, leave_copy);
691 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
693 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
697 class HoistedParameter : HoistedVariable
699 sealed class HoistedFieldAssign : Assign
701 public HoistedFieldAssign (Expression target, Expression source)
702 : base (target, source, source.Location)
706 protected override Expression ResolveConversions (EmitContext ec)
709 // Implicit conversion check fails for hoisted type arguments
710 // as they are of different types (!!0 x !0)
716 readonly ParameterReference parameter;
718 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
719 : base (scope, par.Name, par.Type)
721 this.parameter = par;
724 public HoistedParameter (HoistedParameter hp, string name)
725 : base (hp.storey, name, hp.parameter.Type)
727 this.parameter = hp.parameter;
730 public void EmitHoistingAssignment (EmitContext ec)
733 // Remove hoisted redirection to emit assignment from original parameter
735 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
736 parameter.Parameter.HoistedVariableReference = null;
738 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
739 if (a.Resolve (ec) != null)
740 a.EmitStatement (ec);
742 parameter.Parameter.HoistedVariableReference = temp;
745 public override void EmitSymbolInfo ()
747 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
751 get { return field; }
755 class HoistedLocalVariable : HoistedVariable
757 readonly string name;
759 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
760 : base (scope, name, local.VariableType)
762 this.name = local.Name;
765 public override void EmitSymbolInfo ()
767 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
771 public class HoistedThis : HoistedVariable
773 readonly This this_reference;
775 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
776 : base (storey, "<>f__this", this_reference.Type)
778 this.this_reference = this_reference;
781 public void EmitHoistingAssignment (EmitContext ec)
783 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
784 if (a.Resolve (ec) != null)
785 a.EmitStatement (ec);
788 public override void EmitSymbolInfo ()
790 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
794 get { return field; }
797 public void RemoveHoisting ()
799 this_reference.RemoveHoisting ();
804 // Anonymous method expression as created by parser
806 public class AnonymousMethodExpression : Expression
808 public readonly Parameters Parameters;
809 ListDictionary compatibles;
810 public ToplevelBlock Block;
812 public AnonymousMethodExpression (Parameters parameters, Location loc)
814 this.Parameters = parameters;
816 this.compatibles = new ListDictionary ();
819 public override string ExprClassName {
821 return "anonymous method";
825 public virtual bool HasExplicitParameters {
827 return Parameters != null;
832 // Returns true if the body of lambda expression can be implicitly
833 // converted to the delegate of type `delegate_type'
835 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
837 using (ec.Set (EmitContext.Flags.ProbingMode)) {
838 return Compatible (ec, delegate_type) != null;
842 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
844 if (TypeManager.IsDelegateType (delegate_type))
845 return delegate_type;
848 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
849 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
850 if (TypeManager.IsDelegateType (delegate_type))
851 return delegate_type;
853 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
854 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
859 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
860 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
864 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
866 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
870 Report.Error (1661, loc,
871 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
872 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
877 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
879 if (Parameters.Count != invoke_pd.Count) {
883 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
884 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
888 bool has_implicit_parameters = !HasExplicitParameters;
891 for (int i = 0; i < Parameters.Count; ++i) {
892 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
893 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
897 if (p_mod == Parameter.Modifier.NONE)
898 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
899 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
901 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
902 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
906 if (has_implicit_parameters)
909 Type type = invoke_pd.Types [i];
911 // We assume that generic parameters are always inflated
912 if (TypeManager.IsGenericParameter (type))
915 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
918 if (invoke_pd.Types [i] != Parameters.Types [i]) {
922 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
924 TypeManager.CSharpName (Parameters.Types [i]),
925 TypeManager.CSharpName (invoke_pd.Types [i]));
934 // Infers type arguments based on explicit arguments
936 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
938 if (!HasExplicitParameters)
941 if (!TypeManager.IsDelegateType (delegate_type)) {
943 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
946 delegate_type = delegate_type.GetGenericArguments () [0];
947 if (!TypeManager.IsDelegateType (delegate_type))
954 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
955 if (d_params.Count != Parameters.Count)
958 for (int i = 0; i < Parameters.Count; ++i) {
959 Type itype = d_params.Types [i];
960 if (!TypeManager.IsGenericParameter (itype)) {
961 if (!TypeManager.HasElementType (itype))
964 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
967 type_inference.ExactInference (Parameters.Types [i], itype);
972 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
974 AnonymousMethodBody am;
975 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
976 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
982 if (am.ReturnType == TypeManager.null_type)
983 am.ReturnType = null;
985 return am.ReturnType;
989 // Returns AnonymousMethod container if this anonymous method
990 // expression can be implicitly converted to the delegate type `delegate_type'
992 public Expression Compatible (EmitContext ec, Type type)
994 Expression am = (Expression) compatibles [type];
998 Type delegate_type = CompatibleChecks (ec, type);
999 if (delegate_type == null)
1003 // At this point its the first time we know the return type that is
1004 // needed for the anonymous method. We create the method here.
1007 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1008 ec.ContainerType, delegate_type);
1009 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1012 Type[] g_args = delegate_type.GetGenericArguments ();
1013 if (return_type.IsGenericParameter)
1014 return_type = g_args [return_type.GenericParameterPosition];
1018 // Second: the return type of the delegate must be compatible with
1019 // the anonymous type. Instead of doing a pass to examine the block
1020 // we satisfy the rule by setting the return type on the EmitContext
1021 // to be the delegate type return type.
1025 int errors = Report.Errors;
1026 am = CompatibleMethod (ec, null, return_type, delegate_type);
1027 if (am != null && delegate_type != type && errors == Report.Errors)
1028 am = CreateExpressionTree (ec, delegate_type);
1030 if (!ec.IsInProbingMode)
1031 compatibles.Add (type, am);
1034 } catch (Exception e) {
1035 throw new InternalErrorException (e, loc);
1039 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1041 return CreateExpressionTree (ec);
1044 public override Expression CreateExpressionTree (EmitContext ec)
1046 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1050 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1052 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1054 if (Parameters == null) {
1056 // We provide a set of inaccessible parameters
1058 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1060 for (int i = 0; i < delegate_parameters.Count; i++) {
1061 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1062 if (i_mod == Parameter.Modifier.OUT) {
1063 Report.Error (1688, loc, "Cannot convert anonymous " +
1064 "method block without a parameter list " +
1065 "to delegate type `{0}' because it has " +
1066 "one or more `out' parameters.",
1067 TypeManager.CSharpName (delegate_type));
1070 fixedpars[i] = new Parameter (
1072 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1075 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1078 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1085 public override Expression DoResolve (EmitContext ec)
1087 if (!ec.IsAnonymousMethodAllowed) {
1088 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1093 // Set class type, set type
1096 eclass = ExprClass.Value;
1099 // This hack means `The type is not accessible
1100 // anywhere', we depend on special conversion
1103 type = TypeManager.anonymous_method_type;
1105 if ((Parameters != null) && !Parameters.Resolve (ec))
1108 // FIXME: The emitted code isn't very careful about reachability
1109 // so, ensure we have a 'ret' at the end
1110 if (ec.CurrentBranching != null &&
1111 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1112 ec.NeedReturnLabel ();
1117 public override void Emit (EmitContext ec)
1119 // nothing, as we only exist to not do anything.
1122 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1124 Report.Error (1686, loc,
1125 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1129 public override string GetSignatureForError ()
1131 return ExprClassName;
1134 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1136 Parameters p = ResolveParameters (ec, tic, delegate_type);
1140 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1142 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1143 if (!anonymous.Compatible (ec))
1149 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1151 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1154 protected override void CloneTo (CloneContext clonectx, Expression t)
1156 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1158 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1163 // Abstract expression for any block which requires variables hoisting
1165 public abstract class AnonymousExpression : Expression
1167 protected class AnonymousMethodMethod : Method
1169 public readonly AnonymousExpression AnonymousMethod;
1170 public readonly AnonymousMethodStorey Storey;
1171 readonly string RealName;
1173 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1174 GenericMethod generic, TypeExpr return_type,
1175 int mod, string real_name, MemberName name,
1176 Parameters parameters)
1177 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1178 name, parameters, null)
1180 this.AnonymousMethod = am;
1181 this.Storey = storey;
1182 this.RealName = real_name;
1184 Parent.PartialContainer.AddMethod (this);
1188 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1190 EmitContext aec = AnonymousMethod.aec;
1192 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1196 public override bool Define ()
1198 if (Storey != null && Storey.IsGeneric && Storey.HasHoistedVariables) {
1199 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1200 if (gstorey != null) {
1201 if (!Parameters.IsEmpty) {
1202 Type [] ptypes = Parameters.Types;
1203 for (int i = 0; i < ptypes.Length; ++i)
1204 ptypes [i] = gstorey.MutateType (ptypes [i]);
1207 member_type = gstorey.MutateType (ReturnType);
1211 return base.Define ();
1214 public override void Emit ()
1217 // Before emitting any code we have to change all MVAR references to VAR
1218 // when the method is of generic type and has hoisted variables
1220 if (Storey == Parent && Storey.IsGeneric) {
1221 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1222 if (gstorey != null) {
1223 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1224 block.MutateHoistedGenericType (gstorey);
1228 if (MethodBuilder == null) {
1235 public override void EmitExtraSymbolInfo (SourceMethod source)
1237 source.SetRealMethodName (RealName);
1242 // The block that makes up the body for the anonymous method
1244 protected readonly ToplevelBlock Block;
1246 public Type ReturnType;
1247 protected EmitContext aec;
1249 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1251 this.ReturnType = return_type;
1256 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1257 public abstract string ContainerType { get; }
1258 public abstract bool IsIterator { get; }
1259 public abstract AnonymousMethodStorey Storey { get; }
1261 public bool Compatible (EmitContext ec)
1263 // TODO: Implement clone
1264 aec = new EmitContext (
1265 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1266 Location, null, ReturnType,
1267 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1269 aec.CurrentAnonymousMethod = this;
1270 aec.IsStatic = ec.IsStatic;
1272 IDisposable aec_dispose = null;
1273 EmitContext.Flags flags = 0;
1274 if (ec.InferReturnType)
1275 flags |= EmitContext.Flags.InferReturnType;
1277 if (ec.IsInProbingMode)
1278 flags |= EmitContext.Flags.ProbingMode;
1280 if (ec.IsInFieldInitializer)
1281 flags |= EmitContext.Flags.InFieldInitializer;
1283 if (ec.IsInUnsafeScope)
1284 flags |= EmitContext.Flags.InUnsafe;
1286 // HACK: Flag with 0 cannot be set
1288 aec_dispose = aec.Set (flags);
1291 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1293 if (ec.InferReturnType)
1294 ReturnType = aec.ReturnType;
1296 if (aec_dispose != null) {
1297 aec_dispose.Dispose ();
1304 public class AnonymousMethodBody : AnonymousExpression
1306 ArrayList referenced_storeys;
1307 protected readonly Parameters parameters;
1308 AnonymousMethodStorey storey;
1310 AnonymousMethodMethod method;
1313 static int unique_id;
1315 public AnonymousMethodBody (Parameters parameters,
1316 ToplevelBlock block, Type return_type, Type delegate_type,
1318 : base (block, return_type, loc)
1320 this.type = delegate_type;
1321 this.parameters = parameters;
1324 public override string ContainerType {
1325 get { return "anonymous method"; }
1328 public override AnonymousMethodStorey Storey {
1329 get { return storey; }
1332 public override bool IsIterator {
1333 get { return false; }
1337 // Adds new storey reference to track out of scope variables
1339 public override void AddStoreyReference (AnonymousMethodStorey storey)
1341 if (referenced_storeys == null) {
1342 referenced_storeys = new ArrayList (2);
1344 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1350 referenced_storeys.Add (storey);
1353 public override Expression CreateExpressionTree (EmitContext ec)
1355 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1359 bool Define (EmitContext ec)
1361 if (aec == null && !Compatible (ec))
1364 if (referenced_storeys != null)
1365 ConnectReferencedStoreys ();
1370 void ConnectReferencedStoreys ()
1372 AnonymousMethodStorey storey = FindBestMethodStorey ();
1374 foreach (AnonymousMethodStorey s in referenced_storeys) {
1376 // An anonymous method has to have an instance access when
1377 // children anonymous method requires access to parent storey
1378 // hoisted variables
1380 for (Block b = Block.Parent; b != s.OriginalSourceBlock; b = b.Parent)
1381 b.Toplevel.HasStoreyAccess = true;
1386 s.HasHoistedVariables = true;
1387 Block.Parent.Explicit.PropagateStoreyReference (s);
1392 // Creates a host for the anonymous method
1394 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1397 // Anonymous method body can be converted to
1399 // 1, an instance method in current scope when only `this' is hoisted
1400 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1401 // 3, an instance method in compiler generated storey when any hoisted variable exists
1405 if (referenced_storeys != null || Block.HasStoreyAccess) {
1406 storey = FindBestMethodStorey ();
1407 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1409 if (ec.CurrentAnonymousMethod != null)
1410 storey = ec.CurrentAnonymousMethod.Storey;
1412 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1415 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1417 MemberCore mc = ec.ResolveContext as MemberCore;
1418 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1419 "m", null, unique_id++);
1421 MemberName member_name;
1422 GenericMethod generic_method;
1423 if (storey == null && mc.MemberName.IsGeneric) {
1424 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1426 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1427 new TypeExpression (ReturnType, Location), parameters);
1429 ArrayList list = new ArrayList ();
1430 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1431 if (tparam.Constraints != null)
1432 list.Add (tparam.Constraints.Clone ());
1434 generic_method.SetParameterInfo (list);
1436 member_name = new MemberName (name, Location);
1437 generic_method = null;
1440 string real_name = String.Format (
1441 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1442 parameters.GetSignatureForError ());
1444 return new AnonymousMethodMethod (parent,
1445 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1446 real_name, member_name, parameters);
1449 public override Expression DoResolve (EmitContext ec)
1451 if (eclass == ExprClass.Invalid) {
1456 eclass = ExprClass.Value;
1460 public override void Emit (EmitContext ec)
1463 // Use same anonymous method implementation for scenarios where same
1464 // code is used from multiple blocks, e.g. field initializers
1466 if (method == null) {
1468 // Delay an anonymous method definition to avoid emitting unused code
1469 // for unreachable blocks or expression trees
1471 method = DoCreateMethodHost (ec);
1475 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1476 if (is_static && am_cache == null) {
1478 // Creates a field cache to store delegate instance if it's not generic
1480 if (!method.MemberName.IsGeneric) {
1481 TypeContainer parent = method.Parent.PartialContainer;
1482 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1483 am_cache = new Field (parent, new TypeExpression (type, loc),
1484 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1485 CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), null, loc);
1487 parent.AddField (am_cache);
1489 // TODO: Implement caching of generated generic static methods
1493 // Some extra class is needed to capture variable generic type
1494 // arguments. Maybe we could re-use anonymous types, with a unique
1495 // anonymous method id, but they are quite heavy.
1497 // Consider : "() => typeof(T);"
1499 // We need something like
1500 // static class Wrap<Tn, Tm, DelegateType> {
1501 // public static DelegateType cache;
1504 // We then specialize local variable to capture all generic parameters
1505 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1510 ILGenerator ig = ec.ig;
1511 Label l_initialized = ig.DefineLabel ();
1513 if (am_cache != null) {
1514 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1515 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1519 // Load method delegate implementation
1523 ig.Emit (OpCodes.Ldnull);
1524 } else if (storey != null) {
1525 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1529 ig.Emit (OpCodes.Ldarg_0);
1532 MethodInfo delegate_method = method.MethodBuilder;
1534 if (storey != null && storey.MemberName.IsGeneric) {
1535 Type t = storey.Instance.Type;
1538 // Mutate anonymous method instance type if we are in nested
1539 // hoisted generic anonymous method storey
1541 if (ec.CurrentAnonymousMethod != null &&
1542 ec.CurrentAnonymousMethod.Storey != null &&
1543 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1544 t = storey.GetGenericStorey ().MutateType (t);
1547 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1550 ig.Emit (OpCodes.Ldftn, delegate_method);
1552 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1554 if (type.IsGenericType && type is TypeBuilder)
1555 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1557 ig.Emit (OpCodes.Newobj, constructor_method);
1559 if (am_cache != null) {
1560 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1561 ig.MarkLabel (l_initialized);
1562 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1567 // Look for the best storey for this anonymous method
1569 AnonymousMethodStorey FindBestMethodStorey ()
1572 // Use the nearest parent block which has a storey
1574 for (Block b = Block.Parent; b != null; b = b.Parent) {
1575 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1583 public override string GetSignatureForError ()
1585 return TypeManager.CSharpName (type);
1588 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1590 type = storey.MutateType (type);
1593 public static void Reset ()
1600 // Anonymous type container
1602 public class AnonymousTypeClass : CompilerGeneratedClass
1604 static int types_counter;
1605 public const string ClassNamePrefix = "<>__AnonType";
1606 public const string SignatureForError = "anonymous type";
1608 readonly ArrayList parameters;
1610 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1611 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1613 this.parameters = parameters;
1616 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1618 if (RootContext.Version <= LanguageVersion.ISO_2)
1619 Report.FeatureIsNotAvailable (loc, "anonymous types");
1621 string name = ClassNamePrefix + types_counter++;
1623 SimpleName [] t_args = new SimpleName [parameters.Count];
1624 Parameter [] ctor_params = new Parameter [parameters.Count];
1625 for (int i = 0; i < parameters.Count; ++i) {
1626 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1628 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1629 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1633 // Create generic anonymous type host with generic arguments
1634 // named upon properties names
1636 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1637 new MemberName (name, new TypeArguments (loc, t_args), loc), parameters, loc);
1639 if (parameters.Count > 0)
1640 a_type.SetParameterInfo (null);
1642 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1643 null, new Parameters (ctor_params), null, loc);
1644 c.Block = new ToplevelBlock (c.Parameters, loc);
1647 // Create fields and contructor body with field initialization
1650 for (int i = 0; i < parameters.Count; ++i) {
1651 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1653 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1654 "<" + p.Name + ">", null, p.Location);
1656 if (!a_type.AddField (f)) {
1658 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1663 c.Block.AddStatement (new StatementExpression (
1664 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1665 c.Block.GetParameterReference (p.Name, p.Location))));
1667 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1668 get_block.AddStatement (new Return (
1669 new MemberAccess (new This (p.Location), f.Name), p.Location));
1670 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1671 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1672 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1673 a_type.AddProperty (prop);
1679 a_type.AddConstructor (c);
1683 public static void Reset ()
1688 protected override bool AddToContainer (MemberCore symbol, string name)
1690 MemberCore mc = (MemberCore) defined_names [name];
1693 defined_names.Add (name, symbol);
1697 Report.SymbolRelatedToPreviousError (mc);
1701 void DefineOverrides ()
1703 Location loc = Location;
1705 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1706 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1707 Mono.CSharp.Parameters.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1709 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1710 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1711 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1713 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1714 TypeExpr current_type;
1716 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
1718 current_type = new TypeExpression (TypeBuilder, loc);
1720 equals_block.AddVariable (current_type, "other", loc);
1721 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1723 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1724 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1726 Expression rs_equals = null;
1727 Expression string_concat = new StringConstant ("<empty type>", loc);
1728 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1729 for (int i = 0; i < parameters.Count; ++i) {
1730 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1731 Field f = (Field) Fields [i];
1733 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1734 system_collections_generic, "EqualityComparer",
1735 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
1738 ArrayList arguments_equal = new ArrayList (2);
1739 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1740 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1742 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1743 "Equals", loc), arguments_equal);
1745 ArrayList arguments_hashcode = new ArrayList (1);
1746 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1747 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1748 "GetHashCode", loc), arguments_hashcode);
1750 IntConstant FNV_prime = new IntConstant (16777619, loc);
1751 rs_hashcode = new Binary (Binary.Operator.Multiply,
1752 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1755 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1756 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1757 new Invocation (new MemberAccess (
1758 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1759 new StringConstant ("<null>", loc));
1761 if (rs_equals == null) {
1762 rs_equals = field_equal;
1763 string_concat = new Binary (Binary.Operator.Addition,
1764 new StringConstant (p.Name + " = ", loc),
1770 // Implementation of ToString () body using string concatenation
1772 string_concat = new Binary (Binary.Operator.Addition,
1773 new Binary (Binary.Operator.Addition,
1775 new StringConstant (", " + p.Name + " = ", loc)),
1778 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1782 // Equals (object obj) override
1784 equals_block.AddStatement (new StatementExpression (
1785 new SimpleAssign (other_variable,
1786 new As (equals_block.GetParameterReference ("obj", loc),
1787 current_type, loc), loc)));
1789 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1790 if (rs_equals != null)
1791 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1792 equals_block.AddStatement (new Return (equals_test, loc));
1794 equals.Block = equals_block;
1799 // GetHashCode () override
1801 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1802 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1803 new MemberName ("GetHashCode", loc),
1804 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1807 // Modified FNV with good avalanche behavior and uniform
1808 // distribution with larger hash sizes.
1810 // const int FNV_prime = 16777619;
1811 // int hash = (int) 2166136261;
1812 // foreach (int d in data)
1813 // hash = (hash ^ d) * FNV_prime;
1814 // hash += hash << 13;
1815 // hash ^= hash >> 7;
1816 // hash += hash << 3;
1817 // hash ^= hash >> 17;
1818 // hash += hash << 5;
1820 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1821 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1822 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1823 hashcode_block.AddStatement (new StatementExpression (
1824 new SimpleAssign (hash_variable, rs_hashcode)));
1826 hashcode_block.AddStatement (new StatementExpression (
1827 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1828 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1829 hashcode_block.AddStatement (new StatementExpression (
1830 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1831 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1832 hashcode_block.AddStatement (new StatementExpression (
1833 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1834 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1835 hashcode_block.AddStatement (new StatementExpression (
1836 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1837 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1838 hashcode_block.AddStatement (new StatementExpression (
1839 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1840 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1842 hashcode_block.AddStatement (new Return (hash_variable, loc));
1843 hashcode.Block = hashcode_block;
1845 AddMethod (hashcode);
1848 // ToString () override
1851 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1852 tostring_block.AddStatement (new Return (string_concat, loc));
1853 tostring.Block = tostring_block;
1855 AddMethod (tostring);
1858 public override bool Define ()
1866 public override string GetSignatureForError ()
1868 return SignatureForError;
1871 public ArrayList Parameters {