1dd8a86468eb1ab0f2727a649f67d3273ed6d8cd
[mono.git] / mcs / mcs / property.cs
1 //
2 // property.cs: Property based handlers
3 //
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 //          Martin Baulig (martin@ximian.com)
6 //          Marek Safar (marek.safar@seznam.cz)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin Inc
13 //
14
15 using System;
16 using System.Collections.Generic;
17 using System.Text;
18 using Mono.CompilerServices.SymbolWriter;
19
20 #if MOBILE
21 using XmlElement = System.Object;
22 #endif
23
24 #if STATIC
25 using IKVM.Reflection;
26 using IKVM.Reflection.Emit;
27 #else
28 using System.Reflection;
29 using System.Reflection.Emit;
30 #endif
31
32 namespace Mono.CSharp
33 {
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
37         {
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)
40                 {
41                 }
42
43                 protected void CheckReservedNameConflict (string prefix, MethodSpec accessor)
44                 {
45                         string name;
46                         AParametersCollection parameters;
47                         if (accessor != null) {
48                                 name = accessor.Name;
49                                 parameters = accessor.Parameters;
50                         } else {
51                                 name = prefix + ShortName;
52                                 if (IsExplicitImpl)
53                                         name = MemberName.Left + "." + name;
54
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;
64
65                                                 parameters = new ParametersImported (data, types, false);
66                                         }
67                                 } else {
68                                         if (prefix[0] == 's')
69                                                 parameters = ParametersCompiled.CreateFullyResolved (new[] { member_type });
70                                         else
71                                                 parameters = ParametersCompiled.EmptyReadOnlyParameters;
72                                 }
73                         }
74
75                         var conflict = MemberCache.FindMember (Parent.Definition,
76                                 new MemberFilter (name, 0, MemberKind.Method, parameters, null),
77                                 BindingRestriction.DeclaredOnly | BindingRestriction.NoAccessors);
78
79                         if (conflict != null) {
80                                 Report.SymbolRelatedToPreviousError (conflict);
81                                 Report.Error (82, Location, "A member `{0}' is already reserved", conflict.GetSignatureForError ());
82                         }
83                 }
84
85                 protected override bool VerifyClsCompliance ()
86                 {
87                         if (!base.VerifyClsCompliance ())
88                                 return false;
89
90                         if (!MemberType.IsCLSCompliant ()) {
91                                 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
92                                         GetSignatureForError ());
93                         }
94                         return true;
95                 }
96
97         }
98
99         public class PropertySpec : MemberSpec, IInterfaceMemberSpec
100         {
101                 PropertyInfo info;
102                 TypeSpec memberType;
103                 MethodSpec set, get;
104
105                 public PropertySpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, PropertyInfo info, Modifiers modifiers)
106                         : base (kind, declaringType, definition, modifiers)
107                 {
108                         this.info = info;
109                         this.memberType = memberType;
110                 }
111
112                 #region Properties
113
114                 public MethodSpec Get {
115                         get {
116                                 return get;
117                         }
118                         set {
119                                 get = value;
120                                 get.IsAccessor = true;
121                         }
122                 }
123
124                 public MethodSpec Set { 
125                         get {
126                                 return set;
127                         }
128                         set {
129                                 set = value;
130                                 set.IsAccessor = true;
131                         }
132                 }
133
134                 public bool HasDifferentAccessibility {
135                         get {
136                                 return HasGet && HasSet && 
137                                         (Get.Modifiers & Modifiers.AccessibilityMask) != (Set.Modifiers & Modifiers.AccessibilityMask);
138                         }
139                 }
140
141                 public bool HasGet {
142                         get {
143                                 return Get != null;
144                         }
145                 }
146
147                 public bool HasSet {
148                         get {
149                                 return Set != null;
150                         }
151                 }
152
153                 public PropertyInfo MetaInfo {
154                         get {
155                                 if ((state & StateFlags.PendingMetaInflate) != 0)
156                                         throw new NotSupportedException ();
157
158                                 return info;
159                         }
160                 }
161
162                 public TypeSpec MemberType {
163                         get {
164                                 return memberType;
165                         }
166                 }
167
168                 #endregion
169
170                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
171                 {
172                         var ps = (PropertySpec) base.InflateMember (inflator);
173                         ps.memberType = inflator.Inflate (memberType);
174                         return ps;
175                 }
176
177                 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
178                 {
179                         return memberType.ResolveMissingDependencies (this);
180                 }
181         }
182
183         //
184         // Properties and Indexers both generate PropertyBuilders, we use this to share 
185         // their common bits.
186         //
187         abstract public class PropertyBase : PropertyBasedMember {
188
189                 public class GetMethod : PropertyMethod
190                 {
191                         static readonly string[] attribute_targets = new string [] { "method", "return" };
192
193                         internal const string Prefix = "get_";
194
195                         public GetMethod (PropertyBase method, Modifiers modifiers, Attributes attrs, Location loc)
196                                 : base (method, Prefix, modifiers, attrs, loc)
197                         {
198                         }
199
200                         public override void Define (TypeContainer parent)
201                         {
202                                 base.Define (parent);
203
204                                 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
205
206                                 method_data = new MethodData (method, ModFlags, flags, this);
207
208                                 method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
209                         }
210
211                         public override TypeSpec ReturnType {
212                                 get {
213                                         return method.MemberType;
214                                 }
215                         }
216
217                         public override ParametersCompiled ParameterInfo {
218                                 get {
219                                         return ParametersCompiled.EmptyReadOnlyParameters;
220                                 }
221                         }
222
223                         public override string[] ValidAttributeTargets {
224                                 get {
225                                         return attribute_targets;
226                                 }
227                         }
228                 }
229
230                 public class SetMethod : PropertyMethod {
231
232                         static readonly string[] attribute_targets = new string[] { "method", "param", "return" };
233
234                         internal const string Prefix = "set_";
235
236                         protected ParametersCompiled parameters;
237
238                         public SetMethod (PropertyBase method, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
239                                 : base (method, Prefix, modifiers, attrs, loc)
240                         {
241                                 this.parameters = parameters;
242                         }
243
244                         protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
245                         {
246                                 if (a.Target == AttributeTargets.Parameter) {
247                                         parameters[parameters.Count - 1].ApplyAttributeBuilder (a, ctor, cdata, pa);
248                                         return;
249                                 }
250
251                                 base.ApplyToExtraTarget (a, ctor, cdata, pa);
252                         }
253
254                         public override ParametersCompiled ParameterInfo {
255                             get {
256                                 return parameters;
257                             }
258                         }
259
260                         public override void Define (TypeContainer parent)
261                         {
262                                 parameters.Resolve (this);
263                                 
264                                 base.Define (parent);
265
266                                 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
267
268                                 method_data = new MethodData (method, ModFlags, flags, this);
269
270                                 method_data.Define (parent.PartialContainer, method.GetFullName (MemberName));
271                         }
272
273                         public override TypeSpec ReturnType {
274                                 get {
275                                         return Parent.Compiler.BuiltinTypes.Void;
276                                 }
277                         }
278
279                         public override string[] ValidAttributeTargets {
280                                 get {
281                                         return attribute_targets;
282                                 }
283                         }
284                 }
285
286                 static readonly string[] attribute_targets = new string[] { "property" };
287
288                 public abstract class PropertyMethod : AbstractPropertyEventMethod
289                 {
290                         const Modifiers AllowedModifiers =
291                                 Modifiers.PUBLIC |
292                                 Modifiers.PROTECTED |
293                                 Modifiers.INTERNAL |
294                                 Modifiers.PRIVATE;
295                 
296                         protected readonly PropertyBase method;
297                         protected MethodAttributes flags;
298
299                         public PropertyMethod (PropertyBase method, string prefix, Modifiers modifiers, Attributes attrs, Location loc)
300                                 : base (method, prefix, attrs, loc)
301                         {
302                                 this.method = method;
303                                 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, modifiers, 0, loc, Report);
304                                 this.ModFlags |= (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
305                         }
306
307                         public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
308                         {
309                                 if (a.Type == pa.MethodImpl) {
310                                         method.is_external_implementation = a.IsInternalCall ();
311                                 }
312
313                                 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
314                         }
315
316                         public override AttributeTargets AttributeTargets {
317                                 get {
318                                         return AttributeTargets.Method;
319                                 }
320                         }
321
322                         public override bool IsClsComplianceRequired ()
323                         {
324                                 return method.IsClsComplianceRequired ();
325                         }
326
327                         public virtual void Define (TypeContainer parent)
328                         {
329                                 var container = parent.PartialContainer;
330
331                                 //
332                                 // Check for custom access modifier
333                                 //
334                                 if ((ModFlags & Modifiers.AccessibilityMask) == 0) {
335                                         ModFlags |= method.ModFlags;
336                                         flags = method.flags;
337                                 } else {
338                                         CheckModifiers (ModFlags);
339                                         ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
340                                         ModFlags |= Modifiers.PROPERTY_CUSTOM;
341
342                                         if (container.Kind == MemberKind.Interface) {
343                                                 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
344                                                         GetSignatureForError ());
345                                         } else if ((ModFlags & Modifiers.PRIVATE) != 0) {
346                                                 if ((method.ModFlags & Modifiers.ABSTRACT) != 0) {
347                                                         Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
348                                                 }
349
350                                                 ModFlags &= ~Modifiers.VIRTUAL;
351                                         }
352
353                                         flags = ModifiersExtensions.MethodAttr (ModFlags) | MethodAttributes.SpecialName;
354                                 }
355
356                                 CheckAbstractAndExtern (block != null);
357                                 CheckProtectedModifier ();
358
359                                 if (block != null) {
360                                         if (block.IsIterator)
361                                                 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
362
363                                         if (Compiler.Settings.WriteMetadataOnly)
364                                                 block = null;
365                                 }
366                         }
367
368                         public bool HasCustomAccessModifier {
369                                 get {
370                                         return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
371                                 }
372                         }
373
374                         public PropertyBase Property {
375                                 get {
376                                         return method;
377                                 }
378                         }
379
380                         public override ObsoleteAttribute GetAttributeObsolete ()
381                         {
382                                 return method.GetAttributeObsolete ();
383                         }
384
385                         public override string GetSignatureForError()
386                         {
387                                 return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
388                         }
389
390                         void CheckModifiers (Modifiers modflags)
391                         {
392                                 if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
393                                         Report.Error (273, Location,
394                                                 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
395                                                 GetSignatureForError (), method.GetSignatureForError ());
396                                 }
397                         }
398                 }
399
400                 PropertyMethod get, set, first;
401                 PropertyBuilder PropertyBuilder;
402
403                 protected PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
404                         : base (parent, type, mod_flags, allowed_mod, name, attrs)
405                 {
406                 }
407
408                 #region Properties
409
410                 public override AttributeTargets AttributeTargets {
411                         get {
412                                 return AttributeTargets.Property;
413                         }
414                 }
415
416                 public PropertyMethod AccessorFirst {
417                         get {
418                                 return first;
419                         }
420                 }
421
422                 public PropertyMethod AccessorSecond {
423                         get {
424                                 return first == get ? set : get;
425                         }
426                 }
427
428                 public override Variance ExpectedMemberTypeVariance {
429                         get {
430                                 return (get != null && set != null) ?
431                                         Variance.None : set == null ?
432                                         Variance.Covariant :
433                                         Variance.Contravariant;
434                         }
435                 }
436
437                 public PropertyMethod Get {
438                         get {
439                                 return get;
440                         }
441                         set {
442                                 get = value;
443                                 if (first == null)
444                                         first = value;
445
446                                 Parent.AddNameToContainer (get, get.MemberName.Basename);
447                         }
448                 }
449
450                 public PropertyMethod Set {
451                         get {
452                                 return set;
453                         }
454                         set {
455                                 set = value;
456                                 if (first == null)
457                                         first = value;
458
459                                 Parent.AddNameToContainer (set, set.MemberName.Basename);
460                         }
461                 }
462
463                 public override string[] ValidAttributeTargets {
464                         get {
465                                 return attribute_targets;
466                         }
467                 }
468
469                 #endregion
470
471                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
472                 {
473                         if (a.HasSecurityAttribute) {
474                                 a.Error_InvalidSecurityParent ();
475                                 return;
476                         }
477
478                         if (a.Type == pa.Dynamic) {
479                                 a.Error_MisusedDynamicAttribute ();
480                                 return;
481                         }
482
483                         PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
484                 }
485
486                 void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
487                 {
488                         if (IsExplicitImpl) {
489                                 MemberFilter filter;
490                                 if (kind == MemberKind.Indexer)
491                                         filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
492                                 else
493                                         filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
494
495                                 var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
496
497                                 if (implementing == null)
498                                         return;
499
500                                 var accessor = get ? implementing.Get : implementing.Set;
501                                 if (accessor != null) {
502                                         Report.SymbolRelatedToPreviousError (accessor);
503                                         Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
504                                                 GetSignatureForError (), accessor.GetSignatureForError ());
505                                 }
506                         }
507                 }
508
509                 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
510                 {
511                         var ok = base.CheckOverrideAgainstBase (base_member);
512
513                         //
514                         // Check base property accessors conflict
515                         //
516                         var base_prop = (PropertySpec) base_member;
517                         if (Get == null) {
518                                 if ((ModFlags & Modifiers.SEALED) != 0 && base_prop.HasGet && !base_prop.Get.IsAccessible (this)) {
519                                         // TODO: Should be different error code but csc uses for some reason same
520                                         Report.SymbolRelatedToPreviousError (base_prop);
521                                         Report.Error (545, Location,
522                                                 "`{0}': cannot override because `{1}' does not have accessible get accessor",
523                                                 GetSignatureForError (), base_prop.GetSignatureForError ());
524                                         ok = false;
525                                 }
526                         } else {
527                                 if (!base_prop.HasGet) {
528                                         if (ok) {
529                                                 Report.SymbolRelatedToPreviousError (base_prop);
530                                                 Report.Error (545, Get.Location,
531                                                         "`{0}': cannot override because `{1}' does not have an overridable get accessor",
532                                                         Get.GetSignatureForError (), base_prop.GetSignatureForError ());
533                                                 ok = false;
534                                         }
535                                 } else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
536                                         if (!base_prop.Get.IsAccessible (this)) {
537                                                 // Same as csc but it should be different error code
538                                                 Report.Error (115, Get.Location, "`{0}' is marked as an override but no accessible `get' accessor found to override",
539                                                         GetSignatureForError ());
540                                                 ok = false;
541                                         } else if (!CheckAccessModifiers (Get, base_prop.Get)) {
542                                                 Error_CannotChangeAccessModifiers (Get, base_prop.Get);
543                                                 ok = false;
544                                         }
545                                 }
546                         }
547
548                         if (Set == null) {
549                                 if (base_prop.HasSet) {
550                                         if ((ModFlags & Modifiers.SEALED) != 0 && !base_prop.Set.IsAccessible (this)) {
551                                                 // TODO: Should be different error code but csc uses for some reason same
552                                                 Report.SymbolRelatedToPreviousError (base_prop);
553                                                 Report.Error (546, Location,
554                                                         "`{0}': cannot override because `{1}' does not have accessible set accessor",
555                                                         GetSignatureForError (), base_prop.GetSignatureForError ());
556                                                 ok = false;
557                                         }
558
559                                         if ((ModFlags & Modifiers.AutoProperty) != 0) {
560                                                 Report.Error (8080, Location, "`{0}': Auto-implemented properties must override all accessors of the overridden property",
561                                                         GetSignatureForError ());
562                                                 ok = false;
563                                         }
564                                 }
565                         } else {
566                                 if (!base_prop.HasSet) {
567                                         if (ok) {
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 ());
572                                                 ok = false;
573                                         }
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 ());
579                                                 ok = false;
580                                         } else if (!CheckAccessModifiers (Set, base_prop.Set)) {
581                                                 Error_CannotChangeAccessModifiers (Set, base_prop.Set);
582                                                 ok = false;
583                                         }
584                                 }
585                         }
586
587                         if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
588                                 if (!CheckAccessModifiers (this, base_prop)) {
589                                         Error_CannotChangeAccessModifiers (this, base_prop);
590                                         ok = false;
591                                 }
592                         }
593
594                         return ok;
595                 }
596
597                 protected override void DoMemberTypeDependentChecks ()
598                 {
599                         base.DoMemberTypeDependentChecks ();
600
601                         IsTypePermitted ();
602
603                         if (MemberType.IsStatic)
604                                 Error_StaticReturnType ();
605                 }
606
607                 protected override void DoMemberTypeIndependentChecks ()
608                 {
609                         base.DoMemberTypeIndependentChecks ();
610
611                         //
612                         // Accessors modifiers check
613                         //
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 ());
618                                 }
619                         } else if ((ModFlags & Modifiers.OVERRIDE) == 0 && 
620                                 ((Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) || (Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0))) {
621                                 Report.Error (276, Location, 
622                                               "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
623                                               GetSignatureForError ());
624                         }
625                 }
626
627                 protected bool DefineAccessors ()
628                 {
629                         first.Define (Parent);
630                         if (AccessorSecond != null)
631                                 AccessorSecond.Define (Parent);
632
633                         return true;
634                 }
635
636                 protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
637                 {
638                         PropertyBuilder = Parent.TypeBuilder.DefineProperty (
639                                 GetFullName (MemberName), PropertyAttributes.None,
640 #if !BOOTSTRAP_BASIC    // Requires trunk version mscorlib
641                                 IsStatic ? 0 : CallingConventions.HasThis,
642 #endif
643                                 MemberType.GetMetaInfo (), null, null,
644                                 parameters.GetMetaInfo (), null, null);
645
646                         PropertySpec spec;
647                         if (kind == MemberKind.Indexer)
648                                 spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
649                         else
650                                 spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
651
652                         if (Get != null) {
653                                 spec.Get = Get.Spec;
654                                 Parent.MemberCache.AddMember (this, Get.Spec.Name, Get.Spec);
655                         } else {
656                                 CheckMissingAccessor (kind, parameters, true);
657                         }
658
659                         if (Set != null) {
660                                 spec.Set = Set.Spec;
661                                 Parent.MemberCache.AddMember (this, Set.Spec.Name, Set.Spec);
662                         } else {
663                                 CheckMissingAccessor (kind, parameters, false);
664                         }
665
666                         Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
667                 }
668
669                 public override void Emit ()
670                 {
671                         CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
672                         CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
673
674                         if (OptAttributes != null)
675                                 OptAttributes.Emit ();
676
677                         if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
678                                 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
679                         } else if (member_type.HasDynamicElement) {
680                                 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
681                         }
682
683                         if (member_type.HasNamedTupleElement) {
684                                 Module.PredefinedAttributes.TupleElementNames.EmitAttribute (PropertyBuilder, member_type, Location);
685                         }
686
687                         ConstraintChecker.Check (this, member_type, type_expr.Location);
688
689                         first.Emit (Parent);
690                         if (AccessorSecond != null)
691                                 AccessorSecond.Emit (Parent);
692
693                         base.Emit ();
694                 }
695
696                 public override bool IsUsed {
697                         get {
698                                 if (IsExplicitImpl)
699                                         return true;
700
701                                 return Get.IsUsed | Set.IsUsed;
702                         }
703                 }
704
705                 public override void PrepareEmit ()
706                 {
707                         AccessorFirst.PrepareEmit ();
708                         if (AccessorSecond != null)
709                                 AccessorSecond.PrepareEmit ();
710
711                         if (get != null) {
712                                 var method = Get.Spec.GetMetaInfo () as MethodBuilder;
713                                 if (method != null)
714                                         PropertyBuilder.SetGetMethod (method);
715                         }
716
717                         if (set != null) {
718                                 var method = Set.Spec.GetMetaInfo () as MethodBuilder;
719                                 if (method != null)
720                                         PropertyBuilder.SetSetMethod (method);
721                         }
722                 }
723
724                 protected override void SetMemberName (MemberName new_name)
725                 {
726                         base.SetMemberName (new_name);
727
728                         if (Get != null)
729                                 Get.UpdateName (this);
730
731                         if (Set != null)
732                                 Set.UpdateName (this);
733                 }
734
735                 public override void WriteDebugSymbol (MonoSymbolFile file)
736                 {
737                         if (get != null)
738                                 get.WriteDebugSymbol (file);
739
740                         if (set != null)
741                                 set.WriteDebugSymbol (file);
742                 }
743
744                 //
745                 //   Represents header string for documentation comment.
746                 //
747                 public override string DocCommentHeader {
748                         get { return "P:"; }
749                 }
750         }
751                         
752         public class Property : PropertyBase
753         {
754                 public sealed class BackingFieldDeclaration : Field
755                 {
756                         readonly Property property;
757                         const Modifiers DefaultModifiers = Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | Modifiers.DEBUGGER_HIDDEN;
758
759                         public BackingFieldDeclaration (Property p, bool readOnly)
760                                 : base (p.Parent, p.type_expr, DefaultModifiers | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
761                                 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
762                         {
763                                 this.property = p;
764                                 if (readOnly)
765                                         ModFlags |= Modifiers.READONLY;
766                         }
767
768                         public Property OriginalProperty {
769                                 get {
770                                         return property;
771                                 }
772                         }
773
774                         public override string GetSignatureForError ()
775                         {
776                                 return property.GetSignatureForError ();
777                         }
778                 }
779
780                 static readonly string[] attribute_target_auto = new string[] { "property", "field" };
781
782                 public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
783                                  MemberName name, Attributes attrs)
784                         : base (parent, type, mod,
785                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
786                                 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
787                                 AllowedModifiersClass,
788                                 name, attrs)
789                 {
790                 }
791
792                 public BackingFieldDeclaration BackingField { get; private set; }
793
794                 public Expression Initializer { get; set; }
795
796                 public override void Accept (StructuralVisitor visitor)
797                 {
798                         visitor.Visit (this);
799                 }
800
801                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
802                 {
803                         if (a.Target == AttributeTargets.Field) {
804                                 BackingField.ApplyAttributeBuilder (a, ctor, cdata, pa);
805                                 return;
806                         }
807
808                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
809                 }
810
811                 void CreateAutomaticProperty ()
812                 {
813                         // Create backing field
814                         BackingField = new BackingFieldDeclaration (this, Initializer == null && Set == null);
815                         if (!BackingField.Define ())
816                                 return;
817
818                         if (Initializer != null) {
819                                 BackingField.Initializer = Initializer;
820                                 Parent.RegisterFieldForInitialization (BackingField, new FieldInitializer (BackingField, Initializer, Location));
821                                 BackingField.ModFlags |= Modifiers.READONLY;
822                         }
823
824                         Parent.PartialContainer.Members.Add (BackingField);
825
826                         FieldExpr fe = new FieldExpr (BackingField, Location);
827                         if ((BackingField.ModFlags & Modifiers.STATIC) == 0) {
828                                 fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
829                                 Parent.PartialContainer.HasInstanceField = true;
830                         }
831
832                         //
833                         // Create get block but we careful with location to
834                         // emit only single sequence point per accessor. This allow
835                         // to set a breakpoint on it even with no user code
836                         //
837                         Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
838                         Return r = new Return (fe, Get.Location);
839                         Get.Block.AddStatement (r);
840                         Get.ModFlags |= Modifiers.COMPILER_GENERATED;
841
842                         // Create set block
843                         if (Set != null) {
844                                 Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
845                                 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
846                                 Set.Block.AddStatement (new StatementExpression (a, Set.Location));
847                                 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
848                         }
849                 }
850
851                 public override bool Define ()
852                 {
853                         if (!base.Define ())
854                                 return false;
855
856                         flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
857
858                         bool auto = AccessorFirst.Block == null && (AccessorSecond == null || AccessorSecond.Block == null) &&
859                                 (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0;
860
861                         if (Initializer != null) {
862                                 if (!auto)
863                                         Report.Error (8050, Location, "`{0}': Only auto-implemented properties can have initializers",
864                                                 GetSignatureForError ());
865
866                                 if (IsInterface)
867                                         Report.Error (8052, Location, "`{0}': Properties inside interfaces cannot have initializers",
868                                                 GetSignatureForError ());
869
870                                 if (Compiler.Settings.Version < LanguageVersion.V_6)
871                                         Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented property initializer");
872                         }
873
874                         if (auto) {
875                                 ModFlags |= Modifiers.AutoProperty;
876                                 if (Get == null) {
877                                         Report.Error (8051, Location, "Auto-implemented property `{0}' must have get accessor",
878                                                 GetSignatureForError ());
879                                         return false;
880                                 }
881
882                                 if (Compiler.Settings.Version < LanguageVersion.V_3 && Initializer == null)
883                                         Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented properties");
884
885                                 CreateAutomaticProperty ();
886                         }
887
888                         if (!DefineAccessors ())
889                                 return false;
890
891                         if (AccessorSecond == null) {
892                                 PropertyMethod pm;
893                                 if (AccessorFirst is GetMethod)
894                                         pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
895                                 else
896                                         pm = new GetMethod (this, 0, null, Location);
897
898                                 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
899                         }
900
901                         if (!CheckBase ())
902                                 return false;
903
904                         DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
905                         return true;
906                 }
907
908                 public override void Emit ()
909                 {
910                         if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.AutoProperty)) == Modifiers.AutoProperty && Parent.PartialContainer.HasExplicitLayout) {
911                                 Report.Error (842, Location,
912                                         "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
913                                         GetSignatureForError ());
914                         }
915
916                         base.Emit ();
917                 }
918
919                 public override string[] ValidAttributeTargets {
920                         get {
921                                 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
922                                         attribute_target_auto : base.ValidAttributeTargets;
923                         }
924                 }
925         }
926
927         /// <summary>
928         /// For case when event is declared like property (with add and remove accessors).
929         /// </summary>
930         public class EventProperty: Event {
931                 public abstract class AEventPropertyAccessor : AEventAccessor
932                 {
933                         protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
934                                 : base (method, prefix, attrs, loc)
935                         {
936                         }
937
938                         public override void Define (TypeContainer ds)
939                         {
940                                 CheckAbstractAndExtern (block != null);
941                                 base.Define (ds);
942                         }
943                         
944                         public override string GetSignatureForError ()
945                         {
946                                 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
947                         }
948                 }
949
950                 public sealed class AddDelegateMethod: AEventPropertyAccessor
951                 {
952                         public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
953                                 : base (method, AddPrefix, attrs, loc)
954                         {
955                         }
956                 }
957
958                 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
959                 {
960                         public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
961                                 : base (method, RemovePrefix, attrs, loc)
962                         {
963                         }
964                 }
965
966                 static readonly string[] attribute_targets = new string [] { "event" };
967
968                 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
969                         : base (parent, type, mod_flags, name, attrs)
970                 {
971                 }
972
973                 public override void Accept (StructuralVisitor visitor)
974                 {
975                         visitor.Visit (this);
976                 }
977                 
978                 public override bool Define()
979                 {
980                         if (!base.Define ())
981                                 return false;
982
983                         SetIsUsed ();
984                         return true;
985                 }
986
987                 public override string[] ValidAttributeTargets {
988                         get {
989                                 return attribute_targets;
990                         }
991                 }
992         }
993
994         /// <summary>
995         /// Event is declared like field.
996         /// </summary>
997         public class EventField : Event
998         {
999                 abstract class EventFieldAccessor : AEventAccessor
1000                 {
1001                         protected EventFieldAccessor (EventField method, string prefix)
1002                                 : base (method, prefix, null, method.Location)
1003                         {
1004                         }
1005
1006                         protected abstract MethodSpec GetOperation (Location loc);
1007
1008                         public override void Emit (TypeDefinition parent)
1009                         {
1010                                 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
1011                                         block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
1012                                                 IsCompilerGenerated = true
1013                                         };
1014                                         FabricateBodyStatement ();
1015                                 }
1016
1017                                 base.Emit (parent);
1018                         }
1019
1020                         void FabricateBodyStatement ()
1021                         {
1022                                 //
1023                                 // Delegate obj1 = backing_field
1024                                 // do {
1025                                 //   Delegate obj2 = obj1;
1026                                 //   obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
1027                                 // } while ((object)obj1 != (object)obj2)
1028                                 //
1029
1030                                 var field_info = ((EventField) method).backing_field;
1031                                 FieldExpr f_expr = new FieldExpr (field_info, Location);
1032                                 if (!IsStatic)
1033                                         f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
1034
1035                                 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1036                                 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1037
1038                                 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
1039
1040                                 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
1041                                         new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
1042                                         new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
1043
1044                                 var body = new ExplicitBlock (block, Location, Location);
1045                                 block.AddStatement (new Do (body, cond, Location, Location));
1046
1047                                 body.AddStatement (new StatementExpression (
1048                                         new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
1049
1050                                 var args_oper = new Arguments (2);
1051                                 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
1052                                 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
1053
1054                                 var op_method = GetOperation (Location);
1055
1056                                 var args = new Arguments (3);
1057                                 args.Add (new Argument (f_expr, Argument.AType.Ref));
1058                                 args.Add (new Argument (new Cast (
1059                                         new TypeExpression (field_info.MemberType, Location),
1060                                         new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
1061                                         Location)));
1062                                 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
1063
1064                                 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
1065                                 if (cas == null) {
1066                                         if (Module.PredefinedMembers.MonitorEnter_v4.Get () != null || Module.PredefinedMembers.MonitorEnter.Get () != null) {
1067                                                 // Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
1068                                                 body.AddStatement (new Lock (
1069                                                         block.GetParameterReference (0, Location),
1070                                                         new StatementExpression (new SimpleAssign (
1071                                                                 f_expr, args [1].Expr, Location), Location), Location));
1072                                         } else {
1073                                                 Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
1074                                         }
1075                                 } else {
1076                                         body.AddStatement (new StatementExpression (new SimpleAssign (
1077                                                 new LocalVariableReference (obj1, Location),
1078                                                 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
1079                                 }
1080                         }
1081                 }
1082
1083                 sealed class AddDelegateMethod: EventFieldAccessor
1084                 {
1085                         public AddDelegateMethod (EventField method):
1086                                 base (method, AddPrefix)
1087                         {
1088                         }
1089
1090                         protected override MethodSpec GetOperation (Location loc)
1091                         {
1092                                 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1093                         }
1094                 }
1095
1096                 sealed class RemoveDelegateMethod: EventFieldAccessor
1097                 {
1098                         public RemoveDelegateMethod (EventField method):
1099                                 base (method, RemovePrefix)
1100                         {
1101                         }
1102
1103                         protected override MethodSpec GetOperation (Location loc)
1104                         {
1105                                 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1106                         }
1107                 }
1108
1109
1110                 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1111                 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1112
1113                 Expression initializer;
1114                 Field backing_field;
1115                 List<FieldDeclarator> declarators;
1116
1117                 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1118                         : base (parent, type, mod_flags, name, attrs)
1119                 {
1120                         Add = new AddDelegateMethod (this);
1121                         Remove = new RemoveDelegateMethod (this);
1122                 }
1123
1124                 #region Properties
1125
1126                 public List<FieldDeclarator> Declarators {
1127                         get {
1128                                 return this.declarators;
1129                         }
1130                 }
1131
1132                 bool HasBackingField {
1133                         get {
1134                                 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1135                         }
1136                 }
1137
1138                 public Expression Initializer {
1139                         get {
1140                                 return initializer;
1141                         }
1142                         set {
1143                                 initializer = value;
1144                         }
1145                 }
1146
1147                 public override string[] ValidAttributeTargets {
1148                         get {
1149                                 return HasBackingField ? attribute_targets : attribute_targets_interface;
1150                         }
1151                 }
1152
1153                 #endregion
1154
1155                 
1156                 public override void Accept (StructuralVisitor visitor)
1157                 {
1158                         visitor.Visit (this);
1159                 }
1160
1161                 public void AddDeclarator (FieldDeclarator declarator)
1162                 {
1163                         if (declarators == null)
1164                                 declarators = new List<FieldDeclarator> (2);
1165
1166                         declarators.Add (declarator);
1167
1168                         Parent.AddNameToContainer (this, declarator.Name.Value);
1169                 }
1170
1171                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1172                 {
1173                         if (a.Target == AttributeTargets.Field) {
1174                                 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1175                                 return;
1176                         }
1177
1178                         if (a.Target == AttributeTargets.Method) {
1179                                 int errors = Report.Errors;
1180                                 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1181                                 if (errors == Report.Errors)
1182                                         Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1183                                 return;
1184                         }
1185
1186                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1187                 }
1188
1189                 public override bool Define()
1190                 {
1191                         var mod_flags_src = ModFlags;
1192
1193                         if (!base.Define ())
1194                                 return false;
1195
1196                         if (declarators != null) {
1197                                 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1198                                         mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1199
1200                                 var t = new TypeExpression (MemberType, TypeExpression.Location);
1201                                 foreach (var d in declarators) {
1202                                         var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1203
1204                                         if (d.Initializer != null)
1205                                                 ef.initializer = d.Initializer;
1206
1207                                         ef.Define ();
1208                                         Parent.PartialContainer.Members.Add (ef);
1209                                 }
1210                         }
1211
1212                         if (!HasBackingField) {
1213                                 SetIsUsed ();
1214                                 return true;
1215                         }
1216
1217                         backing_field = new Field (Parent,
1218                                 new TypeExpression (MemberType, Location),
1219                                 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1220                                 MemberName, null);
1221
1222                         Parent.PartialContainer.Members.Add (backing_field);
1223                         backing_field.Initializer = Initializer;
1224
1225                         // Call define because we passed fields definition
1226                         backing_field.Define ();
1227
1228                         // Set backing field for event fields
1229                         spec.BackingField = backing_field.Spec;
1230
1231                         return true;
1232                 }
1233         }
1234
1235         public abstract class Event : PropertyBasedMember
1236         {
1237                 public abstract class AEventAccessor : AbstractPropertyEventMethod
1238                 {
1239                         protected readonly Event method;
1240                         readonly ParametersCompiled parameters;
1241
1242                         static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1243
1244                         public const string AddPrefix = "add_";
1245                         public const string RemovePrefix = "remove_";
1246
1247                         protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1248                                 : base (method, prefix, attrs, loc)
1249                         {
1250                                 this.method = method;
1251                                 this.ModFlags = method.ModFlags;
1252                                 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1253                         }
1254
1255                         public bool IsInterfaceImplementation {
1256                                 get { return method_data.implementing != null; }
1257                         }
1258
1259                         public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1260                         {
1261                                 if (a.Type == pa.MethodImpl) {
1262                                         method.is_external_implementation = a.IsInternalCall ();
1263                                 }
1264
1265                                 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1266                         }
1267
1268                         protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1269                         {
1270                                 if (a.Target == AttributeTargets.Parameter) {
1271                                         parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1272                                         return;
1273                                 }
1274
1275                                 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1276                         }
1277
1278                         public override AttributeTargets AttributeTargets {
1279                                 get {
1280                                         return AttributeTargets.Method;
1281                                 }
1282                         }
1283
1284                         public override bool IsClsComplianceRequired ()
1285                         {
1286                                 return method.IsClsComplianceRequired ();
1287                         }
1288
1289                         public virtual void Define (TypeContainer parent)
1290                         {
1291                                 // Fill in already resolved event type to speed things up and
1292                                 // avoid confusing duplicate errors
1293                                 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1294                                 parameters.Types = new TypeSpec[] { method.member_type };
1295
1296                                 method_data = new MethodData (method, method.ModFlags,
1297                                         method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1298
1299                                 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1300                                         return;
1301
1302                                 if (Compiler.Settings.WriteMetadataOnly)
1303                                         block = null;
1304
1305                                 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1306                                 Spec.IsAccessor = true;
1307                         }
1308
1309                         public override TypeSpec ReturnType {
1310                                 get {
1311                                         return Parent.Compiler.BuiltinTypes.Void;
1312                                 }
1313                         }
1314
1315                         public override ObsoleteAttribute GetAttributeObsolete ()
1316                         {
1317                                 return method.GetAttributeObsolete ();
1318                         }
1319
1320                         public MethodData MethodData {
1321                                 get {
1322                                         return method_data;
1323                                 }
1324                         }
1325
1326                         public override string[] ValidAttributeTargets {
1327                                 get {
1328                                         return attribute_targets;
1329                                 }
1330                         }
1331
1332                         public override ParametersCompiled ParameterInfo {
1333                                 get {
1334                                         return parameters;
1335                                 }
1336                         }
1337                 }
1338
1339                 AEventAccessor add, remove;
1340                 EventBuilder EventBuilder;
1341                 protected EventSpec spec;
1342
1343                 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1344                         : base (parent, type, mod_flags,
1345                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1346                                 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1347                                 AllowedModifiersClass,
1348                                 name, attrs)
1349                 {
1350                 }
1351
1352                 #region Properties
1353
1354                 public override AttributeTargets AttributeTargets {
1355                         get {
1356                                 return AttributeTargets.Event;
1357                         }
1358                 }
1359
1360                 public AEventAccessor Add {
1361                         get {
1362                                 return this.add;
1363                         }
1364                         set {
1365                                 add = value;
1366                                 Parent.AddNameToContainer (value, value.MemberName.Basename);
1367                         }
1368                 }
1369
1370                 public override Variance ExpectedMemberTypeVariance {
1371                         get {
1372                                 return Variance.Contravariant;
1373                         }
1374                 }
1375
1376                 public AEventAccessor Remove {
1377                         get {
1378                                 return this.remove;
1379                         }
1380                         set {
1381                                 remove = value;
1382                                 Parent.AddNameToContainer (value, value.MemberName.Basename);
1383                         }
1384                 }
1385                 #endregion
1386
1387                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1388                 {
1389                         if ((a.HasSecurityAttribute)) {
1390                                 a.Error_InvalidSecurityParent ();
1391                                 return;
1392                         }
1393
1394                         EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1395                 }
1396
1397                 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1398                 {
1399                         var ok = base.CheckOverrideAgainstBase (base_member);
1400
1401                         if (!CheckAccessModifiers (this, base_member)) {
1402                                 Error_CannotChangeAccessModifiers (this, base_member);
1403                                 ok = false;
1404                         }
1405
1406                         return ok;
1407                 }
1408
1409                 public override bool Define ()
1410                 {
1411                         if (!base.Define ())
1412                                 return false;
1413
1414                         if (!MemberType.IsDelegate) {
1415                                 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1416                         }
1417
1418                         if (!CheckBase ())
1419                                 return false;
1420
1421                         //
1422                         // Now define the accessors
1423                         //
1424                         add.Define (Parent);
1425                         remove.Define (Parent);
1426
1427                         EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1428
1429                         spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1430
1431                         Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1432                         Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1433                         Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1434
1435                         return true;
1436                 }
1437
1438                 public override void Emit ()
1439                 {
1440                         CheckReservedNameConflict (null, add.Spec);
1441                         CheckReservedNameConflict (null, remove.Spec);
1442
1443                         if (OptAttributes != null) {
1444                                 OptAttributes.Emit ();
1445                         }
1446
1447                         ConstraintChecker.Check (this, member_type, type_expr.Location);
1448
1449                         Add.Emit (Parent);
1450                         Remove.Emit (Parent);
1451
1452                         base.Emit ();
1453                 }
1454
1455                 public override void PrepareEmit ()
1456                 {
1457                         base.PrepareEmit ();
1458
1459                         add.PrepareEmit ();
1460                         remove.PrepareEmit ();
1461
1462                         EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1463                         EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
1464                 }
1465
1466                 public override void WriteDebugSymbol (MonoSymbolFile file)
1467                 {
1468                         add.WriteDebugSymbol (file);
1469                         remove.WriteDebugSymbol (file);
1470                 }
1471
1472                 //
1473                 //   Represents header string for documentation comment.
1474                 //
1475                 public override string DocCommentHeader {
1476                         get { return "E:"; }
1477                 }
1478         }
1479
1480         public class EventSpec : MemberSpec, IInterfaceMemberSpec
1481         {
1482                 MethodSpec add, remove;
1483                 FieldSpec backing_field;
1484
1485                 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1486                         : base (MemberKind.Event, declaringType, definition, modifiers)
1487                 {
1488                         this.AccessorAdd = add;
1489                         this.AccessorRemove = remove;
1490                         this.MemberType = eventType;
1491                 }
1492
1493                 #region Properties
1494
1495                 public MethodSpec AccessorAdd { 
1496                         get {
1497                                 return add;
1498                         }
1499                         set {
1500                                 add = value;
1501                         }
1502                 }
1503
1504                 public MethodSpec AccessorRemove {
1505                         get {
1506                                 return remove;
1507                         }
1508                         set {
1509                                 remove = value;
1510                         }
1511                 }
1512
1513                 public FieldSpec BackingField {
1514                         get {
1515                                 return backing_field;
1516                         }
1517                         set {
1518                                 backing_field = value;
1519                         }
1520                 }
1521
1522                 public TypeSpec MemberType { get; private set; }
1523
1524                 #endregion
1525
1526                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1527                 {
1528                         var es = (EventSpec) base.InflateMember (inflator);
1529                         es.MemberType = inflator.Inflate (MemberType);
1530
1531                         if (backing_field != null)
1532                                 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1533
1534                         return es;
1535                 }
1536
1537                 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1538                 {
1539                         return MemberType.ResolveMissingDependencies (this);
1540                 }
1541         }
1542  
1543         public class Indexer : PropertyBase, IParametersMember
1544         {
1545                 public class GetIndexerMethod : GetMethod, IParametersMember
1546                 {
1547                         ParametersCompiled parameters;
1548
1549                         public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1550                                 : base (property, modifiers, attrs, loc)
1551                         {
1552                                 this.parameters = parameters;
1553                         }
1554
1555                         public override void Define (TypeContainer parent)
1556                         {
1557                                 // Disable reporting, parameters are resolved twice
1558                                 Report.DisableReporting ();
1559                                 try {
1560                                         parameters.Resolve (this);
1561                                 } finally {
1562                                         Report.EnableReporting ();
1563                                 }
1564
1565                                 base.Define (parent);
1566                         }
1567
1568                         public override ParametersCompiled ParameterInfo {
1569                                 get {
1570                                         return parameters;
1571                                 }
1572                         }
1573
1574                         #region IParametersMember Members
1575
1576                         AParametersCollection IParametersMember.Parameters {
1577                                 get {
1578                                         return parameters;
1579                                 }
1580                         }
1581
1582                         TypeSpec IInterfaceMemberSpec.MemberType {
1583                                 get {
1584                                         return ReturnType;
1585                                 }
1586                         }
1587
1588                         #endregion
1589                 }
1590
1591                 public class SetIndexerMethod : SetMethod, IParametersMember
1592                 {
1593                         public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1594                                 : base (property, modifiers, parameters, attrs, loc)
1595                         {
1596                         }
1597
1598                         #region IParametersMember Members
1599
1600                         AParametersCollection IParametersMember.Parameters {
1601                                 get {
1602                                         return parameters;
1603                                 }
1604                         }
1605
1606                         TypeSpec IInterfaceMemberSpec.MemberType {
1607                                 get {
1608                                         return ReturnType;
1609                                 }
1610                         }
1611
1612                         #endregion
1613                 }
1614
1615                 const Modifiers AllowedModifiers =
1616                         Modifiers.NEW |
1617                         Modifiers.PUBLIC |
1618                         Modifiers.PROTECTED |
1619                         Modifiers.INTERNAL |
1620                         Modifiers.PRIVATE |
1621                         Modifiers.VIRTUAL |
1622                         Modifiers.SEALED |
1623                         Modifiers.OVERRIDE |
1624                         Modifiers.UNSAFE |
1625                         Modifiers.EXTERN |
1626                         Modifiers.ABSTRACT;
1627
1628                 const Modifiers AllowedInterfaceModifiers =
1629                         Modifiers.NEW;
1630
1631                 readonly ParametersCompiled parameters;
1632
1633                 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1634                         : base (parent, type, mod,
1635                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1636                                 name, attrs)
1637                 {
1638                         this.parameters = parameters;
1639                 }
1640
1641                 #region Properties
1642
1643                 AParametersCollection IParametersMember.Parameters {
1644                         get {
1645                                 return parameters;
1646                         }
1647                 }
1648
1649                 public ParametersCompiled ParameterInfo {
1650                         get {
1651                                 return parameters;
1652                         }
1653                 }
1654
1655                 #endregion
1656
1657                 
1658                 public override void Accept (StructuralVisitor visitor)
1659                 {
1660                         visitor.Visit (this);
1661                 }
1662
1663                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1664                 {
1665                         if (a.Type == pa.IndexerName) {
1666                                 // Attribute was copied to container
1667                                 return;
1668                         }
1669
1670                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1671                 }
1672
1673                 protected override bool CheckForDuplications ()
1674                 {
1675                         return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1676                 }
1677                 
1678                 public override bool Define ()
1679                 {
1680                         if (!base.Define ())
1681                                 return false;
1682
1683                         if (!DefineParameters (parameters))
1684                                 return false;
1685
1686                         if (OptAttributes != null) {
1687                                 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1688                                 if (indexer_attr != null) {
1689                                         var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1690                                         if (compiling != null)
1691                                                 compiling.Define ();
1692
1693                                         if (IsExplicitImpl) {
1694                                                 Report.Error (415, indexer_attr.Location,
1695                                                         "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1696                                                         indexer_attr.Type.GetSignatureForError ());
1697                                         } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1698                                                 Report.Error (609, indexer_attr.Location,
1699                                                         "Cannot set the `IndexerName' attribute on an indexer marked override");
1700                                         } else {
1701                                                 string name = indexer_attr.GetIndexerAttributeValue ();
1702
1703                                                 if (!string.IsNullOrEmpty (name)) {
1704                                                         SetMemberName (new MemberName (MemberName.Left, name, Location));
1705                                                 }
1706                                         }
1707                                 }
1708                         }
1709
1710                         if (InterfaceType != null) {
1711                                 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1712                                 if (base_IndexerName != ShortName) {
1713                                         SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1714                                 }
1715                         }
1716
1717                         Parent.AddNameToContainer (this, MemberName.Basename);
1718
1719                         flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1720                         
1721                         if (!DefineAccessors ())
1722                                 return false;
1723
1724                         if (!CheckBase ())
1725                                 return false;
1726
1727                         DefineBuilders (MemberKind.Indexer, parameters);
1728                         return true;
1729                 }
1730
1731                 public override bool EnableOverloadChecks (MemberCore overload)
1732                 {
1733                         if (overload is Indexer) {
1734                                 caching_flags |= Flags.MethodOverloadsExist;
1735                                 return true;
1736                         }
1737
1738                         return base.EnableOverloadChecks (overload);
1739                 }
1740
1741                 public override void Emit ()
1742                 {
1743                         parameters.CheckConstraints (this);
1744
1745                         base.Emit ();
1746                 }
1747
1748                 public override string GetSignatureForError ()
1749                 {
1750                         StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1751                         if (MemberName.ExplicitInterface != null) {
1752                                 sb.Append (".");
1753                                 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1754                         }
1755
1756                         sb.Append (".this");
1757                         sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1758                         return sb.ToString ();
1759                 }
1760
1761                 public override string GetSignatureForDocumentation ()
1762                 {
1763                         return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1764                 }
1765
1766                 public override void PrepareEmit ()
1767                 {
1768                         base.PrepareEmit ();
1769                         parameters.ResolveDefaultValues (this);
1770                 }
1771
1772                 protected override bool VerifyClsCompliance ()
1773                 {
1774                         if (!base.VerifyClsCompliance ())
1775                                 return false;
1776
1777                         parameters.VerifyClsCompliance (this);
1778                         return true;
1779                 }
1780         }
1781
1782         public class IndexerSpec : PropertySpec, IParametersMember
1783         {
1784                 AParametersCollection parameters;
1785
1786                 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1787                         : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1788                 {
1789                         this.parameters = parameters;
1790                 }
1791
1792                 #region Properties
1793                 public AParametersCollection Parameters {
1794                         get {
1795                                 return parameters;
1796                         }
1797                 }
1798                 #endregion
1799
1800                 public static ParametersImported CreateParametersFromSetter (MethodSpec setter, int set_param_count)
1801                 {
1802                         //
1803                         // Creates indexer parameters based on setter method parameters (the last parameter has to be removed)
1804                         //
1805                         var data = new IParameterData [set_param_count];
1806                         var types = new TypeSpec [set_param_count];
1807                         Array.Copy (setter.Parameters.FixedParameters, data, set_param_count);
1808                         Array.Copy (setter.Parameters.Types, types, set_param_count);
1809                         return new ParametersImported (data, types, setter.Parameters.HasParams);
1810                 }
1811
1812                 public override string GetSignatureForDocumentation ()
1813                 {
1814                         return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1815                 }
1816
1817                 public override string GetSignatureForError ()
1818                 {
1819                         return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1820                 }
1821
1822                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1823                 {
1824                         var spec = (IndexerSpec) base.InflateMember (inflator);
1825                         spec.parameters = parameters.Inflate (inflator);
1826                         return spec;
1827                 }
1828
1829                 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1830                 {
1831                         var missing = base.ResolveMissingDependencies (caller);
1832
1833                         foreach (var pt in parameters.Types) {
1834                                 var m = pt.GetMissingDependencies (caller);
1835                                 if (m == null)
1836                                         continue;
1837
1838                                 if (missing == null)
1839                                         missing = new List<MissingTypeSpecReference> ();
1840
1841                                 missing.AddRange (m);
1842                         }
1843
1844                         return missing;
1845                 }
1846         }
1847 }