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, TypeContainer 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.CurrentType, 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 (ResolveContext 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 (ResolveContext 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.CurrentTypeParameters;
299 TypeArguments targs = new TypeArguments ();
301 if (tparams.Length < CountTypeParameters) {
302 TypeParameter[] parent_tparams = ec.MemberContext.CurrentTypeDefinition.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 ResolveContext rc = new ResolveContext (this);
316 Expression e = new New (storey_type_expr, null, Location).Resolve (rc);
319 Instance = new LocalTemporary (storey_type_expr.Type);
322 EmitHoistedFieldsInitialization (ec);
324 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
325 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
328 void EmitHoistedFieldsInitialization (EmitContext ec)
331 // Initialize all storey reference fields by using local or hoisted variables
333 if (used_parent_storeys != null) {
334 foreach (StoreyFieldPair sf in used_parent_storeys) {
336 // Setting local field
338 Expression instace_expr = GetStoreyInstanceExpression (ec);
339 FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
340 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
341 new FieldExpr (sf.Field.FieldBuilder, Location);
342 f_set_expr.InstanceExpression = instace_expr;
344 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
345 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
346 a.EmitStatement (ec);
351 // Define hoisted `this' in top-level storey only
353 if (OriginalSourceBlock.Explicit.HasCapturedThis && !(Parent is AnonymousMethodStorey)) {
354 AddCapturedThisField (ec);
355 OriginalSourceBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
359 // Setting currect anonymous method to null blocks any further variable hoisting
361 AnonymousExpression ae = ec.CurrentAnonymousMethod;
362 ec.CurrentAnonymousMethod = null;
364 if (hoisted_params != null) {
365 EmitHoistedParameters (ec, hoisted_params);
368 ec.CurrentAnonymousMethod = ae;
371 protected virtual void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
373 foreach (HoistedParameter hp in hoisted) {
374 hp.EmitHoistingAssignment (ec);
378 public override void EmitType ()
380 SymbolWriter.DefineAnonymousScope (ID);
382 if (hoisted_this != null)
383 hoisted_this.EmitSymbolInfo ();
385 if (hoisted_locals != null) {
386 foreach (HoistedVariable local in hoisted_locals)
387 local.EmitSymbolInfo ();
390 if (hoisted_params != null) {
391 foreach (HoistedParameter param in hoisted_params)
392 param.EmitSymbolInfo ();
395 if (used_parent_storeys != null) {
396 foreach (StoreyFieldPair sf in used_parent_storeys) {
397 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
404 public AnonymousMethodStorey GetGenericStorey ()
406 DeclSpace storey = this;
407 while (storey != null && storey.CurrentTypeParameters == null)
408 storey = storey.Parent;
410 return storey as AnonymousMethodStorey;
414 // Returns a field which holds referenced storey instance
416 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
418 if (used_parent_storeys == null)
421 foreach (StoreyFieldPair sf in used_parent_storeys) {
422 if (sf.Storey == storey)
430 // Creates storey instance expression regardless of currect IP
432 public Expression GetStoreyInstanceExpression (EmitContext ec)
434 AnonymousExpression am = ec.CurrentAnonymousMethod;
437 // Access from original block -> storey
443 // Access from anonymous method implemented as a static -> storey
445 if (am.Storey == null)
448 Field f = am.Storey.GetReferencedStoreyField (this);
450 if (am.Storey == this) {
452 // Access inside of same storey (S -> S)
454 return new CompilerGeneratedThis (TypeBuilder, Location);
457 // External field access
463 // Storey was cached to local field
465 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
466 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
470 protected virtual string GetVariableMangledName (LocalInfo local_info)
473 // No need to mangle anonymous method hoisted variables cause they
474 // are hoisted in their own scopes
476 return local_info.Name;
479 public HoistedThis HoistedThis {
480 get { return hoisted_this; }
484 // Mutate type dispatcher
486 public Type MutateType (Type type)
489 if (TypeManager.IsGenericType (type))
490 return MutateGenericType (type);
492 if (TypeManager.IsGenericParameter (type))
493 return MutateGenericArgument (type);
496 return MutateArrayType (type);
502 // Changes method type arguments (MVAR) to storey (VAR) type arguments
504 public MethodInfo MutateGenericMethod (MethodInfo method)
507 Type [] t_args = TypeManager.GetGenericArguments (method);
508 if (TypeManager.IsGenericType (method.DeclaringType)) {
509 Type t = MutateGenericType (method.DeclaringType);
510 if (t != method.DeclaringType) {
511 method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
512 if (method.Module == Module.Builder)
513 method = TypeBuilder.GetMethod (t, method);
515 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
519 if (t_args == null || t_args.Length == 0)
522 for (int i = 0; i < t_args.Length; ++i)
523 t_args [i] = MutateType (t_args [i]);
525 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
527 throw new NotSupportedException ();
531 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
534 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
535 Type t = MutateGenericType (ctor.DeclaringType);
536 if (t != ctor.DeclaringType) {
537 ctor = (ConstructorInfo) TypeManager.DropGenericMethodArguments (ctor);
538 if (ctor.Module == Module.Builder)
539 return TypeBuilder.GetConstructor (t, ctor);
541 return (ConstructorInfo) ConstructorInfo.GetMethodFromHandle (ctor.MethodHandle, t.TypeHandle);
548 public FieldInfo MutateField (FieldInfo field)
551 if (TypeManager.IsGenericType (field.DeclaringType)) {
552 Type t = MutateGenericType (field.DeclaringType);
553 if (t != field.DeclaringType) {
554 field = TypeManager.DropGenericTypeArguments (field.DeclaringType).GetField (field.Name, TypeManager.AllMembers);
555 if (field.Module == Module.Builder)
556 return TypeBuilder.GetField (t, field);
558 return FieldInfo.GetFieldFromHandle (field.FieldHandle, t.TypeHandle);
566 protected Type MutateArrayType (Type array)
568 Type element = TypeManager.GetElementType (array);
569 if (element.IsArray) {
570 element = MutateArrayType (element);
571 } else if (TypeManager.IsGenericParameter (element)) {
572 element = MutateGenericArgument (element);
573 } else if (TypeManager.IsGenericType (element)) {
574 element = MutateGenericType (element);
579 int rank = array.GetArrayRank ();
581 return element.MakeArrayType ();
583 return element.MakeArrayType (rank);
586 protected Type MutateGenericType (Type type)
588 Type [] t_args = TypeManager.GetTypeArguments (type);
589 if (t_args == null || t_args.Length == 0)
592 for (int i = 0; i < t_args.Length; ++i)
593 t_args [i] = MutateType (t_args [i]);
595 return TypeManager.DropGenericTypeArguments (type).MakeGenericType (t_args);
600 // Changes method generic argument (MVAR) to type generic argument (VAR)
602 public Type MutateGenericArgument (Type type)
604 if (CurrentTypeParameters != null) {
605 TypeParameter tp = TypeParameter.FindTypeParameter (CurrentTypeParameters, type.Name);
613 public ArrayList ReferencesFromChildrenBlock {
614 get { return children_references; }
617 public static void Reset ()
623 public abstract class HoistedVariable
625 class ExpressionTreeProxy : Expression
627 readonly HoistedVariable hv;
629 public ExpressionTreeProxy (HoistedVariable hv)
634 public override Expression CreateExpressionTree (ResolveContext ec)
636 throw new NotSupportedException ("ET");
639 public override Expression DoResolve (ResolveContext ec)
641 eclass = ExprClass.Value;
642 type = TypeManager.expression_type_expr.Type;
646 public override void Emit (EmitContext ec)
648 ResolveContext rc = new ResolveContext (ec.MemberContext);
649 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc);
650 // This should never fail
657 protected readonly AnonymousMethodStorey storey;
658 protected Field field;
659 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
660 FieldExpr cached_outer_access;
662 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
663 : this (storey, storey.AddCapturedVariable (name, type))
667 protected HoistedVariable (AnonymousMethodStorey storey, Field field)
669 this.storey = storey;
673 public void AddressOf (EmitContext ec, AddressOp mode)
675 GetFieldExpression (ec).AddressOf (ec, mode);
678 public Expression CreateExpressionTree (ResolveContext ec)
680 return new ExpressionTreeProxy (this);
683 public void Emit (EmitContext ec)
685 GetFieldExpression (ec).Emit (ec);
689 // Creates field access expression for hoisted variable
691 protected FieldExpr GetFieldExpression (EmitContext ec)
693 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
694 if (cached_outer_access != null)
695 return cached_outer_access;
698 // When setting top-level hoisted variable in generic storey
699 // change storey generic types to method generic types (VAR -> MVAR)
701 cached_outer_access = storey.MemberName.IsGeneric ?
702 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
703 new FieldExpr (field.FieldBuilder, field.Location);
705 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
706 return cached_outer_access;
709 FieldExpr inner_access;
710 if (cached_inner_access != null) {
711 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
714 cached_inner_access = new Hashtable (4);
717 if (inner_access == null) {
718 inner_access = field.Parent.MemberName.IsGeneric ?
719 new FieldExpr (field.FieldBuilder, field.Parent.CurrentType, field.Location) :
720 new FieldExpr (field.FieldBuilder, field.Location);
722 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
723 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
729 public abstract void EmitSymbolInfo ();
731 public void Emit (EmitContext ec, bool leave_copy)
733 GetFieldExpression (ec).Emit (ec, leave_copy);
736 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
738 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
742 class HoistedParameter : HoistedVariable
744 sealed class HoistedFieldAssign : Assign
746 public HoistedFieldAssign (Expression target, Expression source)
747 : base (target, source, source.Location)
751 protected override Expression ResolveConversions (ResolveContext ec)
754 // Implicit conversion check fails for hoisted type arguments
755 // as they are of different types (!!0 x !0)
761 readonly ParameterReference parameter;
763 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
764 : base (scope, par.Name, par.Type)
766 this.parameter = par;
769 public HoistedParameter (HoistedParameter hp, string name)
770 : base (hp.storey, name, hp.parameter.Type)
772 this.parameter = hp.parameter;
775 public void EmitHoistingAssignment (EmitContext ec)
778 // Remove hoisted redirection to emit assignment from original parameter
780 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
781 parameter.Parameter.HoistedVariableReference = null;
783 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
784 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
785 a.EmitStatement (ec);
787 parameter.Parameter.HoistedVariableReference = temp;
790 public override void EmitSymbolInfo ()
792 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
796 get { return field; }
800 class HoistedLocalVariable : HoistedVariable
802 readonly string name;
804 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
805 : base (scope, name, local.VariableType)
807 this.name = local.Name;
810 public override void EmitSymbolInfo ()
812 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
816 public class HoistedThis : HoistedVariable
818 public HoistedThis (AnonymousMethodStorey storey, Field field)
819 : base (storey, field)
823 public void EmitHoistingAssignment (EmitContext ec)
825 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), new CompilerGeneratedThis (ec.CurrentType, field.Location));
826 if (a.Resolve (new ResolveContext (ec.MemberContext)) != null)
827 a.EmitStatement (ec);
830 public override void EmitSymbolInfo ()
832 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
836 get { return field; }
841 // Anonymous method expression as created by parser
843 public class AnonymousMethodExpression : Expression
845 ListDictionary compatibles;
846 public ToplevelBlock Block;
848 public AnonymousMethodExpression (Location loc)
851 this.compatibles = new ListDictionary ();
854 public override string ExprClassName {
856 return "anonymous method";
860 public virtual bool HasExplicitParameters {
862 return Parameters != ParametersCompiled.Undefined;
866 public ParametersCompiled Parameters {
867 get { return Block.Parameters; }
871 // Returns true if the body of lambda expression can be implicitly
872 // converted to the delegate of type `delegate_type'
874 public bool ImplicitStandardConversionExists (ResolveContext ec, Type delegate_type)
876 using (ec.With (ResolveContext.Options.InferReturnType, false)) {
877 using (ec.Set (ResolveContext.Options.ProbingMode)) {
878 return Compatible (ec, delegate_type) != null;
883 protected Type CompatibleChecks (ResolveContext ec, Type delegate_type)
885 if (TypeManager.IsDelegateType (delegate_type))
886 return delegate_type;
888 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
889 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
890 if (TypeManager.IsDelegateType (delegate_type))
891 return delegate_type;
893 ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
894 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
898 ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
899 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
903 protected bool VerifyExplicitParameters (ResolveContext ec, Type delegate_type, AParametersCollection parameters)
905 if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
908 if (!ec.IsInProbingMode)
909 ec.Report.Error (1661, loc,
910 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
911 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
916 protected bool VerifyParameterCompatibility (ResolveContext ec, Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
918 if (Parameters.Count != invoke_pd.Count) {
922 ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
923 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
927 bool has_implicit_parameters = !HasExplicitParameters;
930 for (int i = 0; i < Parameters.Count; ++i) {
931 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
932 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
936 if (p_mod == Parameter.Modifier.NONE)
937 ec.Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
938 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
940 ec.Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
941 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
945 if (has_implicit_parameters)
948 Type type = invoke_pd.Types [i];
950 // We assume that generic parameters are always inflated
951 if (TypeManager.IsGenericParameter (type))
954 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
957 if (invoke_pd.Types [i] != Parameters.Types [i]) {
961 ec.Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
963 TypeManager.CSharpName (Parameters.Types [i]),
964 TypeManager.CSharpName (invoke_pd.Types [i]));
973 // Infers type arguments based on explicit arguments
975 public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, Type delegate_type)
977 if (!HasExplicitParameters)
980 if (!TypeManager.IsDelegateType (delegate_type)) {
981 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
984 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
985 if (!TypeManager.IsDelegateType (delegate_type))
989 AParametersCollection d_params = TypeManager.GetDelegateParameters (ec, delegate_type);
990 if (d_params.Count != Parameters.Count)
993 for (int i = 0; i < Parameters.Count; ++i) {
994 Type itype = d_params.Types [i];
995 if (!TypeManager.IsGenericParameter (itype)) {
996 if (!TypeManager.HasElementType (itype))
999 if (!TypeManager.IsGenericParameter (TypeManager.GetElementType (itype)))
1002 type_inference.ExactInference (Parameters.Types [i], itype);
1007 public Type InferReturnType (ResolveContext ec, TypeInferenceContext tic, Type delegate_type)
1009 AnonymousMethodBody am;
1010 using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
1011 am = CompatibleMethod (ec, tic, InternalType.Arglist, delegate_type);
1017 return am.ReturnType;
1021 // Returns AnonymousMethod container if this anonymous method
1022 // expression can be implicitly converted to the delegate type `delegate_type'
1024 public Expression Compatible (ResolveContext ec, Type type)
1026 Expression am = (Expression) compatibles [type];
1030 Type delegate_type = CompatibleChecks (ec, type);
1031 if (delegate_type == null)
1035 // At this point its the first time we know the return type that is
1036 // needed for the anonymous method. We create the method here.
1039 MethodInfo invoke_mb = Delegate.GetInvokeMethod (ec.Compiler,
1040 ec.CurrentType, delegate_type);
1041 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1044 Type[] g_args = delegate_type.GetGenericArguments ();
1045 if (return_type.IsGenericParameter)
1046 return_type = g_args [return_type.GenericParameterPosition];
1050 // Second: the return type of the delegate must be compatible with
1051 // the anonymous type. Instead of doing a pass to examine the block
1052 // we satisfy the rule by setting the return type on the EmitContext
1053 // to be the delegate type return type.
1057 int errors = ec.Report.Errors;
1058 am = CompatibleMethod (ec, null, return_type, delegate_type);
1059 if (am != null && delegate_type != type && errors == ec.Report.Errors)
1060 am = CreateExpressionTree (ec, delegate_type);
1062 if (!ec.IsInProbingMode)
1063 compatibles.Add (type, am == null ? EmptyExpression.Null : am);
1066 } catch (CompletionResult){
1068 } catch (Exception e) {
1069 throw new InternalErrorException (e, loc);
1073 protected virtual Expression CreateExpressionTree (ResolveContext ec, Type delegate_type)
1075 return CreateExpressionTree (ec);
1078 public override Expression CreateExpressionTree (ResolveContext ec)
1080 ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1084 protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, Type delegate_type)
1086 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (ec, delegate_type);
1088 if (Parameters == ParametersCompiled.Undefined) {
1090 // We provide a set of inaccessible parameters
1092 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1094 for (int i = 0; i < delegate_parameters.Count; i++) {
1095 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1096 if (i_mod == Parameter.Modifier.OUT) {
1097 ec.Report.Error (1688, loc, "Cannot convert anonymous " +
1098 "method block without a parameter list " +
1099 "to delegate type `{0}' because it has " +
1100 "one or more `out' parameters.",
1101 TypeManager.CSharpName (delegate_type));
1104 fixedpars[i] = new Parameter (
1106 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1109 return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1112 if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
1119 public override Expression DoResolve (ResolveContext ec)
1121 if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
1122 ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1127 // Set class type, set type
1130 eclass = ExprClass.Value;
1133 // This hack means `The type is not accessible
1134 // anywhere', we depend on special conversion
1137 type = InternalType.AnonymousMethod;
1139 if ((Parameters != null) && !Parameters.Resolve (ec))
1142 // FIXME: The emitted code isn't very careful about reachability
1143 // so, ensure we have a 'ret' at the end
1144 BlockContext bc = ec as BlockContext;
1145 if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
1146 bc.NeedReturnLabel ();
1151 public override void Emit (EmitContext ec)
1153 // nothing, as we only exist to not do anything.
1156 public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
1158 ec.Report.Error (1686, loc,
1159 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1163 public override string GetSignatureForError ()
1165 return ExprClassName;
1168 protected AnonymousMethodBody CompatibleMethod (ResolveContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1170 ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
1174 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1176 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1177 if (!anonymous.Compatible (ec))
1183 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, ParametersCompiled p, ToplevelBlock b)
1185 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1188 protected override void CloneTo (CloneContext clonectx, Expression t)
1190 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1192 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1197 // Abstract expression for any block which requires variables hoisting
1199 public abstract class AnonymousExpression : Expression
1201 protected class AnonymousMethodMethod : Method
1203 public readonly AnonymousExpression AnonymousMethod;
1204 public readonly AnonymousMethodStorey Storey;
1205 readonly string RealName;
1207 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1208 GenericMethod generic, TypeExpr return_type,
1209 int mod, string real_name, MemberName name,
1210 ParametersCompiled parameters)
1211 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1212 name, parameters, null)
1214 this.AnonymousMethod = am;
1215 this.Storey = storey;
1216 this.RealName = real_name;
1218 Parent.PartialContainer.AddMethod (this);
1222 public override EmitContext CreateEmitContext (ILGenerator ig)
1224 EmitContext ec = new EmitContext (this, ig, ReturnType);
1225 ec.CurrentAnonymousMethod = AnonymousMethod;
1226 if (AnonymousMethod.return_label != null) {
1227 ec.HasReturnLabel = true;
1228 ec.ReturnLabel = (Label) AnonymousMethod.return_label;
1234 protected override bool ResolveMemberType ()
1236 if (!base.ResolveMemberType ())
1239 if (Storey != null && Storey.IsGeneric) {
1240 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1241 if (gstorey != null) {
1242 if (!Parameters.IsEmpty) {
1243 Type [] ptypes = Parameters.Types;
1244 for (int i = 0; i < ptypes.Length; ++i)
1245 ptypes [i] = gstorey.MutateType (ptypes [i]);
1248 member_type = gstorey.MutateType (member_type);
1255 public override void Emit ()
1258 // Before emitting any code we have to change all MVAR references to VAR
1259 // when the method is of generic type and has hoisted variables
1261 if (Storey == Parent && Storey.IsGeneric) {
1262 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1263 if (gstorey != null) {
1264 block.MutateHoistedGenericType (gstorey);
1268 if (MethodBuilder == null) {
1275 public override void EmitExtraSymbolInfo (SourceMethod source)
1277 source.SetRealMethodName (RealName);
1282 // The block that makes up the body for the anonymous method
1284 protected readonly ToplevelBlock Block;
1286 public Type ReturnType;
1288 object return_label;
1290 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1292 this.ReturnType = return_type;
1297 public abstract string ContainerType { get; }
1298 public abstract bool IsIterator { get; }
1299 public abstract AnonymousMethodStorey Storey { get; }
1301 public bool Compatible (ResolveContext ec)
1303 // TODO: Implement clone
1304 BlockContext aec = new BlockContext (ec.MemberContext, Block, ReturnType);
1305 aec.CurrentAnonymousMethod = this;
1307 IDisposable aec_dispose = null;
1308 ResolveContext.Options flags = 0;
1309 if (ec.HasSet (ResolveContext.Options.InferReturnType)) {
1310 flags |= ResolveContext.Options.InferReturnType;
1311 aec.ReturnTypeInference = new TypeInferenceContext ();
1314 if (ec.IsInProbingMode)
1315 flags |= ResolveContext.Options.ProbingMode;
1317 if (ec.HasSet (ResolveContext.Options.FieldInitializerScope))
1318 flags |= ResolveContext.Options.FieldInitializerScope;
1321 flags |= ResolveContext.Options.UnsafeScope;
1323 // HACK: Flag with 0 cannot be set
1325 aec_dispose = aec.Set (flags);
1327 bool res = Block.Resolve (ec.CurrentBranching, aec, Block.Parameters, null);
1329 if (aec.HasReturnLabel)
1330 return_label = aec.ReturnLabel;
1332 if (ec.HasSet (ResolveContext.Options.InferReturnType)) {
1333 aec.ReturnTypeInference.FixAllTypes (ec);
1334 ReturnType = aec.ReturnTypeInference.InferredTypeArguments [0];
1337 if (aec_dispose != null) {
1338 aec_dispose.Dispose ();
1344 public void SetHasThisAccess ()
1346 Block.HasCapturedThis = true;
1347 ExplicitBlock b = Block.Parent.Explicit;
1350 if (b.HasCapturedThis)
1353 b.HasCapturedThis = true;
1354 b = b.Parent == null ? null : b.Parent.Explicit;
1359 public class AnonymousMethodBody : AnonymousExpression
1361 protected readonly ParametersCompiled parameters;
1362 AnonymousMethodStorey storey;
1364 AnonymousMethodMethod method;
1368 static int unique_id;
1370 public AnonymousMethodBody (ParametersCompiled parameters,
1371 ToplevelBlock block, Type return_type, Type delegate_type,
1373 : base (block, return_type, loc)
1375 this.type = delegate_type;
1376 this.parameters = parameters;
1379 public override string ContainerType {
1380 get { return "anonymous method"; }
1383 public override AnonymousMethodStorey Storey {
1384 get { return storey; }
1387 public override bool IsIterator {
1388 get { return false; }
1391 public override Expression CreateExpressionTree (ResolveContext ec)
1393 ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1397 bool Define (ResolveContext ec)
1399 if (!Block.Resolved && !Compatible (ec))
1402 if (block_name == null) {
1403 MemberCore mc = (MemberCore) ec.MemberContext;
1404 block_name = mc.MemberName.Basename;
1411 // Creates a host for the anonymous method
1413 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1416 // Anonymous method body can be converted to
1418 // 1, an instance method in current scope when only `this' is hoisted
1419 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1420 // 3, an instance method in compiler generated storey when any hoisted variable exists
1424 if (Block.HasCapturedVariable || Block.HasCapturedThis) {
1425 storey = FindBestMethodStorey ();
1426 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1428 if (ec.CurrentAnonymousMethod != null)
1429 storey = ec.CurrentAnonymousMethod.Storey;
1431 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1434 TypeContainer parent = storey != null ? storey : ec.CurrentTypeDefinition;
1436 MemberCore mc = ec.MemberContext as MemberCore;
1437 string name = CompilerGeneratedClass.MakeName (parent != storey ? block_name : null,
1438 "m", null, unique_id++);
1440 MemberName member_name;
1441 GenericMethod generic_method;
1442 if (storey == null && mc.MemberName.IsGeneric) {
1443 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1445 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1446 new TypeExpression (ReturnType, Location), parameters);
1448 ArrayList list = new ArrayList ();
1449 foreach (TypeParameter tparam in ec.CurrentTypeParameters) {
1450 if (tparam.Constraints != null)
1451 list.Add (tparam.Constraints.Clone ());
1453 generic_method.SetParameterInfo (list);
1455 member_name = new MemberName (name, Location);
1456 generic_method = null;
1459 string real_name = String.Format (
1460 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1461 parameters.GetSignatureForError ());
1463 return new AnonymousMethodMethod (parent,
1464 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1465 real_name, member_name, parameters);
1468 public override Expression DoResolve (ResolveContext ec)
1470 if (eclass == ExprClass.Invalid) {
1475 eclass = ExprClass.Value;
1479 public override void Emit (EmitContext ec)
1482 // Use same anonymous method implementation for scenarios where same
1483 // code is used from multiple blocks, e.g. field initializers
1485 if (method == null) {
1487 // Delay an anonymous method definition to avoid emitting unused code
1488 // for unreachable blocks or expression trees
1490 method = DoCreateMethodHost (ec);
1494 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1495 if (is_static && am_cache == null) {
1497 // Creates a field cache to store delegate instance if it's not generic
1499 if (!method.MemberName.IsGeneric) {
1500 TypeContainer parent = method.Parent.PartialContainer;
1501 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1502 am_cache = new Field (parent, new TypeExpression (type, loc),
1503 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1504 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1506 parent.AddField (am_cache);
1508 // TODO: Implement caching of generated generic static methods
1512 // Some extra class is needed to capture variable generic type
1513 // arguments. Maybe we could re-use anonymous types, with a unique
1514 // anonymous method id, but they are quite heavy.
1516 // Consider : "() => typeof(T);"
1518 // We need something like
1519 // static class Wrap<Tn, Tm, DelegateType> {
1520 // public static DelegateType cache;
1523 // We then specialize local variable to capture all generic parameters
1524 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1529 ILGenerator ig = ec.ig;
1530 Label l_initialized = ig.DefineLabel ();
1532 if (am_cache != null) {
1533 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1534 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1538 // Load method delegate implementation
1542 ig.Emit (OpCodes.Ldnull);
1543 } else if (storey != null) {
1544 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
1548 ig.Emit (OpCodes.Ldarg_0);
1551 MethodInfo delegate_method = method.MethodBuilder;
1552 if (storey != null && storey.MemberName.IsGeneric) {
1553 Type t = storey.Instance.Type;
1556 // Mutate anonymous method instance type if we are in nested
1557 // hoisted generic anonymous method storey
1559 if (ec.CurrentAnonymousMethod != null &&
1560 ec.CurrentAnonymousMethod.Storey != null &&
1561 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1562 t = storey.GetGenericStorey ().MutateType (t);
1566 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1568 throw new NotSupportedException ();
1572 ig.Emit (OpCodes.Ldftn, delegate_method);
1574 ConstructorInfo constructor_method = Delegate.GetConstructor (RootContext.ToplevelTypes.Compiler, ec.CurrentType, type);
1576 if (type.IsGenericType && type is TypeBuilder)
1577 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1579 ig.Emit (OpCodes.Newobj, constructor_method);
1581 if (am_cache != null) {
1582 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1583 ig.MarkLabel (l_initialized);
1584 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1589 // Look for the best storey for this anonymous method
1591 AnonymousMethodStorey FindBestMethodStorey ()
1594 // Use the nearest parent block which has a storey
1596 for (Block b = Block.Parent; b != null; b = b.Parent) {
1597 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1605 public override string GetSignatureForError ()
1607 return TypeManager.CSharpName (type);
1610 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1612 type = storey.MutateType (type);
1615 public static void Reset ()
1622 // Anonymous type container
1624 public class AnonymousTypeClass : CompilerGeneratedClass
1626 sealed class AnonymousParameters : ParametersCompiled
1628 public AnonymousParameters (params Parameter[] parameters)
1633 protected override void ErrorDuplicateName (Parameter p, Report Report)
1635 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1640 static int types_counter;
1641 public const string ClassNamePrefix = "<>__AnonType";
1642 public const string SignatureForError = "anonymous type";
1644 readonly ArrayList parameters;
1646 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1647 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1649 this.parameters = parameters;
1652 public static AnonymousTypeClass Create (CompilerContext ctx, TypeContainer parent, ArrayList parameters, Location loc)
1654 string name = ClassNamePrefix + types_counter++;
1656 SimpleName [] t_args = new SimpleName [parameters.Count];
1657 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1658 Parameter [] ctor_params = new Parameter [parameters.Count];
1659 for (int i = 0; i < parameters.Count; ++i) {
1660 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1662 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1663 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1664 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1668 // Create generic anonymous type host with generic arguments
1669 // named upon properties names
1671 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1672 new MemberName (name, new TypeArguments (t_params), loc), parameters, loc);
1674 if (parameters.Count > 0)
1675 a_type.SetParameterInfo (null);
1677 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1678 null, new AnonymousParameters (ctor_params), null, loc);
1679 c.Block = new ToplevelBlock (ctx, c.Parameters, loc);
1682 // Create fields and contructor body with field initialization
1685 for (int i = 0; i < parameters.Count; ++i) {
1686 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1688 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1689 new MemberName ("<" + p.Name + ">", p.Location), null);
1691 if (!a_type.AddField (f)) {
1696 c.Block.AddStatement (new StatementExpression (
1697 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1698 c.Block.GetParameterReference (p.Name, p.Location))));
1700 ToplevelBlock get_block = new ToplevelBlock (ctx, p.Location);
1701 get_block.AddStatement (new Return (
1702 new MemberAccess (new This (p.Location), f.Name), p.Location));
1703 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1704 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1705 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1706 a_type.AddProperty (prop);
1712 a_type.AddConstructor (c);
1716 public static void Reset ()
1721 protected override bool AddToContainer (MemberCore symbol, string name)
1723 MemberCore mc = (MemberCore) defined_names [name];
1726 defined_names.Add (name, symbol);
1730 Report.SymbolRelatedToPreviousError (mc);
1734 void DefineOverrides ()
1736 Location loc = Location;
1738 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1739 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1740 Mono.CSharp.ParametersCompiled.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1742 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1743 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1744 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1746 ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.Parameters, loc);
1747 TypeExpr current_type;
1749 current_type = new GenericTypeExpr (this, loc);
1751 current_type = new TypeExpression (TypeBuilder, loc);
1753 equals_block.AddVariable (current_type, "other", loc);
1754 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1756 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1757 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1759 Expression rs_equals = null;
1760 Expression string_concat = new StringConstant ("{", loc);
1761 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1762 for (int i = 0; i < parameters.Count; ++i) {
1763 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1764 Field f = (Field) Fields [i];
1766 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1767 system_collections_generic, "EqualityComparer",
1768 new TypeArguments (new SimpleName (TypeParameters [i].Name, loc)), loc),
1771 Arguments arguments_equal = new Arguments (2);
1772 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1773 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1775 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1776 "Equals", loc), arguments_equal);
1778 Arguments arguments_hashcode = new Arguments (1);
1779 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1780 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1781 "GetHashCode", loc), arguments_hashcode);
1783 IntConstant FNV_prime = new IntConstant (16777619, loc);
1784 rs_hashcode = new Binary (Binary.Operator.Multiply,
1785 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1788 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1789 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1790 new Invocation (new MemberAccess (
1791 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1792 new StringConstant (string.Empty, loc));
1794 if (rs_equals == null) {
1795 rs_equals = field_equal;
1796 string_concat = new Binary (Binary.Operator.Addition,
1798 new Binary (Binary.Operator.Addition,
1799 new StringConstant (" " + p.Name + " = ", loc),
1805 // Implementation of ToString () body using string concatenation
1807 string_concat = new Binary (Binary.Operator.Addition,
1808 new Binary (Binary.Operator.Addition,
1810 new StringConstant (", " + p.Name + " = ", loc)),
1813 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1816 string_concat = new Binary (Binary.Operator.Addition,
1818 new StringConstant (" }", loc));
1821 // Equals (object obj) override
1823 LocalVariableReference other_variable_assign = new LocalVariableReference (equals_block, "other", loc);
1824 equals_block.AddStatement (new StatementExpression (
1825 new SimpleAssign (other_variable_assign,
1826 new As (equals_block.GetParameterReference ("obj", loc),
1827 current_type, loc), loc)));
1829 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1830 if (rs_equals != null)
1831 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1832 equals_block.AddStatement (new Return (equals_test, loc));
1834 equals.Block = equals_block;
1839 // GetHashCode () override
1841 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1842 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1843 new MemberName ("GetHashCode", loc),
1844 Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
1847 // Modified FNV with good avalanche behavior and uniform
1848 // distribution with larger hash sizes.
1850 // const int FNV_prime = 16777619;
1851 // int hash = (int) 2166136261;
1852 // foreach (int d in data)
1853 // hash = (hash ^ d) * FNV_prime;
1854 // hash += hash << 13;
1855 // hash ^= hash >> 7;
1856 // hash += hash << 3;
1857 // hash ^= hash >> 17;
1858 // hash += hash << 5;
1860 ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
1861 Block hashcode_block = new Block (hashcode_top);
1862 hashcode_top.AddStatement (new Unchecked (hashcode_block));
1864 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1865 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1866 LocalVariableReference hash_variable_assign = new LocalVariableReference (hashcode_block, "hash", loc);
1867 hashcode_block.AddStatement (new StatementExpression (
1868 new SimpleAssign (hash_variable_assign, rs_hashcode)));
1870 hashcode_block.AddStatement (new StatementExpression (
1871 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1872 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1873 hashcode_block.AddStatement (new StatementExpression (
1874 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1875 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1876 hashcode_block.AddStatement (new StatementExpression (
1877 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1878 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1879 hashcode_block.AddStatement (new StatementExpression (
1880 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1881 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1882 hashcode_block.AddStatement (new StatementExpression (
1883 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1884 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1886 hashcode_block.AddStatement (new Return (hash_variable, loc));
1887 hashcode.Block = hashcode_top;
1889 AddMethod (hashcode);
1892 // ToString () override
1895 ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
1896 tostring_block.AddStatement (new Return (string_concat, loc));
1897 tostring.Block = tostring_block;
1899 AddMethod (tostring);
1902 public override bool Define ()
1904 if (!base.Define ())
1911 public override string GetSignatureForError ()
1913 return SignatureForError;
1916 public ArrayList Parameters {