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, name, attrs, loc)
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;
111 protected HoistedThis hoisted_this;
113 // Local variable which holds this storey instance
114 public LocalTemporary Instance;
116 bool references_defined;
117 bool has_hoisted_variable;
119 // When propagating storey reference we may capture
120 // parent storey reference which is not used later
121 public bool IsParentStoreyUsed;
123 public AnonymousMethodStorey (Block block, DeclSpace parent, MemberBase host, GenericMethod generic, string name)
124 : base (parent, generic, MakeMemberName (host, name, generic, block.StartLocation), Modifiers.PRIVATE)
127 OriginalSourceBlock = block;
131 static MemberName MakeMemberName (MemberBase host, string name, GenericMethod generic, Location loc)
133 string host_name = host == null ? null : host.Name;
134 string tname = MakeName (host_name, "c", name, unique_id);
135 TypeArguments args = null;
136 if (generic != null) {
137 args = new TypeArguments (loc);
138 foreach (TypeParameter tparam in generic.CurrentTypeParameters)
139 args.Add (new SimpleName (tparam.Name, loc));
142 return new MemberName (tname, args, loc);
145 public Field AddCapturedVariable (string name, Type type)
147 CheckMembersDefined ();
149 FullNamedExpression field_type = new TypeExpression (type, Location);
151 return AddCompilerGeneratedField (name, field_type);
153 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
154 Field f = new HoistedGenericField (this, field_type, mod, name, null, Location);
159 protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
161 const int mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
162 Field f = new Field (this, type, mod, name, null, Location);
167 public void AddParentStoreyReference (AnonymousMethodStorey s)
169 CheckMembersDefined ();
171 if (used_parent_storeys == null)
172 used_parent_storeys = new ArrayList ();
173 else if (used_parent_storeys.IndexOf (s) != -1)
176 has_hoisted_variable = true;
177 used_parent_storeys.Add (new StoreyFieldPair (s));
180 public void CaptureLocalVariable (EmitContext ec, LocalInfo local_info)
182 if (local_info.HoistedVariableReference != null)
185 HoistedVariable var = new HoistedLocalVariable (this, local_info, GetVariableMangledName (local_info));
186 local_info.HoistedVariableReference = var;
187 has_hoisted_variable = true;
190 public void CaptureParameter (EmitContext ec, ParameterReference param_ref)
192 if (param_ref.HoistedVariable != null)
195 if (hoisted_params == null)
196 hoisted_params = new ArrayList (2);
198 HoistedVariable expr = new HoistedParameter (this, param_ref);
199 param_ref.Parameter.HoistedVariableReference = expr;
200 hoisted_params.Add (expr);
203 public HoistedThis CaptureThis (EmitContext ec, This t)
205 hoisted_this = new HoistedThis (this, t);
209 public void ChangeParentStorey (AnonymousMethodStorey parentStorey)
211 Parent = parentStorey;
215 void DefineStoreyReferences ()
217 if (used_parent_storeys == null || references_defined)
220 references_defined = true;
221 if (!IsParentStoreyUsed) {
222 used_parent_storeys = null;
227 // For each used variable from parent scope we allocate its local reference point
229 for (int i = 0; i < used_parent_storeys.Count; ++i) {
230 StoreyFieldPair sf = (StoreyFieldPair) used_parent_storeys [i];
231 AnonymousMethodStorey p_storey = sf.Storey;
232 TypeExpr type_expr = new TypeExpression (p_storey.TypeBuilder, Location);
234 sf.Field = AddCompilerGeneratedField ("<>f__ref$" + p_storey.ID, type_expr);
240 // Initializes all hoisted variables
242 public void EmitHoistedVariables (EmitContext ec)
244 // There can be only one instance variable for each storey type
245 if (Instance != null)
246 throw new InternalErrorException ();
249 // A storey with hoisted `this' is an instance method
251 if (!HasHoistedVariables) {
252 hoisted_this.RemoveHoisting ();
256 SymbolWriter.OpenCompilerGeneratedBlock (ec.ig);
258 DefineStoreyReferences ();
261 // Create an instance of storey type
263 Expression storey_type_expr;
266 // Use current method type parameter (MVAR) for top level storey only. All
267 // nested storeys use class type parameter (VAR)
269 TypeParameter[] tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
270 ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
271 ec.GenericDeclContainer.CurrentTypeParameters;
273 if (tparams.Length != CountTypeParameters) {
274 TypeParameter [] full = new TypeParameter [CountTypeParameters];
275 DeclSpace parent = ec.DeclContainer.Parent;
276 parent.CurrentTypeParameters.CopyTo (full, 0);
277 tparams.CopyTo (full, parent.CountTypeParameters);
281 storey_type_expr = new ConstructedType (TypeBuilder, tparams, Location);
283 storey_type_expr = new TypeExpression (TypeBuilder, Location);
286 Expression e = new New (storey_type_expr, new ArrayList (0), Location).Resolve (ec);
289 Instance = new LocalTemporary (storey_type_expr.Type);
292 SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
294 EmitHoistedFieldsInitialization (ec);
296 SymbolWriter.CloseCompilerGeneratedBlock (ec.ig);
299 void EmitHoistedFieldsInitialization (EmitContext ec)
302 // Initialize all storey reference fields by using local or hoisted variables
304 if (used_parent_storeys != null) {
305 foreach (StoreyFieldPair sf in used_parent_storeys) {
307 // Setting local field
309 Expression instace_expr = GetStoreyInstanceExpression (ec);
310 FieldExpr f_set_expr = TypeManager.IsGenericType (instace_expr.Type) ?
311 new FieldExpr (sf.Field.FieldBuilder, instace_expr.Type, Location) :
312 new FieldExpr (sf.Field.FieldBuilder, Location);
313 f_set_expr.InstanceExpression = instace_expr;
315 SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
316 if (a.Resolve (ec) != null)
317 a.EmitStatement (ec);
322 // Setting currect anonymous method to null blocks any further variable hoisting
324 AnonymousExpression ae = ec.CurrentAnonymousMethod;
325 ec.CurrentAnonymousMethod = null;
327 if (hoisted_params != null) {
328 foreach (HoistedParameter hp in hoisted_params) {
329 hp.EmitHoistingAssignment (ec);
333 if (hoisted_this != null) {
334 hoisted_this.EmitHoistingAssignment (ec);
337 ec.CurrentAnonymousMethod = ae;
340 public override void EmitType ()
342 SymbolWriter.DefineAnonymousScope (ID);
344 if (hoisted_this != null)
345 hoisted_this.EmitSymbolInfo ();
347 foreach (LocalInfo li in OriginalSourceBlock.Variables.Values) {
348 HoistedVariable hv = li.HoistedVariableReference;
350 hv.EmitSymbolInfo ();
353 if (hoisted_params != null) {
354 foreach (HoistedParameter param in hoisted_params)
355 param.EmitSymbolInfo ();
358 DefineStoreyReferences ();
360 if (used_parent_storeys != null) {
361 foreach (StoreyFieldPair sf in used_parent_storeys) {
362 SymbolWriter.DefineCapturedScope (ID, sf.Storey.ID, sf.Field.Name);
369 public AnonymousMethodStorey GetGenericStorey ()
371 DeclSpace storey = this;
372 while (storey != null && storey.CurrentTypeParameters.Length == 0)
373 storey = storey.Parent;
375 return storey as AnonymousMethodStorey;
379 // Returns a field which holds referenced storey instance
381 Field GetReferencedStoreyField (AnonymousMethodStorey storey)
383 if (used_parent_storeys == null)
386 foreach (StoreyFieldPair sf in used_parent_storeys) {
387 if (sf.Storey == storey)
395 // Creates storey instance expression regardless of currect IP
397 public Expression GetStoreyInstanceExpression (EmitContext ec)
399 AnonymousExpression am = ec.CurrentAnonymousMethod;
402 // Access from original block -> storey
408 // Access from anonymous method implemented as a static -> storey
410 if (am.Storey == null)
413 Field f = am.Storey.GetReferencedStoreyField (this);
415 if (am.Storey == this) {
417 // Access inside of same storey (S -> S)
419 return new CompilerGeneratedThis (TypeBuilder, Location);
422 // External field access
428 // Storey was cached to local field
430 FieldExpr f_ind = new FieldExpr (f.FieldBuilder, Location);
431 f_ind.InstanceExpression = new CompilerGeneratedThis (TypeBuilder, Location);
435 protected virtual string GetVariableMangledName (LocalInfo local_info)
438 // No need to mangle anonymous method hoisted variables cause they
439 // are hoisted in their own scopes
441 return local_info.Name;
445 // Returns true when at least one local variable or parameter is
446 // hoisted, or story is transitioned
448 public bool HasHoistedVariables {
450 return has_hoisted_variable || hoisted_params != null;
453 has_hoisted_variable = value;
458 // Mutate type dispatcher
460 public Type MutateType (Type type)
463 if (TypeManager.IsGenericType (type))
464 return MutateGenericType (type);
466 if (TypeManager.IsGenericParameter (type))
467 return MutateGenericArgument (type);
470 return MutateArrayType (type);
476 // Changes method type arguments (MVAR) to storey (VAR) type arguments
478 public MethodInfo MutateGenericMethod (MethodInfo method)
481 Type [] t_args = TypeManager.GetGenericArguments (method);
482 if (TypeManager.IsGenericType (method.DeclaringType)) {
483 Type t = MutateGenericType (method.DeclaringType);
484 if (t != method.DeclaringType) {
485 method = (MethodInfo) TypeManager.DropGenericMethodArguments (method);
486 if (method.Module == CodeGen.Module.Builder)
487 method = TypeBuilder.GetMethod (t, method);
489 method = (MethodInfo) MethodInfo.GetMethodFromHandle (method.MethodHandle, t.TypeHandle);
493 if (t_args == null || t_args.Length == 0)
496 for (int i = 0; i < t_args.Length; ++i)
497 t_args [i] = MutateType (t_args [i]);
499 return method.GetGenericMethodDefinition ().MakeGenericMethod (t_args);
501 throw new NotSupportedException ();
505 public ConstructorInfo MutateConstructor (ConstructorInfo ctor)
508 if (TypeManager.IsGenericType (ctor.DeclaringType)) {
509 Type t = MutateGenericType (ctor.DeclaringType);
510 if (t != ctor.DeclaringType) {
511 // TODO: It should throw on imported types
512 return TypeBuilder.GetConstructor (t, ctor);
519 public FieldInfo MutateField (FieldInfo field)
522 if (TypeManager.IsGenericType (field.DeclaringType)) {
523 Type t = MutateGenericType (field.DeclaringType);
524 if (t != field.DeclaringType) {
525 // TODO: It should throw on imported types
526 return TypeBuilder.GetField (t, field);
534 protected Type MutateArrayType (Type array)
536 int rank = array.GetArrayRank ();
537 Type element = TypeManager.GetElementType (array);
539 throw new NotImplementedException ();
541 if (TypeManager.IsGenericParameter (element)) {
542 element = MutateGenericArgument (element);
543 } else if (TypeManager.IsGenericType (element)) {
544 element = MutateGenericType (element);
549 return element.MakeArrayType (rank);
552 protected Type MutateGenericType (Type type)
554 Type [] t_args = TypeManager.GetTypeArguments (type);
555 if (t_args == null || t_args.Length == 0)
558 for (int i = 0; i < t_args.Length; ++i)
559 t_args [i] = MutateType (t_args [i]);
561 return type.GetGenericTypeDefinition ().MakeGenericType (t_args);
566 // Changes method generic argument (MVAR) to type generic argument (VAR)
568 public Type MutateGenericArgument (Type type)
570 foreach (TypeParameter tp in CurrentTypeParameters) {
571 if (tp.Name == type.Name) {
579 public static void Reset ()
586 if (hoisted_this != null)
587 hoisted_this.RemoveHoisting ();
591 public abstract class HoistedVariable
593 class ExpressionTreeProxy : Expression
595 readonly HoistedVariable hv;
597 public ExpressionTreeProxy (HoistedVariable hv)
602 public override Expression CreateExpressionTree (EmitContext ec)
604 throw new NotSupportedException ("ET");
607 public override Expression DoResolve (EmitContext ec)
609 eclass = ExprClass.Value;
610 type = TypeManager.expression_type_expr.Type;
614 public override void Emit (EmitContext ec)
616 Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (ec);
617 // This should never fail
624 protected readonly AnonymousMethodStorey storey;
625 protected Field field;
626 Hashtable cached_inner_access; // TODO: Hashtable is too heavyweight
628 protected HoistedVariable (AnonymousMethodStorey storey, string name, Type type)
630 this.storey = storey;
632 this.field = storey.AddCapturedVariable (name, type);
635 public void AddressOf (EmitContext ec, AddressOp mode)
637 GetFieldExpression (ec).AddressOf (ec, mode);
640 public Expression CreateExpressionTree (EmitContext ec)
642 return new ExpressionTreeProxy (this);
645 public void Emit (EmitContext ec)
647 GetFieldExpression (ec).Emit (ec);
651 // Creates field access expression for hoisted variable
653 protected FieldExpr GetFieldExpression (EmitContext ec)
655 if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
657 // When setting top-level hoisted variable in generic storey
658 // change storey generic types to method generic types (VAR -> MVAR)
660 FieldExpr outer_access = storey.MemberName.IsGeneric ?
661 new FieldExpr (field.FieldBuilder, storey.Instance.Type, field.Location) :
662 new FieldExpr (field.FieldBuilder, field.Location);
664 outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
665 outer_access.Resolve (ec);
669 FieldExpr inner_access;
670 if (cached_inner_access != null) {
671 inner_access = (FieldExpr) cached_inner_access [ec.CurrentAnonymousMethod];
674 cached_inner_access = new Hashtable (4);
677 if (inner_access == null) {
678 inner_access = new FieldExpr (field.FieldBuilder, field.Location);
679 inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
680 inner_access.Resolve (ec);
681 cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
687 public abstract void EmitSymbolInfo ();
689 public void Emit (EmitContext ec, bool leave_copy)
691 GetFieldExpression (ec).Emit (ec, leave_copy);
694 public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool prepare_for_load)
696 GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
700 class HoistedParameter : HoistedVariable
702 class HoistedFieldAssign : Assign
704 public HoistedFieldAssign (Expression target, Expression source)
705 : base (target, source, source.Location)
709 protected override Expression ResolveConversions (EmitContext ec)
712 // Implicit conversion check fails for hoisted type arguments
713 // as they are of different types (!!0 x !0)
719 readonly ParameterReference parameter;
721 public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
722 : base (scope, par.Name, par.Type)
724 this.parameter = par;
727 public void EmitHoistingAssignment (EmitContext ec)
730 // Remove hoisted redirection to emit assignment from original parameter
732 HoistedVariable temp = parameter.Parameter.HoistedVariableReference;
733 parameter.Parameter.HoistedVariableReference = null;
735 Assign a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
736 if (a.Resolve (ec) != null)
737 a.EmitStatement (ec);
739 parameter.Parameter.HoistedVariableReference = temp;
742 public override void EmitSymbolInfo ()
744 SymbolWriter.DefineCapturedParameter (storey.ID, field.Name, field.Name);
748 get { return field; }
752 class HoistedLocalVariable : HoistedVariable
754 readonly string name;
756 public HoistedLocalVariable (AnonymousMethodStorey scope, LocalInfo local, string name)
757 : base (scope, name, local.VariableType)
759 this.name = local.Name;
762 public override void EmitSymbolInfo ()
764 SymbolWriter.DefineCapturedLocal (storey.ID, name, field.Name);
768 public class HoistedThis : HoistedVariable
770 readonly This this_reference;
772 public HoistedThis (AnonymousMethodStorey storey, This this_reference)
773 : base (storey, "<>f__this", this_reference.Type)
775 this.this_reference = this_reference;
778 public void EmitHoistingAssignment (EmitContext ec)
780 SimpleAssign a = new SimpleAssign (GetFieldExpression (ec), this_reference);
781 if (a.Resolve (ec) != null)
782 a.EmitStatement (ec);
785 public override void EmitSymbolInfo ()
787 SymbolWriter.DefineCapturedThis (storey.ID, field.Name);
791 get { return field; }
794 public void RemoveHoisting ()
796 this_reference.RemoveHoisting ();
801 // Anonymous method expression as created by parser
803 public class AnonymousMethodExpression : Expression
805 public readonly Parameters Parameters;
806 ListDictionary compatibles;
807 public ToplevelBlock Block;
809 public AnonymousMethodExpression (Parameters parameters, Location loc)
811 this.Parameters = parameters;
813 this.compatibles = new ListDictionary ();
816 public override string ExprClassName {
818 return "anonymous method";
822 public virtual bool HasExplicitParameters {
824 return Parameters != null;
829 // Returns true if the body of lambda expression can be implicitly
830 // converted to the delegate of type `delegate_type'
832 public bool ImplicitStandardConversionExists (EmitContext ec, Type delegate_type)
834 using (ec.Set (EmitContext.Flags.ProbingMode)) {
835 return Compatible (ec, delegate_type) != null;
839 protected Type CompatibleChecks (EmitContext ec, Type delegate_type)
841 if (TypeManager.IsDelegateType (delegate_type))
842 return delegate_type;
845 if (TypeManager.DropGenericTypeArguments (delegate_type) == TypeManager.expression_type) {
846 delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
847 if (TypeManager.IsDelegateType (delegate_type))
848 return delegate_type;
850 Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
851 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
856 Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
857 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
861 protected bool VerifyExplicitParameters (Type delegate_type, AParametersCollection parameters, bool ignore_error)
863 if (VerifyParameterCompatibility (delegate_type, parameters, ignore_error))
867 Report.Error (1661, loc,
868 "Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
869 GetSignatureForError (), TypeManager.CSharpName (delegate_type));
874 protected bool VerifyParameterCompatibility (Type delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
876 if (Parameters.Count != invoke_pd.Count) {
880 Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
881 TypeManager.CSharpName (delegate_type), Parameters.Count.ToString ());
885 bool has_implicit_parameters = !HasExplicitParameters;
888 for (int i = 0; i < Parameters.Count; ++i) {
889 Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
890 if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
894 if (p_mod == Parameter.Modifier.NONE)
895 Report.Error (1677, loc, "Parameter `{0}' should not be declared with the `{1}' keyword",
896 (i + 1).ToString (), Parameter.GetModifierSignature (Parameters.FixedParameters [i].ModFlags));
898 Report.Error (1676, loc, "Parameter `{0}' must be declared with the `{1}' keyword",
899 (i+1).ToString (), Parameter.GetModifierSignature (p_mod));
903 if (has_implicit_parameters)
906 Type type = invoke_pd.Types [i];
908 // We assume that generic parameters are always inflated
909 if (TypeManager.IsGenericParameter (type))
912 if (TypeManager.HasElementType (type) && TypeManager.IsGenericParameter (TypeManager.GetElementType (type)))
915 if (invoke_pd.Types [i] != Parameters.Types [i]) {
919 Report.Error (1678, loc, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
921 TypeManager.CSharpName (Parameters.Types [i]),
922 TypeManager.CSharpName (invoke_pd.Types [i]));
931 // Infers type arguments based on explicit arguments
933 public bool ExplicitTypeInference (TypeInferenceContext type_inference, Type delegate_type)
935 if (!HasExplicitParameters)
938 if (!TypeManager.IsDelegateType (delegate_type)) {
940 if (TypeManager.DropGenericTypeArguments (delegate_type) != TypeManager.expression_type)
943 delegate_type = delegate_type.GetGenericArguments () [0];
944 if (!TypeManager.IsDelegateType (delegate_type))
951 AParametersCollection d_params = TypeManager.GetDelegateParameters (delegate_type);
952 if (d_params.Count != Parameters.Count)
955 for (int i = 0; i < Parameters.Count; ++i) {
956 Type itype = d_params.Types [i];
957 if (!TypeManager.IsGenericParameter (itype)) {
958 if (!TypeManager.HasElementType (itype))
961 if (!TypeManager.IsGenericParameter (itype.GetElementType ()))
964 type_inference.ExactInference (Parameters.Types [i], itype);
969 public Type InferReturnType (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
971 AnonymousMethodBody am;
972 using (ec.Set (EmitContext.Flags.ProbingMode | EmitContext.Flags.InferReturnType)) {
973 am = CompatibleMethod (ec, tic, GetType (), delegate_type);
979 if (am.ReturnType == TypeManager.null_type)
980 am.ReturnType = null;
982 return am.ReturnType;
986 // Returns AnonymousMethod container if this anonymous method
987 // expression can be implicitly converted to the delegate type `delegate_type'
989 public Expression Compatible (EmitContext ec, Type type)
991 Expression am = (Expression) compatibles [type];
995 Type delegate_type = CompatibleChecks (ec, type);
996 if (delegate_type == null)
1000 // At this point its the first time we know the return type that is
1001 // needed for the anonymous method. We create the method here.
1004 MethodInfo invoke_mb = Delegate.GetInvokeMethod (
1005 ec.ContainerType, delegate_type);
1006 Type return_type = TypeManager.TypeToCoreType (invoke_mb.ReturnType);
1009 Type[] g_args = delegate_type.GetGenericArguments ();
1010 if (return_type.IsGenericParameter)
1011 return_type = g_args [return_type.GenericParameterPosition];
1015 // Second: the return type of the delegate must be compatible with
1016 // the anonymous type. Instead of doing a pass to examine the block
1017 // we satisfy the rule by setting the return type on the EmitContext
1018 // to be the delegate type return type.
1022 int errors = Report.Errors;
1023 am = CompatibleMethod (ec, null, return_type, delegate_type);
1024 if (am != null && delegate_type != type && errors == Report.Errors)
1025 am = CreateExpressionTree (ec, delegate_type);
1027 if (!ec.IsInProbingMode)
1028 compatibles.Add (type, am);
1031 } catch (Exception e) {
1032 throw new InternalErrorException (e, loc);
1036 protected virtual Expression CreateExpressionTree (EmitContext ec, Type delegate_type)
1038 return CreateExpressionTree (ec);
1041 public override Expression CreateExpressionTree (EmitContext ec)
1043 Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
1047 protected virtual Parameters ResolveParameters (EmitContext ec, TypeInferenceContext tic, Type delegate_type)
1049 AParametersCollection delegate_parameters = TypeManager.GetDelegateParameters (delegate_type);
1051 if (Parameters == null) {
1053 // We provide a set of inaccessible parameters
1055 Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
1057 for (int i = 0; i < delegate_parameters.Count; i++) {
1058 Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
1059 if (i_mod == Parameter.Modifier.OUT) {
1060 Report.Error (1688, loc, "Cannot convert anonymous " +
1061 "method block without a parameter list " +
1062 "to delegate type `{0}' because it has " +
1063 "one or more `out' parameters.",
1064 TypeManager.CSharpName (delegate_type));
1067 fixedpars[i] = new Parameter (
1069 delegate_parameters.FixedParameters [i].ModFlags, null, loc);
1072 return Parameters.CreateFullyResolved (fixedpars, delegate_parameters.Types);
1075 if (!VerifyExplicitParameters (delegate_type, delegate_parameters, ec.IsInProbingMode)) {
1082 public override Expression DoResolve (EmitContext ec)
1084 if (!ec.IsAnonymousMethodAllowed) {
1085 Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
1090 // Set class type, set type
1093 eclass = ExprClass.Value;
1096 // This hack means `The type is not accessible
1097 // anywhere', we depend on special conversion
1100 type = TypeManager.anonymous_method_type;
1102 if ((Parameters != null) && !Parameters.Resolve (ec))
1105 // FIXME: The emitted code isn't very careful about reachability
1106 // so, ensure we have a 'ret' at the end
1107 if (ec.CurrentBranching != null &&
1108 ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
1109 ec.NeedReturnLabel ();
1114 public override void Emit (EmitContext ec)
1116 // nothing, as we only exist to not do anything.
1119 public static void Error_AddressOfCapturedVar (IVariableReference var, Location loc)
1121 Report.Error (1686, loc,
1122 "Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method or lambda expression",
1126 public override string GetSignatureForError ()
1128 return ExprClassName;
1131 protected AnonymousMethodBody CompatibleMethod (EmitContext ec, TypeInferenceContext tic, Type return_type, Type delegate_type)
1133 Parameters p = ResolveParameters (ec, tic, delegate_type);
1137 ToplevelBlock b = ec.IsInProbingMode ? (ToplevelBlock) Block.PerformClone () : Block;
1139 AnonymousMethodBody anonymous = CompatibleMethodFactory (return_type, delegate_type, p, b);
1140 if (!anonymous.Compatible (ec))
1146 protected virtual AnonymousMethodBody CompatibleMethodFactory (Type return_type, Type delegate_type, Parameters p, ToplevelBlock b)
1148 return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
1151 protected override void CloneTo (CloneContext clonectx, Expression t)
1153 AnonymousMethodExpression target = (AnonymousMethodExpression) t;
1155 target.Block = (ToplevelBlock) clonectx.LookupBlock (Block);
1160 // Abstract expression for any block which requires variables hoisting
1162 public abstract class AnonymousExpression : Expression
1164 protected class AnonymousMethodMethod : Method
1166 public readonly AnonymousExpression AnonymousMethod;
1167 public readonly AnonymousMethodStorey Storey;
1168 readonly string RealName;
1170 public AnonymousMethodMethod (DeclSpace parent, AnonymousExpression am, AnonymousMethodStorey storey,
1171 GenericMethod generic, TypeExpr return_type,
1172 int mod, string real_name, MemberName name,
1173 Parameters parameters)
1174 : base (parent, generic, return_type, mod | Modifiers.COMPILER_GENERATED,
1175 name, parameters, null)
1177 this.AnonymousMethod = am;
1178 this.Storey = storey;
1179 this.RealName = real_name;
1181 Parent.PartialContainer.AddMethod (this);
1185 public override EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
1187 EmitContext aec = AnonymousMethod.aec;
1189 aec.IsStatic = (ModFlags & Modifiers.STATIC) != 0;
1193 public override bool Define ()
1195 if (Storey != null && Storey.IsGeneric && Storey.HasHoistedVariables) {
1196 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1197 if (gstorey != null) {
1198 if (!Parameters.IsEmpty) {
1199 Type [] ptypes = Parameters.Types;
1200 for (int i = 0; i < ptypes.Length; ++i)
1201 ptypes [i] = gstorey.MutateType (ptypes [i]);
1204 member_type = gstorey.MutateType (ReturnType);
1208 return base.Define ();
1211 public override void Emit ()
1214 // Before emitting any code we have to change all MVAR references to VAR
1215 // when the method is of generic type and has hoisted variables
1217 if (Storey == Parent && Storey.IsGeneric) {
1218 AnonymousMethodStorey gstorey = Storey.GetGenericStorey ();
1219 if (gstorey != null) {
1220 AnonymousMethod.aec.ReturnType = gstorey.MutateType (ReturnType);
1221 block.MutateHoistedGenericType (gstorey);
1225 if (MethodBuilder == null) {
1233 public override void EmitExtraSymbolInfo (SourceMethod source)
1235 source.SetRealMethodName (RealName);
1240 // The block that makes up the body for the anonymous method
1242 protected readonly ToplevelBlock Block;
1244 public Type ReturnType;
1245 protected EmitContext aec;
1247 protected AnonymousExpression (ToplevelBlock block, Type return_type, Location loc)
1249 this.ReturnType = return_type;
1254 public abstract void AddStoreyReference (AnonymousMethodStorey storey);
1255 public abstract string ContainerType { get; }
1256 public abstract bool IsIterator { get; }
1257 public abstract AnonymousMethodStorey Storey { get; }
1259 public bool Compatible (EmitContext ec)
1261 // TODO: Implement clone
1262 aec = new EmitContext (
1263 ec.ResolveContext, ec.TypeContainer, ec.DeclContainer,
1264 Location, null, ReturnType,
1265 (ec.InUnsafe ? Modifiers.UNSAFE : 0), /* No constructor */ false);
1267 aec.CurrentAnonymousMethod = this;
1268 aec.IsStatic = ec.IsStatic;
1270 IDisposable aec_dispose = null;
1271 EmitContext.Flags flags = 0;
1272 if (ec.InferReturnType)
1273 flags |= EmitContext.Flags.InferReturnType;
1275 if (ec.IsInProbingMode)
1276 flags |= EmitContext.Flags.ProbingMode;
1278 if (ec.IsInFieldInitializer)
1279 flags |= EmitContext.Flags.InFieldInitializer;
1281 if (ec.IsInUnsafeScope)
1282 flags |= EmitContext.Flags.InUnsafe;
1284 // HACK: Flag with 0 cannot be set
1286 aec_dispose = aec.Set (flags);
1289 bool res = aec.ResolveTopBlock (ec, Block, Block.Parameters, null, out unreachable);
1291 if (ec.InferReturnType)
1292 ReturnType = aec.ReturnType;
1294 if (aec_dispose != null) {
1295 aec_dispose.Dispose ();
1302 public class AnonymousMethodBody : AnonymousExpression
1304 ArrayList referenced_storeys;
1305 protected readonly Parameters parameters;
1306 AnonymousMethodStorey storey;
1308 AnonymousMethodMethod method;
1311 static int unique_id;
1313 public AnonymousMethodBody (Parameters parameters,
1314 ToplevelBlock block, Type return_type, Type delegate_type,
1316 : base (block, return_type, loc)
1318 this.type = delegate_type;
1319 this.parameters = parameters;
1322 public override string ContainerType {
1323 get { return "anonymous method"; }
1326 public override AnonymousMethodStorey Storey {
1327 get { return storey; }
1330 public override bool IsIterator {
1331 get { return false; }
1335 // Adds new storey reference to track out of scope variables
1337 public override void AddStoreyReference (AnonymousMethodStorey storey)
1339 if (referenced_storeys == null) {
1340 referenced_storeys = new ArrayList (2);
1342 foreach (AnonymousMethodStorey ams in referenced_storeys) {
1348 referenced_storeys.Add (storey);
1351 public override Expression CreateExpressionTree (EmitContext ec)
1353 Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
1357 bool Define (EmitContext ec)
1359 if (aec == null && !Compatible (ec))
1362 if (referenced_storeys != null)
1363 ConnectReferencedStoreys ();
1368 void ConnectReferencedStoreys ()
1370 AnonymousMethodStorey storey = FindBestMethodStorey ();
1371 storey.IsParentStoreyUsed = true;
1373 foreach (AnonymousMethodStorey s in referenced_storeys) {
1375 // An anonymous method has to have an instance access when
1376 // children anonymous method requires access to parent storey
1377 // hoisted variables
1379 for (Block b = Block.Parent; b != s.OriginalSourceBlock; b = b.Parent)
1380 b.Toplevel.HasStoreyAccess = true;
1385 storey.AddParentStoreyReference (s);
1386 s.HasHoistedVariables = true;
1387 Block.Parent.Explicit.PropagateStoreyReference (s);
1392 // Creates a host for the anonymous method
1394 AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
1397 // Anonymous method body can be converted to
1399 // 1, an instance method in current scope when only `this' is hoisted
1400 // 2, a static method in current scope when neither `this' nor any variable is hoisted
1401 // 3, an instance method in compiler generated storey when any hoisted variable exists
1405 if (referenced_storeys != null || Block.HasStoreyAccess) {
1406 storey = FindBestMethodStorey ();
1407 modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
1409 if (ec.CurrentAnonymousMethod != null)
1410 storey = ec.CurrentAnonymousMethod.Storey;
1412 modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
1415 DeclSpace parent = storey != null ? storey : ec.TypeContainer;
1417 MemberCore mc = ec.ResolveContext as MemberCore;
1418 string name = CompilerGeneratedClass.MakeName (parent != storey ? mc.Name : null,
1419 "m", null, unique_id++);
1421 MemberName member_name;
1422 GenericMethod generic_method;
1423 if (storey == null && mc.MemberName.IsGeneric) {
1424 member_name = new MemberName (name, mc.MemberName.TypeArguments.Clone (), Location);
1426 generic_method = new GenericMethod (parent.NamespaceEntry, parent, member_name,
1427 new TypeExpression (ReturnType, Location), parameters);
1429 ArrayList list = new ArrayList ();
1430 foreach (TypeParameter tparam in ((IMethodData)mc).GenericMethod.CurrentTypeParameters) {
1431 if (tparam.Constraints != null)
1432 list.Add (tparam.Constraints.Clone ());
1434 generic_method.SetParameterInfo (list);
1436 member_name = new MemberName (name, Location);
1437 generic_method = null;
1440 string real_name = String.Format (
1441 "{0}~{1}{2}", mc.GetSignatureForError (), GetSignatureForError (),
1442 parameters.GetSignatureForError ());
1444 return new AnonymousMethodMethod (parent,
1445 this, storey, generic_method, new TypeExpression (ReturnType, Location), modifiers,
1446 real_name, member_name, parameters);
1449 public override Expression DoResolve (EmitContext ec)
1451 if (eclass == ExprClass.Invalid) {
1456 eclass = ExprClass.Value;
1460 public override void Emit (EmitContext ec)
1463 // Use same anonymous method implementation for scenarios where same
1464 // code is used from multiple blocks, e.g. field initializers
1466 if (method == null) {
1468 // Delay an anonymous method definition to avoid emitting unused code
1469 // for unreachable blocks or expression trees
1471 method = DoCreateMethodHost (ec);
1472 method.ResolveMembers ();
1476 bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
1477 if (is_static && am_cache == null) {
1479 // Creates a field cache to store delegate instance if it's not generic
1481 if (!method.MemberName.IsGeneric) {
1482 TypeContainer parent = method.Parent.PartialContainer;
1483 int id = parent.Fields == null ? 0 : parent.Fields.Count;
1484 am_cache = new Field (parent, new TypeExpression (type, loc),
1485 Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
1486 CompilerGeneratedClass.MakeName (null, "f", "am$cache", id), null, loc);
1488 parent.AddField (am_cache);
1490 // TODO: Implement caching of generated generic static methods
1494 // Some extra class is needed to capture variable generic type
1495 // arguments. Maybe we could re-use anonymous types, with a unique
1496 // anonymous method id, but they are quite heavy.
1498 // Consider : "() => typeof(T);"
1500 // We need something like
1501 // static class Wrap<Tn, Tm, DelegateType> {
1502 // public static DelegateType cache;
1505 // We then specialize local variable to capture all generic parameters
1506 // and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
1511 ILGenerator ig = ec.ig;
1512 Label l_initialized = ig.DefineLabel ();
1514 if (am_cache != null) {
1515 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1516 ig.Emit (OpCodes.Brtrue_S, l_initialized);
1520 // Load method delegate implementation
1524 ig.Emit (OpCodes.Ldnull);
1525 } else if (storey != null) {
1526 Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (ec);
1530 ig.Emit (OpCodes.Ldarg_0);
1533 MethodInfo delegate_method = method.MethodBuilder;
1535 if (storey != null && storey.MemberName.IsGeneric) {
1536 delegate_method = TypeBuilder.GetMethod (Storey.Instance.Type, delegate_method);
1539 ig.Emit (OpCodes.Ldftn, delegate_method);
1541 ConstructorInfo constructor_method = Delegate.GetConstructor (ec.ContainerType, type);
1543 if (type.IsGenericType && type is TypeBuilder)
1544 constructor_method = TypeBuilder.GetConstructor (type, constructor_method);
1546 ig.Emit (OpCodes.Newobj, constructor_method);
1548 if (am_cache != null) {
1549 ig.Emit (OpCodes.Stsfld, am_cache.FieldBuilder);
1550 ig.MarkLabel (l_initialized);
1551 ig.Emit (OpCodes.Ldsfld, am_cache.FieldBuilder);
1556 // Look for the best storey for this anonymous method
1558 AnonymousMethodStorey FindBestMethodStorey ()
1561 // Use the nearest parent block which has a storey
1563 for (Block b = Block.Parent; b != null; b = b.Parent) {
1564 AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
1572 public override string GetSignatureForError ()
1574 return TypeManager.CSharpName (type);
1577 public override void MutateHoistedGenericType (AnonymousMethodStorey storey)
1579 type = storey.MutateType (type);
1582 public static void Reset ()
1589 // Anonymous type container
1591 public class AnonymousTypeClass : CompilerGeneratedClass
1593 static int types_counter;
1594 public const string ClassNamePrefix = "<>__AnonType";
1595 public const string SignatureForError = "anonymous type";
1597 readonly ArrayList parameters;
1599 private AnonymousTypeClass (DeclSpace parent, MemberName name, ArrayList parameters, Location loc)
1600 : base (parent, name, (RootContext.EvalMode ? Modifiers.PUBLIC : 0) | Modifiers.SEALED)
1602 this.parameters = parameters;
1605 public static AnonymousTypeClass Create (TypeContainer parent, ArrayList parameters, Location loc)
1607 if (RootContext.Version <= LanguageVersion.ISO_2)
1608 Report.FeatureIsNotAvailable (loc, "anonymous types");
1610 string name = ClassNamePrefix + types_counter++;
1612 SimpleName [] t_args = new SimpleName [parameters.Count];
1613 Parameter [] ctor_params = new Parameter [parameters.Count];
1614 for (int i = 0; i < parameters.Count; ++i) {
1615 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1617 t_args [i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
1618 ctor_params [i] = new Parameter (t_args [i], p.Name, 0, null, p.Location);
1622 // Create generic anonymous type host with generic arguments
1623 // named upon properties names
1625 AnonymousTypeClass a_type = new AnonymousTypeClass (parent.NamespaceEntry.SlaveDeclSpace,
1626 new MemberName (name, new TypeArguments (loc, t_args), loc), parameters, loc);
1628 if (parameters.Count > 0)
1629 a_type.SetParameterInfo (null);
1631 Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
1632 null, new Parameters (ctor_params), null, loc);
1633 c.Block = new ToplevelBlock (c.Parameters, loc);
1636 // Create fields and contructor body with field initialization
1639 for (int i = 0; i < parameters.Count; ++i) {
1640 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1642 Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY,
1643 "<" + p.Name + ">", null, p.Location);
1645 if (!a_type.AddField (f)) {
1647 Report.Error (833, p.Location, "`{0}': An anonymous type cannot have multiple properties with the same name",
1652 c.Block.AddStatement (new StatementExpression (
1653 new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
1654 c.Block.GetParameterReference (p.Name, p.Location))));
1656 ToplevelBlock get_block = new ToplevelBlock (p.Location);
1657 get_block.AddStatement (new Return (
1658 new MemberAccess (new This (p.Location), f.Name), p.Location));
1659 Accessor get_accessor = new Accessor (get_block, 0, null, null, p.Location);
1660 Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
1661 new MemberName (p.Name, p.Location), null, get_accessor, null, false);
1662 a_type.AddProperty (prop);
1668 a_type.AddConstructor (c);
1672 public static void Reset ()
1677 protected override bool AddToContainer (MemberCore symbol, string name)
1679 MemberCore mc = (MemberCore) defined_names [name];
1682 defined_names.Add (name, symbol);
1686 Report.SymbolRelatedToPreviousError (mc);
1690 protected override void RemoveFromContainer (string name)
1692 defined_names.Remove (name);
1695 void DefineOverrides ()
1697 Location loc = Location;
1699 Method equals = new Method (this, null, TypeManager.system_boolean_expr,
1700 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
1701 Mono.CSharp.Parameters.CreateFullyResolved (new Parameter (null, "obj", 0, null, loc), TypeManager.object_type), null);
1703 Method tostring = new Method (this, null, TypeManager.system_string_expr,
1704 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
1705 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1707 ToplevelBlock equals_block = new ToplevelBlock (equals.Parameters, loc);
1708 TypeExpr current_type;
1710 current_type = new ConstructedType (TypeBuilder, TypeParameters, loc);
1712 current_type = new TypeExpression (TypeBuilder, loc);
1714 equals_block.AddVariable (current_type, "other", loc);
1715 LocalVariableReference other_variable = new LocalVariableReference (equals_block, "other", loc);
1717 MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
1718 new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
1720 Expression rs_equals = null;
1721 Expression string_concat = new StringConstant ("<empty type>", loc);
1722 Expression rs_hashcode = new IntConstant (-2128831035, loc);
1723 for (int i = 0; i < parameters.Count; ++i) {
1724 AnonymousTypeParameter p = (AnonymousTypeParameter) parameters [i];
1725 Field f = (Field) Fields [i];
1727 MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
1728 system_collections_generic, "EqualityComparer",
1729 new TypeArguments (loc, new SimpleName (TypeParameters [i].Name, loc)), loc),
1732 ArrayList arguments_equal = new ArrayList (2);
1733 arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1734 arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
1736 Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
1737 "Equals", loc), arguments_equal);
1739 ArrayList arguments_hashcode = new ArrayList (1);
1740 arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
1741 Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
1742 "GetHashCode", loc), arguments_hashcode);
1744 IntConstant FNV_prime = new IntConstant (16777619, loc);
1745 rs_hashcode = new Binary (Binary.Operator.Multiply,
1746 new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
1749 Expression field_to_string = new Conditional (new Binary (Binary.Operator.Inequality,
1750 new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc)),
1751 new Invocation (new MemberAccess (
1752 new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
1753 new StringConstant ("<null>", loc));
1755 if (rs_equals == null) {
1756 rs_equals = field_equal;
1757 string_concat = new Binary (Binary.Operator.Addition,
1758 new StringConstant (p.Name + " = ", loc),
1764 // Implementation of ToString () body using string concatenation
1766 string_concat = new Binary (Binary.Operator.Addition,
1767 new Binary (Binary.Operator.Addition,
1769 new StringConstant (", " + p.Name + " = ", loc)),
1772 rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
1776 // Equals (object obj) override
1778 equals_block.AddStatement (new StatementExpression (
1779 new SimpleAssign (other_variable,
1780 new As (equals_block.GetParameterReference ("obj", loc),
1781 current_type, loc), loc)));
1783 Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
1784 if (rs_equals != null)
1785 equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
1786 equals_block.AddStatement (new Return (equals_test, loc));
1788 equals.Block = equals_block;
1789 equals.ResolveMembers ();
1793 // GetHashCode () override
1795 Method hashcode = new Method (this, null, TypeManager.system_int32_expr,
1796 Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
1797 new MemberName ("GetHashCode", loc),
1798 Mono.CSharp.Parameters.EmptyReadOnlyParameters, null);
1801 // Modified FNV with good avalanche behavior and uniform
1802 // distribution with larger hash sizes.
1804 // const int FNV_prime = 16777619;
1805 // int hash = (int) 2166136261;
1806 // foreach (int d in data)
1807 // hash = (hash ^ d) * FNV_prime;
1808 // hash += hash << 13;
1809 // hash ^= hash >> 7;
1810 // hash += hash << 3;
1811 // hash ^= hash >> 17;
1812 // hash += hash << 5;
1814 ToplevelBlock hashcode_block = new ToplevelBlock (loc);
1815 hashcode_block.AddVariable (TypeManager.system_int32_expr, "hash", loc);
1816 LocalVariableReference hash_variable = new LocalVariableReference (hashcode_block, "hash", loc);
1817 hashcode_block.AddStatement (new StatementExpression (
1818 new SimpleAssign (hash_variable, rs_hashcode)));
1820 hashcode_block.AddStatement (new StatementExpression (
1821 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1822 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (13, loc)))));
1823 hashcode_block.AddStatement (new StatementExpression (
1824 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1825 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (7, loc)))));
1826 hashcode_block.AddStatement (new StatementExpression (
1827 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1828 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (3, loc)))));
1829 hashcode_block.AddStatement (new StatementExpression (
1830 new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
1831 new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (17, loc)))));
1832 hashcode_block.AddStatement (new StatementExpression (
1833 new CompoundAssign (Binary.Operator.Addition, hash_variable,
1834 new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (5, loc)))));
1836 hashcode_block.AddStatement (new Return (hash_variable, loc));
1837 hashcode.Block = hashcode_block;
1838 hashcode.ResolveMembers ();
1839 AddMethod (hashcode);
1842 // ToString () override
1845 ToplevelBlock tostring_block = new ToplevelBlock (loc);
1846 tostring_block.AddStatement (new Return (string_concat, loc));
1847 tostring.Block = tostring_block;
1848 tostring.ResolveMembers ();
1849 AddMethod (tostring);
1852 public override bool Define ()
1856 return base.Define ();
1859 public override string GetSignatureForError ()
1861 return SignatureForError;
1864 public ArrayList Parameters {