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 readonly AnonymousMethodStorey Storey;
62 public readonly Field Field;
64 public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
70 public override int GetHashCode ()
72 return Storey.ID.GetHashCode ();
75 public override bool Equals (object obj)
77 return (AnonymousMethodStorey)obj == Storey;
81 sealed class HoistedGenericField : Field
83 public HoistedGenericField (DeclSpace parent, FullNamedExpression type, int mod, string name,
84 Attributes attrs, Location loc)
85 : base (parent, type, mod, new MemberName (name, loc), attrs)
89 protected override bool ResolveMemberType ()
91 if (!base.ResolveMemberType ())
94 AnonymousMethodStorey parent = ((AnonymousMethodStorey) Parent).GetGenericStorey ();
96 member_type = parent.MutateType (member_type);
103 // Needed to delay hoisted _this_ initialization. When an anonymous
104 // method is used inside ctor and _this_ is hoisted, base ctor has to
105 // be called first, otherwise _this_ will be initialized with
106 // uninitialized value.
108 sealed class ThisInitializer : Statement
110 readonly HoistedThis hoisted_this;
112 public ThisInitializer (HoistedThis hoisted_this)
114 this.hoisted_this = hoisted_this;
117 protected override void DoEmit (EmitContext ec)
119 hoisted_this.EmitHoistingAssignment (ec);
122 protected override void CloneTo (CloneContext clonectx, Statement target)
127 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
134 public readonly int ID;
135 static int unique_id;
137 public readonly Block OriginalSourceBlock;
139 // A list of StoreyFieldPair with local field keeping parent storey instance
140 ArrayList used_parent_storeys;
141 ArrayList children_references;
143 // A list of hoisted parameters
144 protected ArrayList hoisted_params;
145 protected ArrayList hoisted_locals;
148 protected HoistedThis hoisted_this;
150 // Local variable which holds this storey instance
151 public LocalTemporary Instance;
153 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
154 : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE)
157 OriginalSourceBlock = block;
161 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
163 string host_name = host == null ? null : host.Name;
164 string tname = MakeName (host_name, "c", name, unique_id);
165 TypeArguments args = null;
166 if (generic != null) {
167 args = new TypeArguments ();
168 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
169 args.Add (new TypeParameterName (tparam.Name, null, loc));
172 return new MemberName (tname, args, loc);
175 public void AddCapturedThisField (EmitContext ec)
177 TypeExpr type_expr = new TypeExpression (ec.ContainerType, Location);
178 Field f = AddCompilerGeneratedField ("<>f__this", type_expr);
180 hoisted_this = new HoistedThis (this, f);
183 public Field AddCapturedVariable (string name, Type type)
185 CheckMembersDefined ();
187 FullNamedExpression field_type = new TypeExpression (type, Location);
189 return AddCompilerGeneratedField (name, field_type);
191 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
192 Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
197 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
199 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
200 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
206 // Creates a link between block and the anonymous method storey
208 // An anonymous method can reference variables from any outer block, but they are
209 // hoisted in their own ExplicitBlock. When more than one block is referenced we
210 // need to create another link between those variable storeys
212 public void AddReferenceFromChildrenBlock (ExplicitBlock block)
214 if (children_references == null)
215 children_references = new ArrayList ();
217 if (!children_references.Contains (block))
218 children_references.Add (block);
221 public void AddParentStoreyReference (AnonymousMethodStorey storey)
223 CheckMembersDefined ();
225 if (used_parent_storeys == null)
226 used_parent_storeys = new ArrayList ();
227 else if (used_parent_storeys.IndexOf (storey) != -1)
230 TypeExpr type_expr = new TypeExpression (storey.TypeBuilder, Location);
231 Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
232 used_parent_storeys.Add (new StoreyFieldPair (storey, f));
235 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
237 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
238 if (ec.CurrentBlock.Explicit != local_info.Block.Explicit)
239 AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
241 if (local_info.HoistedVariableReference != null)
244 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
245 local_info.HoistedVariableReference = var;
247 if (hoisted_locals == null)
248 hoisted_locals = new ArrayList ();
250 hoisted_locals.Add (var);
253 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
255 ec.CurrentBlock.Explicit.HasCapturedVariable = true;
256 AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
258 if (param_ref.GetHoistedVariable (ec) != null)
261 if (hoisted_params == null)
262 hoisted_params = new ArrayList (2);
264 HoistedVariable expr = new HoistedParameter (this, param_ref);
265 param_ref.Parameter.HoistedVariableReference = expr;
266 hoisted_params.Add (expr);
269 public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
271 Parent = parentStorey;
276 // Initializes all hoisted variables
278 public void EmitStoreyInstantiation (EmitContext ec)
280 // There can be only one instance variable for each storey type
281 if (Instance != null)
282 throw new InternalErrorException ();
284 SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
287 // Create an instance of storey type
289 Expression storey_type_expr;
292 // Use current method type parameter (MVAR) for top level storey only. All
293 // nested storeys use class type parameter (VAR)
295 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
296 ec.CurrentAnonymousMethod.Storey.TypeParameters :
297 ec.GenericDeclContainer.TypeParameters;
299 TypeArguments targs = new TypeArguments ();
301 if (tparams.Length < CountTypeParameters) {
302 TypeParameter[] parent_tparams = ec.DeclContainer.Parent.PartialContainer.TypeParameters;
303 for (int i = 0; i < parent_tparams.Length; ++i)
304 targs.Add (new TypeParameterExpr (parent_tparams[i], Location));
307 for (int i = 0; i < tparams.Length; ++i)
308 targs.Add (new TypeParameterExpr (tparams[i], Location));
310 storey_type_expr = new GenericTypeExpr (TypeBuilder, targs, Location);
312 storey_type_expr = new TypeExpression (TypeBuilder, Location);
315 Expression e = new New (storey_type_expr, new ArrayList (0), Location).Resolve (ec);
318 Instance = new LocalTemporary (storey_type_expr.Type);
321 EmitHoistedFieldsInitialization (ec);
323 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
324 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
327 void EmitHoistedFieldsInitialization (EmitContext ec)
330 // Initialize all storey reference fields by using local or hoisted variables
332 if (used_parent_storeys != null) {
333 foreach (StoreyFieldPair sf in used_parent_storeys) {
335 // Setting local field
337 Expression instace_expr = GetStoreyInstanceExpression (ec);
338 FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
339 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
340 new FieldExpr (sf.Field.FieldBuilder, Location);
341 f_set_expr.InstanceExpression = instace_expr;
343 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
344 if (a.Resolve (ec) != null)
345 a.EmitStatement (ec);
350 // Define hoisted `this' in top-level storey only
352 if (OriginalSourceBlock.Explicit.HasCapturedThis && !(Parent is AnonymousMethodStorey)) {
353 AddCapturedThisField (ec);
354 OriginalSourceBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
358 // Setting currect anonymous method to null blocks any further variable hoisting
360 AnonymousExpression ae = ec.CurrentAnonymousMethod;
361 ec.CurrentAnonymousMethod = null;
363 if (hoisted_params != null) {
364 EmitHoistedParameters (ec, hoisted_params);
367 ec.CurrentAnonymousMethod = ae;
370 protected virtual void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
372 foreach (HoistedParameter hp in hoisted) {
373 hp.EmitHoistingAssignment (ec);
377 public override void EmitType ()
379 SymbolWriter.DefineAnonymousScope (ID);
381 if (hoisted_this != null)
382 hoisted_this.EmitSymbolInfo ();
384 if (hoisted_locals != null) {
385 foreach (HoistedVariable local in hoisted_locals)
386 local.EmitSymbolInfo ();
389 if (hoisted_params != null) {
390 foreach (HoistedParameter param in hoisted_params)
391 param.EmitSymbolInfo ();
394 if (used_parent_storeys != null) {
395 foreach (StoreyFieldPair sf in used_parent_storeys) {
396 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
403 public AnonymousMethodStorey GetGenericStorey ()
405 DeclSpace storey = this;
406 while (storey != null && storey.CurrentTypeParameters.Length == 0)
407 storey = storey.Parent;
409 return storey as AnonymousMethodStorey;
413 // Returns a field which holds referenced storey instance
415 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
417 if (used_parent_storeys == null)
420 foreach (StoreyFieldPair sf in used_parent_storeys) {
421 if (sf.Storey == storey)
429 // Creates storey instance expression regardless of currect IP
431 public Expression GetStoreyInstanceExpression (EmitContext ec)
433 AnonymousExpression am = ec.CurrentAnonymousMethod;
436 // Access from original block -> storey
442 // Access from anonymous method implemented as a static -> storey
444 if (am.Storey == null)
447 Field f = am.Storey.GetReferencedStoreyField (this);
449 if (am.Storey == this) {
451 // Access inside of same storey (S -> S)
453 return new CompilerGeneratedThis (TypeBuilder, Location);
456 // External field access
462 // Storey was cached to local field
464 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
465 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
469 protected virtual string GetVariableMangledName (LocalInfo local_info)
472 // No need to mangle anonymous method hoisted variables cause they
473 // are hoisted in their own scopes
475 return local_info.Name;
478 public HoistedThis HoistedThis {
479 get { return hoisted_this; }
483 // Mutate type dispatcher
485 public Type MutateType (Type type)
488 if (TypeManager.IsGenericType (type))
489 return MutateGenericType (type);
491 if (TypeManager.IsGenericParameter (type))
492 return MutateGenericArgument (type);
495 return MutateArrayType (type);
501 // Changes method type arguments (MVAR) to storey (VAR) type arguments
503 public MethodInfo MutateGenericMethod (MethodInfo method)
506 Type [] t_args = TypeManager.GetGenericArguments (method);
507 if (TypeManager.IsGenericType (method.DeclaringType)) {
508 Type t = MutateGenericType (method.DeclaringType);
509 if (t != method.DeclaringType) {
510 method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
511 if (method.Module == CodeGen.Module.Builder)
512 method = TypeBuilder.GetMethod (t, method);
514 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
518 if (t_args == null || t_args.Length == 0)
521 for (int i = 0; i < t_args.Length; ++i)
522 t_args [i] = MutateType (t_args [i]);
524 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
526 throw new NotSupportedException ();
530 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
533 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
534 Type t = MutateGenericType (ctor.DeclaringType);
535 if (t != ctor.DeclaringType) {
536 ctor = (ConstructorInfo) TypeManager.DropGenericMethodArguments (ctor);
537 if (ctor.Module == CodeGen.Module.Builder)
538 return TypeBuilder.GetConstructor (t, ctor);
540 return (ConstructorInfo) ConstructorInfo.GetMethodFromHandle (ctor.MethodHandle, t.TypeHandle);
547 public FieldInfo MutateField (FieldInfo field)
550 if (TypeManager.IsGenericType (field.DeclaringType)) {
551 Type t = MutateGenericType (field.DeclaringType);
552 if (t != field.DeclaringType) {
553 // TODO: It should throw on imported types
554 return TypeBuilder.GetField (t, field);
562 protected Type MutateArrayType (Type array)
564 int rank = array.GetArrayRank ();
565 Type element = TypeManager.GetElementType (array);
566 if (element.IsArray) {
567 element = MutateArrayType (element);
568 } else if (TypeManager.IsGenericParameter (element)) {
569 element = MutateGenericArgument (element);
570 } else if (TypeManager.IsGenericType (element)) {
571 element = MutateGenericType (element);
576 return element.MakeArrayType (rank);
579 protected Type MutateGenericType (Type type)
581 Type [] t_args = TypeManager.GetTypeArguments (type);
582 if (t_args == null || t_args.Length == 0)
585 for (int i = 0; i < t_args.Length; ++i)
586 t_args [i] = MutateType (t_args [i]);
588 return type.GetGenericTypeDefinition ().MakeGenericType (t_args);
593 // Changes method generic argument (MVAR) to type generic argument (VAR)
595 public Type MutateGenericArgument (Type type)
597 foreach (TypeParameter tp in CurrentTypeParameters) {
598 if (tp.Name == type.Name) {
606 public ArrayList ReferencesFromChildrenBlock {
607 get { return children_references; }
610 public static void Reset ()
616 public abstract class HoistedVariable
618 class ExpressionTreeProxy : Expression
620 readonly HoistedVariable hv;
622 public ExpressionTreeProxy (HoistedVariable hv)
627 public override Expression CreateExpressionTree (EmitContext ec)
629 throw new NotSupportedException ("ET");
632 public override Expression DoResolve (EmitContext ec)
634 eclass = ExprClass.Value;
635 type = TypeManager.expression_type_expr.Type;
639 public override void Emit (EmitContext ec)
641 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (ec);
642 // This should never fail
649 protected readonly AnonymousMethodStorey storey;
650 protected Field field;
651 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
652 FieldExpr cached_outer_access;
654 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
655 : this (storey, storey.AddCapturedVariable (name, type))
659 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
661 this.storey = storey;
665 public void AddressOf (EmitContext ec, AddressOp mode)
667 GetFieldExpression (ec).AddressOf (ec, mode);
670 public Expression CreateExpressionTree (EmitContext ec)
672 return new ExpressionTreeProxy (this);
675 public void Emit (EmitContext ec)
677 GetFieldExpression (ec).Emit (ec);
681 // Creates field access expression for hoisted variable
683 protected FieldExpr GetFieldExpression (EmitContext ec)
685 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
686 if (cached_outer_access != null)
687 return cached_outer_access;
690 // When setting top-level hoisted variable in generic storey
691 // change storey generic types to method generic types (VAR -> MVAR)
693 cached_outer_access = storey.MemberName.IsGeneric ?
694 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
695 new FieldExpr (field.FieldBuilder, field.Location);
697 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
698 cached_outer_access.Resolve (ec);
699 return cached_outer_access;
702 FieldExpr inner_access;
703 if (cached_inner_access != null) {
704 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
707 cached_inner_access = new Hashtable (4);
710 if (inner_access == null) {
711 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
712 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
713 inner_access.Resolve (ec);
714 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
720 public abstract void EmitSymbolInfo ();
722 public void Emit (EmitContext ec, bool leave_copy)
724 GetFieldExpression (ec).Emit (ec, leave_copy);
727 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
729 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
733 class HoistedParameter : HoistedVariable
735 sealed class HoistedFieldAssign : Assign
737 public HoistedFieldAssign (Expression target, Expression source)
738 : base (target, source, source.Location)
742 protected override Expression ResolveConversions (EmitContext ec)
745 // Implicit conversion check fails for hoisted type arguments
746 // as they are of different types (!!0 x !0)
752 readonly ParameterReference parameter;
754 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
755 : base (scope, par.Name, par.Type)
757 this.parameter = par;
760 public HoistedParameter (HoistedParameter hp, string name)
761 : base (hp.storey, name, hp.parameter.Type)
763 this.parameter = hp.parameter;
766 public void EmitHoistingAssignment (EmitContext ec)
769 // Remove hoisted redirection to emit assignment from original parameter
771 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
772 parameter.Parameter.HoistedVariableReference = null;
774 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
775 if (a.Resolve (ec) != null)
776 a.EmitStatement (ec);
778 parameter.Parameter.HoistedVariableReference = temp;
781 public override void EmitSymbolInfo ()
783 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
787 get { return field; }
791 class HoistedLocalVariable : HoistedVariable
793 readonly string name;
795 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
796 : base (scope, name, local.VariableType)
798 this.name = local.Name;
801 public override void EmitSymbolInfo ()
803 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
807 public class HoistedThis : HoistedVariable
809 public HoistedThis (AnonymousMethodStorey storey, Field field)
810 : base (storey, field)
814 public void EmitHoistingAssignment (EmitContext ec)
816 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), ec.GetThis (field.Location));
817 if (a.Resolve (ec) != null)
818 a.EmitStatement (ec);
821 public override void EmitSymbolInfo ()
823 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
827 get { return field; }
832 // Anonymous method expression as created by parser
834 public class AnonymousMethodExpression : Expression
836 ListDictionary compatibles;
837 public ToplevelBlock Block;
839 public AnonymousMethodExpression (Location loc)
842 this.compatibles = new ListDictionary ();
845 public override string ExprClassName {
847 return "anonymous method";
851 public virtual bool HasExplicitParameters {
853 return Parameters != ParametersCompiled.Undefined;
857 public ParametersCompiled Parameters {
858 get { return Block.Parameters; }
862 // Returns true if the body of lambda expression can be implicitly
863 // converted to the delegate of type `delegate_type'
865 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
867 using (ec.Set (EmitContext.Flags.ProbingMode)) {
868 return Compatible (ec, delegate_type) != null;
872 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
874 if (TypeManager.IsDelegateType (delegate_type))
875 return delegate_type;
878 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
879 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
880 if (TypeManager.IsDelegateType (delegate_type))
881 return delegate_type;
883 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
884 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
889 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
890 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
894 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
896 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
900 Report.Error (1661, loc,
901 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
902 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
907 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
909 if (Parameters.Count != invoke_pd.Count) {
913 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
914 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
918 bool has_implicit_parameters = !HasExplicitParameters;
921 for (int i = 0; i < Parameters.Count; ++i) {
922 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
923 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
927 if (p_mod == Parameter.Modifier.NONE)
928 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
929 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
931 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
932 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
936 if (has_implicit_parameters)
939 Type type = invoke_pd.Types [i];
941 // We assume that generic parameters are always inflated
942 if (TypeManager.IsGenericParameter (type))
945 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
948 if (invoke_pd.Types [i] != Parameters.Types [i]) {
952 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
954 TypeManager.CSharpName (Parameters.Types [i]),
955 TypeManager.CSharpName (invoke_pd.Types [i]));
964 // Infers type arguments based on explicit arguments
966 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
968 if (!HasExplicitParameters)
971 if (!TypeManager.IsDelegateType (delegate_type)) {
973 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
976 delegate_type = delegate_type.GetGenericArguments () [0];
977 if (!TypeManager.IsDelegateType (delegate_type))
984 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
985 if (d_params.Count != Parameters.Count)
988 for (int i = 0; i < Parameters.Count; ++i) {
989 Type itype = d_params.Types [i];
990 if (!TypeManager.IsGenericParameter (itype)) {
991 if (!TypeManager.HasElementType (itype))
994 if (!TypeManager.IsGenericParameter (TypeManager.GetElementType (itype)))
997 type_inference.ExactInference (Parameters.Types [i], itype);
1002 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1004 AnonymousMethodBody am;
1005 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
1006 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
1012 // Stop referencing gmcs NullLiteral type
1013 if (am.ReturnType == TypeManager.null_type)
1014 am.ReturnType = null;
1016 return am.ReturnType;
1020 // Returns AnonymousMethod container if this anonymous method
1021 // expression can be implicitly converted to the delegate type `delegate_type'
1023 public Expression Compatible (EmitContext ec, Type type)
1025 Expression am = (Expression) compatibles [type];
1029 Type delegate_type = CompatibleChecks (ec, type);
1030 if (delegate_type == null)
1034 // At this point its the first time we know the return type that is
1035 // needed for the anonymous method. We create the method here.
1038 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1039 ec.ContainerType, delegate_type);
1040 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1043 Type[] g_args = delegate_type.GetGenericArguments ();
1044 if (return_type.IsGenericParameter)
1045 return_type = g_args [return_type.GenericParameterPosition];
1049 // Second: the return type of the delegate must be compatible with
1050 // the anonymous type. Instead of doing a pass to examine the block
1051 // we satisfy the rule by setting the return type on the EmitContext
1052 // to be the delegate type return type.
1056 int errors = Report.Errors;
1057 am = CompatibleMethod (ec, null, return_type, delegate_type);
1058 if (am != null && delegate_type != type && errors == Report.Errors)
1059 am = CreateExpressionTree (ec, delegate_type);
1061 if (!ec.IsInProbingMode)
1062 compatibles.Add (type, am == null ? EmptyExpression.Null : am);
1065 } catch (Exception e) {
1066 throw new InternalErrorException (e, loc);
1070 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1072 return CreateExpressionTree (ec);
1075 public override Expression CreateExpressionTree (EmitContext ec)
1077 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1081 protected virtual ParametersCompiled ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1083 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1085 if (Parameters == ParametersCompiled.Undefined) {
1087 // We provide a set of inaccessible parameters
1089 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1091 for (int i = 0; i < delegate_parameters.Count; i++) {
1092 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1093 if (i_mod == Parameter.Modifier.OUT) {
1094 Report.Error (1688, loc, "Cannot convert anonymous " +
1095 "method block without a parameter list " +
1096 "to delegate type `{0}' because it has " +
1097 "one or more `out' parameters.",
1098 TypeManager.CSharpName (delegate_type));
1101 fixedpars[i] = new Parameter (
1103 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1106 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1109 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1116 public override Expression DoResolve (EmitContext ec)
1118 if (!ec.IsAnonymousMethodAllowed) {
1119 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1124 // Set class type, set type
1127 eclass = ExprClass.Value;
1130 // This hack means `The type is not accessible
1131 // anywhere', we depend on special conversion
1134 type = TypeManager.anonymous_method_type;
1136 if ((Parameters != null) && !Parameters.Resolve (ec))
1139 // FIXME: The emitted code isn't very careful about reachability
1140 // so, ensure we have a 'ret' at the end
1141 if (ec.CurrentBranching != null &&
1142 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1143 ec.NeedReturnLabel ();
1148 public override void Emit (EmitContext ec)
1150 // nothing, as we only exist to not do anything.
1153 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1155 Report.Error (1686, loc,
1156 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1160 public override string GetSignatureForError ()
1162 return ExprClassName;
1165 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1167 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1171 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1173 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1174 if (!anonymous.Compatible (ec))
1180 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, ParametersCompiled p, ToplevelBlock b)
1182 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1185 protected override void CloneTo (CloneContext clonectx, Expression t)
1187 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1189 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1194 // Abstract expression for any block which requires variables hoisting
1196 public abstract class AnonymousExpression : Expression
1198 protected class AnonymousMethodMethod : Method
1200 public readonly AnonymousExpression AnonymousMethod;
1201 public readonly AnonymousMethodStorey Storey;
1202 readonly string RealName;
1204 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1205 GenericMethod generic, TypeExpr return_type,
1206 int mod, string real_name, MemberName name,
1207 ParametersCompiled parameters)
1208 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1209 name, parameters, null)
1211 this.AnonymousMethod = am;
1212 this.Storey = storey;
1213 this.RealName = real_name;
1215 Parent.PartialContainer.AddMethod (this);
1219 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1221 EmitContext aec = AnonymousMethod.aec;
1223 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1227 protected override bool ResolveMemberType ()
1229 if (!base.ResolveMemberType ())
1232 if (Storey != null && Storey.IsGeneric) {
1233 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1234 if (gstorey != null) {
1235 if (!Parameters.IsEmpty) {
1236 Type [] ptypes = Parameters.Types;
1237 for (int i = 0; i < ptypes.Length; ++i)
1238 ptypes [i] = gstorey.MutateType (ptypes [i]);
1241 member_type = gstorey.MutateType (member_type);
1248 public override void Emit ()
1251 // Before emitting any code we have to change all MVAR references to VAR
1252 // when the method is of generic type and has hoisted variables
1254 if (Storey == Parent && Storey.IsGeneric) {
1255 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1256 if (gstorey != null) {
1257 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1258 block.MutateHoistedGenericType (gstorey);
1262 if (MethodBuilder == null) {
1269 public override void EmitExtraSymbolInfo (SourceMethod source)
1271 source.SetRealMethodName (RealName);
1276 // The block that makes up the body for the anonymous method
1278 protected readonly ToplevelBlock Block;
1280 public Type ReturnType;
1281 protected EmitContext aec;
1283 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1285 this.ReturnType = return_type;
1290 public abstract string ContainerType { get; }
1291 public abstract bool IsIterator { get; }
1292 public abstract AnonymousMethodStorey Storey { get; }
1294 public bool Compatible (EmitContext ec)
1296 // TODO: Implement clone
1297 aec = new EmitContext (
1298 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1299 Location, null, ReturnType,
1300 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1302 aec.CurrentAnonymousMethod = this;
1303 aec.IsStatic = ec.IsStatic;
1305 IDisposable aec_dispose = null;
1306 EmitContext.Flags flags = 0;
1307 if (ec.InferReturnType)
1308 flags |= EmitContext.Flags.InferReturnType;
1310 if (ec.IsInProbingMode)
1311 flags |= EmitContext.Flags.ProbingMode;
1313 if (ec.IsInFieldInitializer)
1314 flags |= EmitContext.Flags.InFieldInitializer;
1316 if (ec.IsInUnsafeScope)
1317 flags |= EmitContext.Flags.InUnsafe;
1319 // HACK: Flag with 0 cannot be set
1321 aec_dispose = aec.Set (flags);
1324 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1326 if (ec.InferReturnType)
1327 ReturnType = aec.ReturnType;
1329 if (aec_dispose != null) {
1330 aec_dispose.Dispose ();
1336 public void SetHasThisAccess ()
1338 Block.HasCapturedThis = true;
1339 ExplicitBlock b = Block.Parent.Explicit;
1342 if (b.HasCapturedThis)
1345 b.HasCapturedThis = true;
1346 b = b.Parent == null ? null : b.Parent.Explicit;
1351 public class AnonymousMethodBody : AnonymousExpression
1353 protected readonly ParametersCompiled parameters;
1354 AnonymousMethodStorey storey;
1356 AnonymousMethodMethod method;
1359 static int unique_id;
1361 public AnonymousMethodBody (ParametersCompiled parameters,
1362 ToplevelBlock block, Type return_type, Type delegate_type,
1364 : base (block, return_type, loc)
1366 this.type = delegate_type;
1367 this.parameters = parameters;
1370 public override string ContainerType {
1371 get { return "anonymous method"; }
1374 public override AnonymousMethodStorey Storey {
1375 get { return storey; }
1378 public override bool IsIterator {
1379 get { return false; }
1382 public override Expression CreateExpressionTree (EmitContext ec)
1384 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1388 bool Define (EmitContext ec)
1390 if (aec == null && !Compatible (ec))
1397 // Creates a host for the anonymous method
1399 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1402 // Anonymous method body can be converted to
1404 // 1, an instance method in current scope when only `this' is hoisted
1405 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1406 // 3, an instance method in compiler generated storey when any hoisted variable exists
1410 if (Block.HasCapturedVariable || Block.HasCapturedThis) {
1411 storey = FindBestMethodStorey ();
1412 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1414 if (ec.CurrentAnonymousMethod != null)
1415 storey = ec.CurrentAnonymousMethod.Storey;
1417 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1420 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1422 MemberCore mc = ec.ResolveContext as MemberCore;
1423 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1424 "m", null, unique_id++);
1426 MemberName member_name;
1427 GenericMethod generic_method;
1428 if (storey == null && mc.MemberName.IsGeneric) {
1429 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1431 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1432 new TypeExpression (ReturnType, Location), parameters);
1434 ArrayList list = new ArrayList ();
1435 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1436 if (tparam.Constraints != null)
1437 list.Add (tparam.Constraints.Clone ());
1439 generic_method.SetParameterInfo (list);
1441 member_name = new MemberName (name, Location);
1442 generic_method = null;
1445 string real_name = String.Format (
1446 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1447 parameters.GetSignatureForError ());
1449 return new AnonymousMethodMethod (parent,
1450 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1451 real_name, member_name, parameters);
1454 public override Expression DoResolve (EmitContext ec)
1456 if (eclass == ExprClass.Invalid) {
1461 eclass = ExprClass.Value;
1465 public override void Emit (EmitContext ec)
1468 // Use same anonymous method implementation for scenarios where same
1469 // code is used from multiple blocks, e.g. field initializers
1471 if (method == null) {
1473 // Delay an anonymous method definition to avoid emitting unused code
1474 // for unreachable blocks or expression trees
1476 method = DoCreateMethodHost (ec);
1480 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1481 if (is_static && am_cache == null) {
1483 // Creates a field cache to store delegate instance if it's not generic
1485 if (!method.MemberName.IsGeneric) {
1486 TypeContainer parent = method.Parent.PartialContainer;
1487 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1488 am_cache = new Field (parent, new TypeExpression (type, loc),
1489 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1490 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1492 parent.AddField (am_cache);
1494 // TODO: Implement caching of generated generic static methods
1498 // Some extra class is needed to capture variable generic type
1499 // arguments. Maybe we could re-use anonymous types, with a unique
1500 // anonymous method id, but they are quite heavy.
1502 // Consider : "() => typeof(T);"
1504 // We need something like
1505 // static class Wrap<Tn, Tm, DelegateType> {
1506 // public static DelegateType cache;
1509 // We then specialize local variable to capture all generic parameters
1510 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1515 ILGenerator ig = ec.ig;
1516 Label l_initialized = ig.DefineLabel ();
1518 if (am_cache != null) {
1519 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1520 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1524 // Load method delegate implementation
1528 ig.Emit (OpCodes.Ldnull);
1529 } else if (storey != null) {
1530 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1534 ig.Emit (OpCodes.Ldarg_0);
1537 MethodInfo delegate_method = method.MethodBuilder;
1539 if (storey != null && storey.MemberName.IsGeneric) {
1540 Type t = storey.Instance.Type;
1543 // Mutate anonymous method instance type if we are in nested
1544 // hoisted generic anonymous method storey
1546 if (ec.CurrentAnonymousMethod != null &&
1547 ec.CurrentAnonymousMethod.Storey != null &&
1548 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1549 t = storey.GetGenericStorey ().MutateType (t);
1552 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1555 ig.Emit (OpCodes.Ldftn, delegate_method);
1557 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1559 if (type.IsGenericType && type is TypeBuilder)
1560 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1562 ig.Emit (OpCodes.Newobj, constructor_method);
1564 if (am_cache != null) {
1565 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1566 ig.MarkLabel (l_initialized);
1567 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1572 // Look for the best storey for this anonymous method
1574 AnonymousMethodStorey FindBestMethodStorey ()
1577 // Use the nearest parent block which has a storey
1579 for (Block b = Block.Parent; b != null; b = b.Parent) {
1580 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1588 public override string GetSignatureForError ()
1590 return TypeManager.CSharpName (type);
1593 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1595 type = storey.MutateType (type);
1598 public static void Reset ()
1605 // Anonymous type container
1607 public class AnonymousTypeClass : CompilerGeneratedClass
1609 sealed class AnonymousParameters : ParametersCompiled
1611 public AnonymousParameters (params Parameter[] parameters)
1616 protected override void ErrorDuplicateName (Parameter p)
1618 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1623 static int types_counter;
1624 public const string ClassNamePrefix = "<>__AnonType";
1625 public const string SignatureForError = "anonymous type";
1627 readonly ArrayList parameters;
1629 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1630 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1632 this.parameters = parameters;
1635 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1637 if (RootContext.Version <= LanguageVersion.ISO_2)
1638 Report.FeatureIsNotAvailable (loc, "anonymous types");
1640 string name = ClassNamePrefix + types_counter++;
1642 SimpleName [] t_args = new SimpleName [parameters.Count];
1643 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1644 Parameter [] ctor_params = new Parameter [parameters.Count];
1645 for (int i = 0; i < parameters.Count; ++i) {
1646 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1648 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1649 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1650 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1654 // Create generic anonymous type host with generic arguments
1655 // named upon properties names
1657 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1658 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1660 if (parameters.Count > 0)
1661 a_type.SetParameterInfo (null);
1663 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1664 null, new AnonymousParameters (ctor_params), null, loc);
1665 c.Block = new ToplevelBlock (c.Parameters, loc);
1668 // Create fields and contructor body with field initialization
1671 for (int i = 0; i < parameters.Count; ++i) {
1672 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1674 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1675 new MemberName ("<" + p.Name + ">", p.Location), null);
1677 if (!a_type.AddField (f)) {
1682 c.Block.AddStatement (new StatementExpression (
1683 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1684 c.Block.GetParameterReference (p.Name, p.Location))));
1686 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1687 get_block.AddStatement (new Return (
1688 new MemberAccess (new This (p.Location), f.Name), p.Location));
1689 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1690 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1691 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1692 a_type.AddProperty (prop);
1698 a_type.AddConstructor (c);
1702 public static void Reset ()
1707 protected override bool AddToContainer (MemberCore symbol, string name)
1709 MemberCore mc = (MemberCore) defined_names [name];
1712 defined_names.Add (name, symbol);
1716 Report.SymbolRelatedToPreviousError (mc);
1720 void DefineOverrides ()
1722 Location loc = Location;
1724 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1725 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1726 Mono.CSharp.ParametersCompiled.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1728 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1729 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1730 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1732 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1733 TypeExpr current_type;
1735 current_type = new GenericTypeExpr (this, loc);
1737 current_type = new TypeExpression (TypeBuilder, loc);
1739 equals_block.AddVariable (current_type, "other", loc);
1740 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1742 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1743 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1745 Expression rs_equals = null;
1746 Expression string_concat = new StringConstant ("{", loc);
1747 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1748 for (int i = 0; i < parameters.Count; ++i) {
1749 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1750 Field f = (Field) Fields [i];
1752 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1753 system_collections_generic, "EqualityComparer",
1754 new TypeArguments (new SimpleName (TypeParameters [i].Name, loc)), loc),
1757 ArrayList arguments_equal = new ArrayList (2);
1758 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1759 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1761 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1762 "Equals", loc), arguments_equal);
1764 ArrayList arguments_hashcode = new ArrayList (1);
1765 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1766 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1767 "GetHashCode", loc), arguments_hashcode);
1769 IntConstant FNV_prime = new IntConstant (16777619, loc);
1770 rs_hashcode = new Binary (Binary.Operator.Multiply,
1771 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1774 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1775 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1776 new Invocation (new MemberAccess (
1777 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1778 new StringConstant (string.Empty, loc));
1780 if (rs_equals == null) {
1781 rs_equals = field_equal;
1782 string_concat = new Binary (Binary.Operator.Addition,
1784 new Binary (Binary.Operator.Addition,
1785 new StringConstant (" " + p.Name + " = ", loc),
1791 // Implementation of ToString () body using string concatenation
1793 string_concat = new Binary (Binary.Operator.Addition,
1794 new Binary (Binary.Operator.Addition,
1796 new StringConstant (", " + p.Name + " = ", loc)),
1799 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1802 string_concat = new Binary (Binary.Operator.Addition,
1804 new StringConstant (" }", loc));
1807 // Equals (object obj) override
1809 equals_block.AddStatement (new StatementExpression (
1810 new SimpleAssign (other_variable,
1811 new As (equals_block.GetParameterReference ("obj", loc),
1812 current_type, loc), loc)));
1814 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1815 if (rs_equals != null)
1816 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1817 equals_block.AddStatement (new Return (equals_test, loc));
1819 equals.Block = equals_block;
1824 // GetHashCode () override
1826 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1827 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1828 new MemberName ("GetHashCode", loc),
1829 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1832 // Modified FNV with good avalanche behavior and uniform
1833 // distribution with larger hash sizes.
1835 // const int FNV_prime = 16777619;
1836 // int hash = (int) 2166136261;
1837 // foreach (int d in data)
1838 // hash = (hash ^ d) * FNV_prime;
1839 // hash += hash << 13;
1840 // hash ^= hash >> 7;
1841 // hash += hash << 3;
1842 // hash ^= hash >> 17;
1843 // hash += hash << 5;
1845 ToplevelBlock hashcode_top = new ToplevelBlock (loc);
1846 Block hashcode_block = new Block (hashcode_top);
1847 hashcode_top.AddStatement (new Unchecked (hashcode_block));
1849 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1850 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1851 hashcode_block.AddStatement (new StatementExpression (
1852 new SimpleAssign (hash_variable, rs_hashcode)));
1854 hashcode_block.AddStatement (new StatementExpression (
1855 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1856 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1857 hashcode_block.AddStatement (new StatementExpression (
1858 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1859 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1860 hashcode_block.AddStatement (new StatementExpression (
1861 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1862 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1863 hashcode_block.AddStatement (new StatementExpression (
1864 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1865 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1866 hashcode_block.AddStatement (new StatementExpression (
1867 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1868 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1870 hashcode_block.AddStatement (new Return (hash_variable, loc));
1871 hashcode.Block = hashcode_top;
1873 AddMethod (hashcode);
1876 // ToString () override
1879 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1880 tostring_block.AddStatement (new Return (string_concat, loc));
1881 tostring.Block = tostring_block;
1883 AddMethod (tostring);
1886 public override bool Define ()
1888 if (!base.Define ())
1895 public override string GetSignatureForError ()
1897 return SignatureForError;
1900 public ArrayList Parameters {