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 ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasSet && !base_prop.Set.IsAccessible (this)) {
552 // TODO: Should be different error code but csc uses for some reason same
553 Report.SymbolRelatedToPreviousError (base_prop);
554 Report.Error (546, Location,
555 "`{0}': cannot override because `{1}' does not have accessible set accessor",
556 GetSignatureForError (), base_prop.GetSignatureForError ());
560 if (Get.IsCompilerGenerated) {
561 Report.Error (8080, Location, "`{0}': Auto-implemented properties must override all accessors of the overridden property",
562 GetSignatureForError ());
566 if (!base_prop.HasSet) {
568 Report.SymbolRelatedToPreviousError (base_prop);
569 Report.Error (546, Set.Location,
570 "`{0}': cannot override because `{1}' does not have an overridable set accessor",
571 Set.GetSignatureForError (), base_prop.GetSignatureForError ());
574 } else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
575 if (!base_prop.Set.IsAccessible (this)) {
576 // Same as csc but it should be different error code
577 Report.Error (115, Set.Location, "`{0}' is marked as an override but no accessible `set' accessor found to override",
578 GetSignatureForError ());
580 } else if (!CheckAccessModifiers (Set, base_prop.Set)) {
581 Error_CannotChangeAccessModifiers (Set, base_prop.Set);
587 if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
588 if (!CheckAccessModifiers (this, base_prop)) {
589 Error_CannotChangeAccessModifiers (this, base_prop);
597 protected override void DoMemberTypeDependentChecks ()
599 base.DoMemberTypeDependentChecks ();
603 if (MemberType.IsStatic)
604 Error_StaticReturnType ();
607 protected override void DoMemberTypeIndependentChecks ()
609 base.DoMemberTypeIndependentChecks ();
612 // Accessors modifiers check
614 if (AccessorSecond != null) {
615 if ((Get.ModFlags & Modifiers.AccessibilityMask) != 0 && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) {
616 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
617 GetSignatureForError ());
619 } else if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
620 (Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) ||
621 (Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0)) {
622 Report.Error (276, Location,
623 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
624 GetSignatureForError ());
628 protected bool DefineAccessors ()
630 first.Define (Parent);
631 if (AccessorSecond != null)
632 AccessorSecond.Define (Parent);
637 protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
639 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
640 GetFullName (MemberName), PropertyAttributes.None,
641 #if !BOOTSTRAP_BASIC // Requires trunk version mscorlib
642 IsStatic ? 0 : CallingConventions.HasThis,
644 MemberType.GetMetaInfo (), null, null,
645 parameters.GetMetaInfo (), null, null);
648 if (kind == MemberKind.Indexer)
649 spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
651 spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
655 Parent.MemberCache.AddMember (this, Get.Spec.Name, Get.Spec);
657 CheckMissingAccessor (kind, parameters, true);
662 Parent.MemberCache.AddMember (this, Set.Spec.Name, Set.Spec);
664 CheckMissingAccessor (kind, parameters, false);
667 Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
670 public override void Emit ()
672 CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
673 CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
675 if (OptAttributes != null)
676 OptAttributes.Emit ();
678 if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
679 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
680 } else if (member_type.HasDynamicElement) {
681 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
684 ConstraintChecker.Check (this, member_type, type_expr.Location);
687 if (AccessorSecond != null)
688 AccessorSecond.Emit (Parent);
693 public override bool IsUsed {
698 return Get.IsUsed | Set.IsUsed;
702 public override void PrepareEmit ()
704 AccessorFirst.PrepareEmit ();
705 if (AccessorSecond != null)
706 AccessorSecond.PrepareEmit ();
709 var method = Get.Spec.GetMetaInfo () as MethodBuilder;
711 PropertyBuilder.SetGetMethod (method);
715 var method = Set.Spec.GetMetaInfo () as MethodBuilder;
717 PropertyBuilder.SetSetMethod (method);
721 protected override void SetMemberName (MemberName new_name)
723 base.SetMemberName (new_name);
726 Get.UpdateName (this);
729 Set.UpdateName (this);
732 public override void WriteDebugSymbol (MonoSymbolFile file)
735 get.WriteDebugSymbol (file);
738 set.WriteDebugSymbol (file);
742 // Represents header string for documentation comment.
744 public override string DocCommentHeader {
749 public class Property : PropertyBase
751 public sealed class BackingFieldDeclaration : Field
753 readonly Property property;
754 const Modifiers DefaultModifiers = Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | Modifiers.DEBUGGER_HIDDEN;
756 public BackingFieldDeclaration (Property p, bool readOnly)
757 : base (p.Parent, p.type_expr, DefaultModifiers | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
758 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
762 ModFlags |= Modifiers.READONLY;
765 public Property OriginalProperty {
771 public override string GetSignatureForError ()
773 return property.GetSignatureForError ();
777 static readonly string[] attribute_target_auto = new string[] { "property", "field" };
779 public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
780 MemberName name, Attributes attrs)
781 : base (parent, type, mod,
782 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
783 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
784 AllowedModifiersClass,
789 public BackingFieldDeclaration BackingField { get; private set; }
791 public Expression Initializer { get; set; }
793 public override void Accept (StructuralVisitor visitor)
795 visitor.Visit (this);
798 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
800 if (a.Target == AttributeTargets.Field) {
801 BackingField.ApplyAttributeBuilder (a, ctor, cdata, pa);
805 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
808 void CreateAutomaticProperty ()
810 // Create backing field
811 BackingField = new BackingFieldDeclaration (this, Initializer == null && Set == null);
812 if (!BackingField.Define ())
815 if (Initializer != null) {
816 BackingField.Initializer = Initializer;
817 Parent.RegisterFieldForInitialization (BackingField, new FieldInitializer (BackingField, Initializer, Location));
818 BackingField.ModFlags |= Modifiers.READONLY;
821 Parent.PartialContainer.Members.Add (BackingField);
823 FieldExpr fe = new FieldExpr (BackingField, Location);
824 if ((BackingField.ModFlags & Modifiers.STATIC) == 0)
825 fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
828 // Create get block but we careful with location to
829 // emit only single sequence point per accessor. This allow
830 // to set a breakpoint on it even with no user code
832 Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
833 Return r = new Return (fe, Get.Location);
834 Get.Block.AddStatement (r);
835 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
839 Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
840 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
841 Set.Block.AddStatement (new StatementExpression (a, Set.Location));
842 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
846 public override bool Define ()
851 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
853 bool auto = AccessorFirst.Block == null && (AccessorSecond == null || AccessorSecond.Block == null) &&
854 (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0;
856 if (Initializer != null) {
858 Report.Error (8050, Location, "`{0}': Only auto-implemented properties can have initializers",
859 GetSignatureForError ());
862 Report.Error (8052, Location, "`{0}': Properties inside interfaces cannot have initializers",
863 GetSignatureForError ());
865 if (Compiler.Settings.Version < LanguageVersion.V_6)
866 Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented property initializer");
871 Report.Error (8051, Location, "Auto-implemented property `{0}' must have get accessor",
872 GetSignatureForError ());
876 if (Compiler.Settings.Version < LanguageVersion.V_3 && Initializer == null)
877 Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented properties");
879 CreateAutomaticProperty ();
882 if (!DefineAccessors ())
885 if (AccessorSecond == null) {
887 if (AccessorFirst is GetMethod)
888 pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
890 pm = new GetMethod (this, 0, null, Location);
892 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
898 DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
902 public override void Emit ()
904 if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
905 Report.Error (842, Location,
906 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
907 GetSignatureForError ());
913 public override string[] ValidAttributeTargets {
915 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
916 attribute_target_auto : base.ValidAttributeTargets;
922 /// For case when event is declared like property (with add and remove accessors).
924 public class EventProperty: Event {
925 public abstract class AEventPropertyAccessor : AEventAccessor
927 protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
928 : base (method, prefix, attrs, loc)
932 public override void Define (TypeContainer ds)
934 CheckAbstractAndExtern (block != null);
938 public override string GetSignatureForError ()
940 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
944 public sealed class AddDelegateMethod: AEventPropertyAccessor
946 public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
947 : base (method, AddPrefix, attrs, loc)
952 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
954 public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
955 : base (method, RemovePrefix, attrs, loc)
960 static readonly string[] attribute_targets = new string [] { "event" };
962 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
963 : base (parent, type, mod_flags, name, attrs)
967 public override void Accept (StructuralVisitor visitor)
969 visitor.Visit (this);
972 public override bool Define()
981 public override string[] ValidAttributeTargets {
983 return attribute_targets;
989 /// Event is declared like field.
991 public class EventField : Event
993 abstract class EventFieldAccessor : AEventAccessor
995 protected EventFieldAccessor (EventField method, string prefix)
996 : base (method, prefix, null, method.Location)
1000 protected abstract MethodSpec GetOperation (Location loc);
1002 public override void Emit (TypeDefinition parent)
1004 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
1005 block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
1006 IsCompilerGenerated = true
1008 FabricateBodyStatement ();
1014 void FabricateBodyStatement ()
1017 // Delegate obj1 = backing_field
1019 // Delegate obj2 = obj1;
1020 // obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
1021 // } while ((object)obj1 != (object)obj2)
1024 var field_info = ((EventField) method).backing_field;
1025 FieldExpr f_expr = new FieldExpr (field_info, Location);
1027 f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
1029 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1030 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1032 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
1034 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
1035 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
1036 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
1038 var body = new ExplicitBlock (block, Location, Location);
1039 block.AddStatement (new Do (body, cond, Location, Location));
1041 body.AddStatement (new StatementExpression (
1042 new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
1044 var args_oper = new Arguments (2);
1045 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
1046 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
1048 var op_method = GetOperation (Location);
1050 var args = new Arguments (3);
1051 args.Add (new Argument (f_expr, Argument.AType.Ref));
1052 args.Add (new Argument (new Cast (
1053 new TypeExpression (field_info.MemberType, Location),
1054 new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
1056 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
1058 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
1060 if (Module.PredefinedMembers.MonitorEnter_v4.Get () != null || Module.PredefinedMembers.MonitorEnter.Get () != null) {
1061 // Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
1062 body.AddStatement (new Lock (
1063 block.GetParameterReference (0, Location),
1064 new StatementExpression (new SimpleAssign (
1065 f_expr, args [1].Expr, Location), Location), Location));
1067 Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
1070 body.AddStatement (new StatementExpression (new SimpleAssign (
1071 new LocalVariableReference (obj1, Location),
1072 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
1077 sealed class AddDelegateMethod: EventFieldAccessor
1079 public AddDelegateMethod (EventField method):
1080 base (method, AddPrefix)
1084 protected override MethodSpec GetOperation (Location loc)
1086 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1090 sealed class RemoveDelegateMethod: EventFieldAccessor
1092 public RemoveDelegateMethod (EventField method):
1093 base (method, RemovePrefix)
1097 protected override MethodSpec GetOperation (Location loc)
1099 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1104 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1105 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1107 Expression initializer;
1108 Field backing_field;
1109 List<FieldDeclarator> declarators;
1111 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1112 : base (parent, type, mod_flags, name, attrs)
1114 Add = new AddDelegateMethod (this);
1115 Remove = new RemoveDelegateMethod (this);
1120 public List<FieldDeclarator> Declarators {
1122 return this.declarators;
1126 bool HasBackingField {
1128 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1132 public Expression Initializer {
1137 initializer = value;
1141 public override string[] ValidAttributeTargets {
1143 return HasBackingField ? attribute_targets : attribute_targets_interface;
1150 public override void Accept (StructuralVisitor visitor)
1152 visitor.Visit (this);
1155 public void AddDeclarator (FieldDeclarator declarator)
1157 if (declarators == null)
1158 declarators = new List<FieldDeclarator> (2);
1160 declarators.Add (declarator);
1162 Parent.AddNameToContainer (this, declarator.Name.Value);
1165 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1167 if (a.Target == AttributeTargets.Field) {
1168 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1172 if (a.Target == AttributeTargets.Method) {
1173 int errors = Report.Errors;
1174 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1175 if (errors == Report.Errors)
1176 Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1180 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1183 public override bool Define()
1185 var mod_flags_src = ModFlags;
1187 if (!base.Define ())
1190 if (declarators != null) {
1191 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1192 mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1194 var t = new TypeExpression (MemberType, TypeExpression.Location);
1195 foreach (var d in declarators) {
1196 var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1198 if (d.Initializer != null)
1199 ef.initializer = d.Initializer;
1202 Parent.PartialContainer.Members.Add (ef);
1206 if (!HasBackingField) {
1211 backing_field = new Field (Parent,
1212 new TypeExpression (MemberType, Location),
1213 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1216 Parent.PartialContainer.Members.Add (backing_field);
1217 backing_field.Initializer = Initializer;
1218 backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
1220 // Call define because we passed fields definition
1221 backing_field.Define ();
1223 // Set backing field for event fields
1224 spec.BackingField = backing_field.Spec;
1230 public abstract class Event : PropertyBasedMember
1232 public abstract class AEventAccessor : AbstractPropertyEventMethod
1234 protected readonly Event method;
1235 readonly ParametersCompiled parameters;
1237 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1239 public const string AddPrefix = "add_";
1240 public const string RemovePrefix = "remove_";
1242 protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1243 : base (method, prefix, attrs, loc)
1245 this.method = method;
1246 this.ModFlags = method.ModFlags;
1247 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1250 public bool IsInterfaceImplementation {
1251 get { return method_data.implementing != null; }
1254 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1256 if (a.Type == pa.MethodImpl) {
1257 method.is_external_implementation = a.IsInternalCall ();
1260 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1263 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1265 if (a.Target == AttributeTargets.Parameter) {
1266 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1270 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1273 public override AttributeTargets AttributeTargets {
1275 return AttributeTargets.Method;
1279 public override bool IsClsComplianceRequired ()
1281 return method.IsClsComplianceRequired ();
1284 public virtual void Define (TypeContainer parent)
1286 // Fill in already resolved event type to speed things up and
1287 // avoid confusing duplicate errors
1288 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1289 parameters.Types = new TypeSpec[] { method.member_type };
1291 method_data = new MethodData (method, method.ModFlags,
1292 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1294 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1297 if (Compiler.Settings.WriteMetadataOnly)
1300 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1301 Spec.IsAccessor = true;
1304 public override TypeSpec ReturnType {
1306 return Parent.Compiler.BuiltinTypes.Void;
1310 public override ObsoleteAttribute GetAttributeObsolete ()
1312 return method.GetAttributeObsolete ();
1315 public MethodData MethodData {
1321 public override string[] ValidAttributeTargets {
1323 return attribute_targets;
1327 public override ParametersCompiled ParameterInfo {
1334 AEventAccessor add, remove;
1335 EventBuilder EventBuilder;
1336 protected EventSpec spec;
1338 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1339 : base (parent, type, mod_flags,
1340 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1341 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1342 AllowedModifiersClass,
1349 public override AttributeTargets AttributeTargets {
1351 return AttributeTargets.Event;
1355 public AEventAccessor Add {
1361 Parent.AddNameToContainer (value, value.MemberName.Basename);
1365 public override Variance ExpectedMemberTypeVariance {
1367 return Variance.Contravariant;
1371 public AEventAccessor Remove {
1377 Parent.AddNameToContainer (value, value.MemberName.Basename);
1382 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1384 if ((a.HasSecurityAttribute)) {
1385 a.Error_InvalidSecurityParent ();
1389 EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1392 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1394 var ok = base.CheckOverrideAgainstBase (base_member);
1396 if (!CheckAccessModifiers (this, base_member)) {
1397 Error_CannotChangeAccessModifiers (this, base_member);
1404 public override bool Define ()
1406 if (!base.Define ())
1409 if (!MemberType.IsDelegate) {
1410 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1417 // Now define the accessors
1419 add.Define (Parent);
1420 remove.Define (Parent);
1422 EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1424 spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1426 Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1427 Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1428 Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1433 public override void Emit ()
1435 CheckReservedNameConflict (null, add.Spec);
1436 CheckReservedNameConflict (null, remove.Spec);
1438 if (OptAttributes != null) {
1439 OptAttributes.Emit ();
1442 ConstraintChecker.Check (this, member_type, type_expr.Location);
1445 Remove.Emit (Parent);
1450 public override void PrepareEmit ()
1453 remove.PrepareEmit ();
1455 EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1456 EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
1459 public override void WriteDebugSymbol (MonoSymbolFile file)
1461 add.WriteDebugSymbol (file);
1462 remove.WriteDebugSymbol (file);
1466 // Represents header string for documentation comment.
1468 public override string DocCommentHeader {
1469 get { return "E:"; }
1473 public class EventSpec : MemberSpec, IInterfaceMemberSpec
1475 MethodSpec add, remove;
1476 FieldSpec backing_field;
1478 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1479 : base (MemberKind.Event, declaringType, definition, modifiers)
1481 this.AccessorAdd = add;
1482 this.AccessorRemove = remove;
1483 this.MemberType = eventType;
1488 public MethodSpec AccessorAdd {
1497 public MethodSpec AccessorRemove {
1506 public FieldSpec BackingField {
1508 return backing_field;
1511 backing_field = value;
1515 public TypeSpec MemberType { get; private set; }
1519 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1521 var es = (EventSpec) base.InflateMember (inflator);
1522 es.MemberType = inflator.Inflate (MemberType);
1524 if (backing_field != null)
1525 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1530 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1532 return MemberType.ResolveMissingDependencies (this);
1536 public class Indexer : PropertyBase, IParametersMember
1538 public class GetIndexerMethod : GetMethod, IParametersMember
1540 ParametersCompiled parameters;
1542 public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1543 : base (property, modifiers, attrs, loc)
1545 this.parameters = parameters;
1548 public override void Define (TypeContainer parent)
1550 // Disable reporting, parameters are resolved twice
1551 Report.DisableReporting ();
1553 parameters.Resolve (this);
1555 Report.EnableReporting ();
1558 base.Define (parent);
1561 public override ParametersCompiled ParameterInfo {
1567 #region IParametersMember Members
1569 AParametersCollection IParametersMember.Parameters {
1575 TypeSpec IInterfaceMemberSpec.MemberType {
1584 public class SetIndexerMethod : SetMethod, IParametersMember
1586 public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1587 : base (property, modifiers, parameters, attrs, loc)
1591 #region IParametersMember Members
1593 AParametersCollection IParametersMember.Parameters {
1599 TypeSpec IInterfaceMemberSpec.MemberType {
1608 const Modifiers AllowedModifiers =
1611 Modifiers.PROTECTED |
1612 Modifiers.INTERNAL |
1616 Modifiers.OVERRIDE |
1621 const Modifiers AllowedInterfaceModifiers =
1624 readonly ParametersCompiled parameters;
1626 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1627 : base (parent, type, mod,
1628 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1631 this.parameters = parameters;
1636 AParametersCollection IParametersMember.Parameters {
1642 public ParametersCompiled ParameterInfo {
1651 public override void Accept (StructuralVisitor visitor)
1653 visitor.Visit (this);
1656 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1658 if (a.Type == pa.IndexerName) {
1659 // Attribute was copied to container
1663 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1666 protected override bool CheckForDuplications ()
1668 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1671 public override bool Define ()
1673 if (!base.Define ())
1676 if (!DefineParameters (parameters))
1679 if (OptAttributes != null) {
1680 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1681 if (indexer_attr != null) {
1682 var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1683 if (compiling != null)
1684 compiling.Define ();
1686 if (IsExplicitImpl) {
1687 Report.Error (415, indexer_attr.Location,
1688 "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1689 indexer_attr.Type.GetSignatureForError ());
1690 } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1691 Report.Error (609, indexer_attr.Location,
1692 "Cannot set the `IndexerName' attribute on an indexer marked override");
1694 string name = indexer_attr.GetIndexerAttributeValue ();
1696 if (!string.IsNullOrEmpty (name)) {
1697 SetMemberName (new MemberName (MemberName.Left, name, Location));
1703 if (InterfaceType != null) {
1704 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1705 if (base_IndexerName != ShortName) {
1706 SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1710 Parent.AddNameToContainer (this, MemberName.Basename);
1712 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1714 if (!DefineAccessors ())
1720 DefineBuilders (MemberKind.Indexer, parameters);
1724 public override bool EnableOverloadChecks (MemberCore overload)
1726 if (overload is Indexer) {
1727 caching_flags |= Flags.MethodOverloadsExist;
1731 return base.EnableOverloadChecks (overload);
1734 public override void Emit ()
1736 parameters.CheckConstraints (this);
1741 public override string GetSignatureForError ()
1743 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1744 if (MemberName.ExplicitInterface != null) {
1746 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1749 sb.Append (".this");
1750 sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1751 return sb.ToString ();
1754 public override string GetSignatureForDocumentation ()
1756 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1759 public override void PrepareEmit ()
1761 parameters.ResolveDefaultValues (this);
1763 base.PrepareEmit ();
1766 protected override bool VerifyClsCompliance ()
1768 if (!base.VerifyClsCompliance ())
1771 parameters.VerifyClsCompliance (this);
1776 public class IndexerSpec : PropertySpec, IParametersMember
1778 AParametersCollection parameters;
1780 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1781 : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1783 this.parameters = parameters;
1787 public AParametersCollection Parameters {
1794 public override string GetSignatureForDocumentation ()
1796 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1799 public override string GetSignatureForError ()
1801 return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1804 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1806 var spec = (IndexerSpec) base.InflateMember (inflator);
1807 spec.parameters = parameters.Inflate (inflator);
1811 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1813 var missing = base.ResolveMissingDependencies (caller);
1815 foreach (var pt in parameters.Types) {
1816 var m = pt.GetMissingDependencies (caller);
1820 if (missing == null)
1821 missing = new List<MissingTypeSpecReference> ();
1823 missing.AddRange (m);