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 CheckModifiers (ModFlags);
341 ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
342 ModFlags |= Modifiers.PROPERTY_CUSTOM;
344 if (container.Kind == MemberKind.Interface) {
345 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
346 GetSignatureForError ());
347 } else if ((ModFlags & Modifiers.PRIVATE) != 0) {
348 if ((method.ModFlags & Modifiers.ABSTRACT) != 0) {
349 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
352 ModFlags &= ~Modifiers.VIRTUAL;
355 flags = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.SpecialName;
358 CheckAbstractAndExtern (block != null);
359 CheckProtectedModifier ();
362 if (block.IsIterator)
363 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
365 if (Compiler.Settings.WriteMetadataOnly)
370 public bool HasCustomAccessModifier {
372 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
376 public PropertyBase Property {
382 public override ObsoleteAttribute GetAttributeObsolete ()
384 return method.GetAttributeObsolete ();
387 public override string GetSignatureForError()
389 return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
392 void CheckModifiers (Modifiers modflags)
394 if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
395 Report.Error (273, Location,
396 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
397 GetSignatureForError (), method.GetSignatureForError ());
402 PropertyMethod get, set, first;
403 PropertyBuilder PropertyBuilder;
405 protected PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
406 : base (parent, type, mod_flags, allowed_mod, name, attrs)
412 public override AttributeTargets AttributeTargets {
414 return AttributeTargets.Property;
418 public PropertyMethod AccessorFirst {
424 public PropertyMethod AccessorSecond {
426 return first == get ? set : get;
430 public override Variance ExpectedMemberTypeVariance {
432 return (get != null && set != null) ?
433 Variance.None : set == null ?
435 Variance.Contravariant;
439 public PropertyMethod Get {
448 Parent.AddNameToContainer (get, get.MemberName.Basename);
452 public PropertyMethod Set {
461 Parent.AddNameToContainer (set, set.MemberName.Basename);
465 public override string[] ValidAttributeTargets {
467 return attribute_targets;
473 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
475 if (a.HasSecurityAttribute) {
476 a.Error_InvalidSecurityParent ();
480 if (a.Type == pa.Dynamic) {
481 a.Error_MisusedDynamicAttribute ();
485 PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
488 void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
490 if (IsExplicitImpl) {
492 if (kind == MemberKind.Indexer)
493 filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
495 filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
497 var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
499 if (implementing == null)
502 var accessor = get ? implementing.Get : implementing.Set;
503 if (accessor != null) {
504 Report.SymbolRelatedToPreviousError (accessor);
505 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
506 GetSignatureForError (), accessor.GetSignatureForError ());
511 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
513 var ok = base.CheckOverrideAgainstBase (base_member);
516 // Check base property accessors conflict
518 var base_prop = (PropertySpec) base_member;
520 if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasGet && !base_prop.Get.IsAccessible (this)) {
521 // TODO: Should be different error code but csc uses for some reason same
522 Report.SymbolRelatedToPreviousError (base_prop);
523 Report.Error (545, Location,
524 "`{0}': cannot override because `{1}' does not have accessible get accessor",
525 GetSignatureForError (), base_prop.GetSignatureForError ());
529 if (!base_prop.HasGet) {
531 Report.SymbolRelatedToPreviousError (base_prop);
532 Report.Error (545, Get.Location,
533 "`{0}': cannot override because `{1}' does not have an overridable get accessor",
534 Get.GetSignatureForError (), base_prop.GetSignatureForError ());
537 } else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
538 if (!base_prop.Get.IsAccessible (this)) {
539 // Same as csc but it should be different error code
540 Report.Error (115, Get.Location, "`{0}' is marked as an override but no accessible `get' accessor found to override",
541 GetSignatureForError ());
543 } else if (!CheckAccessModifiers (Get, base_prop.Get)) {
544 Error_CannotChangeAccessModifiers (Get, base_prop.Get);
551 if (base_prop.HasSet) {
552 if ((ModFlags & Modifiers.SEALED) != 0 && !base_prop.Set.IsAccessible (this)) {
553 // TODO: Should be different error code but csc uses for some reason same
554 Report.SymbolRelatedToPreviousError (base_prop);
555 Report.Error (546, Location,
556 "`{0}': cannot override because `{1}' does not have accessible set accessor",
557 GetSignatureForError (), base_prop.GetSignatureForError ());
561 if ((ModFlags & Modifiers.AutoProperty) != 0) {
562 Report.Error (8080, Location, "`{0}': Auto-implemented properties must override all accessors of the overridden property",
563 GetSignatureForError ());
568 if (!base_prop.HasSet) {
570 Report.SymbolRelatedToPreviousError (base_prop);
571 Report.Error (546, Set.Location,
572 "`{0}': cannot override because `{1}' does not have an overridable set accessor",
573 Set.GetSignatureForError (), base_prop.GetSignatureForError ());
576 } else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
577 if (!base_prop.Set.IsAccessible (this)) {
578 // Same as csc but it should be different error code
579 Report.Error (115, Set.Location, "`{0}' is marked as an override but no accessible `set' accessor found to override",
580 GetSignatureForError ());
582 } else if (!CheckAccessModifiers (Set, base_prop.Set)) {
583 Error_CannotChangeAccessModifiers (Set, base_prop.Set);
589 if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
590 if (!CheckAccessModifiers (this, base_prop)) {
591 Error_CannotChangeAccessModifiers (this, base_prop);
599 protected override void DoMemberTypeDependentChecks ()
601 base.DoMemberTypeDependentChecks ();
605 if (MemberType.IsStatic)
606 Error_StaticReturnType ();
609 protected override void DoMemberTypeIndependentChecks ()
611 base.DoMemberTypeIndependentChecks ();
614 // Accessors modifiers check
616 if (AccessorSecond != null) {
617 if ((Get.ModFlags & Modifiers.AccessibilityMask) != 0 && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) {
618 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
619 GetSignatureForError ());
621 } else if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
622 (Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) ||
623 (Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0)) {
624 Report.Error (276, Location,
625 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
626 GetSignatureForError ());
630 protected bool DefineAccessors ()
632 first.Define (Parent);
633 if (AccessorSecond != null)
634 AccessorSecond.Define (Parent);
639 protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
641 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
642 GetFullName (MemberName), PropertyAttributes.None,
643 #if !BOOTSTRAP_BASIC // Requires trunk version mscorlib
644 IsStatic ? 0 : CallingConventions.HasThis,
646 MemberType.GetMetaInfo (), null, null,
647 parameters.GetMetaInfo (), null, null);
650 if (kind == MemberKind.Indexer)
651 spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
653 spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
657 Parent.MemberCache.AddMember (this, Get.Spec.Name, Get.Spec);
659 CheckMissingAccessor (kind, parameters, true);
664 Parent.MemberCache.AddMember (this, Set.Spec.Name, Set.Spec);
666 CheckMissingAccessor (kind, parameters, false);
669 Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
672 public override void Emit ()
674 CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
675 CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
677 if (OptAttributes != null)
678 OptAttributes.Emit ();
680 if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
681 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
682 } else if (member_type.HasDynamicElement) {
683 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
686 ConstraintChecker.Check (this, member_type, type_expr.Location);
689 if (AccessorSecond != null)
690 AccessorSecond.Emit (Parent);
695 public override bool IsUsed {
700 return Get.IsUsed | Set.IsUsed;
704 public override void PrepareEmit ()
706 AccessorFirst.PrepareEmit ();
707 if (AccessorSecond != null)
708 AccessorSecond.PrepareEmit ();
711 var method = Get.Spec.GetMetaInfo () as MethodBuilder;
713 PropertyBuilder.SetGetMethod (method);
717 var method = Set.Spec.GetMetaInfo () as MethodBuilder;
719 PropertyBuilder.SetSetMethod (method);
723 protected override void SetMemberName (MemberName new_name)
725 base.SetMemberName (new_name);
728 Get.UpdateName (this);
731 Set.UpdateName (this);
734 public override void WriteDebugSymbol (MonoSymbolFile file)
737 get.WriteDebugSymbol (file);
740 set.WriteDebugSymbol (file);
744 // Represents header string for documentation comment.
746 public override string DocCommentHeader {
751 public class Property : PropertyBase
753 public sealed class BackingFieldDeclaration : Field
755 readonly Property property;
756 const Modifiers DefaultModifiers = Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | Modifiers.DEBUGGER_HIDDEN;
758 public BackingFieldDeclaration (Property p, bool readOnly)
759 : base (p.Parent, p.type_expr, DefaultModifiers | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
760 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
764 ModFlags |= Modifiers.READONLY;
767 public Property OriginalProperty {
773 public override string GetSignatureForError ()
775 return property.GetSignatureForError ();
779 static readonly string[] attribute_target_auto = new string[] { "property", "field" };
781 public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
782 MemberName name, Attributes attrs)
783 : base (parent, type, mod,
784 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
785 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
786 AllowedModifiersClass,
791 public BackingFieldDeclaration BackingField { get; private set; }
793 public Expression Initializer { get; set; }
795 public override void Accept (StructuralVisitor visitor)
797 visitor.Visit (this);
800 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
802 if (a.Target == AttributeTargets.Field) {
803 BackingField.ApplyAttributeBuilder (a, ctor, cdata, pa);
807 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
810 void CreateAutomaticProperty ()
812 // Create backing field
813 BackingField = new BackingFieldDeclaration (this, Initializer == null && Set == null);
814 if (!BackingField.Define ())
817 if (Initializer != null) {
818 BackingField.Initializer = Initializer;
819 Parent.RegisterFieldForInitialization (BackingField, new FieldInitializer (BackingField, Initializer, Location));
820 BackingField.ModFlags |= Modifiers.READONLY;
823 Parent.PartialContainer.Members.Add (BackingField);
825 FieldExpr fe = new FieldExpr (BackingField, Location);
826 if ((BackingField.ModFlags & Modifiers.STATIC) == 0)
827 fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
830 // Create get block but we careful with location to
831 // emit only single sequence point per accessor. This allow
832 // to set a breakpoint on it even with no user code
834 Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
835 Return r = new Return (fe, Get.Location);
836 Get.Block.AddStatement (r);
837 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
841 Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
842 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
843 Set.Block.AddStatement (new StatementExpression (a, Set.Location));
844 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
848 public override bool Define ()
853 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
855 bool auto = AccessorFirst.Block == null && (AccessorSecond == null || AccessorSecond.Block == null) &&
856 (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0;
858 if (Initializer != null) {
860 Report.Error (8050, Location, "`{0}': Only auto-implemented properties can have initializers",
861 GetSignatureForError ());
864 Report.Error (8052, Location, "`{0}': Properties inside interfaces cannot have initializers",
865 GetSignatureForError ());
867 if (Compiler.Settings.Version < LanguageVersion.V_6)
868 Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented property initializer");
872 ModFlags |= Modifiers.AutoProperty;
874 Report.Error (8051, Location, "Auto-implemented property `{0}' must have get accessor",
875 GetSignatureForError ());
879 if (Compiler.Settings.Version < LanguageVersion.V_3 && Initializer == null)
880 Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented properties");
882 CreateAutomaticProperty ();
885 if (!DefineAccessors ())
888 if (AccessorSecond == null) {
890 if (AccessorFirst is GetMethod)
891 pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
893 pm = new GetMethod (this, 0, null, Location);
895 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
901 DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
905 public override void Emit ()
907 if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
908 Report.Error (842, Location,
909 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
910 GetSignatureForError ());
916 public override string[] ValidAttributeTargets {
918 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
919 attribute_target_auto : base.ValidAttributeTargets;
925 /// For case when event is declared like property (with add and remove accessors).
927 public class EventProperty: Event {
928 public abstract class AEventPropertyAccessor : AEventAccessor
930 protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
931 : base (method, prefix, attrs, loc)
935 public override void Define (TypeContainer ds)
937 CheckAbstractAndExtern (block != null);
941 public override string GetSignatureForError ()
943 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
947 public sealed class AddDelegateMethod: AEventPropertyAccessor
949 public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
950 : base (method, AddPrefix, attrs, loc)
955 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
957 public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
958 : base (method, RemovePrefix, attrs, loc)
963 static readonly string[] attribute_targets = new string [] { "event" };
965 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
966 : base (parent, type, mod_flags, name, attrs)
970 public override void Accept (StructuralVisitor visitor)
972 visitor.Visit (this);
975 public override bool Define()
984 public override string[] ValidAttributeTargets {
986 return attribute_targets;
992 /// Event is declared like field.
994 public class EventField : Event
996 abstract class EventFieldAccessor : AEventAccessor
998 protected EventFieldAccessor (EventField method, string prefix)
999 : base (method, prefix, null, method.Location)
1003 protected abstract MethodSpec GetOperation (Location loc);
1005 public override void Emit (TypeDefinition parent)
1007 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
1008 block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
1009 IsCompilerGenerated = true
1011 FabricateBodyStatement ();
1017 void FabricateBodyStatement ()
1020 // Delegate obj1 = backing_field
1022 // Delegate obj2 = obj1;
1023 // obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
1024 // } while ((object)obj1 != (object)obj2)
1027 var field_info = ((EventField) method).backing_field;
1028 FieldExpr f_expr = new FieldExpr (field_info, Location);
1030 f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
1032 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1033 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1035 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
1037 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
1038 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
1039 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
1041 var body = new ExplicitBlock (block, Location, Location);
1042 block.AddStatement (new Do (body, cond, Location, Location));
1044 body.AddStatement (new StatementExpression (
1045 new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
1047 var args_oper = new Arguments (2);
1048 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
1049 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
1051 var op_method = GetOperation (Location);
1053 var args = new Arguments (3);
1054 args.Add (new Argument (f_expr, Argument.AType.Ref));
1055 args.Add (new Argument (new Cast (
1056 new TypeExpression (field_info.MemberType, Location),
1057 new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
1059 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
1061 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
1063 if (Module.PredefinedMembers.MonitorEnter_v4.Get () != null || Module.PredefinedMembers.MonitorEnter.Get () != null) {
1064 // Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
1065 body.AddStatement (new Lock (
1066 block.GetParameterReference (0, Location),
1067 new StatementExpression (new SimpleAssign (
1068 f_expr, args [1].Expr, Location), Location), Location));
1070 Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
1073 body.AddStatement (new StatementExpression (new SimpleAssign (
1074 new LocalVariableReference (obj1, Location),
1075 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
1080 sealed class AddDelegateMethod: EventFieldAccessor
1082 public AddDelegateMethod (EventField method):
1083 base (method, AddPrefix)
1087 protected override MethodSpec GetOperation (Location loc)
1089 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1093 sealed class RemoveDelegateMethod: EventFieldAccessor
1095 public RemoveDelegateMethod (EventField method):
1096 base (method, RemovePrefix)
1100 protected override MethodSpec GetOperation (Location loc)
1102 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1107 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1108 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1110 Expression initializer;
1111 Field backing_field;
1112 List<FieldDeclarator> declarators;
1114 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1115 : base (parent, type, mod_flags, name, attrs)
1117 Add = new AddDelegateMethod (this);
1118 Remove = new RemoveDelegateMethod (this);
1123 public List<FieldDeclarator> Declarators {
1125 return this.declarators;
1129 bool HasBackingField {
1131 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1135 public Expression Initializer {
1140 initializer = value;
1144 public override string[] ValidAttributeTargets {
1146 return HasBackingField ? attribute_targets : attribute_targets_interface;
1153 public override void Accept (StructuralVisitor visitor)
1155 visitor.Visit (this);
1158 public void AddDeclarator (FieldDeclarator declarator)
1160 if (declarators == null)
1161 declarators = new List<FieldDeclarator> (2);
1163 declarators.Add (declarator);
1165 Parent.AddNameToContainer (this, declarator.Name.Value);
1168 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1170 if (a.Target == AttributeTargets.Field) {
1171 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1175 if (a.Target == AttributeTargets.Method) {
1176 int errors = Report.Errors;
1177 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1178 if (errors == Report.Errors)
1179 Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1183 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1186 public override bool Define()
1188 var mod_flags_src = ModFlags;
1190 if (!base.Define ())
1193 if (declarators != null) {
1194 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1195 mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1197 var t = new TypeExpression (MemberType, TypeExpression.Location);
1198 foreach (var d in declarators) {
1199 var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1201 if (d.Initializer != null)
1202 ef.initializer = d.Initializer;
1205 Parent.PartialContainer.Members.Add (ef);
1209 if (!HasBackingField) {
1214 backing_field = new Field (Parent,
1215 new TypeExpression (MemberType, Location),
1216 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1219 Parent.PartialContainer.Members.Add (backing_field);
1220 backing_field.Initializer = Initializer;
1221 backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
1223 // Call define because we passed fields definition
1224 backing_field.Define ();
1226 // Set backing field for event fields
1227 spec.BackingField = backing_field.Spec;
1233 public abstract class Event : PropertyBasedMember
1235 public abstract class AEventAccessor : AbstractPropertyEventMethod
1237 protected readonly Event method;
1238 readonly ParametersCompiled parameters;
1240 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1242 public const string AddPrefix = "add_";
1243 public const string RemovePrefix = "remove_";
1245 protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1246 : base (method, prefix, attrs, loc)
1248 this.method = method;
1249 this.ModFlags = method.ModFlags;
1250 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1253 public bool IsInterfaceImplementation {
1254 get { return method_data.implementing != null; }
1257 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1259 if (a.Type == pa.MethodImpl) {
1260 method.is_external_implementation = a.IsInternalCall ();
1263 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1266 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1268 if (a.Target == AttributeTargets.Parameter) {
1269 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1273 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1276 public override AttributeTargets AttributeTargets {
1278 return AttributeTargets.Method;
1282 public override bool IsClsComplianceRequired ()
1284 return method.IsClsComplianceRequired ();
1287 public virtual void Define (TypeContainer parent)
1289 // Fill in already resolved event type to speed things up and
1290 // avoid confusing duplicate errors
1291 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1292 parameters.Types = new TypeSpec[] { method.member_type };
1294 method_data = new MethodData (method, method.ModFlags,
1295 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1297 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1300 if (Compiler.Settings.WriteMetadataOnly)
1303 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1304 Spec.IsAccessor = true;
1307 public override TypeSpec ReturnType {
1309 return Parent.Compiler.BuiltinTypes.Void;
1313 public override ObsoleteAttribute GetAttributeObsolete ()
1315 return method.GetAttributeObsolete ();
1318 public MethodData MethodData {
1324 public override string[] ValidAttributeTargets {
1326 return attribute_targets;
1330 public override ParametersCompiled ParameterInfo {
1337 AEventAccessor add, remove;
1338 EventBuilder EventBuilder;
1339 protected EventSpec spec;
1341 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1342 : base (parent, type, mod_flags,
1343 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1344 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1345 AllowedModifiersClass,
1352 public override AttributeTargets AttributeTargets {
1354 return AttributeTargets.Event;
1358 public AEventAccessor Add {
1364 Parent.AddNameToContainer (value, value.MemberName.Basename);
1368 public override Variance ExpectedMemberTypeVariance {
1370 return Variance.Contravariant;
1374 public AEventAccessor Remove {
1380 Parent.AddNameToContainer (value, value.MemberName.Basename);
1385 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1387 if ((a.HasSecurityAttribute)) {
1388 a.Error_InvalidSecurityParent ();
1392 EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1395 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1397 var ok = base.CheckOverrideAgainstBase (base_member);
1399 if (!CheckAccessModifiers (this, base_member)) {
1400 Error_CannotChangeAccessModifiers (this, base_member);
1407 public override bool Define ()
1409 if (!base.Define ())
1412 if (!MemberType.IsDelegate) {
1413 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1420 // Now define the accessors
1422 add.Define (Parent);
1423 remove.Define (Parent);
1425 EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1427 spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1429 Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1430 Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1431 Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1436 public override void Emit ()
1438 CheckReservedNameConflict (null, add.Spec);
1439 CheckReservedNameConflict (null, remove.Spec);
1441 if (OptAttributes != null) {
1442 OptAttributes.Emit ();
1445 ConstraintChecker.Check (this, member_type, type_expr.Location);
1448 Remove.Emit (Parent);
1453 public override void PrepareEmit ()
1456 remove.PrepareEmit ();
1458 EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1459 EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
1462 public override void WriteDebugSymbol (MonoSymbolFile file)
1464 add.WriteDebugSymbol (file);
1465 remove.WriteDebugSymbol (file);
1469 // Represents header string for documentation comment.
1471 public override string DocCommentHeader {
1472 get { return "E:"; }
1476 public class EventSpec : MemberSpec, IInterfaceMemberSpec
1478 MethodSpec add, remove;
1479 FieldSpec backing_field;
1481 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1482 : base (MemberKind.Event, declaringType, definition, modifiers)
1484 this.AccessorAdd = add;
1485 this.AccessorRemove = remove;
1486 this.MemberType = eventType;
1491 public MethodSpec AccessorAdd {
1500 public MethodSpec AccessorRemove {
1509 public FieldSpec BackingField {
1511 return backing_field;
1514 backing_field = value;
1518 public TypeSpec MemberType { get; private set; }
1522 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1524 var es = (EventSpec) base.InflateMember (inflator);
1525 es.MemberType = inflator.Inflate (MemberType);
1527 if (backing_field != null)
1528 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1533 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1535 return MemberType.ResolveMissingDependencies (this);
1539 public class Indexer : PropertyBase, IParametersMember
1541 public class GetIndexerMethod : GetMethod, IParametersMember
1543 ParametersCompiled parameters;
1545 public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1546 : base (property, modifiers, attrs, loc)
1548 this.parameters = parameters;
1551 public override void Define (TypeContainer parent)
1553 // Disable reporting, parameters are resolved twice
1554 Report.DisableReporting ();
1556 parameters.Resolve (this);
1558 Report.EnableReporting ();
1561 base.Define (parent);
1564 public override ParametersCompiled ParameterInfo {
1570 #region IParametersMember Members
1572 AParametersCollection IParametersMember.Parameters {
1578 TypeSpec IInterfaceMemberSpec.MemberType {
1587 public class SetIndexerMethod : SetMethod, IParametersMember
1589 public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1590 : base (property, modifiers, parameters, attrs, loc)
1594 #region IParametersMember Members
1596 AParametersCollection IParametersMember.Parameters {
1602 TypeSpec IInterfaceMemberSpec.MemberType {
1611 const Modifiers AllowedModifiers =
1614 Modifiers.PROTECTED |
1615 Modifiers.INTERNAL |
1619 Modifiers.OVERRIDE |
1624 const Modifiers AllowedInterfaceModifiers =
1627 readonly ParametersCompiled parameters;
1629 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1630 : base (parent, type, mod,
1631 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1634 this.parameters = parameters;
1639 AParametersCollection IParametersMember.Parameters {
1645 public ParametersCompiled ParameterInfo {
1654 public override void Accept (StructuralVisitor visitor)
1656 visitor.Visit (this);
1659 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1661 if (a.Type == pa.IndexerName) {
1662 // Attribute was copied to container
1666 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1669 protected override bool CheckForDuplications ()
1671 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1674 public override bool Define ()
1676 if (!base.Define ())
1679 if (!DefineParameters (parameters))
1682 if (OptAttributes != null) {
1683 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1684 if (indexer_attr != null) {
1685 var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1686 if (compiling != null)
1687 compiling.Define ();
1689 if (IsExplicitImpl) {
1690 Report.Error (415, indexer_attr.Location,
1691 "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1692 indexer_attr.Type.GetSignatureForError ());
1693 } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1694 Report.Error (609, indexer_attr.Location,
1695 "Cannot set the `IndexerName' attribute on an indexer marked override");
1697 string name = indexer_attr.GetIndexerAttributeValue ();
1699 if (!string.IsNullOrEmpty (name)) {
1700 SetMemberName (new MemberName (MemberName.Left, name, Location));
1706 if (InterfaceType != null) {
1707 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1708 if (base_IndexerName != ShortName) {
1709 SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1713 Parent.AddNameToContainer (this, MemberName.Basename);
1715 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1717 if (!DefineAccessors ())
1723 DefineBuilders (MemberKind.Indexer, parameters);
1727 public override bool EnableOverloadChecks (MemberCore overload)
1729 if (overload is Indexer) {
1730 caching_flags |= Flags.MethodOverloadsExist;
1734 return base.EnableOverloadChecks (overload);
1737 public override void Emit ()
1739 parameters.CheckConstraints (this);
1744 public override string GetSignatureForError ()
1746 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1747 if (MemberName.ExplicitInterface != null) {
1749 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1752 sb.Append (".this");
1753 sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1754 return sb.ToString ();
1757 public override string GetSignatureForDocumentation ()
1759 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1762 public override void PrepareEmit ()
1764 parameters.ResolveDefaultValues (this);
1766 base.PrepareEmit ();
1769 protected override bool VerifyClsCompliance ()
1771 if (!base.VerifyClsCompliance ())
1774 parameters.VerifyClsCompliance (this);
1779 public class IndexerSpec : PropertySpec, IParametersMember
1781 AParametersCollection parameters;
1783 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1784 : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1786 this.parameters = parameters;
1790 public AParametersCollection Parameters {
1797 public override string GetSignatureForDocumentation ()
1799 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1802 public override string GetSignatureForError ()
1804 return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1807 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1809 var spec = (IndexerSpec) base.InflateMember (inflator);
1810 spec.parameters = parameters.Inflate (inflator);
1814 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1816 var missing = base.ResolveMissingDependencies (caller);
1818 foreach (var pt in parameters.Types) {
1819 var m = pt.GetMissingDependencies (caller);
1823 if (missing == null)
1824 missing = new List<MissingTypeSpecReference> ();
1826 missing.AddRange (m);