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 protected override bool VerifyClsCompliance ()
87 if (!base.VerifyClsCompliance ())
90 if (!MemberType.IsCLSCompliant ()) {
91 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
92 GetSignatureForError ());
99 public class PropertySpec : MemberSpec, IInterfaceMemberSpec
105 public PropertySpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, PropertyInfo info, Modifiers modifiers)
106 : base (kind, declaringType, definition, modifiers)
109 this.memberType = memberType;
114 public MethodSpec Get {
120 get.IsAccessor = true;
124 public MethodSpec Set {
130 set.IsAccessor = true;
134 public bool HasDifferentAccessibility {
136 return HasGet && HasSet &&
137 (Get.Modifiers & Modifiers.AccessibilityMask) != (Set.Modifiers & Modifiers.AccessibilityMask);
153 public PropertyInfo MetaInfo {
155 if ((state & StateFlags.PendingMetaInflate) != 0)
156 throw new NotSupportedException ();
162 public TypeSpec MemberType {
170 public override MemberSpec InflateMember (TypeParameterInflator inflator)
172 var ps = (PropertySpec) base.InflateMember (inflator);
173 ps.memberType = inflator.Inflate (memberType);
177 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
179 return memberType.ResolveMissingDependencies (this);
184 // Properties and Indexers both generate PropertyBuilders, we use this to share
185 // their common bits.
187 abstract public class PropertyBase : PropertyBasedMember {
189 public class GetMethod : PropertyMethod
191 static readonly string[] attribute_targets = new string [] { "method", "return" };
193 internal const string Prefix = "get_";
195 public GetMethod (PropertyBase method, Modifiers modifiers, Attributes attrs, Location loc)
196 : base (method, Prefix, modifiers, attrs, loc)
200 public override void Define (TypeContainer parent)
202 base.Define (parent);
204 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
206 method_data = new MethodData (method, ModFlags, flags, this);
208 method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
211 public override TypeSpec ReturnType {
213 return method.MemberType;
217 public override ParametersCompiled ParameterInfo {
219 return ParametersCompiled.EmptyReadOnlyParameters;
223 public override string[] ValidAttributeTargets {
225 return attribute_targets;
230 public class SetMethod : PropertyMethod {
232 static readonly string[] attribute_targets = new string[] { "method", "param", "return" };
234 internal const string Prefix = "set_";
236 protected ParametersCompiled parameters;
238 public SetMethod (PropertyBase method, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
239 : base (method, Prefix, modifiers, attrs, loc)
241 this.parameters = parameters;
244 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
246 if (a.Target == AttributeTargets.Parameter) {
247 parameters[parameters.Count - 1].ApplyAttributeBuilder (a, ctor, cdata, pa);
251 base.ApplyToExtraTarget (a, ctor, cdata, pa);
254 public override ParametersCompiled ParameterInfo {
260 public override void Define (TypeContainer parent)
262 parameters.Resolve (this);
264 base.Define (parent);
266 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
268 method_data = new MethodData (method, ModFlags, flags, this);
270 method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
273 public override TypeSpec ReturnType {
275 return Parent.Compiler.BuiltinTypes.Void;
279 public override string[] ValidAttributeTargets {
281 return attribute_targets;
286 static readonly string[] attribute_targets = new string[] { "property" };
288 public abstract class PropertyMethod : AbstractPropertyEventMethod
290 const Modifiers AllowedModifiers =
292 Modifiers.PROTECTED |
296 protected readonly PropertyBase method;
297 protected MethodAttributes flags;
299 public PropertyMethod (PropertyBase method, string prefix, Modifiers modifiers, Attributes attrs, Location loc)
300 : base (method, prefix, attrs, loc)
302 this.method = method;
303 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, modifiers, 0, loc, Report);
304 this.ModFlags |= (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
307 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
309 if (a.Type == pa.MethodImpl) {
310 method.is_external_implementation = a.IsInternalCall ();
313 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
316 public override AttributeTargets AttributeTargets {
318 return AttributeTargets.Method;
322 public override bool IsClsComplianceRequired ()
324 return method.IsClsComplianceRequired ();
327 public virtual void Define (TypeContainer parent)
329 var container = parent.PartialContainer;
332 // Check for custom access modifier
334 if ((ModFlags & Modifiers.AccessibilityMask) == 0) {
335 ModFlags |= method.ModFlags;
336 flags = method.flags;
338 CheckModifiers (ModFlags);
339 ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
340 ModFlags |= Modifiers.PROPERTY_CUSTOM;
342 if (container.Kind == MemberKind.Interface) {
343 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
344 GetSignatureForError ());
345 } else if ((ModFlags & Modifiers.PRIVATE) != 0) {
346 if ((method.ModFlags & Modifiers.ABSTRACT) != 0) {
347 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
350 ModFlags &= ~Modifiers.VIRTUAL;
353 flags = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.SpecialName;
356 CheckAbstractAndExtern (block != null);
357 CheckProtectedModifier ();
360 if (block.IsIterator)
361 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
363 if (Compiler.Settings.WriteMetadataOnly)
368 public bool HasCustomAccessModifier {
370 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
374 public PropertyBase Property {
380 public override ObsoleteAttribute GetAttributeObsolete ()
382 return method.GetAttributeObsolete ();
385 public override string GetSignatureForError()
387 return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
390 void CheckModifiers (Modifiers modflags)
392 if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
393 Report.Error (273, Location,
394 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
395 GetSignatureForError (), method.GetSignatureForError ());
400 PropertyMethod get, set, first;
401 PropertyBuilder PropertyBuilder;
403 protected PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
404 : base (parent, type, mod_flags, allowed_mod, name, attrs)
410 public override AttributeTargets AttributeTargets {
412 return AttributeTargets.Property;
416 public PropertyMethod AccessorFirst {
422 public PropertyMethod AccessorSecond {
424 return first == get ? set : get;
428 public override Variance ExpectedMemberTypeVariance {
430 return (get != null && set != null) ?
431 Variance.None : set == null ?
433 Variance.Contravariant;
437 public PropertyMethod Get {
446 Parent.AddNameToContainer (get, get.MemberName.Basename);
450 public PropertyMethod Set {
459 Parent.AddNameToContainer (set, set.MemberName.Basename);
463 public override string[] ValidAttributeTargets {
465 return attribute_targets;
471 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
473 if (a.HasSecurityAttribute) {
474 a.Error_InvalidSecurityParent ();
478 if (a.Type == pa.Dynamic) {
479 a.Error_MisusedDynamicAttribute ();
483 PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
486 void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
488 if (IsExplicitImpl) {
490 if (kind == MemberKind.Indexer)
491 filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
493 filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
495 var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
497 if (implementing == null)
500 var accessor = get ? implementing.Get : implementing.Set;
501 if (accessor != null) {
502 Report.SymbolRelatedToPreviousError (accessor);
503 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
504 GetSignatureForError (), accessor.GetSignatureForError ());
509 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
511 var ok = base.CheckOverrideAgainstBase (base_member);
514 // Check base property accessors conflict
516 var base_prop = (PropertySpec) base_member;
518 if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasGet && !base_prop.Get.IsAccessible (this)) {
519 // TODO: Should be different error code but csc uses for some reason same
520 Report.SymbolRelatedToPreviousError (base_prop);
521 Report.Error (545, Location,
522 "`{0}': cannot override because `{1}' does not have accessible get accessor",
523 GetSignatureForError (), base_prop.GetSignatureForError ());
527 if (!base_prop.HasGet) {
529 Report.SymbolRelatedToPreviousError (base_prop);
530 Report.Error (545, Get.Location,
531 "`{0}': cannot override because `{1}' does not have an overridable get accessor",
532 Get.GetSignatureForError (), base_prop.GetSignatureForError ());
535 } else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
536 if (!base_prop.Get.IsAccessible (this)) {
537 // Same as csc but it should be different error code
538 Report.Error (115, Get.Location, "`{0}' is marked as an override but no accessible `get' accessor found to override",
539 GetSignatureForError ());
541 } else if (!CheckAccessModifiers (Get, base_prop.Get)) {
542 Error_CannotChangeAccessModifiers (Get, base_prop.Get);
549 if (base_prop.HasSet) {
550 if ((ModFlags & Modifiers.SEALED) != 0 && !base_prop.Set.IsAccessible (this)) {
551 // TODO: Should be different error code but csc uses for some reason same
552 Report.SymbolRelatedToPreviousError (base_prop);
553 Report.Error (546, Location,
554 "`{0}': cannot override because `{1}' does not have accessible set accessor",
555 GetSignatureForError (), base_prop.GetSignatureForError ());
559 if ((ModFlags & Modifiers.AutoProperty) != 0) {
560 Report.Error (8080, Location, "`{0}': Auto-implemented properties must override all accessors of the overridden property",
561 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) || (Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0))) {
621 Report.Error (276, Location,
622 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
623 GetSignatureForError ());
627 protected bool DefineAccessors ()
629 first.Define (Parent);
630 if (AccessorSecond != null)
631 AccessorSecond.Define (Parent);
636 protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
638 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
639 GetFullName (MemberName), PropertyAttributes.None,
640 #if !BOOTSTRAP_BASIC // Requires trunk version mscorlib
641 IsStatic ? 0 : CallingConventions.HasThis,
643 MemberType.GetMetaInfo (), null, null,
644 parameters.GetMetaInfo (), null, null);
647 if (kind == MemberKind.Indexer)
648 spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
650 spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
654 Parent.MemberCache.AddMember (this, Get.Spec.Name, Get.Spec);
656 CheckMissingAccessor (kind, parameters, true);
661 Parent.MemberCache.AddMember (this, Set.Spec.Name, Set.Spec);
663 CheckMissingAccessor (kind, parameters, false);
666 Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
669 public override void Emit ()
671 CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
672 CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
674 if (OptAttributes != null)
675 OptAttributes.Emit ();
677 if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
678 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
679 } else if (member_type.HasDynamicElement) {
680 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
683 if (member_type.HasNamedTupleElement) {
684 Module.PredefinedAttributes.TupleElementNames.EmitAttribute (PropertyBuilder, member_type, Location);
687 ConstraintChecker.Check (this, member_type, type_expr.Location);
690 if (AccessorSecond != null)
691 AccessorSecond.Emit (Parent);
696 public override bool IsUsed {
701 return Get.IsUsed | Set.IsUsed;
705 public override void PrepareEmit ()
707 AccessorFirst.PrepareEmit ();
708 if (AccessorSecond != null)
709 AccessorSecond.PrepareEmit ();
712 var method = Get.Spec.GetMetaInfo () as MethodBuilder;
714 PropertyBuilder.SetGetMethod (method);
718 var method = Set.Spec.GetMetaInfo () as MethodBuilder;
720 PropertyBuilder.SetSetMethod (method);
724 protected override void SetMemberName (MemberName new_name)
726 base.SetMemberName (new_name);
729 Get.UpdateName (this);
732 Set.UpdateName (this);
735 public override void WriteDebugSymbol (MonoSymbolFile file)
738 get.WriteDebugSymbol (file);
741 set.WriteDebugSymbol (file);
745 // Represents header string for documentation comment.
747 public override string DocCommentHeader {
752 public class Property : PropertyBase
754 public sealed class BackingFieldDeclaration : Field
756 readonly Property property;
757 const Modifiers DefaultModifiers = Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | Modifiers.DEBUGGER_HIDDEN;
759 public BackingFieldDeclaration (Property p, bool readOnly)
760 : base (p.Parent, p.type_expr, DefaultModifiers | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
761 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
765 ModFlags |= Modifiers.READONLY;
768 public Property OriginalProperty {
774 public override string GetSignatureForError ()
776 return property.GetSignatureForError ();
780 static readonly string[] attribute_target_auto = new string[] { "property", "field" };
782 public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
783 MemberName name, Attributes attrs)
784 : base (parent, type, mod,
785 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
786 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
787 AllowedModifiersClass,
792 public BackingFieldDeclaration BackingField { get; private set; }
794 public Expression Initializer { get; set; }
796 public override void Accept (StructuralVisitor visitor)
798 visitor.Visit (this);
801 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
803 if (a.Target == AttributeTargets.Field) {
804 BackingField.ApplyAttributeBuilder (a, ctor, cdata, pa);
808 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
811 void CreateAutomaticProperty ()
813 // Create backing field
814 BackingField = new BackingFieldDeclaration (this, Initializer == null && Set == null);
815 if (!BackingField.Define ())
818 if (Initializer != null) {
819 BackingField.Initializer = Initializer;
820 Parent.RegisterFieldForInitialization (BackingField, new FieldInitializer (BackingField, Initializer, Location));
821 BackingField.ModFlags |= Modifiers.READONLY;
824 Parent.PartialContainer.Members.Add (BackingField);
826 FieldExpr fe = new FieldExpr (BackingField, Location);
827 if ((BackingField.ModFlags & Modifiers.STATIC) == 0) {
828 fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
829 Parent.PartialContainer.HasInstanceField = true;
833 // Create get block but we careful with location to
834 // emit only single sequence point per accessor. This allow
835 // to set a breakpoint on it even with no user code
837 Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
838 Return r = new Return (fe, Get.Location);
839 Get.Block.AddStatement (r);
840 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
844 Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
845 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
846 Set.Block.AddStatement (new StatementExpression (a, Set.Location));
847 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
851 public override bool Define ()
856 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
858 bool auto = AccessorFirst.Block == null && (AccessorSecond == null || AccessorSecond.Block == null) &&
859 (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0;
861 if (Initializer != null) {
863 Report.Error (8050, Location, "`{0}': Only auto-implemented properties can have initializers",
864 GetSignatureForError ());
867 Report.Error (8052, Location, "`{0}': Properties inside interfaces cannot have initializers",
868 GetSignatureForError ());
870 if (Compiler.Settings.Version < LanguageVersion.V_6)
871 Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented property initializer");
875 ModFlags |= Modifiers.AutoProperty;
877 Report.Error (8051, Location, "Auto-implemented property `{0}' must have get accessor",
878 GetSignatureForError ());
882 if (MemberType.Kind == MemberKind.ByRef) {
883 Report.Error (8145, Location, "Auto-implemented property `{0}' cannot return by reference",
884 GetSignatureForError ());
888 if ((Parent.PartialContainer.ModFlags & Modifiers.READONLY) != 0 && Set != null && !IsStatic) {
889 Report.Error (8341, Location, "Auto-implemented instance property `{0}' in readonly structs must be readonly",
890 GetSignatureForError ());
893 if (Compiler.Settings.Version < LanguageVersion.V_3 && Initializer == null)
894 Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented properties");
896 CreateAutomaticProperty ();
899 if (!DefineAccessors ())
902 if (AccessorSecond == null) {
904 if (AccessorFirst is GetMethod)
905 pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
907 pm = new GetMethod (this, 0, null, Location);
909 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
915 DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
919 public override void Emit ()
921 if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.AutoProperty)) == Modifiers.AutoProperty && Parent.PartialContainer.HasExplicitLayout) {
922 Report.Error (842, Location,
923 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
924 GetSignatureForError ());
930 public override string[] ValidAttributeTargets {
932 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
933 attribute_target_auto : base.ValidAttributeTargets;
939 /// For case when event is declared like property (with add and remove accessors).
941 public class EventProperty: Event {
942 public abstract class AEventPropertyAccessor : AEventAccessor
944 protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
945 : base (method, prefix, attrs, loc)
949 public override void Define (TypeContainer ds)
951 CheckAbstractAndExtern (block != null);
955 public override string GetSignatureForError ()
957 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
961 public sealed class AddDelegateMethod: AEventPropertyAccessor
963 public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
964 : base (method, AddPrefix, attrs, loc)
969 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
971 public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
972 : base (method, RemovePrefix, attrs, loc)
977 static readonly string[] attribute_targets = new string [] { "event" };
979 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
980 : base (parent, type, mod_flags, name, attrs)
984 public override void Accept (StructuralVisitor visitor)
986 visitor.Visit (this);
989 public override bool Define()
998 public override string[] ValidAttributeTargets {
1000 return attribute_targets;
1006 /// Event is declared like field.
1008 public class EventField : Event
1010 abstract class EventFieldAccessor : AEventAccessor
1012 protected EventFieldAccessor (EventField method, string prefix)
1013 : base (method, prefix, null, method.Location)
1017 protected abstract MethodSpec GetOperation (Location loc);
1019 public override void Emit (TypeDefinition parent)
1021 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
1022 block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
1023 IsCompilerGenerated = true
1025 FabricateBodyStatement ();
1031 void FabricateBodyStatement ()
1034 // Delegate obj1 = backing_field
1036 // Delegate obj2 = obj1;
1037 // obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
1038 // } while ((object)obj1 != (object)obj2)
1041 var field_info = ((EventField) method).backing_field;
1042 FieldExpr f_expr = new FieldExpr (field_info, Location);
1044 f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
1046 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1047 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1049 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
1051 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
1052 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
1053 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
1055 var body = new ExplicitBlock (block, Location, Location);
1056 block.AddStatement (new Do (body, cond, Location, Location));
1058 body.AddStatement (new StatementExpression (
1059 new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
1061 var args_oper = new Arguments (2);
1062 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
1063 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
1065 var op_method = GetOperation (Location);
1067 var args = new Arguments (3);
1068 args.Add (new Argument (f_expr, Argument.AType.Ref));
1069 args.Add (new Argument (new Cast (
1070 new TypeExpression (field_info.MemberType, Location),
1071 new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
1073 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
1075 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
1077 if (Module.PredefinedMembers.MonitorEnter_v4.Get () != null || Module.PredefinedMembers.MonitorEnter.Get () != null) {
1078 // Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
1079 body.AddStatement (new Lock (
1080 block.GetParameterReference (0, Location),
1081 new StatementExpression (new SimpleAssign (
1082 f_expr, args [1].Expr, Location), Location), Location));
1084 Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
1087 body.AddStatement (new StatementExpression (new SimpleAssign (
1088 new LocalVariableReference (obj1, Location),
1089 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
1094 sealed class AddDelegateMethod: EventFieldAccessor
1096 public AddDelegateMethod (EventField method):
1097 base (method, AddPrefix)
1101 protected override MethodSpec GetOperation (Location loc)
1103 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1107 sealed class RemoveDelegateMethod: EventFieldAccessor
1109 public RemoveDelegateMethod (EventField method):
1110 base (method, RemovePrefix)
1114 protected override MethodSpec GetOperation (Location loc)
1116 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1121 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1122 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1124 Expression initializer;
1125 Field backing_field;
1126 List<FieldDeclarator> declarators;
1128 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1129 : base (parent, type, mod_flags, name, attrs)
1131 Add = new AddDelegateMethod (this);
1132 Remove = new RemoveDelegateMethod (this);
1137 public List<FieldDeclarator> Declarators {
1139 return this.declarators;
1143 bool HasBackingField {
1145 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1149 public Expression Initializer {
1154 initializer = value;
1158 public override string[] ValidAttributeTargets {
1160 return HasBackingField ? attribute_targets : attribute_targets_interface;
1167 public override void Accept (StructuralVisitor visitor)
1169 visitor.Visit (this);
1172 public void AddDeclarator (FieldDeclarator declarator)
1174 if (declarators == null)
1175 declarators = new List<FieldDeclarator> (2);
1177 declarators.Add (declarator);
1179 Parent.AddNameToContainer (this, declarator.Name.Value);
1182 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1184 if (a.Target == AttributeTargets.Field) {
1185 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1189 if (a.Target == AttributeTargets.Method) {
1190 int errors = Report.Errors;
1191 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1192 if (errors == Report.Errors)
1193 Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1197 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1200 protected override void DoMemberTypeIndependentChecks ()
1202 if ((Parent.PartialContainer.ModFlags & Modifiers.READONLY) != 0 && (ModFlags & Modifiers.STATIC) == 0) {
1203 Report.Error (8342, Location, "`{0}': Field-like instance events are not allowed in readonly structs",
1204 GetSignatureForError ());
1207 base.DoMemberTypeIndependentChecks ();
1210 public override bool Define()
1212 var mod_flags_src = ModFlags;
1214 if (!base.Define ())
1217 if (declarators != null) {
1218 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1219 mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1221 var t = new TypeExpression (MemberType, TypeExpression.Location);
1222 foreach (var d in declarators) {
1223 var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1225 if (d.Initializer != null)
1226 ef.initializer = d.Initializer;
1229 Parent.PartialContainer.Members.Add (ef);
1233 if (!HasBackingField) {
1238 backing_field = new Field (Parent,
1239 new TypeExpression (MemberType, Location),
1240 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1243 Parent.PartialContainer.Members.Add (backing_field);
1244 backing_field.Initializer = Initializer;
1246 // Call define because we passed fields definition
1247 backing_field.Define ();
1249 // Set backing field for event fields
1250 spec.BackingField = backing_field.Spec;
1256 public abstract class Event : PropertyBasedMember
1258 public abstract class AEventAccessor : AbstractPropertyEventMethod
1260 protected readonly Event method;
1261 readonly ParametersCompiled parameters;
1263 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1265 public const string AddPrefix = "add_";
1266 public const string RemovePrefix = "remove_";
1268 protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1269 : base (method, prefix, attrs, loc)
1271 this.method = method;
1272 this.ModFlags = method.ModFlags;
1273 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1276 public bool IsInterfaceImplementation {
1277 get { return method_data.implementing != null; }
1280 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1282 if (a.Type == pa.MethodImpl) {
1283 method.is_external_implementation = a.IsInternalCall ();
1286 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1289 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1291 if (a.Target == AttributeTargets.Parameter) {
1292 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1296 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1299 public override AttributeTargets AttributeTargets {
1301 return AttributeTargets.Method;
1305 public override bool IsClsComplianceRequired ()
1307 return method.IsClsComplianceRequired ();
1310 public virtual void Define (TypeContainer parent)
1312 // Fill in already resolved event type to speed things up and
1313 // avoid confusing duplicate errors
1314 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1315 parameters.Types = new TypeSpec[] { method.member_type };
1317 method_data = new MethodData (method, method.ModFlags,
1318 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1320 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1323 if (Compiler.Settings.WriteMetadataOnly)
1326 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1327 Spec.IsAccessor = true;
1330 public override TypeSpec ReturnType {
1332 return Parent.Compiler.BuiltinTypes.Void;
1336 public override ObsoleteAttribute GetAttributeObsolete ()
1338 return method.GetAttributeObsolete ();
1341 public MethodData MethodData {
1347 public override string[] ValidAttributeTargets {
1349 return attribute_targets;
1353 public override ParametersCompiled ParameterInfo {
1360 AEventAccessor add, remove;
1361 EventBuilder EventBuilder;
1362 protected EventSpec spec;
1364 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1365 : base (parent, type, mod_flags,
1366 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1367 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1368 AllowedModifiersClass,
1375 public override AttributeTargets AttributeTargets {
1377 return AttributeTargets.Event;
1381 public AEventAccessor Add {
1387 Parent.AddNameToContainer (value, value.MemberName.Basename);
1391 public override Variance ExpectedMemberTypeVariance {
1393 return Variance.Contravariant;
1397 public AEventAccessor Remove {
1403 Parent.AddNameToContainer (value, value.MemberName.Basename);
1408 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1410 if ((a.HasSecurityAttribute)) {
1411 a.Error_InvalidSecurityParent ();
1415 EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1418 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1420 var ok = base.CheckOverrideAgainstBase (base_member);
1422 if (!CheckAccessModifiers (this, base_member)) {
1423 Error_CannotChangeAccessModifiers (this, base_member);
1430 public override bool Define ()
1432 if (!base.Define ())
1435 if (!MemberType.IsDelegate) {
1436 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1443 // Now define the accessors
1445 add.Define (Parent);
1446 remove.Define (Parent);
1448 EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1450 spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1452 Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1453 Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1454 Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1459 public override void Emit ()
1461 CheckReservedNameConflict (null, add.Spec);
1462 CheckReservedNameConflict (null, remove.Spec);
1464 if (OptAttributes != null) {
1465 OptAttributes.Emit ();
1468 ConstraintChecker.Check (this, member_type, type_expr.Location);
1471 Remove.Emit (Parent);
1476 public override void PrepareEmit ()
1478 base.PrepareEmit ();
1481 remove.PrepareEmit ();
1483 EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1484 EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
1487 public override void WriteDebugSymbol (MonoSymbolFile file)
1489 add.WriteDebugSymbol (file);
1490 remove.WriteDebugSymbol (file);
1494 // Represents header string for documentation comment.
1496 public override string DocCommentHeader {
1497 get { return "E:"; }
1501 public class EventSpec : MemberSpec, IInterfaceMemberSpec
1503 MethodSpec add, remove;
1504 FieldSpec backing_field;
1506 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1507 : base (MemberKind.Event, declaringType, definition, modifiers)
1509 this.AccessorAdd = add;
1510 this.AccessorRemove = remove;
1511 this.MemberType = eventType;
1516 public MethodSpec AccessorAdd {
1525 public MethodSpec AccessorRemove {
1534 public FieldSpec BackingField {
1536 return backing_field;
1539 backing_field = value;
1543 public TypeSpec MemberType { get; private set; }
1547 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1549 var es = (EventSpec) base.InflateMember (inflator);
1550 es.MemberType = inflator.Inflate (MemberType);
1552 if (backing_field != null)
1553 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1558 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1560 return MemberType.ResolveMissingDependencies (this);
1564 public class Indexer : PropertyBase, IParametersMember
1566 public class GetIndexerMethod : GetMethod, IParametersMember
1568 ParametersCompiled parameters;
1570 public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1571 : base (property, modifiers, attrs, loc)
1573 this.parameters = parameters;
1576 public override void Define (TypeContainer parent)
1578 // Disable reporting, parameters are resolved twice
1579 Report.DisableReporting ();
1581 parameters.Resolve (this);
1583 Report.EnableReporting ();
1586 base.Define (parent);
1589 public override ParametersCompiled ParameterInfo {
1595 #region IParametersMember Members
1597 AParametersCollection IParametersMember.Parameters {
1603 TypeSpec IInterfaceMemberSpec.MemberType {
1612 public class SetIndexerMethod : SetMethod, IParametersMember
1614 public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1615 : base (property, modifiers, parameters, attrs, loc)
1619 #region IParametersMember Members
1621 AParametersCollection IParametersMember.Parameters {
1627 TypeSpec IInterfaceMemberSpec.MemberType {
1636 const Modifiers AllowedModifiers =
1639 Modifiers.PROTECTED |
1640 Modifiers.INTERNAL |
1644 Modifiers.OVERRIDE |
1649 const Modifiers AllowedInterfaceModifiers =
1652 readonly ParametersCompiled parameters;
1654 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1655 : base (parent, type, mod,
1656 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1659 this.parameters = parameters;
1664 AParametersCollection IParametersMember.Parameters {
1670 public ParametersCompiled ParameterInfo {
1679 public override void Accept (StructuralVisitor visitor)
1681 visitor.Visit (this);
1684 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1686 if (a.Type == pa.IndexerName) {
1687 // Attribute was copied to container
1691 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1694 protected override bool CheckForDuplications ()
1696 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1699 public override bool Define ()
1701 if (!base.Define ())
1704 if (!DefineParameters (parameters))
1707 if (OptAttributes != null) {
1708 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1709 if (indexer_attr != null) {
1710 var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1711 if (compiling != null)
1712 compiling.Define ();
1714 if (IsExplicitImpl) {
1715 Report.Error (415, indexer_attr.Location,
1716 "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1717 indexer_attr.Type.GetSignatureForError ());
1718 } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1719 Report.Error (609, indexer_attr.Location,
1720 "Cannot set the `IndexerName' attribute on an indexer marked override");
1722 string name = indexer_attr.GetIndexerAttributeValue ();
1724 if (!string.IsNullOrEmpty (name)) {
1725 SetMemberName (new MemberName (MemberName.Left, name, Location));
1731 if (InterfaceType != null) {
1732 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1733 if (base_IndexerName != ShortName) {
1734 SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1738 Parent.AddNameToContainer (this, MemberName.Basename);
1740 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1742 if (!DefineAccessors ())
1748 DefineBuilders (MemberKind.Indexer, parameters);
1752 public override bool EnableOverloadChecks (MemberCore overload)
1754 if (overload is Indexer) {
1755 caching_flags |= Flags.MethodOverloadsExist;
1759 return base.EnableOverloadChecks (overload);
1762 public override void Emit ()
1764 parameters.CheckConstraints (this);
1769 public override string GetSignatureForError ()
1771 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1772 if (MemberName.ExplicitInterface != null) {
1774 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1777 sb.Append (".this");
1778 sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1779 return sb.ToString ();
1782 public override string GetSignatureForDocumentation ()
1784 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1787 public override void PrepareEmit ()
1789 base.PrepareEmit ();
1790 parameters.ResolveDefaultValues (this);
1793 protected override bool VerifyClsCompliance ()
1795 if (!base.VerifyClsCompliance ())
1798 parameters.VerifyClsCompliance (this);
1803 public class IndexerSpec : PropertySpec, IParametersMember
1805 AParametersCollection parameters;
1807 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1808 : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1810 this.parameters = parameters;
1814 public AParametersCollection Parameters {
1821 public static ParametersImported CreateParametersFromSetter (MethodSpec setter, int set_param_count)
1824 // Creates indexer parameters based on setter method parameters (the last parameter has to be removed)
1826 var data = new IParameterData [set_param_count];
1827 var types = new TypeSpec [set_param_count];
1828 Array.Copy (setter.Parameters.FixedParameters, data, set_param_count);
1829 Array.Copy (setter.Parameters.Types, types, set_param_count);
1830 return new ParametersImported (data, types, setter.Parameters.HasParams);
1833 public override string GetSignatureForDocumentation ()
1835 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1838 public override string GetSignatureForError ()
1840 return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1843 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1845 var spec = (IndexerSpec) base.InflateMember (inflator);
1846 spec.parameters = parameters.Inflate (inflator);
1850 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1852 var missing = base.ResolveMissingDependencies (caller);
1854 foreach (var pt in parameters.Types) {
1855 var m = pt.GetMissingDependencies (caller);
1859 if (missing == null)
1860 missing = new List<MissingTypeSpecReference> ();
1862 missing.AddRange (m);