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 MethodBuilder 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 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
211 method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
213 return method_data.MethodBuilder;
216 public override TypeSpec ReturnType {
218 return method.MemberType;
222 public override ParametersCompiled ParameterInfo {
224 return ParametersCompiled.EmptyReadOnlyParameters;
228 public override string[] ValidAttributeTargets {
230 return attribute_targets;
235 public class SetMethod : PropertyMethod {
237 static readonly string[] attribute_targets = new string[] { "method", "param", "return" };
239 internal const string Prefix = "set_";
241 protected ParametersCompiled parameters;
243 public SetMethod (PropertyBase method, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
244 : base (method, Prefix, modifiers, attrs, loc)
246 this.parameters = parameters;
249 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
251 if (a.Target == AttributeTargets.Parameter) {
252 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
256 base.ApplyToExtraTarget (a, ctor, cdata, pa);
259 public override ParametersCompiled ParameterInfo {
265 public override MethodBuilder Define (TypeContainer parent)
267 parameters.Resolve (this);
269 base.Define (parent);
271 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
273 method_data = new MethodData (method, ModFlags, flags, this);
275 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
278 method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
280 return method_data.MethodBuilder;
283 public override TypeSpec ReturnType {
285 return Parent.Compiler.BuiltinTypes.Void;
289 public override string[] ValidAttributeTargets {
291 return attribute_targets;
296 static readonly string[] attribute_targets = new string[] { "property" };
298 public abstract class PropertyMethod : AbstractPropertyEventMethod
300 const Modifiers AllowedModifiers =
302 Modifiers.PROTECTED |
306 protected readonly PropertyBase method;
307 protected MethodAttributes flags;
309 public PropertyMethod (PropertyBase method, string prefix, Modifiers modifiers, Attributes attrs, Location loc)
310 : base (method, prefix, attrs, loc)
312 this.method = method;
313 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, modifiers, 0, loc, Report);
314 this.ModFlags |= (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
317 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
319 if (a.Type == pa.MethodImpl) {
320 method.is_external_implementation = a.IsInternalCall ();
323 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
326 public override AttributeTargets AttributeTargets {
328 return AttributeTargets.Method;
332 public override bool IsClsComplianceRequired ()
334 return method.IsClsComplianceRequired ();
337 public virtual MethodBuilder Define (TypeContainer parent)
339 var container = parent.PartialContainer;
342 // Check for custom access modifier
344 if ((ModFlags & Modifiers.AccessibilityMask) == 0) {
345 ModFlags |= method.ModFlags;
346 flags = method.flags;
348 if (container.Kind == MemberKind.Interface)
349 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
350 GetSignatureForError ());
351 else if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
352 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
355 CheckModifiers (ModFlags);
356 ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
357 ModFlags |= Modifiers.PROPERTY_CUSTOM;
358 flags = ModifiersExtensions.MethodAttr (ModFlags);
359 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
362 CheckAbstractAndExtern (block != null);
363 CheckProtectedModifier ();
366 if (block.IsIterator)
367 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
369 if (Compiler.Settings.WriteMetadataOnly)
376 public bool HasCustomAccessModifier {
378 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
382 public PropertyBase Property {
388 public override ObsoleteAttribute GetAttributeObsolete ()
390 return method.GetAttributeObsolete ();
393 public override string GetSignatureForError()
395 return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
398 void CheckModifiers (Modifiers modflags)
400 if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
401 Report.Error (273, Location,
402 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
403 GetSignatureForError (), method.GetSignatureForError ());
408 PropertyMethod get, set, first;
409 PropertyBuilder PropertyBuilder;
411 protected PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
412 : base (parent, type, mod_flags, allowed_mod, name, attrs)
418 public override AttributeTargets AttributeTargets {
420 return AttributeTargets.Property;
424 public PropertyMethod AccessorFirst {
430 public PropertyMethod AccessorSecond {
432 return first == get ? set : get;
436 public override Variance ExpectedMemberTypeVariance {
438 return (get != null && set != null) ?
439 Variance.None : set == null ?
441 Variance.Contravariant;
445 public PropertyMethod Get {
454 Parent.AddNameToContainer (get, get.MemberName.Basename);
458 public PropertyMethod Set {
467 Parent.AddNameToContainer (set, set.MemberName.Basename);
471 public override string[] ValidAttributeTargets {
473 return attribute_targets;
479 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
481 if (a.HasSecurityAttribute) {
482 a.Error_InvalidSecurityParent ();
486 if (a.Type == pa.Dynamic) {
487 a.Error_MisusedDynamicAttribute ();
491 PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
494 void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
496 if (IsExplicitImpl) {
498 if (kind == MemberKind.Indexer)
499 filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
501 filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
503 var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
505 if (implementing == null)
508 var accessor = get ? implementing.Get : implementing.Set;
509 if (accessor != null) {
510 Report.SymbolRelatedToPreviousError (accessor);
511 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
512 GetSignatureForError (), accessor.GetSignatureForError ());
517 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
519 var ok = base.CheckOverrideAgainstBase (base_member);
522 // Check base property accessors conflict
524 var base_prop = (PropertySpec) base_member;
526 if (!base_prop.HasGet) {
528 Report.SymbolRelatedToPreviousError (base_prop);
529 Report.Error (545, Get.Location,
530 "`{0}': cannot override because `{1}' does not have an overridable get accessor",
531 Get.GetSignatureForError (), base_prop.GetSignatureForError ());
534 } else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
535 if (!CheckAccessModifiers (Get, base_prop.Get)) {
536 Error_CannotChangeAccessModifiers (Get, base_prop.Get);
543 if (!base_prop.HasSet) {
545 Report.SymbolRelatedToPreviousError (base_prop);
546 Report.Error (546, Set.Location,
547 "`{0}': cannot override because `{1}' does not have an overridable set accessor",
548 Set.GetSignatureForError (), base_prop.GetSignatureForError ());
551 } else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
552 if (!CheckAccessModifiers (Set, base_prop.Set)) {
553 Error_CannotChangeAccessModifiers (Set, base_prop.Set);
559 if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
560 if (!CheckAccessModifiers (this, base_prop)) {
561 Error_CannotChangeAccessModifiers (this, base_prop);
569 protected override void DoMemberTypeDependentChecks ()
571 base.DoMemberTypeDependentChecks ();
575 if (MemberType.IsStatic)
576 Error_StaticReturnType ();
579 protected override void DoMemberTypeIndependentChecks ()
581 base.DoMemberTypeIndependentChecks ();
584 // Accessors modifiers check
586 if (AccessorSecond != null) {
587 if ((Get.ModFlags & Modifiers.AccessibilityMask) != 0 && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) {
588 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
589 GetSignatureForError ());
591 } else if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
592 (Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) ||
593 (Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0)) {
594 Report.Error (276, Location,
595 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
596 GetSignatureForError ());
600 protected bool DefineAccessors ()
602 first.Define (Parent);
603 if (AccessorSecond != null)
604 AccessorSecond.Define (Parent);
609 protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
611 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
612 GetFullName (MemberName), PropertyAttributes.None,
613 #if !BOOTSTRAP_BASIC // Requires trunk version mscorlib
614 IsStatic ? 0 : CallingConventions.HasThis,
616 MemberType.GetMetaInfo (), null, null,
617 parameters.GetMetaInfo (), null, null);
620 if (kind == MemberKind.Indexer)
621 spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
623 spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
628 var method = Get.Spec.GetMetaInfo () as MethodBuilder;
629 if (method != null) {
630 PropertyBuilder.SetGetMethod (method);
631 Parent.MemberCache.AddMember (this, method.Name, Get.Spec);
634 CheckMissingAccessor (kind, parameters, true);
640 var method = Set.Spec.GetMetaInfo () as MethodBuilder;
641 if (method != null) {
642 PropertyBuilder.SetSetMethod (method);
643 Parent.MemberCache.AddMember (this, method.Name, Set.Spec);
646 CheckMissingAccessor (kind, parameters, false);
649 Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
652 public override void Emit ()
654 CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
655 CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
657 if (OptAttributes != null)
658 OptAttributes.Emit ();
660 if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
661 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
662 } else if (member_type.HasDynamicElement) {
663 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
666 ConstraintChecker.Check (this, member_type, type_expr.Location);
669 if (AccessorSecond != null)
670 AccessorSecond.Emit (Parent);
675 public override bool IsUsed {
680 return Get.IsUsed | Set.IsUsed;
684 protected override void SetMemberName (MemberName new_name)
686 base.SetMemberName (new_name);
689 Get.UpdateName (this);
692 Set.UpdateName (this);
695 public override void WriteDebugSymbol (MonoSymbolFile file)
698 get.WriteDebugSymbol (file);
701 set.WriteDebugSymbol (file);
705 // Represents header string for documentation comment.
707 public override string DocCommentHeader {
712 public class Property : PropertyBase
714 public sealed class BackingField : Field
716 readonly Property property;
718 public BackingField (Property p)
719 : base (p.Parent, p.type_expr,
720 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
721 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
726 public Property OriginalProperty {
732 public override string GetSignatureForError ()
734 return property.GetSignatureForError ();
738 static readonly string[] attribute_target_auto = new string[] { "property", "field" };
742 public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
743 MemberName name, Attributes attrs)
744 : base (parent, type, mod,
745 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
746 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
747 AllowedModifiersClass,
752 public override void Accept (StructuralVisitor visitor)
754 visitor.Visit (this);
757 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
759 if (a.Target == AttributeTargets.Field) {
760 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
764 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
767 void CreateAutomaticProperty ()
769 // Create backing field
770 backing_field = new BackingField (this);
771 if (!backing_field.Define ())
774 Parent.PartialContainer.Members.Add (backing_field);
776 FieldExpr fe = new FieldExpr (backing_field, Location);
777 if ((backing_field.ModFlags & Modifiers.STATIC) == 0)
778 fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
781 // Create get block but we careful with location to
782 // emit only single sequence point per accessor. This allow
783 // to set a breakpoint on it even with no user code
785 Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
786 Return r = new Return (fe, Get.Location);
787 Get.Block.AddStatement (r);
790 Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
791 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
792 Set.Block.AddStatement (new StatementExpression (a, Set.Location));
795 public override bool Define ()
800 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
802 if (!IsInterface && (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
803 AccessorSecond != null && Get.Block == null && Set.Block == null) {
804 if (Compiler.Settings.Version <= LanguageVersion.ISO_2)
805 Report.FeatureIsNotAvailable (Compiler, Location, "automatically implemented properties");
807 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
808 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
809 CreateAutomaticProperty ();
812 if (!DefineAccessors ())
815 if (AccessorSecond == null) {
817 if (AccessorFirst is GetMethod)
818 pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
820 pm = new GetMethod (this, 0, null, Location);
822 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
828 DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
832 public override void Emit ()
834 if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
835 Report.Error (842, Location,
836 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
837 GetSignatureForError ());
843 public override string[] ValidAttributeTargets {
845 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
846 attribute_target_auto : base.ValidAttributeTargets;
852 /// For case when event is declared like property (with add and remove accessors).
854 public class EventProperty: Event {
855 public abstract class AEventPropertyAccessor : AEventAccessor
857 protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
858 : base (method, prefix, attrs, loc)
862 public override MethodBuilder Define (TypeContainer ds)
864 CheckAbstractAndExtern (block != null);
865 return base.Define (ds);
868 public override string GetSignatureForError ()
870 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
874 public sealed class AddDelegateMethod: AEventPropertyAccessor
876 public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
877 : base (method, AddPrefix, attrs, loc)
882 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
884 public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
885 : base (method, RemovePrefix, attrs, loc)
890 static readonly string[] attribute_targets = new string [] { "event" };
892 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
893 : base (parent, type, mod_flags, name, attrs)
897 public override void Accept (StructuralVisitor visitor)
899 visitor.Visit (this);
902 public override bool Define()
911 public override string[] ValidAttributeTargets {
913 return attribute_targets;
919 /// Event is declared like field.
921 public class EventField : Event
923 abstract class EventFieldAccessor : AEventAccessor
925 protected EventFieldAccessor (EventField method, string prefix)
926 : base (method, prefix, null, method.Location)
930 protected abstract MethodSpec GetOperation (Location loc);
932 public override void Emit (TypeDefinition parent)
934 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
935 block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
936 IsCompilerGenerated = true
938 FabricateBodyStatement ();
944 void FabricateBodyStatement ()
947 // Delegate obj1 = backing_field
949 // Delegate obj2 = obj1;
950 // obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
951 // } while ((object)obj1 != (object)obj2)
954 var field_info = ((EventField) method).backing_field;
955 FieldExpr f_expr = new FieldExpr (field_info, Location);
957 f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
959 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
960 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
962 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
964 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
965 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
966 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
968 var body = new ExplicitBlock (block, Location, Location);
969 block.AddStatement (new Do (body, cond, Location, Location));
971 body.AddStatement (new StatementExpression (
972 new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
974 var args_oper = new Arguments (2);
975 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
976 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
978 var op_method = GetOperation (Location);
980 var args = new Arguments (3);
981 args.Add (new Argument (f_expr, Argument.AType.Ref));
982 args.Add (new Argument (new Cast (
983 new TypeExpression (field_info.MemberType, Location),
984 new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
986 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
988 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
992 body.AddStatement (new StatementExpression (new SimpleAssign (
993 new LocalVariableReference (obj1, Location),
994 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
998 sealed class AddDelegateMethod: EventFieldAccessor
1000 public AddDelegateMethod (EventField method):
1001 base (method, AddPrefix)
1005 protected override MethodSpec GetOperation (Location loc)
1007 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1011 sealed class RemoveDelegateMethod: EventFieldAccessor
1013 public RemoveDelegateMethod (EventField method):
1014 base (method, RemovePrefix)
1018 protected override MethodSpec GetOperation (Location loc)
1020 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1025 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1026 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1028 Expression initializer;
1029 Field backing_field;
1030 List<FieldDeclarator> declarators;
1032 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1033 : base (parent, type, mod_flags, name, attrs)
1035 Add = new AddDelegateMethod (this);
1036 Remove = new RemoveDelegateMethod (this);
1041 public List<FieldDeclarator> Declarators {
1043 return this.declarators;
1047 bool HasBackingField {
1049 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1053 public Expression Initializer {
1058 initializer = value;
1062 public override string[] ValidAttributeTargets {
1064 return HasBackingField ? attribute_targets : attribute_targets_interface;
1071 public override void Accept (StructuralVisitor visitor)
1073 visitor.Visit (this);
1076 public void AddDeclarator (FieldDeclarator declarator)
1078 if (declarators == null)
1079 declarators = new List<FieldDeclarator> (2);
1081 declarators.Add (declarator);
1083 Parent.AddNameToContainer (this, declarator.Name.Value);
1086 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1088 if (a.Target == AttributeTargets.Field) {
1089 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1093 if (a.Target == AttributeTargets.Method) {
1094 int errors = Report.Errors;
1095 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1096 if (errors == Report.Errors)
1097 Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1101 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1104 public override bool Define()
1106 var mod_flags_src = ModFlags;
1108 if (!base.Define ())
1111 if (declarators != null) {
1112 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFER) != 0)
1113 mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFER);
1115 var t = new TypeExpression (MemberType, TypeExpression.Location);
1116 foreach (var d in declarators) {
1117 var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1119 if (d.Initializer != null)
1120 ef.initializer = d.Initializer;
1123 Parent.PartialContainer.Members.Add (ef);
1127 if (!HasBackingField) {
1132 if (Add.IsInterfaceImplementation)
1135 backing_field = new Field (Parent,
1136 new TypeExpression (MemberType, Location),
1137 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1140 Parent.PartialContainer.Members.Add (backing_field);
1141 backing_field.Initializer = Initializer;
1142 backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
1144 // Call define because we passed fields definition
1145 backing_field.Define ();
1147 // Set backing field for event fields
1148 spec.BackingField = backing_field.Spec;
1154 public abstract class Event : PropertyBasedMember
1156 public abstract class AEventAccessor : AbstractPropertyEventMethod
1158 protected readonly Event method;
1159 readonly ParametersCompiled parameters;
1161 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1163 public const string AddPrefix = "add_";
1164 public const string RemovePrefix = "remove_";
1166 protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1167 : base (method, prefix, attrs, loc)
1169 this.method = method;
1170 this.ModFlags = method.ModFlags;
1171 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1174 public bool IsInterfaceImplementation {
1175 get { return method_data.implementing != null; }
1178 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1180 if (a.Type == pa.MethodImpl) {
1181 method.is_external_implementation = a.IsInternalCall ();
1184 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1187 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1189 if (a.Target == AttributeTargets.Parameter) {
1190 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1194 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1197 public override AttributeTargets AttributeTargets {
1199 return AttributeTargets.Method;
1203 public override bool IsClsComplianceRequired ()
1205 return method.IsClsComplianceRequired ();
1208 public virtual MethodBuilder Define (TypeContainer parent)
1210 // Fill in already resolved event type to speed things up and
1211 // avoid confusing duplicate errors
1212 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1213 parameters.Types = new TypeSpec[] { method.member_type };
1215 method_data = new MethodData (method, method.ModFlags,
1216 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1218 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1221 method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
1223 if (Compiler.Settings.WriteMetadataOnly)
1226 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1227 Spec.IsAccessor = true;
1229 return method_data.MethodBuilder;
1232 public override TypeSpec ReturnType {
1234 return Parent.Compiler.BuiltinTypes.Void;
1238 public override ObsoleteAttribute GetAttributeObsolete ()
1240 return method.GetAttributeObsolete ();
1243 public override string[] ValidAttributeTargets {
1245 return attribute_targets;
1249 public override ParametersCompiled ParameterInfo {
1256 AEventAccessor add, remove;
1257 EventBuilder EventBuilder;
1258 protected EventSpec spec;
1260 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1261 : base (parent, type, mod_flags,
1262 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1263 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1264 AllowedModifiersClass,
1271 public override AttributeTargets AttributeTargets {
1273 return AttributeTargets.Event;
1277 public AEventAccessor Add {
1283 Parent.AddNameToContainer (value, value.MemberName.Basename);
1287 public override Variance ExpectedMemberTypeVariance {
1289 return Variance.Contravariant;
1293 public AEventAccessor Remove {
1299 Parent.AddNameToContainer (value, value.MemberName.Basename);
1304 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1306 if ((a.HasSecurityAttribute)) {
1307 a.Error_InvalidSecurityParent ();
1311 EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1314 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1316 var ok = base.CheckOverrideAgainstBase (base_member);
1318 if (!CheckAccessModifiers (this, base_member)) {
1319 Error_CannotChangeAccessModifiers (this, base_member);
1326 public override bool Define ()
1328 if (!base.Define ())
1331 if (!MemberType.IsDelegate) {
1332 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1339 // Now define the accessors
1341 var AddBuilder = Add.Define (Parent);
1342 if (AddBuilder == null)
1345 var RemoveBuilder = remove.Define (Parent);
1346 if (RemoveBuilder == null)
1349 EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1350 EventBuilder.SetAddOnMethod (AddBuilder);
1351 EventBuilder.SetRemoveOnMethod (RemoveBuilder);
1353 spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1355 Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1356 Parent.MemberCache.AddMember (this, AddBuilder.Name, Add.Spec);
1357 Parent.MemberCache.AddMember (this, RemoveBuilder.Name, remove.Spec);
1362 public override void Emit ()
1364 CheckReservedNameConflict (null, add.Spec);
1365 CheckReservedNameConflict (null, remove.Spec);
1367 if (OptAttributes != null) {
1368 OptAttributes.Emit ();
1371 ConstraintChecker.Check (this, member_type, type_expr.Location);
1374 Remove.Emit (Parent);
1379 public override void WriteDebugSymbol (MonoSymbolFile file)
1381 add.WriteDebugSymbol (file);
1382 remove.WriteDebugSymbol (file);
1386 // Represents header string for documentation comment.
1388 public override string DocCommentHeader {
1389 get { return "E:"; }
1393 public class EventSpec : MemberSpec, IInterfaceMemberSpec
1395 MethodSpec add, remove;
1396 FieldSpec backing_field;
1398 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1399 : base (MemberKind.Event, declaringType, definition, modifiers)
1401 this.AccessorAdd = add;
1402 this.AccessorRemove = remove;
1403 this.MemberType = eventType;
1408 public MethodSpec AccessorAdd {
1417 public MethodSpec AccessorRemove {
1426 public FieldSpec BackingField {
1428 return backing_field;
1431 backing_field = value;
1435 public TypeSpec MemberType { get; private set; }
1439 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1441 var es = (EventSpec) base.InflateMember (inflator);
1442 es.MemberType = inflator.Inflate (MemberType);
1444 if (backing_field != null)
1445 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1450 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1452 return MemberType.ResolveMissingDependencies (this);
1456 public class Indexer : PropertyBase, IParametersMember
1458 public class GetIndexerMethod : GetMethod, IParametersMember
1460 ParametersCompiled parameters;
1462 public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1463 : base (property, modifiers, attrs, loc)
1465 this.parameters = parameters;
1468 public override MethodBuilder Define (TypeContainer parent)
1470 // Disable reporting, parameters are resolved twice
1471 Report.DisableReporting ();
1473 parameters.Resolve (this);
1475 Report.EnableReporting ();
1478 return base.Define (parent);
1481 public override ParametersCompiled ParameterInfo {
1487 #region IParametersMember Members
1489 AParametersCollection IParametersMember.Parameters {
1495 TypeSpec IInterfaceMemberSpec.MemberType {
1504 public class SetIndexerMethod : SetMethod, IParametersMember
1506 public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1507 : base (property, modifiers, parameters, attrs, loc)
1511 #region IParametersMember Members
1513 AParametersCollection IParametersMember.Parameters {
1519 TypeSpec IInterfaceMemberSpec.MemberType {
1528 const Modifiers AllowedModifiers =
1531 Modifiers.PROTECTED |
1532 Modifiers.INTERNAL |
1536 Modifiers.OVERRIDE |
1541 const Modifiers AllowedInterfaceModifiers =
1544 readonly ParametersCompiled parameters;
1546 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1547 : base (parent, type, mod,
1548 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1551 this.parameters = parameters;
1556 AParametersCollection IParametersMember.Parameters {
1562 public ParametersCompiled ParameterInfo {
1571 public override void Accept (StructuralVisitor visitor)
1573 visitor.Visit (this);
1576 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1578 if (a.Type == pa.IndexerName) {
1579 // Attribute was copied to container
1583 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1586 protected override bool CheckForDuplications ()
1588 return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1591 public override bool Define ()
1593 if (!base.Define ())
1596 if (!DefineParameters (parameters))
1599 if (OptAttributes != null) {
1600 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1601 if (indexer_attr != null) {
1602 var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1603 if (compiling != null)
1604 compiling.Define ();
1606 if (IsExplicitImpl) {
1607 Report.Error (415, indexer_attr.Location,
1608 "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1609 indexer_attr.Type.GetSignatureForError ());
1610 } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1611 Report.Error (609, indexer_attr.Location,
1612 "Cannot set the `IndexerName' attribute on an indexer marked override");
1614 string name = indexer_attr.GetIndexerAttributeValue ();
1616 if (!string.IsNullOrEmpty (name)) {
1617 SetMemberName (new MemberName (MemberName.Left, name, Location));
1623 if (InterfaceType != null) {
1624 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1625 if (base_IndexerName != ShortName) {
1626 SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1630 Parent.AddNameToContainer (this, MemberName.Basename);
1632 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1634 if (!DefineAccessors ())
1640 DefineBuilders (MemberKind.Indexer, parameters);
1644 public override bool EnableOverloadChecks (MemberCore overload)
1646 if (overload is Indexer) {
1647 caching_flags |= Flags.MethodOverloadsExist;
1651 return base.EnableOverloadChecks (overload);
1654 public override void Emit ()
1656 parameters.CheckConstraints (this);
1661 public override string GetSignatureForError ()
1663 StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1664 if (MemberName.ExplicitInterface != null) {
1666 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1669 sb.Append (".this");
1670 sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1671 return sb.ToString ();
1674 public override string GetSignatureForDocumentation ()
1676 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1679 protected override bool VerifyClsCompliance ()
1681 if (!base.VerifyClsCompliance ())
1684 parameters.VerifyClsCompliance (this);
1689 public class IndexerSpec : PropertySpec, IParametersMember
1691 AParametersCollection parameters;
1693 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1694 : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1696 this.parameters = parameters;
1700 public AParametersCollection Parameters {
1707 public override string GetSignatureForDocumentation ()
1709 return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1712 public override string GetSignatureForError ()
1714 return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1717 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1719 var spec = (IndexerSpec) base.InflateMember (inflator);
1720 spec.parameters = parameters.Inflate (inflator);
1724 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1726 var missing = base.ResolveMissingDependencies (caller);
1728 foreach (var pt in parameters.Types) {
1729 var m = pt.GetMissingDependencies (caller);
1733 if (missing == null)
1734 missing = new List<MissingTypeSpecReference> ();
1736 missing.AddRange (m);