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;
120 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
121 : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE)
124 OriginalSourceBlock = block;
128 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
130 string host_name = host == null ? null : host.Name;
131 string tname = MakeName (host_name, "c", name, unique_id);
132 TypeArguments args = null;
133 if (generic != null) {
134 args = new TypeArguments (loc);
135 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
136 args.Add (new TypeParameterName (tparam.Name, null, loc));
139 return new MemberName (tname, args, loc);
142 public Field AddCapturedVariable (string name, Type type)
144 CheckMembersDefined ();
146 FullNamedExpression field_type = new TypeExpression (type, Location);
148 return AddCompilerGeneratedField (name, field_type);
150 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
151 Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
156 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
158 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
159 Field f = new Field (this, type, mod, new MemberName (name, Location), null);
164 public void AddParentStoreyReference (AnonymousMethodStorey s)
166 CheckMembersDefined ();
168 if (used_parent_storeys == null)
169 used_parent_storeys = new ArrayList ();
170 else if (used_parent_storeys.IndexOf (s) != -1)
173 has_hoisted_variable = true;
174 used_parent_storeys.Add (new StoreyFieldPair (s));
177 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
179 if (local_info.HoistedVariableReference != null)
182 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
183 local_info.HoistedVariableReference = var;
184 has_hoisted_variable = true;
186 if (hoisted_locals == null)
187 hoisted_locals = new ArrayList ();
189 hoisted_locals.Add (var);
192 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
194 if (param_ref.HoistedVariable != null)
197 if (hoisted_params == null)
198 hoisted_params = new ArrayList (2);
200 HoistedVariable expr = new HoistedParameter (this, param_ref);
201 param_ref.Parameter.HoistedVariableReference = expr;
202 hoisted_params.Add (expr);
205 public HoistedThis CaptureThis (EmitContext ec, This t)
207 hoisted_this = new HoistedThis (this, t);
211 public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
213 Parent = parentStorey;
217 void DefineStoreyReferences ()
219 if (used_parent_storeys == null || references_defined)
222 references_defined = true;
225 // For each used variable from parent scope we allocate its local reference point
227 for (int i = 0; i < used_parent_storeys.Count; ++i) {
228 StoreyFieldPair sf = (StoreyFieldPair) used_parent_storeys [i];
229 AnonymousMethodStorey p_storey = sf.Storey;
230 TypeExpr type_expr = new TypeExpression (p_storey.TypeBuilder, Location);
232 sf.Field = AddCompilerGeneratedField ("<>f__ref$" + p_storey.ID, type_expr);
238 // Initializes all hoisted variables
240 public void EmitHoistedVariables (EmitContext ec)
242 // There can be only one instance variable for each storey type
243 if (Instance != null)
244 throw new InternalErrorException ();
247 // A storey with hoisted `this' is an instance method
249 if (!HasHoistedVariables) {
250 hoisted_this.RemoveHoisting ();
254 SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
256 DefineStoreyReferences ();
259 // Create an instance of storey type
261 Expression storey_type_expr;
264 // Use current method type parameter (MVAR) for top level storey only. All
265 // nested storeys use class type parameter (VAR)
267 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
268 ec.CurrentAnonymousMethod.Storey.TypeParameters :
269 ec.GenericDeclContainer.TypeParameters;
271 if (tparams.Length != CountTypeParameters) {
272 TypeParameter [] full = new TypeParameter [CountTypeParameters];
273 DeclSpace parent = ec.DeclContainer.Parent;
274 parent.CurrentTypeParameters.CopyTo (full, 0);
275 tparams.CopyTo (full, parent.CountTypeParameters);
279 storey_type_expr = new ConstructedType (TypeBuilder, tparams, Location);
281 storey_type_expr = new TypeExpression (TypeBuilder, Location);
284 Expression e = new New (storey_type_expr, new ArrayList (0), Location).Resolve (ec);
287 Instance = new LocalTemporary (storey_type_expr.Type);
290 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
292 EmitHoistedFieldsInitialization (ec);
294 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
297 void EmitHoistedFieldsInitialization (EmitContext ec)
300 // Initialize all storey reference fields by using local or hoisted variables
302 if (used_parent_storeys != null) {
303 foreach (StoreyFieldPair sf in used_parent_storeys) {
305 // Setting local field
307 Expression instace_expr = GetStoreyInstanceExpression (ec);
308 FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
309 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
310 new FieldExpr (sf.Field.FieldBuilder, Location);
311 f_set_expr.InstanceExpression = instace_expr;
313 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
314 if (a.Resolve (ec) != null)
315 a.EmitStatement (ec);
320 // Setting currect anonymous method to null blocks any further variable hoisting
322 AnonymousExpression ae = ec.CurrentAnonymousMethod;
323 ec.CurrentAnonymousMethod = null;
325 if (hoisted_params != null) {
326 EmitHoistedParameters (ec, hoisted_params);
329 if (hoisted_this != null) {
330 hoisted_this.EmitHoistingAssignment (ec);
333 ec.CurrentAnonymousMethod = ae;
336 protected virtual void EmitHoistedParameters (EmitContext ec, ArrayList hoisted)
338 foreach (HoistedParameter hp in hoisted) {
339 hp.EmitHoistingAssignment (ec);
343 public override void EmitType ()
345 SymbolWriter.DefineAnonymousScope (ID);
347 if (hoisted_this != null)
348 hoisted_this.EmitSymbolInfo ();
350 if (hoisted_locals != null) {
351 foreach (HoistedVariable local in hoisted_locals)
352 local.EmitSymbolInfo ();
355 if (hoisted_params != null) {
356 foreach (HoistedParameter param in hoisted_params)
357 param.EmitSymbolInfo ();
360 DefineStoreyReferences ();
362 if (used_parent_storeys != null) {
363 foreach (StoreyFieldPair sf in used_parent_storeys) {
364 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
371 public AnonymousMethodStorey GetGenericStorey ()
373 DeclSpace storey = this;
374 while (storey != null && storey.CurrentTypeParameters.Length == 0)
375 storey = storey.Parent;
377 return storey as AnonymousMethodStorey;
381 // Returns a field which holds referenced storey instance
383 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
385 if (used_parent_storeys == null)
388 foreach (StoreyFieldPair sf in used_parent_storeys) {
389 if (sf.Storey == storey)
397 // Creates storey instance expression regardless of currect IP
399 public Expression GetStoreyInstanceExpression (EmitContext ec)
401 AnonymousExpression am = ec.CurrentAnonymousMethod;
404 // Access from original block -> storey
410 // Access from anonymous method implemented as a static -> storey
412 if (am.Storey == null)
415 Field f = am.Storey.GetReferencedStoreyField (this);
417 if (am.Storey == this) {
419 // Access inside of same storey (S -> S)
421 return new CompilerGeneratedThis (TypeBuilder, Location);
424 // External field access
430 // Storey was cached to local field
432 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
433 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
437 protected virtual string GetVariableMangledName (LocalInfo local_info)
440 // No need to mangle anonymous method hoisted variables cause they
441 // are hoisted in their own scopes
443 return local_info.Name;
447 // Returns true when at least one local variable or parameter is
448 // hoisted, or story is transitioned
450 public bool HasHoistedVariables {
452 return has_hoisted_variable || hoisted_params != null;
455 has_hoisted_variable = value;
460 // Mutate type dispatcher
462 public Type MutateType (Type type)
465 if (TypeManager.IsGenericType (type))
466 return MutateGenericType (type);
468 if (TypeManager.IsGenericParameter (type))
469 return MutateGenericArgument (type);
472 return MutateArrayType (type);
478 // Changes method type arguments (MVAR) to storey (VAR) type arguments
480 public MethodInfo MutateGenericMethod (MethodInfo method)
483 Type [] t_args = TypeManager.GetGenericArguments (method);
484 if (TypeManager.IsGenericType (method.DeclaringType)) {
485 Type t = MutateGenericType (method.DeclaringType);
486 if (t != method.DeclaringType) {
487 method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
488 if (method.Module == CodeGen.Module.Builder)
489 method = TypeBuilder.GetMethod (t, method);
491 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
495 if (t_args == null || t_args.Length == 0)
498 for (int i = 0; i < t_args.Length; ++i)
499 t_args [i] = MutateType (t_args [i]);
501 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
503 throw new NotSupportedException ();
507 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
510 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
511 Type t = MutateGenericType (ctor.DeclaringType);
512 if (t != ctor.DeclaringType) {
513 // TODO: It should throw on imported types
514 return TypeBuilder.GetConstructor (t, ctor);
521 public FieldInfo MutateField (FieldInfo field)
524 if (TypeManager.IsGenericType (field.DeclaringType)) {
525 Type t = MutateGenericType (field.DeclaringType);
526 if (t != field.DeclaringType) {
527 // TODO: It should throw on imported types
528 return TypeBuilder.GetField (t, field);
536 protected Type MutateArrayType (Type array)
538 int rank = array.GetArrayRank ();
539 Type element = TypeManager.GetElementType (array);
541 throw new NotImplementedException ();
543 if (TypeManager.IsGenericParameter (element)) {
544 element = MutateGenericArgument (element);
545 } else if (TypeManager.IsGenericType (element)) {
546 element = MutateGenericType (element);
551 return element.MakeArrayType (rank);
554 protected Type MutateGenericType (Type type)
556 Type [] t_args = TypeManager.GetTypeArguments (type);
557 if (t_args == null || t_args.Length == 0)
560 for (int i = 0; i < t_args.Length; ++i)
561 t_args [i] = MutateType (t_args [i]);
563 return type.GetGenericTypeDefinition ().MakeGenericType (t_args);
568 // Changes method generic argument (MVAR) to type generic argument (VAR)
570 public Type MutateGenericArgument (Type type)
572 foreach (TypeParameter tp in CurrentTypeParameters) {
573 if (tp.Name == type.Name) {
581 public static void Reset ()
588 if (hoisted_this != null)
589 hoisted_this.RemoveHoisting ();
593 public abstract class HoistedVariable
595 class ExpressionTreeProxy : Expression
597 readonly HoistedVariable hv;
599 public ExpressionTreeProxy (HoistedVariable hv)
604 public override Expression CreateExpressionTree (EmitContext ec)
606 throw new NotSupportedException ("ET");
609 public override Expression DoResolve (EmitContext ec)
611 eclass = ExprClass.Value;
612 type = TypeManager.expression_type_expr.Type;
616 public override void Emit (EmitContext ec)
618 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (ec);
619 // This should never fail
626 protected readonly AnonymousMethodStorey storey;
627 protected Field field;
628 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
630 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
632 this.storey = storey;
634 this.field = storey.AddCapturedVariable (name, type);
637 public void AddressOf (EmitContext ec, AddressOp mode)
639 GetFieldExpression (ec).AddressOf (ec, mode);
642 public Expression CreateExpressionTree (EmitContext ec)
644 return new ExpressionTreeProxy (this);
647 public void Emit (EmitContext ec)
649 GetFieldExpression (ec).Emit (ec);
653 // Creates field access expression for hoisted variable
655 protected FieldExpr GetFieldExpression (EmitContext ec)
657 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
659 // When setting top-level hoisted variable in generic storey
660 // change storey generic types to method generic types (VAR -> MVAR)
662 FieldExpr outer_access = storey.MemberName.IsGeneric ?
663 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
664 new FieldExpr (field.FieldBuilder, field.Location);
666 outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
667 outer_access.Resolve (ec);
671 FieldExpr inner_access;
672 if (cached_inner_access != null) {
673 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
676 cached_inner_access = new Hashtable (4);
679 if (inner_access == null) {
680 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
681 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
682 inner_access.Resolve (ec);
683 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
689 public abstract void EmitSymbolInfo ();
691 public void Emit (EmitContext ec, bool leave_copy)
693 GetFieldExpression (ec).Emit (ec, leave_copy);
696 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
698 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
702 class HoistedParameter : HoistedVariable
704 sealed class HoistedFieldAssign : Assign
706 public HoistedFieldAssign (Expression target, Expression source)
707 : base (target, source, source.Location)
711 protected override Expression ResolveConversions (EmitContext ec)
714 // Implicit conversion check fails for hoisted type arguments
715 // as they are of different types (!!0 x !0)
721 readonly ParameterReference parameter;
723 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
724 : base (scope, par.Name, par.Type)
726 this.parameter = par;
729 public HoistedParameter (HoistedParameter hp, string name)
730 : base (hp.storey, name, hp.parameter.Type)
732 this.parameter = hp.parameter;
735 public void EmitHoistingAssignment (EmitContext ec)
738 // Remove hoisted redirection to emit assignment from original parameter
740 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
741 parameter.Parameter.HoistedVariableReference = null;
743 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
744 if (a.Resolve (ec) != null)
745 a.EmitStatement (ec);
747 parameter.Parameter.HoistedVariableReference = temp;
750 public override void EmitSymbolInfo ()
752 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
756 get { return field; }
760 class HoistedLocalVariable : HoistedVariable
762 readonly string name;
764 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
765 : base (scope, name, local.VariableType)
767 this.name = local.Name;
770 public override void EmitSymbolInfo ()
772 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
776 public class HoistedThis : HoistedVariable
778 readonly This this_reference;
780 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
781 : base (storey, "<>f__this", this_reference.Type)
783 this.this_reference = this_reference;
786 public void EmitHoistingAssignment (EmitContext ec)
788 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
789 if (a.Resolve (ec) != null)
790 a.EmitStatement (ec);
793 public override void EmitSymbolInfo ()
795 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
799 get { return field; }
802 public void RemoveHoisting ()
804 this_reference.RemoveHoisting ();
809 // Anonymous method expression as created by parser
811 public class AnonymousMethodExpression : Expression
813 public readonly Parameters Parameters;
814 ListDictionary compatibles;
815 public ToplevelBlock Block;
817 public AnonymousMethodExpression (Parameters parameters, Location loc)
819 this.Parameters = parameters;
821 this.compatibles = new ListDictionary ();
824 public override string ExprClassName {
826 return "anonymous method";
830 public virtual bool HasExplicitParameters {
832 return Parameters != null;
837 // Returns true if the body of lambda expression can be implicitly
838 // converted to the delegate of type `delegate_type'
840 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
842 using (ec.Set (EmitContext.Flags.ProbingMode)) {
843 return Compatible (ec, delegate_type) != null;
847 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
849 if (TypeManager.IsDelegateType (delegate_type))
850 return delegate_type;
853 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
854 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
855 if (TypeManager.IsDelegateType (delegate_type))
856 return delegate_type;
858 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
859 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
864 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
865 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
869 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
871 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
875 Report.Error (1661, loc,
876 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
877 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
882 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
884 if (Parameters.Count != invoke_pd.Count) {
888 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
889 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
893 bool has_implicit_parameters = !HasExplicitParameters;
896 for (int i = 0; i < Parameters.Count; ++i) {
897 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
898 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
902 if (p_mod == Parameter.Modifier.NONE)
903 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
904 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
906 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
907 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
911 if (has_implicit_parameters)
914 Type type = invoke_pd.Types [i];
916 // We assume that generic parameters are always inflated
917 if (TypeManager.IsGenericParameter (type))
920 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
923 if (invoke_pd.Types [i] != Parameters.Types [i]) {
927 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
929 TypeManager.CSharpName (Parameters.Types [i]),
930 TypeManager.CSharpName (invoke_pd.Types [i]));
939 // Infers type arguments based on explicit arguments
941 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
943 if (!HasExplicitParameters)
946 if (!TypeManager.IsDelegateType (delegate_type)) {
948 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
951 delegate_type = delegate_type.GetGenericArguments () [0];
952 if (!TypeManager.IsDelegateType (delegate_type))
959 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
960 if (d_params.Count != Parameters.Count)
963 for (int i = 0; i < Parameters.Count; ++i) {
964 Type itype = d_params.Types [i];
965 if (!TypeManager.IsGenericParameter (itype)) {
966 if (!TypeManager.HasElementType (itype))
969 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
972 type_inference.ExactInference (Parameters.Types [i], itype);
977 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
979 AnonymousMethodBody am;
980 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
981 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
987 if (am.ReturnType == TypeManager.null_type)
988 am.ReturnType = null;
990 return am.ReturnType;
994 // Returns AnonymousMethod container if this anonymous method
995 // expression can be implicitly converted to the delegate type `delegate_type'
997 public Expression Compatible (EmitContext ec, Type type)
999 Expression am = (Expression) compatibles [type];
1003 Type delegate_type = CompatibleChecks (ec, type);
1004 if (delegate_type == null)
1008 // At this point its the first time we know the return type that is
1009 // needed for the anonymous method. We create the method here.
1012 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1013 ec.ContainerType, delegate_type);
1014 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1017 Type[] g_args = delegate_type.GetGenericArguments ();
1018 if (return_type.IsGenericParameter)
1019 return_type = g_args [return_type.GenericParameterPosition];
1023 // Second: the return type of the delegate must be compatible with
1024 // the anonymous type. Instead of doing a pass to examine the block
1025 // we satisfy the rule by setting the return type on the EmitContext
1026 // to be the delegate type return type.
1030 int errors = Report.Errors;
1031 am = CompatibleMethod (ec, null, return_type, delegate_type);
1032 if (am != null && delegate_type != type && errors == Report.Errors)
1033 am = CreateExpressionTree (ec, delegate_type);
1035 if (!ec.IsInProbingMode)
1036 compatibles.Add (type, am);
1039 } catch (Exception e) {
1040 throw new InternalErrorException (e, loc);
1044 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1046 return CreateExpressionTree (ec);
1049 public override Expression CreateExpressionTree (EmitContext ec)
1051 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1055 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1057 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1059 if (Parameters == null) {
1061 // We provide a set of inaccessible parameters
1063 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1065 for (int i = 0; i < delegate_parameters.Count; i++) {
1066 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1067 if (i_mod == Parameter.Modifier.OUT) {
1068 Report.Error (1688, loc, "Cannot convert anonymous " +
1069 "method block without a parameter list " +
1070 "to delegate type `{0}' because it has " +
1071 "one or more `out' parameters.",
1072 TypeManager.CSharpName (delegate_type));
1075 fixedpars[i] = new Parameter (
1077 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1080 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1083 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1090 public override Expression DoResolve (EmitContext ec)
1092 if (!ec.IsAnonymousMethodAllowed) {
1093 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1098 // Set class type, set type
1101 eclass = ExprClass.Value;
1104 // This hack means `The type is not accessible
1105 // anywhere', we depend on special conversion
1108 type = TypeManager.anonymous_method_type;
1110 if ((Parameters != null) && !Parameters.Resolve (ec))
1113 // FIXME: The emitted code isn't very careful about reachability
1114 // so, ensure we have a 'ret' at the end
1115 if (ec.CurrentBranching != null &&
1116 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1117 ec.NeedReturnLabel ();
1122 public override void Emit (EmitContext ec)
1124 // nothing, as we only exist to not do anything.
1127 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1129 Report.Error (1686, loc,
1130 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1134 public override string GetSignatureForError ()
1136 return ExprClassName;
1139 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1141 Parameters p = ResolveParameters (ec, tic, delegate_type);
1145 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1147 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1148 if (!anonymous.Compatible (ec))
1154 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1156 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1159 protected override void CloneTo (CloneContext clonectx, Expression t)
1161 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1163 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1168 // Abstract expression for any block which requires variables hoisting
1170 public abstract class AnonymousExpression : Expression
1172 protected class AnonymousMethodMethod : Method
1174 public readonly AnonymousExpression AnonymousMethod;
1175 public readonly AnonymousMethodStorey Storey;
1176 readonly string RealName;
1178 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1179 GenericMethod generic, TypeExpr return_type,
1180 int mod, string real_name, MemberName name,
1181 Parameters parameters)
1182 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1183 name, parameters, null)
1185 this.AnonymousMethod = am;
1186 this.Storey = storey;
1187 this.RealName = real_name;
1189 Parent.PartialContainer.AddMethod (this);
1193 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1195 EmitContext aec = AnonymousMethod.aec;
1197 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1201 public override bool Define ()
1203 if (Storey != null && Storey.IsGeneric && Storey.HasHoistedVariables) {
1204 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1205 if (gstorey != null) {
1206 if (!Parameters.IsEmpty) {
1207 Type [] ptypes = Parameters.Types;
1208 for (int i = 0; i < ptypes.Length; ++i)
1209 ptypes [i] = gstorey.MutateType (ptypes [i]);
1212 member_type = gstorey.MutateType (ReturnType);
1216 return base.Define ();
1219 public override void Emit ()
1222 // Before emitting any code we have to change all MVAR references to VAR
1223 // when the method is of generic type and has hoisted variables
1225 if (Storey == Parent && Storey.IsGeneric) {
1226 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1227 if (gstorey != null) {
1228 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1229 block.MutateHoistedGenericType (gstorey);
1233 if (MethodBuilder == null) {
1240 public override void EmitExtraSymbolInfo (SourceMethod source)
1242 source.SetRealMethodName (RealName);
1247 // The block that makes up the body for the anonymous method
1249 protected readonly ToplevelBlock Block;
1251 public Type ReturnType;
1252 protected EmitContext aec;
1254 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1256 this.ReturnType = return_type;
1261 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1262 public abstract string ContainerType { get; }
1263 public abstract bool IsIterator { get; }
1264 public abstract AnonymousMethodStorey Storey { get; }
1266 public bool Compatible (EmitContext ec)
1268 // TODO: Implement clone
1269 aec = new EmitContext (
1270 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1271 Location, null, ReturnType,
1272 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1274 aec.CurrentAnonymousMethod = this;
1275 aec.IsStatic = ec.IsStatic;
1277 IDisposable aec_dispose = null;
1278 EmitContext.Flags flags = 0;
1279 if (ec.InferReturnType)
1280 flags |= EmitContext.Flags.InferReturnType;
1282 if (ec.IsInProbingMode)
1283 flags |= EmitContext.Flags.ProbingMode;
1285 if (ec.IsInFieldInitializer)
1286 flags |= EmitContext.Flags.InFieldInitializer;
1288 if (ec.IsInUnsafeScope)
1289 flags |= EmitContext.Flags.InUnsafe;
1291 // HACK: Flag with 0 cannot be set
1293 aec_dispose = aec.Set (flags);
1296 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1298 if (ec.InferReturnType)
1299 ReturnType = aec.ReturnType;
1301 if (aec_dispose != null) {
1302 aec_dispose.Dispose ();
1309 public class AnonymousMethodBody : AnonymousExpression
1311 ArrayList referenced_storeys;
1312 protected readonly Parameters parameters;
1313 AnonymousMethodStorey storey;
1315 AnonymousMethodMethod method;
1318 static int unique_id;
1320 public AnonymousMethodBody (Parameters parameters,
1321 ToplevelBlock block, Type return_type, Type delegate_type,
1323 : base (block, return_type, loc)
1325 this.type = delegate_type;
1326 this.parameters = parameters;
1329 public override string ContainerType {
1330 get { return "anonymous method"; }
1333 public override AnonymousMethodStorey Storey {
1334 get { return storey; }
1337 public override bool IsIterator {
1338 get { return false; }
1342 // Adds new storey reference to track out of scope variables
1344 public override void AddStoreyReference (AnonymousMethodStorey storey)
1346 if (referenced_storeys == null) {
1347 referenced_storeys = new ArrayList (2);
1349 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1355 referenced_storeys.Add (storey);
1358 public override Expression CreateExpressionTree (EmitContext ec)
1360 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1364 bool Define (EmitContext ec)
1366 if (aec == null && !Compatible (ec))
1369 if (referenced_storeys != null)
1370 ConnectReferencedStoreys ();
1375 void ConnectReferencedStoreys ()
1377 AnonymousMethodStorey storey = FindBestMethodStorey ();
1379 foreach (AnonymousMethodStorey s in referenced_storeys) {
1381 // An anonymous method has to have an instance access when
1382 // children anonymous method requires access to parent storey
1383 // hoisted variables
1385 for (Block b = Block.Parent; b != s.OriginalSourceBlock; b = b.Parent)
1386 b.Toplevel.HasStoreyAccess = true;
1391 s.HasHoistedVariables = true;
1392 Block.Parent.Explicit.PropagateStoreyReference (s);
1397 // Creates a host for the anonymous method
1399 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1402 // Anonymous method body can be converted to
1404 // 1, an instance method in current scope when only `this' is hoisted
1405 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1406 // 3, an instance method in compiler generated storey when any hoisted variable exists
1410 if (referenced_storeys != null || Block.HasStoreyAccess) {
1411 storey = FindBestMethodStorey ();
1412 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1414 if (ec.CurrentAnonymousMethod != null)
1415 storey = ec.CurrentAnonymousMethod.Storey;
1417 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1420 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1422 MemberCore mc = ec.ResolveContext as MemberCore;
1423 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1424 "m", null, unique_id++);
1426 MemberName member_name;
1427 GenericMethod generic_method;
1428 if (storey == null && mc.MemberName.IsGeneric) {
1429 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1431 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1432 new TypeExpression (ReturnType, Location), parameters);
1434 ArrayList list = new ArrayList ();
1435 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1436 if (tparam.Constraints != null)
1437 list.Add (tparam.Constraints.Clone ());
1439 generic_method.SetParameterInfo (list);
1441 member_name = new MemberName (name, Location);
1442 generic_method = null;
1445 string real_name = String.Format (
1446 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1447 parameters.GetSignatureForError ());
1449 return new AnonymousMethodMethod (parent,
1450 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1451 real_name, member_name, parameters);
1454 public override Expression DoResolve (EmitContext ec)
1456 if (eclass == ExprClass.Invalid) {
1461 eclass = ExprClass.Value;
1465 public override void Emit (EmitContext ec)
1468 // Use same anonymous method implementation for scenarios where same
1469 // code is used from multiple blocks, e.g. field initializers
1471 if (method == null) {
1473 // Delay an anonymous method definition to avoid emitting unused code
1474 // for unreachable blocks or expression trees
1476 method = DoCreateMethodHost (ec);
1480 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1481 if (is_static && am_cache == null) {
1483 // Creates a field cache to store delegate instance if it's not generic
1485 if (!method.MemberName.IsGeneric) {
1486 TypeContainer parent = method.Parent.PartialContainer;
1487 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1488 am_cache = new Field (parent, new TypeExpression (type, loc),
1489 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1490 new MemberName (CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), loc), null);
1492 parent.AddField (am_cache);
1494 // TODO: Implement caching of generated generic static methods
1498 // Some extra class is needed to capture variable generic type
1499 // arguments. Maybe we could re-use anonymous types, with a unique
1500 // anonymous method id, but they are quite heavy.
1502 // Consider : "() => typeof(T);"
1504 // We need something like
1505 // static class Wrap<Tn, Tm, DelegateType> {
1506 // public static DelegateType cache;
1509 // We then specialize local variable to capture all generic parameters
1510 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1515 ILGenerator ig = ec.ig;
1516 Label l_initialized = ig.DefineLabel ();
1518 if (am_cache != null) {
1519 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1520 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1524 // Load method delegate implementation
1528 ig.Emit (OpCodes.Ldnull);
1529 } else if (storey != null) {
1530 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1534 ig.Emit (OpCodes.Ldarg_0);
1537 MethodInfo delegate_method = method.MethodBuilder;
1539 if (storey != null && storey.MemberName.IsGeneric) {
1540 Type t = storey.Instance.Type;
1543 // Mutate anonymous method instance type if we are in nested
1544 // hoisted generic anonymous method storey
1546 if (ec.CurrentAnonymousMethod != null &&
1547 ec.CurrentAnonymousMethod.Storey != null &&
1548 ec.CurrentAnonymousMethod.Storey.IsGeneric) {
1549 t = storey.GetGenericStorey ().MutateType (t);
1552 delegate_method = TypeBuilder.GetMethod (t, delegate_method);
1555 ig.Emit (OpCodes.Ldftn, delegate_method);
1557 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1559 if (type.IsGenericType && type is TypeBuilder)
1560 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1562 ig.Emit (OpCodes.Newobj, constructor_method);
1564 if (am_cache != null) {
1565 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1566 ig.MarkLabel (l_initialized);
1567 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1572 // Look for the best storey for this anonymous method
1574 AnonymousMethodStorey FindBestMethodStorey ()
1577 // Use the nearest parent block which has a storey
1579 for (Block b = Block.Parent; b != null; b = b.Parent) {
1580 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1588 public override string GetSignatureForError ()
1590 return TypeManager.CSharpName (type);
1593 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1595 type = storey.MutateType (type);
1598 public static void Reset ()
1605 // Anonymous type container
1607 public class AnonymousTypeClass : CompilerGeneratedClass
1609 static int types_counter;
1610 public const string ClassNamePrefix = "<>__AnonType";
1611 public const string SignatureForError = "anonymous type";
1613 readonly ArrayList parameters;
1615 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1616 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1618 this.parameters = parameters;
1621 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1623 if (RootContext.Version <= LanguageVersion.ISO_2)
1624 Report.FeatureIsNotAvailable (loc, "anonymous types");
1626 string name = ClassNamePrefix + types_counter++;
1628 SimpleName [] t_args = new SimpleName [parameters.Count];
1629 TypeParameterName [] t_params = new TypeParameterName [parameters.Count];
1630 Parameter [] ctor_params = new Parameter [parameters.Count];
1631 for (int i = 0; i < parameters.Count; ++i) {
1632 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1634 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1635 t_params [i] = new TypeParameterName (t_args [i].Name, null, p.Location);
1636 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1640 // Create generic anonymous type host with generic arguments
1641 // named upon properties names
1643 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1644 new MemberName (name, new TypeArguments (loc, t_params), loc), parameters, loc);
1646 if (parameters.Count > 0)
1647 a_type.SetParameterInfo (null);
1649 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1650 null, new Parameters (ctor_params), null, loc);
1651 c.Block = new ToplevelBlock (c.Parameters, loc);
1654 // Create fields and contructor body with field initialization
1657 for (int i = 0; i < parameters.Count; ++i) {
1658 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1660 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1661 new MemberName ("<" + p.Name + ">", p.Location), null);
1663 if (!a_type.AddField (f)) {
1665 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1670 c.Block.AddStatement (new StatementExpression (
1671 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1672 c.Block.GetParameterReference (p.Name, p.Location))));
1674 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1675 get_block.AddStatement (new Return (
1676 new MemberAccess (new This (p.Location), f.Name), p.Location));
1677 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1678 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1679 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1680 a_type.AddProperty (prop);
1686 a_type.AddConstructor (c);
1690 public static void Reset ()
1695 protected override bool AddToContainer (MemberCore symbol, string name)
1697 MemberCore mc = (MemberCore) defined_names [name];
1700 defined_names.Add (name, symbol);
1704 Report.SymbolRelatedToPreviousError (mc);
1708 void DefineOverrides ()
1710 Location loc = Location;
1712 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1713 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1714 Mono.CSharp.Parameters.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1716 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1717 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1718 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1720 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1721 TypeExpr current_type;
1723 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
1725 current_type = new TypeExpression (TypeBuilder, loc);
1727 equals_block.AddVariable (current_type, "other", loc);
1728 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1730 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1731 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1733 Expression rs_equals = null;
1734 Expression string_concat = new StringConstant ("<empty type>", loc);
1735 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1736 for (int i = 0; i < parameters.Count; ++i) {
1737 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1738 Field f = (Field) Fields [i];
1740 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1741 system_collections_generic, "EqualityComparer",
1742 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
1745 ArrayList arguments_equal = new ArrayList (2);
1746 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1747 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1749 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1750 "Equals", loc), arguments_equal);
1752 ArrayList arguments_hashcode = new ArrayList (1);
1753 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1754 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1755 "GetHashCode", loc), arguments_hashcode);
1757 IntConstant FNV_prime = new IntConstant (16777619, loc);
1758 rs_hashcode = new Binary (Binary.Operator.Multiply,
1759 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1762 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1763 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1764 new Invocation (new MemberAccess (
1765 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1766 new StringConstant ("<null>", loc));
1768 if (rs_equals == null) {
1769 rs_equals = field_equal;
1770 string_concat = new Binary (Binary.Operator.Addition,
1771 new StringConstant (p.Name + " = ", loc),
1777 // Implementation of ToString () body using string concatenation
1779 string_concat = new Binary (Binary.Operator.Addition,
1780 new Binary (Binary.Operator.Addition,
1782 new StringConstant (", " + p.Name + " = ", loc)),
1785 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1789 // Equals (object obj) override
1791 equals_block.AddStatement (new StatementExpression (
1792 new SimpleAssign (other_variable,
1793 new As (equals_block.GetParameterReference ("obj", loc),
1794 current_type, loc), loc)));
1796 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1797 if (rs_equals != null)
1798 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1799 equals_block.AddStatement (new Return (equals_test, loc));
1801 equals.Block = equals_block;
1806 // GetHashCode () override
1808 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1809 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1810 new MemberName ("GetHashCode", loc),
1811 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1814 // Modified FNV with good avalanche behavior and uniform
1815 // distribution with larger hash sizes.
1817 // const int FNV_prime = 16777619;
1818 // int hash = (int) 2166136261;
1819 // foreach (int d in data)
1820 // hash = (hash ^ d) * FNV_prime;
1821 // hash += hash << 13;
1822 // hash ^= hash >> 7;
1823 // hash += hash << 3;
1824 // hash ^= hash >> 17;
1825 // hash += hash << 5;
1827 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1828 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1829 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1830 hashcode_block.AddStatement (new StatementExpression (
1831 new SimpleAssign (hash_variable, rs_hashcode)));
1833 hashcode_block.AddStatement (new StatementExpression (
1834 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1835 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1836 hashcode_block.AddStatement (new StatementExpression (
1837 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1838 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1839 hashcode_block.AddStatement (new StatementExpression (
1840 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1841 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1842 hashcode_block.AddStatement (new StatementExpression (
1843 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1844 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1845 hashcode_block.AddStatement (new StatementExpression (
1846 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1847 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1849 hashcode_block.AddStatement (new Return (hash_variable, loc));
1850 hashcode.Block = hashcode_block;
1852 AddMethod (hashcode);
1855 // ToString () override
1858 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1859 tostring_block.AddStatement (new Return (string_concat, loc));
1860 tostring.Block = tostring_block;
1862 AddMethod (tostring);
1865 public override bool Define ()
1873 public override string GetSignatureForError ()
1875 return SignatureForError;
1878 public ArrayList Parameters {