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 if (container.Kind == MemberKind.Interface)
341 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
342 GetSignatureForError ());
343 else if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
344 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
347 CheckModifiers (ModFlags);
348 ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
349 ModFlags |= Modifiers.PROPERTY_CUSTOM;
350 flags = ModifiersExtensions.MethodAttr (ModFlags);
351 flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
354 CheckAbstractAndExtern (block != null);
355 CheckProtectedModifier ();
358 if (block.IsIterator)
359 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
361 if (Compiler.Settings.WriteMetadataOnly)
366 public bool HasCustomAccessModifier {
368 return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
372 public PropertyBase Property {
378 public override ObsoleteAttribute GetAttributeObsolete ()
380 return method.GetAttributeObsolete ();
383 public override string GetSignatureForError()
385 return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
388 void CheckModifiers (Modifiers modflags)
390 if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
391 Report.Error (273, Location,
392 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
393 GetSignatureForError (), method.GetSignatureForError ());
398 PropertyMethod get, set, first;
399 PropertyBuilder PropertyBuilder;
401 protected PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
402 : base (parent, type, mod_flags, allowed_mod, name, attrs)
408 public override AttributeTargets AttributeTargets {
410 return AttributeTargets.Property;
414 public PropertyMethod AccessorFirst {
420 public PropertyMethod AccessorSecond {
422 return first == get ? set : get;
426 public override Variance ExpectedMemberTypeVariance {
428 return (get != null && set != null) ?
429 Variance.None : set == null ?
431 Variance.Contravariant;
435 public PropertyMethod Get {
444 Parent.AddNameToContainer (get, get.MemberName.Basename);
448 public PropertyMethod Set {
457 Parent.AddNameToContainer (set, set.MemberName.Basename);
461 public override string[] ValidAttributeTargets {
463 return attribute_targets;
469 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
471 if (a.HasSecurityAttribute) {
472 a.Error_InvalidSecurityParent ();
476 if (a.Type == pa.Dynamic) {
477 a.Error_MisusedDynamicAttribute ();
481 PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
484 void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
486 if (IsExplicitImpl) {
488 if (kind == MemberKind.Indexer)
489 filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
491 filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
493 var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
495 if (implementing == null)
498 var accessor = get ? implementing.Get : implementing.Set;
499 if (accessor != null) {
500 Report.SymbolRelatedToPreviousError (accessor);
501 Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
502 GetSignatureForError (), accessor.GetSignatureForError ());
507 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
509 var ok = base.CheckOverrideAgainstBase (base_member);
512 // Check base property accessors conflict
514 var base_prop = (PropertySpec) base_member;
516 if (!base_prop.HasGet) {
518 Report.SymbolRelatedToPreviousError (base_prop);
519 Report.Error (545, Get.Location,
520 "`{0}': cannot override because `{1}' does not have an overridable get accessor",
521 Get.GetSignatureForError (), base_prop.GetSignatureForError ());
524 } else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
525 if (!CheckAccessModifiers (Get, base_prop.Get)) {
526 Error_CannotChangeAccessModifiers (Get, base_prop.Get);
533 if (!base_prop.HasSet) {
535 Report.SymbolRelatedToPreviousError (base_prop);
536 Report.Error (546, Set.Location,
537 "`{0}': cannot override because `{1}' does not have an overridable set accessor",
538 Set.GetSignatureForError (), base_prop.GetSignatureForError ());
541 } else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
542 if (!CheckAccessModifiers (Set, base_prop.Set)) {
543 Error_CannotChangeAccessModifiers (Set, base_prop.Set);
549 if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
550 if (!CheckAccessModifiers (this, base_prop)) {
551 Error_CannotChangeAccessModifiers (this, base_prop);
559 protected override void DoMemberTypeDependentChecks ()
561 base.DoMemberTypeDependentChecks ();
565 if (MemberType.IsStatic)
566 Error_StaticReturnType ();
569 protected override void DoMemberTypeIndependentChecks ()
571 base.DoMemberTypeIndependentChecks ();
574 // Accessors modifiers check
576 if (AccessorSecond != null) {
577 if ((Get.ModFlags & Modifiers.AccessibilityMask) != 0 && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) {
578 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
579 GetSignatureForError ());
581 } else if ((ModFlags & Modifiers.OVERRIDE) == 0 &&
582 (Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) ||
583 (Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0)) {
584 Report.Error (276, Location,
585 "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
586 GetSignatureForError ());
590 protected bool DefineAccessors ()
592 first.Define (Parent);
593 if (AccessorSecond != null)
594 AccessorSecond.Define (Parent);
599 protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
601 PropertyBuilder = Parent.TypeBuilder.DefineProperty (
602 GetFullName (MemberName), PropertyAttributes.None,
603 #if !BOOTSTRAP_BASIC // Requires trunk version mscorlib
604 IsStatic ? 0 : CallingConventions.HasThis,
606 MemberType.GetMetaInfo (), null, null,
607 parameters.GetMetaInfo (), null, null);
610 if (kind == MemberKind.Indexer)
611 spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
613 spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
617 Parent.MemberCache.AddMember (this, Get.Spec.Name, Get.Spec);
619 CheckMissingAccessor (kind, parameters, true);
624 Parent.MemberCache.AddMember (this, Set.Spec.Name, Set.Spec);
626 CheckMissingAccessor (kind, parameters, false);
629 Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
632 public override void Emit ()
634 CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
635 CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
637 if (OptAttributes != null)
638 OptAttributes.Emit ();
640 if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
641 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
642 } else if (member_type.HasDynamicElement) {
643 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
646 ConstraintChecker.Check (this, member_type, type_expr.Location);
649 if (AccessorSecond != null)
650 AccessorSecond.Emit (Parent);
655 public override bool IsUsed {
660 return Get.IsUsed | Set.IsUsed;
664 public override void PrepareEmit ()
666 AccessorFirst.PrepareEmit ();
667 if (AccessorSecond != null)
668 AccessorSecond.PrepareEmit ();
671 var method = Get.Spec.GetMetaInfo () as MethodBuilder;
673 PropertyBuilder.SetGetMethod (method);
677 var method = Set.Spec.GetMetaInfo () as MethodBuilder;
679 PropertyBuilder.SetSetMethod (method);
683 protected override void SetMemberName (MemberName new_name)
685 base.SetMemberName (new_name);
688 Get.UpdateName (this);
691 Set.UpdateName (this);
694 public override void WriteDebugSymbol (MonoSymbolFile file)
697 get.WriteDebugSymbol (file);
700 set.WriteDebugSymbol (file);
704 // Represents header string for documentation comment.
706 public override string DocCommentHeader {
711 public class Property : PropertyBase
713 public sealed class BackingField : Field
715 readonly Property property;
717 public BackingField (Property p)
718 : base (p.Parent, p.type_expr,
719 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
720 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
725 public Property OriginalProperty {
731 public override string GetSignatureForError ()
733 return property.GetSignatureForError ();
737 static readonly string[] attribute_target_auto = new string[] { "property", "field" };
741 public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
742 MemberName name, Attributes attrs)
743 : base (parent, type, mod,
744 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
745 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
746 AllowedModifiersClass,
751 public override void Accept (StructuralVisitor visitor)
753 visitor.Visit (this);
756 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
758 if (a.Target == AttributeTargets.Field) {
759 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
763 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
766 void CreateAutomaticProperty ()
768 // Create backing field
769 backing_field = new BackingField (this);
770 if (!backing_field.Define ())
773 Parent.PartialContainer.Members.Add (backing_field);
775 FieldExpr fe = new FieldExpr (backing_field, Location);
776 if ((backing_field.ModFlags & Modifiers.STATIC) == 0)
777 fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
780 // Create get block but we careful with location to
781 // emit only single sequence point per accessor. This allow
782 // to set a breakpoint on it even with no user code
784 Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
785 Return r = new Return (fe, Get.Location);
786 Get.Block.AddStatement (r);
789 Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
790 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
791 Set.Block.AddStatement (new StatementExpression (a, Set.Location));
794 public override bool Define ()
799 flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
801 if (!IsInterface && (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
802 AccessorSecond != null && Get.Block == null && Set.Block == null) {
803 if (Compiler.Settings.Version <= LanguageVersion.ISO_2)
804 Report.FeatureIsNotAvailable (Compiler, Location, "automatically implemented properties");
806 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
807 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
808 CreateAutomaticProperty ();
811 if (!DefineAccessors ())
814 if (AccessorSecond == null) {
816 if (AccessorFirst is GetMethod)
817 pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
819 pm = new GetMethod (this, 0, null, Location);
821 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
827 DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
831 public override void Emit ()
833 if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
834 Report.Error (842, Location,
835 "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
836 GetSignatureForError ());
842 public override string[] ValidAttributeTargets {
844 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
845 attribute_target_auto : base.ValidAttributeTargets;
851 /// For case when event is declared like property (with add and remove accessors).
853 public class EventProperty: Event {
854 public abstract class AEventPropertyAccessor : AEventAccessor
856 protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
857 : base (method, prefix, attrs, loc)
861 public override void Define (TypeContainer ds)
863 CheckAbstractAndExtern (block != null);
867 public override string GetSignatureForError ()
869 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
873 public sealed class AddDelegateMethod: AEventPropertyAccessor
875 public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
876 : base (method, AddPrefix, attrs, loc)
881 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
883 public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
884 : base (method, RemovePrefix, attrs, loc)
889 static readonly string[] attribute_targets = new string [] { "event" };
891 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
892 : base (parent, type, mod_flags, name, attrs)
896 public override void Accept (StructuralVisitor visitor)
898 visitor.Visit (this);
901 public override bool Define()
910 public override string[] ValidAttributeTargets {
912 return attribute_targets;
918 /// Event is declared like field.
920 public class EventField : Event
922 abstract class EventFieldAccessor : AEventAccessor
924 protected EventFieldAccessor (EventField method, string prefix)
925 : base (method, prefix, null, method.Location)
929 protected abstract MethodSpec GetOperation (Location loc);
931 public override void Emit (TypeDefinition parent)
933 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
934 block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
935 IsCompilerGenerated = true
937 FabricateBodyStatement ();
943 void FabricateBodyStatement ()
946 // Delegate obj1 = backing_field
948 // Delegate obj2 = obj1;
949 // obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
950 // } while ((object)obj1 != (object)obj2)
953 var field_info = ((EventField) method).backing_field;
954 FieldExpr f_expr = new FieldExpr (field_info, Location);
956 f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
958 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
959 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
961 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
963 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
964 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
965 new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
967 var body = new ExplicitBlock (block, Location, Location);
968 block.AddStatement (new Do (body, cond, Location, Location));
970 body.AddStatement (new StatementExpression (
971 new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
973 var args_oper = new Arguments (2);
974 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
975 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
977 var op_method = GetOperation (Location);
979 var args = new Arguments (3);
980 args.Add (new Argument (f_expr, Argument.AType.Ref));
981 args.Add (new Argument (new Cast (
982 new TypeExpression (field_info.MemberType, Location),
983 new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
985 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
987 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
991 body.AddStatement (new StatementExpression (new SimpleAssign (
992 new LocalVariableReference (obj1, Location),
993 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
997 sealed class AddDelegateMethod: EventFieldAccessor
999 public AddDelegateMethod (EventField method):
1000 base (method, AddPrefix)
1004 protected override MethodSpec GetOperation (Location loc)
1006 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1010 sealed class RemoveDelegateMethod: EventFieldAccessor
1012 public RemoveDelegateMethod (EventField method):
1013 base (method, RemovePrefix)
1017 protected override MethodSpec GetOperation (Location loc)
1019 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1024 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1025 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1027 Expression initializer;
1028 Field backing_field;
1029 List<FieldDeclarator> declarators;
1031 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1032 : base (parent, type, mod_flags, name, attrs)
1034 Add = new AddDelegateMethod (this);
1035 Remove = new RemoveDelegateMethod (this);
1040 public List<FieldDeclarator> Declarators {
1042 return this.declarators;
1046 bool HasBackingField {
1048 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1052 public Expression Initializer {
1057 initializer = value;
1061 public override string[] ValidAttributeTargets {
1063 return HasBackingField ? attribute_targets : attribute_targets_interface;
1070 public override void Accept (StructuralVisitor visitor)
1072 visitor.Visit (this);
1075 public void AddDeclarator (FieldDeclarator declarator)
1077 if (declarators == null)
1078 declarators = new List<FieldDeclarator> (2);
1080 declarators.Add (declarator);
1082 Parent.AddNameToContainer (this, declarator.Name.Value);
1085 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1087 if (a.Target == AttributeTargets.Field) {
1088 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1092 if (a.Target == AttributeTargets.Method) {
1093 int errors = Report.Errors;
1094 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1095 if (errors == Report.Errors)
1096 Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1100 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1103 public override bool Define()
1105 var mod_flags_src = ModFlags;
1107 if (!base.Define ())
1110 if (declarators != null) {
1111 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1112 mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1114 var t = new TypeExpression (MemberType, TypeExpression.Location);
1115 foreach (var d in declarators) {
1116 var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1118 if (d.Initializer != null)
1119 ef.initializer = d.Initializer;
1122 Parent.PartialContainer.Members.Add (ef);
1126 if (!HasBackingField) {
1131 backing_field = new Field (Parent,
1132 new TypeExpression (MemberType, Location),
1133 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1136 Parent.PartialContainer.Members.Add (backing_field);
1137 backing_field.Initializer = Initializer;
1138 backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
1140 // Call define because we passed fields definition
1141 backing_field.Define ();
1143 // Set backing field for event fields
1144 spec.BackingField = backing_field.Spec;
1150 public abstract class Event : PropertyBasedMember
1152 public abstract class AEventAccessor : AbstractPropertyEventMethod
1154 protected readonly Event method;
1155 readonly ParametersCompiled parameters;
1157 static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1159 public const string AddPrefix = "add_";
1160 public const string RemovePrefix = "remove_";
1162 protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1163 : base (method, prefix, attrs, loc)
1165 this.method = method;
1166 this.ModFlags = method.ModFlags;
1167 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1170 public bool IsInterfaceImplementation {
1171 get { return method_data.implementing != null; }
1174 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1176 if (a.Type == pa.MethodImpl) {
1177 method.is_external_implementation = a.IsInternalCall ();
1180 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1183 protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1185 if (a.Target == AttributeTargets.Parameter) {
1186 parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1190 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1193 public override AttributeTargets AttributeTargets {
1195 return AttributeTargets.Method;
1199 public override bool IsClsComplianceRequired ()
1201 return method.IsClsComplianceRequired ();
1204 public virtual void Define (TypeContainer parent)
1206 // Fill in already resolved event type to speed things up and
1207 // avoid confusing duplicate errors
1208 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1209 parameters.Types = new TypeSpec[] { method.member_type };
1211 method_data = new MethodData (method, method.ModFlags,
1212 method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1214 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1217 if (Compiler.Settings.WriteMetadataOnly)
1220 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1221 Spec.IsAccessor = true;
1224 public override TypeSpec ReturnType {
1226 return Parent.Compiler.BuiltinTypes.Void;
1230 public override ObsoleteAttribute GetAttributeObsolete ()
1232 return method.GetAttributeObsolete ();
1235 public MethodData MethodData {
1241 public override string[] ValidAttributeTargets {
1243 return attribute_targets;
1247 public override ParametersCompiled ParameterInfo {
1254 AEventAccessor add, remove;
1255 EventBuilder EventBuilder;
1256 protected EventSpec spec;
1258 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1259 : base (parent, type, mod_flags,
1260 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1261 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1262 AllowedModifiersClass,
1269 public override AttributeTargets AttributeTargets {
1271 return AttributeTargets.Event;
1275 public AEventAccessor Add {
1281 Parent.AddNameToContainer (value, value.MemberName.Basename);
1285 public override Variance ExpectedMemberTypeVariance {
1287 return Variance.Contravariant;
1291 public AEventAccessor Remove {
1297 Parent.AddNameToContainer (value, value.MemberName.Basename);
1302 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1304 if ((a.HasSecurityAttribute)) {
1305 a.Error_InvalidSecurityParent ();
1309 EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1312 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1314 var ok = base.CheckOverrideAgainstBase (base_member);
1316 if (!CheckAccessModifiers (this, base_member)) {
1317 Error_CannotChangeAccessModifiers (this, base_member);
1324 public override bool Define ()
1326 if (!base.Define ())
1329 if (!MemberType.IsDelegate) {
1330 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1337 // Now define the accessors
1339 add.Define (Parent);
1340 remove.Define (Parent);
1342 EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1344 spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1346 Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1347 Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1348 Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1353 public override void Emit ()
1355 CheckReservedNameConflict (null, add.Spec);
1356 CheckReservedNameConflict (null, remove.Spec);
1358 if (OptAttributes != null) {
1359 OptAttributes.Emit ();
1362 ConstraintChecker.Check (this, member_type, type_expr.Location);
1365 Remove.Emit (Parent);
1370 public override void PrepareEmit ()
1373 remove.PrepareEmit ();
1375 EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1376 EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
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 void Define (TypeContainer parent)
1470 // Disable reporting, parameters are resolved twice
1471 Report.DisableReporting ();
1473 parameters.Resolve (this);
1475 Report.EnableReporting ();
1478 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);