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
638 FieldExpr cached_outer_access;
640 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
642 this.storey = storey;
644 this.field = storey.AddCapturedVariable (name, type);
647 public void AddressOf (EmitContext ec, AddressOp mode)
649 GetFieldExpression (ec).AddressOf (ec, mode);
652 public Expression CreateExpressionTree (EmitContext ec)
654 return new ExpressionTreeProxy (this);
657 public void Emit (EmitContext ec)
659 GetFieldExpression (ec).Emit (ec);
663 // Creates field access expression for hoisted variable
665 protected FieldExpr GetFieldExpression (EmitContext ec)
667 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
668 if (cached_outer_access != null)
669 return cached_outer_access;
672 // When setting top-level hoisted variable in generic storey
673 // change storey generic types to method generic types (VAR -> MVAR)
675 cached_outer_access = storey.MemberName.IsGeneric ?
676 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
677 new FieldExpr (field.FieldBuilder, field.Location);
679 cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
680 cached_outer_access.Resolve (ec);
681 return cached_outer_access;
684 FieldExpr inner_access;
685 if (cached_inner_access != null) {
686 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
689 cached_inner_access = new Hashtable (4);
692 if (inner_access == null) {
693 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
694 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
695 inner_access.Resolve (ec);
696 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
702 public abstract void EmitSymbolInfo ();
704 public void Emit (EmitContext ec, bool leave_copy)
706 GetFieldExpression (ec).Emit (ec, leave_copy);
709 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
711 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
715 class HoistedParameter : HoistedVariable
717 sealed class HoistedFieldAssign : Assign
719 public HoistedFieldAssign (Expression target, Expression source)
720 : base (target, source, source.Location)
724 protected override Expression ResolveConversions (EmitContext ec)
727 // Implicit conversion check fails for hoisted type arguments
728 // as they are of different types (!!0 x !0)
734 readonly ParameterReference parameter;
736 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
737 : base (scope, par.Name, par.Type)
739 this.parameter = par;
742 public HoistedParameter (HoistedParameter hp, string name)
743 : base (hp.storey, name, hp.parameter.Type)
745 this.parameter = hp.parameter;
748 public void EmitHoistingAssignment (EmitContext ec)
751 // Remove hoisted redirection to emit assignment from original parameter
753 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
754 parameter.Parameter.HoistedVariableReference = null;
756 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
757 if (a.Resolve (ec) != null)
758 a.EmitStatement (ec);
760 parameter.Parameter.HoistedVariableReference = temp;
763 public override void EmitSymbolInfo ()
765 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
769 get { return field; }
773 class HoistedLocalVariable : HoistedVariable
775 readonly string name;
777 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
778 : base (scope, name, local.VariableType)
780 this.name = local.Name;
783 public override void EmitSymbolInfo ()
785 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
789 public class HoistedThis : HoistedVariable
791 readonly This this_reference;
793 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
794 : base (storey, "<>f__this", this_reference.Type)
796 this.this_reference = this_reference;
799 public void EmitHoistingAssignment (EmitContext ec)
801 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
802 if (a.Resolve (ec) != null)
803 a.EmitStatement (ec);
806 public override void EmitSymbolInfo ()
808 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
812 get { return field; }
815 public void RemoveHoisting ()
817 this_reference.RemoveHoisting ();
822 // Anonymous method expression as created by parser
824 public class AnonymousMethodExpression : Expression
826 public readonly Parameters Parameters;
827 ListDictionary compatibles;
828 public ToplevelBlock Block;
830 public AnonymousMethodExpression (Parameters parameters, Location loc)
832 this.Parameters = parameters;
834 this.compatibles = new ListDictionary ();
837 public override string ExprClassName {
839 return "anonymous method";
843 public virtual bool HasExplicitParameters {
845 return Parameters != null;
850 // Returns true if the body of lambda expression can be implicitly
851 // converted to the delegate of type `delegate_type'
853 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
855 using (ec.Set (EmitContext.Flags.ProbingMode)) {
856 return Compatible (ec, delegate_type) != null;
860 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
862 if (TypeManager.IsDelegateType (delegate_type))
863 return delegate_type;
866 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
867 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
868 if (TypeManager.IsDelegateType (delegate_type))
869 return delegate_type;
871 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
872 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
877 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
878 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
882 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
884 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
888 Report.Error (1661, loc,
889 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
890 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
895 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
897 if (Parameters.Count != invoke_pd.Count) {
901 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
902 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
906 bool has_implicit_parameters = !HasExplicitParameters;
909 for (int i = 0; i < Parameters.Count; ++i) {
910 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
911 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
915 if (p_mod == Parameter.Modifier.NONE)
916 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
917 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
919 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
920 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
924 if (has_implicit_parameters)
927 Type type = invoke_pd.Types [i];
929 // We assume that generic parameters are always inflated
930 if (TypeManager.IsGenericParameter (type))
933 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
936 if (invoke_pd.Types [i] != Parameters.Types [i]) {
940 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
942 TypeManager.CSharpName (Parameters.Types [i]),
943 TypeManager.CSharpName (invoke_pd.Types [i]));
952 // Infers type arguments based on explicit arguments
954 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
956 if (!HasExplicitParameters)
959 if (!TypeManager.IsDelegateType (delegate_type)) {
961 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
964 delegate_type = delegate_type.GetGenericArguments () [0];
965 if (!TypeManager.IsDelegateType (delegate_type))
972 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
973 if (d_params.Count != Parameters.Count)
976 for (int i = 0; i < Parameters.Count; ++i) {
977 Type itype = d_params.Types [i];
978 if (!TypeManager.IsGenericParameter (itype)) {
979 if (!TypeManager.HasElementType (itype))
982 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
985 type_inference.ExactInference (Parameters.Types [i], itype);
990 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
992 AnonymousMethodBody am;
993 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
994 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
1000 if (am.ReturnType == TypeManager.null_type)
1001 am.ReturnType = null;
1003 return am.ReturnType;
1007 // Returns AnonymousMethod container if this anonymous method
1008 // expression can be implicitly converted to the delegate type `delegate_type'
1010 public Expression Compatible (EmitContext ec, Type type)
1012 Expression am = (Expression) compatibles [type];
1016 Type delegate_type = CompatibleChecks (ec, type);
1017 if (delegate_type == null)
1021 // At this point its the first time we know the return type that is
1022 // needed for the anonymous method. We create the method here.
1025 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1026 ec.ContainerType, delegate_type);
1027 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1030 Type[] g_args = delegate_type.GetGenericArguments ();
1031 if (return_type.IsGenericParameter)
1032 return_type = g_args [return_type.GenericParameterPosition];
1036 // Second: the return type of the delegate must be compatible with
1037 // the anonymous type. Instead of doing a pass to examine the block
1038 // we satisfy the rule by setting the return type on the EmitContext
1039 // to be the delegate type return type.
1043 int errors = Report.Errors;
1044 am = CompatibleMethod (ec, null, return_type, delegate_type);
1045 if (am != null && delegate_type != type && errors == Report.Errors)
1046 am = CreateExpressionTree (ec, delegate_type);
1048 if (!ec.IsInProbingMode)
1049 compatibles.Add (type, am);
1052 } catch (Exception e) {
1053 throw new InternalErrorException (e, loc);
1057 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1059 return CreateExpressionTree (ec);
1062 public override Expression CreateExpressionTree (EmitContext ec)
1064 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1068 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1070 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1072 if (Parameters == null) {
1074 // We provide a set of inaccessible parameters
1076 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1078 for (int i = 0; i < delegate_parameters.Count; i++) {
1079 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1080 if (i_mod == Parameter.Modifier.OUT) {
1081 Report.Error (1688, loc, "Cannot convert anonymous " +
1082 "method block without a parameter list " +
1083 "to delegate type `{0}' because it has " +
1084 "one or more `out' parameters.",
1085 TypeManager.CSharpName (delegate_type));
1088 fixedpars[i] = new Parameter (
1090 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1093 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1096 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1103 public override Expression DoResolve (EmitContext ec)
1105 if (!ec.IsAnonymousMethodAllowed) {
1106 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1111 // Set class type, set type
1114 eclass = ExprClass.Value;
1117 // This hack means `The type is not accessible
1118 // anywhere', we depend on special conversion
1121 type = TypeManager.anonymous_method_type;
1123 if ((Parameters != null) && !Parameters.Resolve (ec))
1126 // FIXME: The emitted code isn't very careful about reachability
1127 // so, ensure we have a 'ret' at the end
1128 if (ec.CurrentBranching != null &&
1129 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1130 ec.NeedReturnLabel ();
1135 public override void Emit (EmitContext ec)
1137 // nothing, as we only exist to not do anything.
1140 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1142 Report.Error (1686, loc,
1143 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1147 public override string GetSignatureForError ()
1149 return ExprClassName;
1152 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1154 Parameters p = ResolveParameters (ec, tic, delegate_type);
1158 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1160 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1161 if (!anonymous.Compatible (ec))
1167 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1169 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1172 protected override void CloneTo (CloneContext clonectx, Expression t)
1174 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1176 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1181 // Abstract expression for any block which requires variables hoisting
1183 public abstract class AnonymousExpression : Expression
1185 protected class AnonymousMethodMethod : Method
1187 public readonly AnonymousExpression AnonymousMethod;
1188 public readonly AnonymousMethodStorey Storey;
1189 readonly string RealName;
1191 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1192 GenericMethod generic, TypeExpr return_type,
1193 int mod, string real_name, MemberName name,
1194 Parameters parameters)
1195 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1196 name, parameters, null)
1198 this.AnonymousMethod = am;
1199 this.Storey = storey;
1200 this.RealName = real_name;
1202 Parent.PartialContainer.AddMethod (this);
1206 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1208 EmitContext aec = AnonymousMethod.aec;
1210 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1214 public override bool Define ()
1216 if (Storey != null && Storey.IsGeneric && Storey.HasHoistedVariables) {
1217 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1218 if (gstorey != null) {
1219 if (!Parameters.IsEmpty) {
1220 Type [] ptypes = Parameters.Types;
1221 for (int i = 0; i < ptypes.Length; ++i)
1222 ptypes [i] = gstorey.MutateType (ptypes [i]);
1225 member_type = gstorey.MutateType (ReturnType);
1229 return base.Define ();
1232 public override void Emit ()
1235 // Before emitting any code we have to change all MVAR references to VAR
1236 // when the method is of generic type and has hoisted variables
1238 if (Storey == Parent && Storey.IsGeneric) {
1239 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1240 if (gstorey != null) {
1241 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1242 block.MutateHoistedGenericType (gstorey);
1246 if (MethodBuilder == null) {
1253 public override void EmitExtraSymbolInfo (SourceMethod source)
1255 source.SetRealMethodName (RealName);
1260 // The block that makes up the body for the anonymous method
1262 protected readonly ToplevelBlock Block;
1264 public Type ReturnType;
1265 protected EmitContext aec;
1267 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1269 this.ReturnType = return_type;
1274 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1275 public abstract string ContainerType { get; }
1276 public abstract bool IsIterator { get; }
1277 public abstract AnonymousMethodStorey Storey { get; }
1279 public bool Compatible (EmitContext ec)
1281 // TODO: Implement clone
1282 aec = new EmitContext (
1283 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1284 Location, null, ReturnType,
1285 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1287 aec.CurrentAnonymousMethod = this;
1288 aec.IsStatic = ec.IsStatic;
1290 IDisposable aec_dispose = null;
1291 EmitContext.Flags flags = 0;
1292 if (ec.InferReturnType)
1293 flags |= EmitContext.Flags.InferReturnType;
1295 if (ec.IsInProbingMode)
1296 flags |= EmitContext.Flags.ProbingMode;
1298 if (ec.IsInFieldInitializer)
1299 flags |= EmitContext.Flags.InFieldInitializer;
1301 if (ec.IsInUnsafeScope)
1302 flags |= EmitContext.Flags.InUnsafe;
1304 // HACK: Flag with 0 cannot be set
1306 aec_dispose = aec.Set (flags);
1309 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1311 if (ec.InferReturnType)
1312 ReturnType = aec.ReturnType;
1314 if (aec_dispose != null) {
1315 aec_dispose.Dispose ();
1322 public class AnonymousMethodBody : AnonymousExpression
1324 ArrayList referenced_storeys;
1325 protected readonly Parameters parameters;
1326 AnonymousMethodStorey storey;
1328 AnonymousMethodMethod method;
1331 static int unique_id;
1333 public AnonymousMethodBody (Parameters parameters,
1334 ToplevelBlock block, Type return_type, Type delegate_type,
1336 : base (block, return_type, loc)
1338 this.type = delegate_type;
1339 this.parameters = parameters;
1342 public override string ContainerType {
1343 get { return "anonymous method"; }
1346 public override AnonymousMethodStorey Storey {
1347 get { return storey; }
1350 public override bool IsIterator {
1351 get { return false; }
1355 // Adds new storey reference to track out of scope variables
1357 public override void AddStoreyReference (AnonymousMethodStorey storey)
1359 if (referenced_storeys == null) {
1360 referenced_storeys = new ArrayList (2);
1362 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1368 referenced_storeys.Add (storey);
1371 public override Expression CreateExpressionTree (EmitContext ec)
1373 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1377 bool Define (EmitContext ec)
1379 if (aec == null && !Compatible (ec))
1382 if (referenced_storeys != null)
1383 ConnectReferencedStoreys ();
1388 void ConnectReferencedStoreys ()
1390 storey = FindBestMethodStorey ();
1392 foreach (AnonymousMethodStorey s in referenced_storeys) {
1394 // An anonymous method has to have an instance access when
1395 // children anonymous method requires access to parent storey
1396 // hoisted variables
1398 for (Block b = Block.Parent; b != s.OriginalSourceBlock; b = b.Parent)
1399 b.Toplevel.HasStoreyAccess = true;
1404 s.HasHoistedVariables = true;
1405 Block.Parent.Explicit.PropagateStoreyReference (s);
1410 // Creates a host for the anonymous method
1412 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1415 // Anonymous method body can be converted to
1417 // 1, an instance method in current scope when only `this' is hoisted
1418 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1419 // 3, an instance method in compiler generated storey when any hoisted variable exists
1423 if (referenced_storeys != null || Block.HasStoreyAccess) {
1424 if (storey == null || storey.IsUndone)
1425 storey = FindBestMethodStorey ();
1427 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1429 if (ec.CurrentAnonymousMethod != null)
1430 storey = ec.CurrentAnonymousMethod.Storey;
1432 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1435 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1437 MemberCore mc = ec.ResolveContext as MemberCore;
1438 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1439 "m", null, unique_id++);
1441 MemberName member_name;
1442 GenericMethod generic_method;
1443 if (storey == null && mc.MemberName.IsGeneric) {
1444 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1446 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1447 new TypeExpression (ReturnType, Location), parameters);
1449 ArrayList list = new ArrayList ();
1450 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1451 if (tparam.Constraints != null)
1452 list.Add (tparam.Constraints.Clone ());
1454 generic_method.SetParameterInfo (list);
1456 member_name = new MemberName (name, Location);
1457 generic_method = null;
1460 string real_name = String.Format (
1461 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1462 parameters.GetSignatureForError ());
1464 return new AnonymousMethodMethod (parent,
1465 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1466 real_name, member_name, parameters);
1469 public override Expression DoResolve (EmitContext ec)
1471 if (eclass == ExprClass.Invalid) {
1476 eclass = ExprClass.Value;
1480 public override void Emit (EmitContext ec)
1483 // Use same anonymous method implementation for scenarios where same
1484 // code is used from multiple blocks, e.g. field initializers
1486 if (method == null) {
1488 // Delay an anonymous method definition to avoid emitting unused code
1489 // for unreachable blocks or expression trees
1491 method = DoCreateMethodHost (ec);
1495 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1496 if (is_static && am_cache == null) {
1498 // Creates a field cache to store delegate instance if it's not generic
1500 if (!method.MemberName.IsGeneric) {
1501 TypeContainer parent = method.Parent.PartialContainer;
1502 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1503 am_cache = new Field (parent, new TypeExpression (type, loc),
1504 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1505 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1507 parent.AddField (am_cache);
1509 // TODO: Implement caching of generated generic static methods
1513 // Some extra class is needed to capture variable generic type
1514 // arguments. Maybe we could re-use anonymous types, with a unique
1515 // anonymous method id, but they are quite heavy.
1517 // Consider : "() => typeof(T);"
1519 // We need something like
1520 // static class Wrap<Tn, Tm, DelegateType> {
1521 // public static DelegateType cache;
1524 // We then specialize local variable to capture all generic parameters
1525 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1530 ILGenerator ig = ec.ig;
1531 Label l_initialized = ig.DefineLabel ();
1533 if (am_cache != null) {
1534 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1535 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1539 // Load method delegate implementation
1543 ig.Emit (OpCodes.Ldnull);
1544 } else if (storey != null) {
1545 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1549 ig.Emit (OpCodes.Ldarg_0);
1552 MethodInfo delegate_method = method.MethodBuilder;
1554 if (storey != null && storey.MemberName.IsGeneric) {
1555 Type t = storey.Instance.Type;
1558 // Mutate anonymous method instance type if we are in nested
1559 // hoisted generic anonymous method storey
1561 if (ec.CurrentAnonymousMethod != null &&
1562 ec.CurrentAnonymousMethod.Storey != null &&
1563 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1564 t = storey.GetGenericStorey ().MutateType (t);
1567 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1570 ig.Emit (OpCodes.Ldftn, delegate_method);
1572 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1574 if (type.IsGenericType && type is TypeBuilder)
1575 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1577 ig.Emit (OpCodes.Newobj, constructor_method);
1579 if (am_cache != null) {
1580 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1581 ig.MarkLabel (l_initialized);
1582 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1587 // Look for the best storey for this anonymous method
1589 AnonymousMethodStorey FindBestMethodStorey ()
1592 // Use the nearest parent block which has a storey
1594 for (Block b = Block.Parent; b != null; b = b.Parent) {
1595 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1603 public override string GetSignatureForError ()
1605 return TypeManager.CSharpName (type);
1608 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1610 type = storey.MutateType (type);
1613 public static void Reset ()
1620 // Anonymous type container
1622 public class AnonymousTypeClass : CompilerGeneratedClass
1624 static int types_counter;
1625 public const string ClassNamePrefix = "<>__AnonType";
1626 public const string SignatureForError = "anonymous type";
1628 readonly ArrayList parameters;
1630 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1631 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1633 this.parameters = parameters;
1636 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1638 if (RootContext.Version <= LanguageVersion.ISO_2)
1639 Report.FeatureIsNotAvailable (loc, "anonymous types");
1641 string name = ClassNamePrefix + types_counter++;
1643 SimpleName [] t_args = new SimpleName [parameters.Count];
1644 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1645 Parameter [] ctor_params = new Parameter [parameters.Count];
1646 for (int i = 0; i < parameters.Count; ++i) {
1647 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1649 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1650 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1651 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1655 // Create generic anonymous type host with generic arguments
1656 // named upon properties names
1658 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1659 new MemberName (name, new TypeArguments (loc, t_params), loc), parameters, loc);
1661 if (parameters.Count > 0)
1662 a_type.SetParameterInfo (null);
1664 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1665 null, new Parameters (ctor_params), null, loc);
1666 c.Block = new ToplevelBlock (c.Parameters, loc);
1669 // Create fields and contructor body with field initialization
1672 for (int i = 0; i < parameters.Count; ++i) {
1673 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1675 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1676 new MemberName ("<" + p.Name + ">", p.Location), null);
1678 if (!a_type.AddField (f)) {
1680 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1685 c.Block.AddStatement (new StatementExpression (
1686 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1687 c.Block.GetParameterReference (p.Name, p.Location))));
1689 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1690 get_block.AddStatement (new Return (
1691 new MemberAccess (new This (p.Location), f.Name), p.Location));
1692 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1693 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1694 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1695 a_type.AddProperty (prop);
1701 a_type.AddConstructor (c);
1705 public static void Reset ()
1710 protected override bool AddToContainer (MemberCore symbol, string name)
1712 MemberCore mc = (MemberCore) defined_names [name];
1715 defined_names.Add (name, symbol);
1719 Report.SymbolRelatedToPreviousError (mc);
1723 void DefineOverrides ()
1725 Location loc = Location;
1727 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1728 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1729 Mono.CSharp.Parameters.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1731 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1732 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1733 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1735 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1736 TypeExpr current_type;
1738 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
1740 current_type = new TypeExpression (TypeBuilder, loc);
1742 equals_block.AddVariable (current_type, "other", loc);
1743 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1745 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1746 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1748 Expression rs_equals = null;
1749 Expression string_concat = new StringConstant ("<empty type>", loc);
1750 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1751 for (int i = 0; i < parameters.Count; ++i) {
1752 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1753 Field f = (Field) Fields [i];
1755 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1756 system_collections_generic, "EqualityComparer",
1757 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
1760 ArrayList arguments_equal = new ArrayList (2);
1761 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1762 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1764 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1765 "Equals", loc), arguments_equal);
1767 ArrayList arguments_hashcode = new ArrayList (1);
1768 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1769 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1770 "GetHashCode", loc), arguments_hashcode);
1772 IntConstant FNV_prime = new IntConstant (16777619, loc);
1773 rs_hashcode = new Binary (Binary.Operator.Multiply,
1774 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1777 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1778 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1779 new Invocation (new MemberAccess (
1780 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1781 new StringConstant ("<null>", loc));
1783 if (rs_equals == null) {
1784 rs_equals = field_equal;
1785 string_concat = new Binary (Binary.Operator.Addition,
1786 new StringConstant (p.Name + " = ", loc),
1792 // Implementation of ToString () body using string concatenation
1794 string_concat = new Binary (Binary.Operator.Addition,
1795 new Binary (Binary.Operator.Addition,
1797 new StringConstant (", " + p.Name + " = ", loc)),
1800 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1804 // Equals (object obj) override
1806 equals_block.AddStatement (new StatementExpression (
1807 new SimpleAssign (other_variable,
1808 new As (equals_block.GetParameterReference ("obj", loc),
1809 current_type, loc), loc)));
1811 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1812 if (rs_equals != null)
1813 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1814 equals_block.AddStatement (new Return (equals_test, loc));
1816 equals.Block = equals_block;
1821 // GetHashCode () override
1823 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1824 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1825 new MemberName ("GetHashCode", loc),
1826 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1829 // Modified FNV with good avalanche behavior and uniform
1830 // distribution with larger hash sizes.
1832 // const int FNV_prime = 16777619;
1833 // int hash = (int) 2166136261;
1834 // foreach (int d in data)
1835 // hash = (hash ^ d) * FNV_prime;
1836 // hash += hash << 13;
1837 // hash ^= hash >> 7;
1838 // hash += hash << 3;
1839 // hash ^= hash >> 17;
1840 // hash += hash << 5;
1842 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1843 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1844 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1845 hashcode_block.AddStatement (new StatementExpression (
1846 new SimpleAssign (hash_variable, rs_hashcode)));
1848 hashcode_block.AddStatement (new StatementExpression (
1849 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1850 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1851 hashcode_block.AddStatement (new StatementExpression (
1852 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1853 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1854 hashcode_block.AddStatement (new StatementExpression (
1855 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1856 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1857 hashcode_block.AddStatement (new StatementExpression (
1858 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1859 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1860 hashcode_block.AddStatement (new StatementExpression (
1861 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1862 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1864 hashcode_block.AddStatement (new Return (hash_variable, loc));
1865 hashcode.Block = hashcode_block;
1867 AddMethod (hashcode);
1870 // ToString () override
1873 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1874 tostring_block.AddStatement (new Return (string_concat, loc));
1875 tostring.Block = tostring_block;
1877 AddMethod (tostring);
1880 public override bool Define ()
1888 public override string GetSignatureForError ()
1890 return SignatureForError;
1893 public ArrayList Parameters {