2 // anonymous.cs: Support for anonymous methods and types
5 // Miguel de Icaza (miguel@ximain.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2003-2008 Novell, Inc.
14 using System.Collections;
15 using System.Collections.Specialized;
16 using System.Reflection;
17 using System.Reflection.Emit;
19 namespace Mono.CSharp {
21 public abstract class CompilerGeneratedClass : Class
23 public static string MakeName (string host, string typePrefix, string name, int id)
25 return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
28 protected CompilerGeneratedClass (DeclSpace parent, MemberName name, int mod)
29 : base (parent.NamespaceEntry, parent, name, mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED, null)
33 protected CompilerGeneratedClass (DeclSpace parent, GenericMethod generic, MemberName name, int mod)
34 : this (parent, name, mod)
36 if (generic != null) {
37 ArrayList list = new ArrayList ();
38 foreach (TypeParameter tparam in generic.TypeParameters) {
39 if (tparam.Constraints != null)
40 list.Add (tparam.Constraints.Clone ());
42 SetParameterInfo (list);
46 protected void CheckMembersDefined ()
49 throw new InternalErrorException ("Helper class already defined!");
54 // Anonymous method storey is created when an anonymous method uses
55 // variable or parameter from outer scope. They are then hoisted to
56 // anonymous method storey (captured)
58 public class AnonymousMethodStorey : CompilerGeneratedClass
60 class StoreyFieldPair {
61 public AnonymousMethodStorey Storey;
64 public StoreyFieldPair (AnonymousMethodStorey storey)
69 public override int GetHashCode ()
71 return Storey.ID.GetHashCode ();
74 public override bool Equals (object obj)
76 return (AnonymousMethodStorey)obj == Storey;
80 class HoistedGenericField : Field
82 public HoistedGenericField (DeclSpace parent, FullNamedExpression type, int mod, string name,
83 Attributes attrs, Location loc)
84 : base (parent, type, mod, new MemberName (name, loc), attrs)
88 public override bool Define ()
90 AnonymousMethodStorey parent = ((AnonymousMethodStorey) Parent).GetGenericStorey ();
92 type_name.Type = parent.MutateType (type_name.Type);
94 return base.Define ();
99 public readonly int ID;
100 static int unique_id;
102 public readonly Block OriginalSourceBlock;
104 // A list of StoreyFieldPair with local field keeping parent storey instance
105 ArrayList used_parent_storeys;
107 // A list of hoisted parameters
108 protected ArrayList hoisted_params;
109 protected ArrayList hoisted_locals;
112 protected HoistedThis hoisted_this;
114 // Local variable which holds this storey instance
115 public LocalTemporary Instance;
117 bool references_defined;
118 bool has_hoisted_variable;
121 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
122 : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE)
125 OriginalSourceBlock = block;
129 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
131 string host_name = host == null ? null : host.Name;
132 string tname = MakeName (host_name, "c", name, unique_id);
133 TypeArguments args = null;
134 if (generic != null) {
135 args = new TypeArguments (loc);
136 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
137 args.Add (new TypeParameterName (tparam.Name, null, loc));
140 return new MemberName (tname, args, loc);
143 public Field AddCapturedVariable (string name, Type type)
145 CheckMembersDefined ();
147 FullNamedExpression field_type = new TypeExpression (type, Location);
149 return AddCompilerGeneratedField (name, field_type);
151 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
152 Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
157 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
159 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
160 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
165 public void AddParentStoreyReference (AnonymousMethodStorey s)
167 CheckMembersDefined ();
169 if (used_parent_storeys == null)
170 used_parent_storeys = new ArrayList ();
171 else if (used_parent_storeys.IndexOf (s) != -1)
174 has_hoisted_variable = true;
175 used_parent_storeys.Add (new StoreyFieldPair (s));
178 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
180 if (local_info.HoistedVariableReference != null)
183 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
184 local_info.HoistedVariableReference = var;
185 has_hoisted_variable = true;
187 if (hoisted_locals == null)
188 hoisted_locals = new ArrayList ();
190 hoisted_locals.Add (var);
193 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
195 if (param_ref.HoistedVariable != null)
198 if (hoisted_params == null)
199 hoisted_params = new ArrayList (2);
201 HoistedVariable expr = new HoistedParameter (this, param_ref);
202 param_ref.Parameter.HoistedVariableReference = expr;
203 hoisted_params.Add (expr);
206 public HoistedThis CaptureThis (EmitContext ec, This t)
208 hoisted_this = new HoistedThis (this, t);
212 public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
214 Parent = parentStorey;
218 void DefineStoreyReferences ()
220 if (used_parent_storeys == null || references_defined)
223 references_defined = true;
226 // For each used variable from parent scope we allocate its local reference point
228 for (int i = 0; i < used_parent_storeys.Count; ++i) {
229 StoreyFieldPair sf = (StoreyFieldPair) used_parent_storeys [i];
230 AnonymousMethodStorey p_storey = sf.Storey;
231 TypeExpr type_expr = new TypeExpression (p_storey.TypeBuilder, Location);
233 sf.Field = AddCompilerGeneratedField ("<>f__ref$" + p_storey.ID, type_expr);
239 // Initializes all hoisted variables
241 public void EmitHoistedVariables (EmitContext ec)
243 // There can be only one instance variable for each storey type
244 if (Instance != null)
245 throw new InternalErrorException ();
248 // A storey with hoisted `this' is an instance method
250 if (!HasHoistedVariables) {
251 hoisted_this.RemoveHoisting ();
255 SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
257 DefineStoreyReferences ();
260 // Create an instance of storey type
262 Expression storey_type_expr;
265 // Use current method type parameter (MVAR) for top level storey only. All
266 // nested storeys use class type parameter (VAR)
268 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
269 ec.CurrentAnonymousMethod.Storey.TypeParameters :
270 ec.GenericDeclContainer.TypeParameters;
272 if (tparams.Length != CountTypeParameters) {
273 TypeParameter [] full = new TypeParameter [CountTypeParameters];
274 DeclSpace parent = ec.DeclContainer.Parent;
275 parent.CurrentTypeParameters.CopyTo (full, 0);
276 tparams.CopyTo (full, parent.CountTypeParameters);
280 storey_type_expr = new ConstructedType (TypeBuilder, tparams, Location);
282 storey_type_expr = new TypeExpression (TypeBuilder, Location);
285 Expression e = new New (storey_type_expr, new ArrayList (0), Location).Resolve (ec);
288 Instance = new LocalTemporary (storey_type_expr.Type);
291 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
293 EmitHoistedFieldsInitialization (ec);
295 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
298 void EmitHoistedFieldsInitialization (EmitContext ec)
301 // Initialize all storey reference fields by using local or hoisted variables
303 if (used_parent_storeys != null) {
304 foreach (StoreyFieldPair sf in used_parent_storeys) {
306 // Setting local field
308 Expression instace_expr = GetStoreyInstanceExpression (ec);
309 FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
310 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
311 new FieldExpr (sf.Field.FieldBuilder, Location);
312 f_set_expr.InstanceExpression = instace_expr;
314 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
315 if (a.Resolve (ec) != null)
316 a.EmitStatement (ec);
321 // Setting currect anonymous method to null blocks any further variable hoisting
323 AnonymousExpression ae = ec.CurrentAnonymousMethod;
324 ec.CurrentAnonymousMethod = null;
326 if (hoisted_params != null) {
327 EmitHoistedParameters (ec, hoisted_params);
330 if (hoisted_this != null) {
331 hoisted_this.EmitHoistingAssignment (ec);
334 ec.CurrentAnonymousMethod = ae;
337 protected virtual void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
339 foreach (HoistedParameter hp in hoisted) {
340 hp.EmitHoistingAssignment (ec);
344 public override void EmitType ()
346 SymbolWriter.DefineAnonymousScope (ID);
348 if (hoisted_this != null)
349 hoisted_this.EmitSymbolInfo ();
351 if (hoisted_locals != null) {
352 foreach (HoistedVariable local in hoisted_locals)
353 local.EmitSymbolInfo ();
356 if (hoisted_params != null) {
357 foreach (HoistedParameter param in hoisted_params)
358 param.EmitSymbolInfo ();
361 DefineStoreyReferences ();
363 if (used_parent_storeys != null) {
364 foreach (StoreyFieldPair sf in used_parent_storeys) {
365 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
372 public AnonymousMethodStorey GetGenericStorey ()
374 DeclSpace storey = this;
375 while (storey != null && storey.CurrentTypeParameters.Length == 0)
376 storey = storey.Parent;
378 return storey as AnonymousMethodStorey;
382 // Returns a field which holds referenced storey instance
384 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
386 if (used_parent_storeys == null)
389 foreach (StoreyFieldPair sf in used_parent_storeys) {
390 if (sf.Storey == storey)
398 // Creates storey instance expression regardless of currect IP
400 public Expression GetStoreyInstanceExpression (EmitContext ec)
402 AnonymousExpression am = ec.CurrentAnonymousMethod;
405 // Access from original block -> storey
411 // Access from anonymous method implemented as a static -> storey
413 if (am.Storey == null)
416 Field f = am.Storey.GetReferencedStoreyField (this);
418 if (am.Storey == this) {
420 // Access inside of same storey (S -> S)
422 return new CompilerGeneratedThis (TypeBuilder, Location);
425 // External field access
431 // Storey was cached to local field
433 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
434 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
438 protected virtual string GetVariableMangledName (LocalInfo local_info)
441 // No need to mangle anonymous method hoisted variables cause they
442 // are hoisted in their own scopes
444 return local_info.Name;
448 // Returns true when at least one local variable or parameter is
449 // hoisted, or story is transitioned
451 public bool HasHoistedVariables {
453 return has_hoisted_variable || hoisted_params != null;
456 has_hoisted_variable = value;
460 public bool IsUndone {
461 get { return is_undone; }
465 // Mutate type dispatcher
467 public Type MutateType (Type type)
470 if (TypeManager.IsGenericType (type))
471 return MutateGenericType (type);
473 if (TypeManager.IsGenericParameter (type))
474 return MutateGenericArgument (type);
477 return MutateArrayType (type);
483 // Changes method type arguments (MVAR) to storey (VAR) type arguments
485 public MethodInfo MutateGenericMethod (MethodInfo method)
488 Type [] t_args = TypeManager.GetGenericArguments (method);
489 if (TypeManager.IsGenericType (method.DeclaringType)) {
490 Type t = MutateGenericType (method.DeclaringType);
491 if (t != method.DeclaringType) {
492 method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
493 if (method.Module == CodeGen.Module.Builder)
494 method = TypeBuilder.GetMethod (t, method);
496 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
500 if (t_args == null || t_args.Length == 0)
503 for (int i = 0; i < t_args.Length; ++i)
504 t_args [i] = MutateType (t_args [i]);
506 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
508 throw new NotSupportedException ();
512 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
515 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
516 Type t = MutateGenericType (ctor.DeclaringType);
517 if (t != ctor.DeclaringType) {
518 ctor = (ConstructorInfo) TypeManager.DropGenericMethodArguments (ctor);
519 if (ctor.Module == CodeGen.Module.Builder)
520 return TypeBuilder.GetConstructor (t, ctor);
522 return (ConstructorInfo) ConstructorInfo.GetMethodFromHandle (ctor.MethodHandle, t.TypeHandle);
529 public FieldInfo MutateField (FieldInfo field)
532 if (TypeManager.IsGenericType (field.DeclaringType)) {
533 Type t = MutateGenericType (field.DeclaringType);
534 if (t != field.DeclaringType) {
535 // TODO: It should throw on imported types
536 return TypeBuilder.GetField (t, field);
544 protected Type MutateArrayType (Type array)
546 int rank = array.GetArrayRank ();
547 Type element = TypeManager.GetElementType (array);
549 throw new NotImplementedException ();
551 if (TypeManager.IsGenericParameter (element)) {
552 element = MutateGenericArgument (element);
553 } else if (TypeManager.IsGenericType (element)) {
554 element = MutateGenericType (element);
559 return element.MakeArrayType (rank);
562 protected Type MutateGenericType (Type type)
564 Type [] t_args = TypeManager.GetTypeArguments (type);
565 if (t_args == null || t_args.Length == 0)
568 for (int i = 0; i < t_args.Length; ++i)
569 t_args [i] = MutateType (t_args [i]);
571 return type.GetGenericTypeDefinition ().MakeGenericType (t_args);
576 // Changes method generic argument (MVAR) to type generic argument (VAR)
578 public Type MutateGenericArgument (Type type)
580 foreach (TypeParameter tp in CurrentTypeParameters) {
581 if (tp.Name == type.Name) {
589 public static void Reset ()
597 if (hoisted_this != null)
598 hoisted_this.RemoveHoisting ();
602 public abstract class HoistedVariable
604 class ExpressionTreeProxy : Expression
606 readonly HoistedVariable hv;
608 public ExpressionTreeProxy (HoistedVariable hv)
613 public override Expression CreateExpressionTree (EmitContext ec)
615 throw new NotSupportedException ("ET");
618 public override Expression DoResolve (EmitContext ec)
620 eclass = ExprClass.Value;
621 type = TypeManager.expression_type_expr.Type;
625 public override void Emit (EmitContext ec)
627 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (ec);
628 // This should never fail
635 protected readonly AnonymousMethodStorey storey;
636 protected Field field;
637 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
639 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
641 this.storey = storey;
643 this.field = storey.AddCapturedVariable (name, type);
646 public void AddressOf (EmitContext ec, AddressOp mode)
648 GetFieldExpression (ec).AddressOf (ec, mode);
651 public Expression CreateExpressionTree (EmitContext ec)
653 return new ExpressionTreeProxy (this);
656 public void Emit (EmitContext ec)
658 GetFieldExpression (ec).Emit (ec);
662 // Creates field access expression for hoisted variable
664 protected FieldExpr GetFieldExpression (EmitContext ec)
666 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
668 // When setting top-level hoisted variable in generic storey
669 // change storey generic types to method generic types (VAR -> MVAR)
671 FieldExpr outer_access = storey.MemberName.IsGeneric ?
672 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
673 new FieldExpr (field.FieldBuilder, field.Location);
675 outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
676 outer_access.Resolve (ec);
680 FieldExpr inner_access;
681 if (cached_inner_access != null) {
682 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
685 cached_inner_access = new Hashtable (4);
688 if (inner_access == null) {
689 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
690 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
691 inner_access.Resolve (ec);
692 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
698 public abstract void EmitSymbolInfo ();
700 public void Emit (EmitContext ec, bool leave_copy)
702 GetFieldExpression (ec).Emit (ec, leave_copy);
705 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
707 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
711 class HoistedParameter : HoistedVariable
713 sealed class HoistedFieldAssign : Assign
715 public HoistedFieldAssign (Expression target, Expression source)
716 : base (target, source, source.Location)
720 protected override Expression ResolveConversions (EmitContext ec)
723 // Implicit conversion check fails for hoisted type arguments
724 // as they are of different types (!!0 x !0)
730 readonly ParameterReference parameter;
732 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
733 : base (scope, par.Name, par.Type)
735 this.parameter = par;
738 public HoistedParameter (HoistedParameter hp, string name)
739 : base (hp.storey, name, hp.parameter.Type)
741 this.parameter = hp.parameter;
744 public void EmitHoistingAssignment (EmitContext ec)
747 // Remove hoisted redirection to emit assignment from original parameter
749 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
750 parameter.Parameter.HoistedVariableReference = null;
752 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
753 if (a.Resolve (ec) != null)
754 a.EmitStatement (ec);
756 parameter.Parameter.HoistedVariableReference = temp;
759 public override void EmitSymbolInfo ()
761 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
765 get { return field; }
769 class HoistedLocalVariable : HoistedVariable
771 readonly string name;
773 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
774 : base (scope, name, local.VariableType)
776 this.name = local.Name;
779 public override void EmitSymbolInfo ()
781 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
785 public class HoistedThis : HoistedVariable
787 readonly This this_reference;
789 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
790 : base (storey, "<>f__this", this_reference.Type)
792 this.this_reference = this_reference;
795 public void EmitHoistingAssignment (EmitContext ec)
797 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
798 if (a.Resolve (ec) != null)
799 a.EmitStatement (ec);
802 public override void EmitSymbolInfo ()
804 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
808 get { return field; }
811 public void RemoveHoisting ()
813 this_reference.RemoveHoisting ();
818 // Anonymous method expression as created by parser
820 public class AnonymousMethodExpression : Expression
822 public readonly Parameters Parameters;
823 ListDictionary compatibles;
824 public ToplevelBlock Block;
826 public AnonymousMethodExpression (Parameters parameters, Location loc)
828 this.Parameters = parameters;
830 this.compatibles = new ListDictionary ();
833 public override string ExprClassName {
835 return "anonymous method";
839 public virtual bool HasExplicitParameters {
841 return Parameters != null;
846 // Returns true if the body of lambda expression can be implicitly
847 // converted to the delegate of type `delegate_type'
849 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
851 using (ec.Set (EmitContext.Flags.ProbingMode)) {
852 return Compatible (ec, delegate_type) != null;
856 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
858 if (TypeManager.IsDelegateType (delegate_type))
859 return delegate_type;
862 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
863 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
864 if (TypeManager.IsDelegateType (delegate_type))
865 return delegate_type;
867 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
868 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
873 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
874 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
878 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
880 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
884 Report.Error (1661, loc,
885 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
886 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
891 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
893 if (Parameters.Count != invoke_pd.Count) {
897 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
898 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
902 bool has_implicit_parameters = !HasExplicitParameters;
905 for (int i = 0; i < Parameters.Count; ++i) {
906 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
907 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
911 if (p_mod == Parameter.Modifier.NONE)
912 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
913 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
915 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
916 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
920 if (has_implicit_parameters)
923 Type type = invoke_pd.Types [i];
925 // We assume that generic parameters are always inflated
926 if (TypeManager.IsGenericParameter (type))
929 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
932 if (invoke_pd.Types [i] != Parameters.Types [i]) {
936 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
938 TypeManager.CSharpName (Parameters.Types [i]),
939 TypeManager.CSharpName (invoke_pd.Types [i]));
948 // Infers type arguments based on explicit arguments
950 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
952 if (!HasExplicitParameters)
955 if (!TypeManager.IsDelegateType (delegate_type)) {
957 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
960 delegate_type = delegate_type.GetGenericArguments () [0];
961 if (!TypeManager.IsDelegateType (delegate_type))
968 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
969 if (d_params.Count != Parameters.Count)
972 for (int i = 0; i < Parameters.Count; ++i) {
973 Type itype = d_params.Types [i];
974 if (!TypeManager.IsGenericParameter (itype)) {
975 if (!TypeManager.HasElementType (itype))
978 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
981 type_inference.ExactInference (Parameters.Types [i], itype);
986 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
988 AnonymousMethodBody am;
989 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
990 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
996 if (am.ReturnType == TypeManager.null_type)
997 am.ReturnType = null;
999 return am.ReturnType;
1003 // Returns AnonymousMethod container if this anonymous method
1004 // expression can be implicitly converted to the delegate type `delegate_type'
1006 public Expression Compatible (EmitContext ec, Type type)
1008 Expression am = (Expression) compatibles [type];
1012 Type delegate_type = CompatibleChecks (ec, type);
1013 if (delegate_type == null)
1017 // At this point its the first time we know the return type that is
1018 // needed for the anonymous method. We create the method here.
1021 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1022 ec.ContainerType, delegate_type);
1023 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1026 Type[] g_args = delegate_type.GetGenericArguments ();
1027 if (return_type.IsGenericParameter)
1028 return_type = g_args [return_type.GenericParameterPosition];
1032 // Second: the return type of the delegate must be compatible with
1033 // the anonymous type. Instead of doing a pass to examine the block
1034 // we satisfy the rule by setting the return type on the EmitContext
1035 // to be the delegate type return type.
1039 int errors = Report.Errors;
1040 am = CompatibleMethod (ec, null, return_type, delegate_type);
1041 if (am != null && delegate_type != type && errors == Report.Errors)
1042 am = CreateExpressionTree (ec, delegate_type);
1044 if (!ec.IsInProbingMode)
1045 compatibles.Add (type, am);
1048 } catch (Exception e) {
1049 throw new InternalErrorException (e, loc);
1053 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1055 return CreateExpressionTree (ec);
1058 public override Expression CreateExpressionTree (EmitContext ec)
1060 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1064 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1066 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1068 if (Parameters == null) {
1070 // We provide a set of inaccessible parameters
1072 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1074 for (int i = 0; i < delegate_parameters.Count; i++) {
1075 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1076 if (i_mod == Parameter.Modifier.OUT) {
1077 Report.Error (1688, loc, "Cannot convert anonymous " +
1078 "method block without a parameter list " +
1079 "to delegate type `{0}' because it has " +
1080 "one or more `out' parameters.",
1081 TypeManager.CSharpName (delegate_type));
1084 fixedpars[i] = new Parameter (
1086 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1089 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1092 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1099 public override Expression DoResolve (EmitContext ec)
1101 if (!ec.IsAnonymousMethodAllowed) {
1102 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1107 // Set class type, set type
1110 eclass = ExprClass.Value;
1113 // This hack means `The type is not accessible
1114 // anywhere', we depend on special conversion
1117 type = TypeManager.anonymous_method_type;
1119 if ((Parameters != null) && !Parameters.Resolve (ec))
1122 // FIXME: The emitted code isn't very careful about reachability
1123 // so, ensure we have a 'ret' at the end
1124 if (ec.CurrentBranching != null &&
1125 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1126 ec.NeedReturnLabel ();
1131 public override void Emit (EmitContext ec)
1133 // nothing, as we only exist to not do anything.
1136 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1138 Report.Error (1686, loc,
1139 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1143 public override string GetSignatureForError ()
1145 return ExprClassName;
1148 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1150 Parameters p = ResolveParameters (ec, tic, delegate_type);
1154 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1156 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1157 if (!anonymous.Compatible (ec))
1163 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1165 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1168 protected override void CloneTo (CloneContext clonectx, Expression t)
1170 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1172 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1177 // Abstract expression for any block which requires variables hoisting
1179 public abstract class AnonymousExpression : Expression
1181 protected class AnonymousMethodMethod : Method
1183 public readonly AnonymousExpression AnonymousMethod;
1184 public readonly AnonymousMethodStorey Storey;
1185 readonly string RealName;
1187 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1188 GenericMethod generic, TypeExpr return_type,
1189 int mod, string real_name, MemberName name,
1190 Parameters parameters)
1191 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1192 name, parameters, null)
1194 this.AnonymousMethod = am;
1195 this.Storey = storey;
1196 this.RealName = real_name;
1198 Parent.PartialContainer.AddMethod (this);
1202 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1204 EmitContext aec = AnonymousMethod.aec;
1206 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1210 public override bool Define ()
1212 if (Storey != null && Storey.IsGeneric && Storey.HasHoistedVariables) {
1213 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1214 if (gstorey != null) {
1215 if (!Parameters.IsEmpty) {
1216 Type [] ptypes = Parameters.Types;
1217 for (int i = 0; i < ptypes.Length; ++i)
1218 ptypes [i] = gstorey.MutateType (ptypes [i]);
1221 member_type = gstorey.MutateType (ReturnType);
1225 return base.Define ();
1228 public override void Emit ()
1231 // Before emitting any code we have to change all MVAR references to VAR
1232 // when the method is of generic type and has hoisted variables
1234 if (Storey == Parent && Storey.IsGeneric) {
1235 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1236 if (gstorey != null) {
1237 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1238 block.MutateHoistedGenericType (gstorey);
1242 if (MethodBuilder == null) {
1249 public override void EmitExtraSymbolInfo (SourceMethod source)
1251 source.SetRealMethodName (RealName);
1256 // The block that makes up the body for the anonymous method
1258 protected readonly ToplevelBlock Block;
1260 public Type ReturnType;
1261 protected EmitContext aec;
1263 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1265 this.ReturnType = return_type;
1270 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1271 public abstract string ContainerType { get; }
1272 public abstract bool IsIterator { get; }
1273 public abstract AnonymousMethodStorey Storey { get; }
1275 public bool Compatible (EmitContext ec)
1277 // TODO: Implement clone
1278 aec = new EmitContext (
1279 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1280 Location, null, ReturnType,
1281 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1283 aec.CurrentAnonymousMethod = this;
1284 aec.IsStatic = ec.IsStatic;
1286 IDisposable aec_dispose = null;
1287 EmitContext.Flags flags = 0;
1288 if (ec.InferReturnType)
1289 flags |= EmitContext.Flags.InferReturnType;
1291 if (ec.IsInProbingMode)
1292 flags |= EmitContext.Flags.ProbingMode;
1294 if (ec.IsInFieldInitializer)
1295 flags |= EmitContext.Flags.InFieldInitializer;
1297 if (ec.IsInUnsafeScope)
1298 flags |= EmitContext.Flags.InUnsafe;
1300 // HACK: Flag with 0 cannot be set
1302 aec_dispose = aec.Set (flags);
1305 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1307 if (ec.InferReturnType)
1308 ReturnType = aec.ReturnType;
1310 if (aec_dispose != null) {
1311 aec_dispose.Dispose ();
1318 public class AnonymousMethodBody : AnonymousExpression
1320 ArrayList referenced_storeys;
1321 protected readonly Parameters parameters;
1322 AnonymousMethodStorey storey;
1324 AnonymousMethodMethod method;
1327 static int unique_id;
1329 public AnonymousMethodBody (Parameters parameters,
1330 ToplevelBlock block, Type return_type, Type delegate_type,
1332 : base (block, return_type, loc)
1334 this.type = delegate_type;
1335 this.parameters = parameters;
1338 public override string ContainerType {
1339 get { return "anonymous method"; }
1342 public override AnonymousMethodStorey Storey {
1343 get { return storey; }
1346 public override bool IsIterator {
1347 get { return false; }
1351 // Adds new storey reference to track out of scope variables
1353 public override void AddStoreyReference (AnonymousMethodStorey storey)
1355 if (referenced_storeys == null) {
1356 referenced_storeys = new ArrayList (2);
1358 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1364 referenced_storeys.Add (storey);
1367 public override Expression CreateExpressionTree (EmitContext ec)
1369 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1373 bool Define (EmitContext ec)
1375 if (aec == null && !Compatible (ec))
1378 if (referenced_storeys != null)
1379 ConnectReferencedStoreys ();
1384 void ConnectReferencedStoreys ()
1386 storey = FindBestMethodStorey ();
1388 foreach (AnonymousMethodStorey s in referenced_storeys) {
1390 // An anonymous method has to have an instance access when
1391 // children anonymous method requires access to parent storey
1392 // hoisted variables
1394 for (Block b = Block.Parent; b != s.OriginalSourceBlock; b = b.Parent)
1395 b.Toplevel.HasStoreyAccess = true;
1400 s.HasHoistedVariables = true;
1401 Block.Parent.Explicit.PropagateStoreyReference (s);
1406 // Creates a host for the anonymous method
1408 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1411 // Anonymous method body can be converted to
1413 // 1, an instance method in current scope when only `this' is hoisted
1414 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1415 // 3, an instance method in compiler generated storey when any hoisted variable exists
1419 if (referenced_storeys != null || Block.HasStoreyAccess) {
1420 if (storey == null || storey.IsUndone)
1421 storey = FindBestMethodStorey ();
1423 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1425 if (ec.CurrentAnonymousMethod != null)
1426 storey = ec.CurrentAnonymousMethod.Storey;
1428 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1431 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1433 MemberCore mc = ec.ResolveContext as MemberCore;
1434 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1435 "m", null, unique_id++);
1437 MemberName member_name;
1438 GenericMethod generic_method;
1439 if (storey == null && mc.MemberName.IsGeneric) {
1440 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1442 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1443 new TypeExpression (ReturnType, Location), parameters);
1445 ArrayList list = new ArrayList ();
1446 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1447 if (tparam.Constraints != null)
1448 list.Add (tparam.Constraints.Clone ());
1450 generic_method.SetParameterInfo (list);
1452 member_name = new MemberName (name, Location);
1453 generic_method = null;
1456 string real_name = String.Format (
1457 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1458 parameters.GetSignatureForError ());
1460 return new AnonymousMethodMethod (parent,
1461 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1462 real_name, member_name, parameters);
1465 public override Expression DoResolve (EmitContext ec)
1467 if (eclass == ExprClass.Invalid) {
1472 eclass = ExprClass.Value;
1476 public override void Emit (EmitContext ec)
1479 // Use same anonymous method implementation for scenarios where same
1480 // code is used from multiple blocks, e.g. field initializers
1482 if (method == null) {
1484 // Delay an anonymous method definition to avoid emitting unused code
1485 // for unreachable blocks or expression trees
1487 method = DoCreateMethodHost (ec);
1491 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1492 if (is_static && am_cache == null) {
1494 // Creates a field cache to store delegate instance if it's not generic
1496 if (!method.MemberName.IsGeneric) {
1497 TypeContainer parent = method.Parent.PartialContainer;
1498 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1499 am_cache = new Field (parent, new TypeExpression (type, loc),
1500 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1501 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1503 parent.AddField (am_cache);
1505 // TODO: Implement caching of generated generic static methods
1509 // Some extra class is needed to capture variable generic type
1510 // arguments. Maybe we could re-use anonymous types, with a unique
1511 // anonymous method id, but they are quite heavy.
1513 // Consider : "() => typeof(T);"
1515 // We need something like
1516 // static class Wrap<Tn, Tm, DelegateType> {
1517 // public static DelegateType cache;
1520 // We then specialize local variable to capture all generic parameters
1521 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1526 ILGenerator ig = ec.ig;
1527 Label l_initialized = ig.DefineLabel ();
1529 if (am_cache != null) {
1530 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1531 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1535 // Load method delegate implementation
1539 ig.Emit (OpCodes.Ldnull);
1540 } else if (storey != null) {
1541 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1545 ig.Emit (OpCodes.Ldarg_0);
1548 MethodInfo delegate_method = method.MethodBuilder;
1550 if (storey != null && storey.MemberName.IsGeneric) {
1551 Type t = storey.Instance.Type;
1554 // Mutate anonymous method instance type if we are in nested
1555 // hoisted generic anonymous method storey
1557 if (ec.CurrentAnonymousMethod != null &&
1558 ec.CurrentAnonymousMethod.Storey != null &&
1559 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1560 t = storey.GetGenericStorey ().MutateType (t);
1563 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1566 ig.Emit (OpCodes.Ldftn, delegate_method);
1568 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1570 if (type.IsGenericType && type is TypeBuilder)
1571 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1573 ig.Emit (OpCodes.Newobj, constructor_method);
1575 if (am_cache != null) {
1576 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1577 ig.MarkLabel (l_initialized);
1578 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1583 // Look for the best storey for this anonymous method
1585 AnonymousMethodStorey FindBestMethodStorey ()
1588 // Use the nearest parent block which has a storey
1590 for (Block b = Block.Parent; b != null; b = b.Parent) {
1591 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1599 public override string GetSignatureForError ()
1601 return TypeManager.CSharpName (type);
1604 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1606 type = storey.MutateType (type);
1609 public static void Reset ()
1616 // Anonymous type container
1618 public class AnonymousTypeClass : CompilerGeneratedClass
1620 static int types_counter;
1621 public const string ClassNamePrefix = "<>__AnonType";
1622 public const string SignatureForError = "anonymous type";
1624 readonly ArrayList parameters;
1626 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1627 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1629 this.parameters = parameters;
1632 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1634 if (RootContext.Version <= LanguageVersion.ISO_2)
1635 Report.FeatureIsNotAvailable (loc, "anonymous types");
1637 string name = ClassNamePrefix + types_counter++;
1639 SimpleName [] t_args = new SimpleName [parameters.Count];
1640 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1641 Parameter [] ctor_params = new Parameter [parameters.Count];
1642 for (int i = 0; i < parameters.Count; ++i) {
1643 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1645 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1646 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1647 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1651 // Create generic anonymous type host with generic arguments
1652 // named upon properties names
1654 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1655 new MemberName (name, new TypeArguments (loc, t_params), loc), parameters, loc);
1657 if (parameters.Count > 0)
1658 a_type.SetParameterInfo (null);
1660 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1661 null, new Parameters (ctor_params), null, loc);
1662 c.Block = new ToplevelBlock (c.Parameters, loc);
1665 // Create fields and contructor body with field initialization
1668 for (int i = 0; i < parameters.Count; ++i) {
1669 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1671 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1672 new MemberName ("<" + p.Name + ">", p.Location), null);
1674 if (!a_type.AddField (f)) {
1676 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1681 c.Block.AddStatement (new StatementExpression (
1682 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1683 c.Block.GetParameterReference (p.Name, p.Location))));
1685 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1686 get_block.AddStatement (new Return (
1687 new MemberAccess (new This (p.Location), f.Name), p.Location));
1688 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1689 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1690 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1691 a_type.AddProperty (prop);
1697 a_type.AddConstructor (c);
1701 public static void Reset ()
1706 protected override bool AddToContainer (MemberCore symbol, string name)
1708 MemberCore mc = (MemberCore) defined_names [name];
1711 defined_names.Add (name, symbol);
1715 Report.SymbolRelatedToPreviousError (mc);
1719 void DefineOverrides ()
1721 Location loc = Location;
1723 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1724 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1725 Mono.CSharp.Parameters.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1727 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1728 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1729 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1731 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1732 TypeExpr current_type;
1734 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
1736 current_type = new TypeExpression (TypeBuilder, loc);
1738 equals_block.AddVariable (current_type, "other", loc);
1739 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1741 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1742 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1744 Expression rs_equals = null;
1745 Expression string_concat = new StringConstant ("<empty type>", loc);
1746 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1747 for (int i = 0; i < parameters.Count; ++i) {
1748 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1749 Field f = (Field) Fields [i];
1751 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1752 system_collections_generic, "EqualityComparer",
1753 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
1756 ArrayList arguments_equal = new ArrayList (2);
1757 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1758 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1760 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1761 "Equals", loc), arguments_equal);
1763 ArrayList arguments_hashcode = new ArrayList (1);
1764 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1765 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1766 "GetHashCode", loc), arguments_hashcode);
1768 IntConstant FNV_prime = new IntConstant (16777619, loc);
1769 rs_hashcode = new Binary (Binary.Operator.Multiply,
1770 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1773 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1774 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1775 new Invocation (new MemberAccess (
1776 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1777 new StringConstant ("<null>", loc));
1779 if (rs_equals == null) {
1780 rs_equals = field_equal;
1781 string_concat = new Binary (Binary.Operator.Addition,
1782 new StringConstant (p.Name + " = ", loc),
1788 // Implementation of ToString () body using string concatenation
1790 string_concat = new Binary (Binary.Operator.Addition,
1791 new Binary (Binary.Operator.Addition,
1793 new StringConstant (", " + p.Name + " = ", loc)),
1796 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1800 // Equals (object obj) override
1802 equals_block.AddStatement (new StatementExpression (
1803 new SimpleAssign (other_variable,
1804 new As (equals_block.GetParameterReference ("obj", loc),
1805 current_type, loc), loc)));
1807 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1808 if (rs_equals != null)
1809 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1810 equals_block.AddStatement (new Return (equals_test, loc));
1812 equals.Block = equals_block;
1817 // GetHashCode () override
1819 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1820 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1821 new MemberName ("GetHashCode", loc),
1822 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1825 // Modified FNV with good avalanche behavior and uniform
1826 // distribution with larger hash sizes.
1828 // const int FNV_prime = 16777619;
1829 // int hash = (int) 2166136261;
1830 // foreach (int d in data)
1831 // hash = (hash ^ d) * FNV_prime;
1832 // hash += hash << 13;
1833 // hash ^= hash >> 7;
1834 // hash += hash << 3;
1835 // hash ^= hash >> 17;
1836 // hash += hash << 5;
1838 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1839 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1840 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1841 hashcode_block.AddStatement (new StatementExpression (
1842 new SimpleAssign (hash_variable, rs_hashcode)));
1844 hashcode_block.AddStatement (new StatementExpression (
1845 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1846 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1847 hashcode_block.AddStatement (new StatementExpression (
1848 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1849 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1850 hashcode_block.AddStatement (new StatementExpression (
1851 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1852 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1853 hashcode_block.AddStatement (new StatementExpression (
1854 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1855 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1856 hashcode_block.AddStatement (new StatementExpression (
1857 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1858 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1860 hashcode_block.AddStatement (new Return (hash_variable, loc));
1861 hashcode.Block = hashcode_block;
1863 AddMethod (hashcode);
1866 // ToString () override
1869 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1870 tostring_block.AddStatement (new Return (string_concat, loc));
1871 tostring.Block = tostring_block;
1873 AddMethod (tostring);
1876 public override bool Define ()
1884 public override string GetSignatureForError ()
1886 return SignatureForError;
1889 public ArrayList Parameters {