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 ((ModFlags & Modifiers.AutoProperty) != 0) {
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");
870 ModFlags |= Modifiers.AutoProperty;
872 Report.Error (8051, Location, "Auto-implemented property `{0}' must have get accessor",
873 GetSignatureForError ());
877 if (Compiler.Settings.Version < LanguageVersion.V_3 && Initializer == null)
878 Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented properties");
880 CreateAutomaticProperty ();
883 if (!DefineAccessors ())
886 if (AccessorSecond == null) {
888 if (AccessorFirst is GetMethod)
889 pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
891 pm = new GetMethod (this, 0, null, Location);
893 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
899 DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
903 public override void Emit ()
905 if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
906 Report.Error (842, Location,
907 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
908 GetSignatureForError ());
914 public override string[] ValidAttributeTargets {
916 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
917 attribute_target_auto : base.ValidAttributeTargets;
923 /// For case when event is declared like property (with add and remove accessors).
925 public class EventProperty: Event {
926 public abstract class AEventPropertyAccessor : AEventAccessor
928 protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
929 : base (method, prefix, attrs, loc)
933 public override void Define (TypeContainer ds)
935 CheckAbstractAndExtern (block != null);
939 public override string GetSignatureForError ()
941 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
945 public sealed class AddDelegateMethod: AEventPropertyAccessor
947 public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
948 : base (method, AddPrefix, attrs, loc)
953 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
955 public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
956 : base (method, RemovePrefix, attrs, loc)
961 static readonly string[] attribute_targets = new string [] { "event" };
963 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
964 : base (parent, type, mod_flags, name, attrs)
968 public override void Accept (StructuralVisitor visitor)
970 visitor.Visit (this);
973 public override bool Define()
982 public override string[] ValidAttributeTargets {
984 return attribute_targets;
990 /// Event is declared like field.
992 public class EventField : Event
994 abstract class EventFieldAccessor : AEventAccessor
996 protected EventFieldAccessor (EventField method, string prefix)
997 : base (method, prefix, null, method.Location)
1001 protected abstract MethodSpec GetOperation (Location loc);
1003 public override void Emit (TypeDefinition parent)
1005 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
1006 block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
1007 IsCompilerGenerated = true
1009 FabricateBodyStatement ();
1015 void FabricateBodyStatement ()
1018 // Delegate obj1 = backing_field
1020 // Delegate obj2 = obj1;
1021 // obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
1022 // } while ((object)obj1 != (object)obj2)
1025 var field_info = ((EventField) method).backing_field;
1026 FieldExpr f_expr = new FieldExpr (field_info, Location);
1028 f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
1030 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1031 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1033 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
1035 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
1036 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
1037 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
1039 var body = new ExplicitBlock (block, Location, Location);
1040 block.AddStatement (new Do (body, cond, Location, Location));
1042 body.AddStatement (new StatementExpression (
1043 new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
1045 var args_oper = new Arguments (2);
1046 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
1047 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
1049 var op_method = GetOperation (Location);
1051 var args = new Arguments (3);
1052 args.Add (new Argument (f_expr, Argument.AType.Ref));
1053 args.Add (new Argument (new Cast (
1054 new TypeExpression (field_info.MemberType, Location),
1055 new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
1057 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
1059 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
1061 if (Module.PredefinedMembers.MonitorEnter_v4.Get () != null || Module.PredefinedMembers.MonitorEnter.Get () != null) {
1062 // Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
1063 body.AddStatement (new Lock (
1064 block.GetParameterReference (0, Location),
1065 new StatementExpression (new SimpleAssign (
1066 f_expr, args [1].Expr, Location), Location), Location));
1068 Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
1071 body.AddStatement (new StatementExpression (new SimpleAssign (
1072 new LocalVariableReference (obj1, Location),
1073 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
1078 sealed class AddDelegateMethod: EventFieldAccessor
1080 public AddDelegateMethod (EventField method):
1081 base (method, AddPrefix)
1085 protected override MethodSpec GetOperation (Location loc)
1087 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1091 sealed class RemoveDelegateMethod: EventFieldAccessor
1093 public RemoveDelegateMethod (EventField method):
1094 base (method, RemovePrefix)
1098 protected override MethodSpec GetOperation (Location loc)
1100 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1105 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1106 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1108 Expression initializer;
1109 Field backing_field;
1110 List<FieldDeclarator> declarators;
1112 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1113 : base (parent, type, mod_flags, name, attrs)
1115 Add = new AddDelegateMethod (this);
1116 Remove = new RemoveDelegateMethod (this);
1121 public List<FieldDeclarator> Declarators {
1123 return this.declarators;
1127 bool HasBackingField {
1129 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1133 public Expression Initializer {
1138 initializer = value;
1142 public override string[] ValidAttributeTargets {
1144 return HasBackingField ? attribute_targets : attribute_targets_interface;
1151 public override void Accept (StructuralVisitor visitor)
1153 visitor.Visit (this);
1156 public void AddDeclarator (FieldDeclarator declarator)
1158 if (declarators == null)
1159 declarators = new List<FieldDeclarator> (2);
1161 declarators.Add (declarator);
1163 Parent.AddNameToContainer (this, declarator.Name.Value);
1166 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1168 if (a.Target == AttributeTargets.Field) {
1169 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1173 if (a.Target == AttributeTargets.Method) {
1174 int errors = Report.Errors;
1175 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1176 if (errors == Report.Errors)
1177 Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1181 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1184 public override bool Define()
1186 var mod_flags_src = ModFlags;
1188 if (!base.Define ())
1191 if (declarators != null) {
1192 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1193 mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1195 var t = new TypeExpression (MemberType, TypeExpression.Location);
1196 foreach (var d in declarators) {
1197 var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1199 if (d.Initializer != null)
1200 ef.initializer = d.Initializer;
1203 Parent.PartialContainer.Members.Add (ef);
1207 if (!HasBackingField) {
1212 backing_field = new Field (Parent,
1213 new TypeExpression (MemberType, Location),
1214 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1217 Parent.PartialContainer.Members.Add (backing_field);
1218 backing_field.Initializer = Initializer;
1219 backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
1221 // Call define because we passed fields definition
1222 backing_field.Define ();
1224 // Set backing field for event fields
1225 spec.BackingField = backing_field.Spec;
1231 public abstract class Event : PropertyBasedMember
1233 public abstract class AEventAccessor : AbstractPropertyEventMethod
1235 protected readonly Event method;
1236 readonly ParametersCompiled parameters;
1238 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1240 public const string AddPrefix = "add_";
1241 public const string RemovePrefix = "remove_";
1243 protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1244 : base (method, prefix, attrs, loc)
1246 this.method = method;
1247 this.ModFlags = method.ModFlags;
1248 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1251 public bool IsInterfaceImplementation {
1252 get { return method_data.implementing != null; }
1255 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1257 if (a.Type == pa.MethodImpl) {
1258 method.is_external_implementation = a.IsInternalCall ();
1261 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1264 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1266 if (a.Target == AttributeTargets.Parameter) {
1267 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1271 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1274 public override AttributeTargets AttributeTargets {
1276 return AttributeTargets.Method;
1280 public override bool IsClsComplianceRequired ()
1282 return method.IsClsComplianceRequired ();
1285 public virtual void Define (TypeContainer parent)
1287 // Fill in already resolved event type to speed things up and
1288 // avoid confusing duplicate errors
1289 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1290 parameters.Types = new TypeSpec[] { method.member_type };
1292 method_data = new MethodData (method, method.ModFlags,
1293 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1295 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1298 if (Compiler.Settings.WriteMetadataOnly)
1301 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1302 Spec.IsAccessor = true;
1305 public override TypeSpec ReturnType {
1307 return Parent.Compiler.BuiltinTypes.Void;
1311 public override ObsoleteAttribute GetAttributeObsolete ()
1313 return method.GetAttributeObsolete ();
1316 public MethodData MethodData {
1322 public override string[] ValidAttributeTargets {
1324 return attribute_targets;
1328 public override ParametersCompiled ParameterInfo {
1335 AEventAccessor add, remove;
1336 EventBuilder EventBuilder;
1337 protected EventSpec spec;
1339 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1340 : base (parent, type, mod_flags,
1341 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1342 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1343 AllowedModifiersClass,
1350 public override AttributeTargets AttributeTargets {
1352 return AttributeTargets.Event;
1356 public AEventAccessor Add {
1362 Parent.AddNameToContainer (value, value.MemberName.Basename);
1366 public override Variance ExpectedMemberTypeVariance {
1368 return Variance.Contravariant;
1372 public AEventAccessor Remove {
1378 Parent.AddNameToContainer (value, value.MemberName.Basename);
1383 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1385 if ((a.HasSecurityAttribute)) {
1386 a.Error_InvalidSecurityParent ();
1390 EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1393 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1395 var ok = base.CheckOverrideAgainstBase (base_member);
1397 if (!CheckAccessModifiers (this, base_member)) {
1398 Error_CannotChangeAccessModifiers (this, base_member);
1405 public override bool Define ()
1407 if (!base.Define ())
1410 if (!MemberType.IsDelegate) {
1411 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1418 // Now define the accessors
1420 add.Define (Parent);
1421 remove.Define (Parent);
1423 EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1425 spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1427 Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1428 Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1429 Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1434 public override void Emit ()
1436 CheckReservedNameConflict (null, add.Spec);
1437 CheckReservedNameConflict (null, remove.Spec);
1439 if (OptAttributes != null) {
1440 OptAttributes.Emit ();
1443 ConstraintChecker.Check (this, member_type, type_expr.Location);
1446 Remove.Emit (Parent);
1451 public override void PrepareEmit ()
1454 remove.PrepareEmit ();
1456 EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1457 EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
1460 public override void WriteDebugSymbol (MonoSymbolFile file)
1462 add.WriteDebugSymbol (file);
1463 remove.WriteDebugSymbol (file);
1467 // Represents header string for documentation comment.
1469 public override string DocCommentHeader {
1470 get { return "E:"; }
1474 public class EventSpec : MemberSpec, IInterfaceMemberSpec
1476 MethodSpec add, remove;
1477 FieldSpec backing_field;
1479 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1480 : base (MemberKind.Event, declaringType, definition, modifiers)
1482 this.AccessorAdd = add;
1483 this.AccessorRemove = remove;
1484 this.MemberType = eventType;
1489 public MethodSpec AccessorAdd {
1498 public MethodSpec AccessorRemove {
1507 public FieldSpec BackingField {
1509 return backing_field;
1512 backing_field = value;
1516 public TypeSpec MemberType { get; private set; }
1520 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1522 var es = (EventSpec) base.InflateMember (inflator);
1523 es.MemberType = inflator.Inflate (MemberType);
1525 if (backing_field != null)
1526 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1531 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1533 return MemberType.ResolveMissingDependencies (this);
1537 public class Indexer : PropertyBase, IParametersMember
1539 public class GetIndexerMethod : GetMethod, IParametersMember
1541 ParametersCompiled parameters;
1543 public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1544 : base (property, modifiers, attrs, loc)
1546 this.parameters = parameters;
1549 public override void Define (TypeContainer parent)
1551 // Disable reporting, parameters are resolved twice
1552 Report.DisableReporting ();
1554 parameters.Resolve (this);
1556 Report.EnableReporting ();
1559 base.Define (parent);
1562 public override ParametersCompiled ParameterInfo {
1568 #region IParametersMember Members
1570 AParametersCollection IParametersMember.Parameters {
1576 TypeSpec IInterfaceMemberSpec.MemberType {
1585 public class SetIndexerMethod : SetMethod, IParametersMember
1587 public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1588 : base (property, modifiers, parameters, attrs, loc)
1592 #region IParametersMember Members
1594 AParametersCollection IParametersMember.Parameters {
1600 TypeSpec IInterfaceMemberSpec.MemberType {
1609 const Modifiers AllowedModifiers =
1612 Modifiers.PROTECTED |
1613 Modifiers.INTERNAL |
1617 Modifiers.OVERRIDE |
1622 const Modifiers AllowedInterfaceModifiers =
1625 readonly ParametersCompiled parameters;
1627 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1628 : base (parent, type, mod,
1629 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1632 this.parameters = parameters;
1637 AParametersCollection IParametersMember.Parameters {
1643 public ParametersCompiled ParameterInfo {
1652 public override void Accept (StructuralVisitor visitor)
1654 visitor.Visit (this);
1657 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1659 if (a.Type == pa.IndexerName) {
1660 // Attribute was copied to container
1664 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1667 protected override bool CheckForDuplications ()
1669 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1672 public override bool Define ()
1674 if (!base.Define ())
1677 if (!DefineParameters (parameters))
1680 if (OptAttributes != null) {
1681 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1682 if (indexer_attr != null) {
1683 var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1684 if (compiling != null)
1685 compiling.Define ();
1687 if (IsExplicitImpl) {
1688 Report.Error (415, indexer_attr.Location,
1689 "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1690 indexer_attr.Type.GetSignatureForError ());
1691 } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1692 Report.Error (609, indexer_attr.Location,
1693 "Cannot set the `IndexerName' attribute on an indexer marked override");
1695 string name = indexer_attr.GetIndexerAttributeValue ();
1697 if (!string.IsNullOrEmpty (name)) {
1698 SetMemberName (new MemberName (MemberName.Left, name, Location));
1704 if (InterfaceType != null) {
1705 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1706 if (base_IndexerName != ShortName) {
1707 SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1711 Parent.AddNameToContainer (this, MemberName.Basename);
1713 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1715 if (!DefineAccessors ())
1721 DefineBuilders (MemberKind.Indexer, parameters);
1725 public override bool EnableOverloadChecks (MemberCore overload)
1727 if (overload is Indexer) {
1728 caching_flags |= Flags.MethodOverloadsExist;
1732 return base.EnableOverloadChecks (overload);
1735 public override void Emit ()
1737 parameters.CheckConstraints (this);
1742 public override string GetSignatureForError ()
1744 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1745 if (MemberName.ExplicitInterface != null) {
1747 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1750 sb.Append (".this");
1751 sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1752 return sb.ToString ();
1755 public override string GetSignatureForDocumentation ()
1757 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1760 public override void PrepareEmit ()
1762 parameters.ResolveDefaultValues (this);
1764 base.PrepareEmit ();
1767 protected override bool VerifyClsCompliance ()
1769 if (!base.VerifyClsCompliance ())
1772 parameters.VerifyClsCompliance (this);
1777 public class IndexerSpec : PropertySpec, IParametersMember
1779 AParametersCollection parameters;
1781 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1782 : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1784 this.parameters = parameters;
1788 public AParametersCollection Parameters {
1795 public override string GetSignatureForDocumentation ()
1797 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1800 public override string GetSignatureForError ()
1802 return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1805 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1807 var spec = (IndexerSpec) base.InflateMember (inflator);
1808 spec.parameters = parameters.Inflate (inflator);
1812 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1814 var missing = base.ResolveMissingDependencies (caller);
1816 foreach (var pt in parameters.Types) {
1817 var m = pt.GetMissingDependencies (caller);
1821 if (missing == null)
1822 missing = new List<MissingTypeSpecReference> ();
1824 missing.AddRange (m);