2 // property.cs: Property based handlers
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 // Martin Baulig (martin@ximian.com)
6 // Marek Safar (marek.safar@seznam.cz)
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin Inc
16 using System.Collections.Generic;
18 using Mono.CompilerServices.SymbolWriter;
21 using XmlElement = System.Object;
25 using IKVM.Reflection;
26 using IKVM.Reflection.Emit;
28 using System.Reflection;
29 using System.Reflection.Emit;
34 // It is used as a base class for all property based members
35 // This includes properties, indexers, and events
36 public abstract class PropertyBasedMember : InterfaceMemberBase
38 protected PropertyBasedMember (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
39 : base (parent, type, mod, allowed_mod, name, attrs)
43 protected void CheckReservedNameConflict (string prefix, MethodSpec accessor)
46 AParametersCollection parameters;
47 if (accessor != null) {
49 parameters = accessor.Parameters;
51 name = prefix + ShortName;
53 name = MemberName.Left + "." + name;
55 if (this is Indexer) {
56 parameters = ((Indexer) this).ParameterInfo;
57 if (prefix[0] == 's') {
58 var data = new IParameterData[parameters.Count + 1];
59 Array.Copy (parameters.FixedParameters, data, data.Length - 1);
60 data[data.Length - 1] = new ParameterData ("value", Parameter.Modifier.NONE);
61 var types = new TypeSpec[data.Length];
62 Array.Copy (parameters.Types, types, data.Length - 1);
63 types[data.Length - 1] = member_type;
65 parameters = new ParametersImported (data, types, false);
69 parameters = ParametersCompiled.CreateFullyResolved (new[] { member_type });
71 parameters = ParametersCompiled.EmptyReadOnlyParameters;
75 var conflict = MemberCache.FindMember (Parent.Definition,
76 new MemberFilter (name, 0, MemberKind.Method, parameters, null),
77 BindingRestriction.DeclaredOnly | BindingRestriction.NoAccessors);
79 if (conflict != null) {
80 Report.SymbolRelatedToPreviousError (conflict);
81 Report.Error (82, Location, "A member `{0}' is already reserved", conflict.GetSignatureForError ());
85 public abstract void PrepareEmit ();
87 protected override bool VerifyClsCompliance ()
89 if (!base.VerifyClsCompliance ())
92 if (!MemberType.IsCLSCompliant ()) {
93 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
94 GetSignatureForError ());
101 public class PropertySpec : MemberSpec, IInterfaceMemberSpec
107 public PropertySpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, PropertyInfo info, Modifiers modifiers)
108 : base (kind, declaringType, definition, modifiers)
111 this.memberType = memberType;
116 public MethodSpec Get {
122 get.IsAccessor = true;
126 public MethodSpec Set {
132 set.IsAccessor = true;
136 public bool HasDifferentAccessibility {
138 return HasGet && HasSet &&
139 (Get.Modifiers & Modifiers.AccessibilityMask) != (Set.Modifiers & Modifiers.AccessibilityMask);
155 public PropertyInfo MetaInfo {
157 if ((state & StateFlags.PendingMetaInflate) != 0)
158 throw new NotSupportedException ();
164 public TypeSpec MemberType {
172 public override MemberSpec InflateMember (TypeParameterInflator inflator)
174 var ps = (PropertySpec) base.InflateMember (inflator);
175 ps.memberType = inflator.Inflate (memberType);
179 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
181 return memberType.ResolveMissingDependencies (this);
186 // Properties and Indexers both generate PropertyBuilders, we use this to share
187 // their common bits.
189 abstract public class PropertyBase : PropertyBasedMember {
191 public class GetMethod : PropertyMethod
193 static readonly string[] attribute_targets = new string [] { "method", "return" };
195 internal const string Prefix = "get_";
197 public GetMethod (PropertyBase method, Modifiers modifiers, Attributes attrs, Location loc)
198 : base (method, Prefix, modifiers, attrs, loc)
202 public override void Define (TypeContainer parent)
204 base.Define (parent);
206 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
208 method_data = new MethodData (method, ModFlags, flags, this);
210 method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
213 public override TypeSpec ReturnType {
215 return method.MemberType;
219 public override ParametersCompiled ParameterInfo {
221 return ParametersCompiled.EmptyReadOnlyParameters;
225 public override string[] ValidAttributeTargets {
227 return attribute_targets;
232 public class SetMethod : PropertyMethod {
234 static readonly string[] attribute_targets = new string[] { "method", "param", "return" };
236 internal const string Prefix = "set_";
238 protected ParametersCompiled parameters;
240 public SetMethod (PropertyBase method, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
241 : base (method, Prefix, modifiers, attrs, loc)
243 this.parameters = parameters;
246 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
248 if (a.Target == AttributeTargets.Parameter) {
249 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
253 base.ApplyToExtraTarget (a, ctor, cdata, pa);
256 public override ParametersCompiled ParameterInfo {
262 public override void Define (TypeContainer parent)
264 parameters.Resolve (this);
266 base.Define (parent);
268 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
270 method_data = new MethodData (method, ModFlags, flags, this);
272 method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
275 public override TypeSpec ReturnType {
277 return Parent.Compiler.BuiltinTypes.Void;
281 public override string[] ValidAttributeTargets {
283 return attribute_targets;
288 static readonly string[] attribute_targets = new string[] { "property" };
290 public abstract class PropertyMethod : AbstractPropertyEventMethod
292 const Modifiers AllowedModifiers =
294 Modifiers.PROTECTED |
298 protected readonly PropertyBase method;
299 protected MethodAttributes flags;
301 public PropertyMethod (PropertyBase method, string prefix, Modifiers modifiers, Attributes attrs, Location loc)
302 : base (method, prefix, attrs, loc)
304 this.method = method;
305 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, modifiers, 0, loc, Report);
306 this.ModFlags |= (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
309 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
311 if (a.Type == pa.MethodImpl) {
312 method.is_external_implementation = a.IsInternalCall ();
315 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
318 public override AttributeTargets AttributeTargets {
320 return AttributeTargets.Method;
324 public override bool IsClsComplianceRequired ()
326 return method.IsClsComplianceRequired ();
329 public virtual void Define (TypeContainer parent)
331 var container = parent.PartialContainer;
334 // Check for custom access modifier
336 if ((ModFlags & Modifiers.AccessibilityMask) == 0) {
337 ModFlags |= method.ModFlags;
338 flags = method.flags;
340 if (container.Kind == MemberKind.Interface)
341 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
342 GetSignatureForError ());
343 else if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
344 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
347 CheckModifiers (ModFlags);
348 ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
349 ModFlags |= Modifiers.PROPERTY_CUSTOM;
350 flags = ModifiersExtensions.MethodAttr (ModFlags);
351 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
354 CheckAbstractAndExtern (block != null);
355 CheckProtectedModifier ();
358 if (block.IsIterator)
359 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
361 if (Compiler.Settings.WriteMetadataOnly)
366 public bool HasCustomAccessModifier {
368 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
372 public PropertyBase Property {
378 public override ObsoleteAttribute GetAttributeObsolete ()
380 return method.GetAttributeObsolete ();
383 public override string GetSignatureForError()
385 return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
388 void CheckModifiers (Modifiers modflags)
390 if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
391 Report.Error (273, Location,
392 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
393 GetSignatureForError (), method.GetSignatureForError ());
398 PropertyMethod get, set, first;
399 PropertyBuilder PropertyBuilder;
401 protected PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
402 : base (parent, type, mod_flags, allowed_mod, name, attrs)
408 public override AttributeTargets AttributeTargets {
410 return AttributeTargets.Property;
414 public PropertyMethod AccessorFirst {
420 public PropertyMethod AccessorSecond {
422 return first == get ? set : get;
426 public override Variance ExpectedMemberTypeVariance {
428 return (get != null && set != null) ?
429 Variance.None : set == null ?
431 Variance.Contravariant;
435 public PropertyMethod Get {
444 Parent.AddNameToContainer (get, get.MemberName.Basename);
448 public PropertyMethod Set {
457 Parent.AddNameToContainer (set, set.MemberName.Basename);
461 public override string[] ValidAttributeTargets {
463 return attribute_targets;
469 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
471 if (a.HasSecurityAttribute) {
472 a.Error_InvalidSecurityParent ();
476 if (a.Type == pa.Dynamic) {
477 a.Error_MisusedDynamicAttribute ();
481 PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
484 void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
486 if (IsExplicitImpl) {
488 if (kind == MemberKind.Indexer)
489 filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
491 filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
493 var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
495 if (implementing == null)
498 var accessor = get ? implementing.Get : implementing.Set;
499 if (accessor != null) {
500 Report.SymbolRelatedToPreviousError (accessor);
501 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
502 GetSignatureForError (), accessor.GetSignatureForError ());
507 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
509 var ok = base.CheckOverrideAgainstBase (base_member);
512 // Check base property accessors conflict
514 var base_prop = (PropertySpec) base_member;
516 if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasGet && !base_prop.Get.IsAccessible (this)) {
517 // TODO: Should be different error code but csc uses for some reason same
518 Report.SymbolRelatedToPreviousError (base_prop);
519 Report.Error (545, Location,
520 "`{0}': cannot override because `{1}' does not have accessible get accessor",
521 GetSignatureForError (), base_prop.GetSignatureForError ());
525 if (!base_prop.HasGet) {
527 Report.SymbolRelatedToPreviousError (base_prop);
528 Report.Error (545, Get.Location,
529 "`{0}': cannot override because `{1}' does not have an overridable get accessor",
530 Get.GetSignatureForError (), base_prop.GetSignatureForError ());
533 } else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
534 if (!CheckAccessModifiers (Get, base_prop.Get)) {
535 Error_CannotChangeAccessModifiers (Get, base_prop.Get);
542 if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasSet && !base_prop.Set.IsAccessible (this)) {
543 // TODO: Should be different error code but csc uses for some reason same
544 Report.SymbolRelatedToPreviousError (base_prop);
545 Report.Error (546, Location,
546 "`{0}': cannot override because `{1}' does not have accessible set accessor",
547 GetSignatureForError (), base_prop.GetSignatureForError ());
551 if (!base_prop.HasSet) {
553 Report.SymbolRelatedToPreviousError (base_prop);
554 Report.Error (546, Set.Location,
555 "`{0}': cannot override because `{1}' does not have an overridable set accessor",
556 Set.GetSignatureForError (), base_prop.GetSignatureForError ());
559 } else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
560 if (!CheckAccessModifiers (Set, base_prop.Set)) {
561 Error_CannotChangeAccessModifiers (Set, base_prop.Set);
567 if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
568 if (!CheckAccessModifiers (this, base_prop)) {
569 Error_CannotChangeAccessModifiers (this, base_prop);
577 protected override void DoMemberTypeDependentChecks ()
579 base.DoMemberTypeDependentChecks ();
583 if (MemberType.IsStatic)
584 Error_StaticReturnType ();
587 protected override void DoMemberTypeIndependentChecks ()
589 base.DoMemberTypeIndependentChecks ();
592 // Accessors modifiers check
594 if (AccessorSecond != null) {
595 if ((Get.ModFlags & Modifiers.AccessibilityMask) != 0 && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) {
596 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
597 GetSignatureForError ());
599 } else if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
600 (Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) ||
601 (Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0)) {
602 Report.Error (276, Location,
603 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
604 GetSignatureForError ());
608 protected bool DefineAccessors ()
610 first.Define (Parent);
611 if (AccessorSecond != null)
612 AccessorSecond.Define (Parent);
617 protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
619 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
620 GetFullName (MemberName), PropertyAttributes.None,
621 #if !BOOTSTRAP_BASIC // Requires trunk version mscorlib
622 IsStatic ? 0 : CallingConventions.HasThis,
624 MemberType.GetMetaInfo (), null, null,
625 parameters.GetMetaInfo (), null, null);
628 if (kind == MemberKind.Indexer)
629 spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
631 spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
635 Parent.MemberCache.AddMember (this, Get.Spec.Name, Get.Spec);
637 CheckMissingAccessor (kind, parameters, true);
642 Parent.MemberCache.AddMember (this, Set.Spec.Name, Set.Spec);
644 CheckMissingAccessor (kind, parameters, false);
647 Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
650 public override void Emit ()
652 CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
653 CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
655 if (OptAttributes != null)
656 OptAttributes.Emit ();
658 if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
659 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
660 } else if (member_type.HasDynamicElement) {
661 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
664 ConstraintChecker.Check (this, member_type, type_expr.Location);
667 if (AccessorSecond != null)
668 AccessorSecond.Emit (Parent);
673 public override bool IsUsed {
678 return Get.IsUsed | Set.IsUsed;
682 public override void PrepareEmit ()
684 AccessorFirst.PrepareEmit ();
685 if (AccessorSecond != null)
686 AccessorSecond.PrepareEmit ();
689 var method = Get.Spec.GetMetaInfo () as MethodBuilder;
691 PropertyBuilder.SetGetMethod (method);
695 var method = Set.Spec.GetMetaInfo () as MethodBuilder;
697 PropertyBuilder.SetSetMethod (method);
701 protected override void SetMemberName (MemberName new_name)
703 base.SetMemberName (new_name);
706 Get.UpdateName (this);
709 Set.UpdateName (this);
712 public override void WriteDebugSymbol (MonoSymbolFile file)
715 get.WriteDebugSymbol (file);
718 set.WriteDebugSymbol (file);
722 // Represents header string for documentation comment.
724 public override string DocCommentHeader {
729 public class Property : PropertyBase
731 public sealed class BackingField : Field
733 readonly Property property;
735 public BackingField (Property p)
736 : base (p.Parent, p.type_expr,
737 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
738 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
743 public Property OriginalProperty {
749 public override string GetSignatureForError ()
751 return property.GetSignatureForError ();
755 static readonly string[] attribute_target_auto = new string[] { "property", "field" };
759 public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
760 MemberName name, Attributes attrs)
761 : base (parent, type, mod,
762 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
763 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
764 AllowedModifiersClass,
769 public override void Accept (StructuralVisitor visitor)
771 visitor.Visit (this);
774 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
776 if (a.Target == AttributeTargets.Field) {
777 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
781 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
784 void CreateAutomaticProperty ()
786 // Create backing field
787 backing_field = new BackingField (this);
788 if (!backing_field.Define ())
791 Parent.PartialContainer.Members.Add (backing_field);
793 FieldExpr fe = new FieldExpr (backing_field, Location);
794 if ((backing_field.ModFlags & Modifiers.STATIC) == 0)
795 fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
798 // Create get block but we careful with location to
799 // emit only single sequence point per accessor. This allow
800 // to set a breakpoint on it even with no user code
802 Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
803 Return r = new Return (fe, Get.Location);
804 Get.Block.AddStatement (r);
807 Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
808 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
809 Set.Block.AddStatement (new StatementExpression (a, Set.Location));
812 public override bool Define ()
817 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
819 if (!IsInterface && (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
820 AccessorSecond != null && Get.Block == null && Set.Block == null) {
821 if (Compiler.Settings.Version <= LanguageVersion.ISO_2)
822 Report.FeatureIsNotAvailable (Compiler, Location, "automatically implemented properties");
824 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
825 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
826 CreateAutomaticProperty ();
829 if (!DefineAccessors ())
832 if (AccessorSecond == null) {
834 if (AccessorFirst is GetMethod)
835 pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
837 pm = new GetMethod (this, 0, null, Location);
839 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
845 DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
849 public override void Emit ()
851 if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
852 Report.Error (842, Location,
853 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
854 GetSignatureForError ());
860 public override string[] ValidAttributeTargets {
862 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
863 attribute_target_auto : base.ValidAttributeTargets;
869 /// For case when event is declared like property (with add and remove accessors).
871 public class EventProperty: Event {
872 public abstract class AEventPropertyAccessor : AEventAccessor
874 protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
875 : base (method, prefix, attrs, loc)
879 public override void Define (TypeContainer ds)
881 CheckAbstractAndExtern (block != null);
885 public override string GetSignatureForError ()
887 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
891 public sealed class AddDelegateMethod: AEventPropertyAccessor
893 public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
894 : base (method, AddPrefix, attrs, loc)
899 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
901 public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
902 : base (method, RemovePrefix, attrs, loc)
907 static readonly string[] attribute_targets = new string [] { "event" };
909 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
910 : base (parent, type, mod_flags, name, attrs)
914 public override void Accept (StructuralVisitor visitor)
916 visitor.Visit (this);
919 public override bool Define()
928 public override string[] ValidAttributeTargets {
930 return attribute_targets;
936 /// Event is declared like field.
938 public class EventField : Event
940 abstract class EventFieldAccessor : AEventAccessor
942 protected EventFieldAccessor (EventField method, string prefix)
943 : base (method, prefix, null, method.Location)
947 protected abstract MethodSpec GetOperation (Location loc);
949 public override void Emit (TypeDefinition parent)
951 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
952 block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
953 IsCompilerGenerated = true
955 FabricateBodyStatement ();
961 void FabricateBodyStatement ()
964 // Delegate obj1 = backing_field
966 // Delegate obj2 = obj1;
967 // obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
968 // } while ((object)obj1 != (object)obj2)
971 var field_info = ((EventField) method).backing_field;
972 FieldExpr f_expr = new FieldExpr (field_info, Location);
974 f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
976 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
977 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
979 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
981 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
982 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
983 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
985 var body = new ExplicitBlock (block, Location, Location);
986 block.AddStatement (new Do (body, cond, Location, Location));
988 body.AddStatement (new StatementExpression (
989 new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
991 var args_oper = new Arguments (2);
992 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
993 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
995 var op_method = GetOperation (Location);
997 var args = new Arguments (3);
998 args.Add (new Argument (f_expr, Argument.AType.Ref));
999 args.Add (new Argument (new Cast (
1000 new TypeExpression (field_info.MemberType, Location),
1001 new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
1003 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
1005 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
1009 body.AddStatement (new StatementExpression (new SimpleAssign (
1010 new LocalVariableReference (obj1, Location),
1011 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
1015 sealed class AddDelegateMethod: EventFieldAccessor
1017 public AddDelegateMethod (EventField method):
1018 base (method, AddPrefix)
1022 protected override MethodSpec GetOperation (Location loc)
1024 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1028 sealed class RemoveDelegateMethod: EventFieldAccessor
1030 public RemoveDelegateMethod (EventField method):
1031 base (method, RemovePrefix)
1035 protected override MethodSpec GetOperation (Location loc)
1037 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1042 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1043 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1045 Expression initializer;
1046 Field backing_field;
1047 List<FieldDeclarator> declarators;
1049 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1050 : base (parent, type, mod_flags, name, attrs)
1052 Add = new AddDelegateMethod (this);
1053 Remove = new RemoveDelegateMethod (this);
1058 public List<FieldDeclarator> Declarators {
1060 return this.declarators;
1064 bool HasBackingField {
1066 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1070 public Expression Initializer {
1075 initializer = value;
1079 public override string[] ValidAttributeTargets {
1081 return HasBackingField ? attribute_targets : attribute_targets_interface;
1088 public override void Accept (StructuralVisitor visitor)
1090 visitor.Visit (this);
1093 public void AddDeclarator (FieldDeclarator declarator)
1095 if (declarators == null)
1096 declarators = new List<FieldDeclarator> (2);
1098 declarators.Add (declarator);
1100 Parent.AddNameToContainer (this, declarator.Name.Value);
1103 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1105 if (a.Target == AttributeTargets.Field) {
1106 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1110 if (a.Target == AttributeTargets.Method) {
1111 int errors = Report.Errors;
1112 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1113 if (errors == Report.Errors)
1114 Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1118 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1121 public override bool Define()
1123 var mod_flags_src = ModFlags;
1125 if (!base.Define ())
1128 if (declarators != null) {
1129 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1130 mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1132 var t = new TypeExpression (MemberType, TypeExpression.Location);
1133 foreach (var d in declarators) {
1134 var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1136 if (d.Initializer != null)
1137 ef.initializer = d.Initializer;
1140 Parent.PartialContainer.Members.Add (ef);
1144 if (!HasBackingField) {
1149 backing_field = new Field (Parent,
1150 new TypeExpression (MemberType, Location),
1151 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1154 Parent.PartialContainer.Members.Add (backing_field);
1155 backing_field.Initializer = Initializer;
1156 backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
1158 // Call define because we passed fields definition
1159 backing_field.Define ();
1161 // Set backing field for event fields
1162 spec.BackingField = backing_field.Spec;
1168 public abstract class Event : PropertyBasedMember
1170 public abstract class AEventAccessor : AbstractPropertyEventMethod
1172 protected readonly Event method;
1173 readonly ParametersCompiled parameters;
1175 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1177 public const string AddPrefix = "add_";
1178 public const string RemovePrefix = "remove_";
1180 protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1181 : base (method, prefix, attrs, loc)
1183 this.method = method;
1184 this.ModFlags = method.ModFlags;
1185 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1188 public bool IsInterfaceImplementation {
1189 get { return method_data.implementing != null; }
1192 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1194 if (a.Type == pa.MethodImpl) {
1195 method.is_external_implementation = a.IsInternalCall ();
1198 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1201 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1203 if (a.Target == AttributeTargets.Parameter) {
1204 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1208 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1211 public override AttributeTargets AttributeTargets {
1213 return AttributeTargets.Method;
1217 public override bool IsClsComplianceRequired ()
1219 return method.IsClsComplianceRequired ();
1222 public virtual void Define (TypeContainer parent)
1224 // Fill in already resolved event type to speed things up and
1225 // avoid confusing duplicate errors
1226 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1227 parameters.Types = new TypeSpec[] { method.member_type };
1229 method_data = new MethodData (method, method.ModFlags,
1230 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1232 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1235 if (Compiler.Settings.WriteMetadataOnly)
1238 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1239 Spec.IsAccessor = true;
1242 public override TypeSpec ReturnType {
1244 return Parent.Compiler.BuiltinTypes.Void;
1248 public override ObsoleteAttribute GetAttributeObsolete ()
1250 return method.GetAttributeObsolete ();
1253 public MethodData MethodData {
1259 public override string[] ValidAttributeTargets {
1261 return attribute_targets;
1265 public override ParametersCompiled ParameterInfo {
1272 AEventAccessor add, remove;
1273 EventBuilder EventBuilder;
1274 protected EventSpec spec;
1276 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1277 : base (parent, type, mod_flags,
1278 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1279 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1280 AllowedModifiersClass,
1287 public override AttributeTargets AttributeTargets {
1289 return AttributeTargets.Event;
1293 public AEventAccessor Add {
1299 Parent.AddNameToContainer (value, value.MemberName.Basename);
1303 public override Variance ExpectedMemberTypeVariance {
1305 return Variance.Contravariant;
1309 public AEventAccessor Remove {
1315 Parent.AddNameToContainer (value, value.MemberName.Basename);
1320 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1322 if ((a.HasSecurityAttribute)) {
1323 a.Error_InvalidSecurityParent ();
1327 EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1330 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1332 var ok = base.CheckOverrideAgainstBase (base_member);
1334 if (!CheckAccessModifiers (this, base_member)) {
1335 Error_CannotChangeAccessModifiers (this, base_member);
1342 public override bool Define ()
1344 if (!base.Define ())
1347 if (!MemberType.IsDelegate) {
1348 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1355 // Now define the accessors
1357 add.Define (Parent);
1358 remove.Define (Parent);
1360 EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1362 spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1364 Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1365 Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1366 Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1371 public override void Emit ()
1373 CheckReservedNameConflict (null, add.Spec);
1374 CheckReservedNameConflict (null, remove.Spec);
1376 if (OptAttributes != null) {
1377 OptAttributes.Emit ();
1380 ConstraintChecker.Check (this, member_type, type_expr.Location);
1383 Remove.Emit (Parent);
1388 public override void PrepareEmit ()
1391 remove.PrepareEmit ();
1393 EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1394 EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
1397 public override void WriteDebugSymbol (MonoSymbolFile file)
1399 add.WriteDebugSymbol (file);
1400 remove.WriteDebugSymbol (file);
1404 // Represents header string for documentation comment.
1406 public override string DocCommentHeader {
1407 get { return "E:"; }
1411 public class EventSpec : MemberSpec, IInterfaceMemberSpec
1413 MethodSpec add, remove;
1414 FieldSpec backing_field;
1416 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1417 : base (MemberKind.Event, declaringType, definition, modifiers)
1419 this.AccessorAdd = add;
1420 this.AccessorRemove = remove;
1421 this.MemberType = eventType;
1426 public MethodSpec AccessorAdd {
1435 public MethodSpec AccessorRemove {
1444 public FieldSpec BackingField {
1446 return backing_field;
1449 backing_field = value;
1453 public TypeSpec MemberType { get; private set; }
1457 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1459 var es = (EventSpec) base.InflateMember (inflator);
1460 es.MemberType = inflator.Inflate (MemberType);
1462 if (backing_field != null)
1463 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1468 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1470 return MemberType.ResolveMissingDependencies (this);
1474 public class Indexer : PropertyBase, IParametersMember
1476 public class GetIndexerMethod : GetMethod, IParametersMember
1478 ParametersCompiled parameters;
1480 public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1481 : base (property, modifiers, attrs, loc)
1483 this.parameters = parameters;
1486 public override void Define (TypeContainer parent)
1488 // Disable reporting, parameters are resolved twice
1489 Report.DisableReporting ();
1491 parameters.Resolve (this);
1493 Report.EnableReporting ();
1496 base.Define (parent);
1499 public override ParametersCompiled ParameterInfo {
1505 #region IParametersMember Members
1507 AParametersCollection IParametersMember.Parameters {
1513 TypeSpec IInterfaceMemberSpec.MemberType {
1522 public class SetIndexerMethod : SetMethod, IParametersMember
1524 public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1525 : base (property, modifiers, parameters, attrs, loc)
1529 #region IParametersMember Members
1531 AParametersCollection IParametersMember.Parameters {
1537 TypeSpec IInterfaceMemberSpec.MemberType {
1546 const Modifiers AllowedModifiers =
1549 Modifiers.PROTECTED |
1550 Modifiers.INTERNAL |
1554 Modifiers.OVERRIDE |
1559 const Modifiers AllowedInterfaceModifiers =
1562 readonly ParametersCompiled parameters;
1564 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1565 : base (parent, type, mod,
1566 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1569 this.parameters = parameters;
1574 AParametersCollection IParametersMember.Parameters {
1580 public ParametersCompiled ParameterInfo {
1589 public override void Accept (StructuralVisitor visitor)
1591 visitor.Visit (this);
1594 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1596 if (a.Type == pa.IndexerName) {
1597 // Attribute was copied to container
1601 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1604 protected override bool CheckForDuplications ()
1606 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1609 public override bool Define ()
1611 if (!base.Define ())
1614 if (!DefineParameters (parameters))
1617 if (OptAttributes != null) {
1618 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1619 if (indexer_attr != null) {
1620 var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1621 if (compiling != null)
1622 compiling.Define ();
1624 if (IsExplicitImpl) {
1625 Report.Error (415, indexer_attr.Location,
1626 "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1627 indexer_attr.Type.GetSignatureForError ());
1628 } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1629 Report.Error (609, indexer_attr.Location,
1630 "Cannot set the `IndexerName' attribute on an indexer marked override");
1632 string name = indexer_attr.GetIndexerAttributeValue ();
1634 if (!string.IsNullOrEmpty (name)) {
1635 SetMemberName (new MemberName (MemberName.Left, name, Location));
1641 if (InterfaceType != null) {
1642 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1643 if (base_IndexerName != ShortName) {
1644 SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1648 Parent.AddNameToContainer (this, MemberName.Basename);
1650 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1652 if (!DefineAccessors ())
1658 DefineBuilders (MemberKind.Indexer, parameters);
1662 public override bool EnableOverloadChecks (MemberCore overload)
1664 if (overload is Indexer) {
1665 caching_flags |= Flags.MethodOverloadsExist;
1669 return base.EnableOverloadChecks (overload);
1672 public override void Emit ()
1674 parameters.CheckConstraints (this);
1679 public override string GetSignatureForError ()
1681 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1682 if (MemberName.ExplicitInterface != null) {
1684 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1687 sb.Append (".this");
1688 sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1689 return sb.ToString ();
1692 public override string GetSignatureForDocumentation ()
1694 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1697 protected override bool VerifyClsCompliance ()
1699 if (!base.VerifyClsCompliance ())
1702 parameters.VerifyClsCompliance (this);
1707 public class IndexerSpec : PropertySpec, IParametersMember
1709 AParametersCollection parameters;
1711 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1712 : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1714 this.parameters = parameters;
1718 public AParametersCollection Parameters {
1725 public override string GetSignatureForDocumentation ()
1727 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1730 public override string GetSignatureForError ()
1732 return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1735 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1737 var spec = (IndexerSpec) base.InflateMember (inflator);
1738 spec.parameters = parameters.Inflate (inflator);
1742 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1744 var missing = base.ResolveMissingDependencies (caller);
1746 foreach (var pt in parameters.Types) {
1747 var m = pt.GetMissingDependencies (caller);
1751 if (missing == null)
1752 missing = new List<MissingTypeSpecReference> ();
1754 missing.AddRange (m);