3478711470a0fa6d93b668621c5d60392e2fda08
[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 (MemberType.Kind == MemberKind.ByRef) {
883                                         Report.Error (8145, Location, "Auto-implemented properties cannot return by reference");
884                                         return false;
885                                 }
886
887                                 if (Compiler.Settings.Version < LanguageVersion.V_3 && Initializer == null)
888                                         Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented properties");
889
890                                 CreateAutomaticProperty ();
891                         }
892
893                         if (!DefineAccessors ())
894                                 return false;
895
896                         if (AccessorSecond == null) {
897                                 PropertyMethod pm;
898                                 if (AccessorFirst is GetMethod)
899                                         pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
900                                 else
901                                         pm = new GetMethod (this, 0, null, Location);
902
903                                 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
904                         }
905
906                         if (!CheckBase ())
907                                 return false;
908
909                         DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
910                         return true;
911                 }
912
913                 public override void Emit ()
914                 {
915                         if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.AutoProperty)) == Modifiers.AutoProperty && Parent.PartialContainer.HasExplicitLayout) {
916                                 Report.Error (842, Location,
917                                         "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
918                                         GetSignatureForError ());
919                         }
920
921                         base.Emit ();
922                 }
923
924                 public override string[] ValidAttributeTargets {
925                         get {
926                                 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
927                                         attribute_target_auto : base.ValidAttributeTargets;
928                         }
929                 }
930         }
931
932         /// <summary>
933         /// For case when event is declared like property (with add and remove accessors).
934         /// </summary>
935         public class EventProperty: Event {
936                 public abstract class AEventPropertyAccessor : AEventAccessor
937                 {
938                         protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
939                                 : base (method, prefix, attrs, loc)
940                         {
941                         }
942
943                         public override void Define (TypeContainer ds)
944                         {
945                                 CheckAbstractAndExtern (block != null);
946                                 base.Define (ds);
947                         }
948                         
949                         public override string GetSignatureForError ()
950                         {
951                                 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
952                         }
953                 }
954
955                 public sealed class AddDelegateMethod: AEventPropertyAccessor
956                 {
957                         public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
958                                 : base (method, AddPrefix, attrs, loc)
959                         {
960                         }
961                 }
962
963                 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
964                 {
965                         public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
966                                 : base (method, RemovePrefix, attrs, loc)
967                         {
968                         }
969                 }
970
971                 static readonly string[] attribute_targets = new string [] { "event" };
972
973                 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
974                         : base (parent, type, mod_flags, name, attrs)
975                 {
976                 }
977
978                 public override void Accept (StructuralVisitor visitor)
979                 {
980                         visitor.Visit (this);
981                 }
982                 
983                 public override bool Define()
984                 {
985                         if (!base.Define ())
986                                 return false;
987
988                         SetIsUsed ();
989                         return true;
990                 }
991
992                 public override string[] ValidAttributeTargets {
993                         get {
994                                 return attribute_targets;
995                         }
996                 }
997         }
998
999         /// <summary>
1000         /// Event is declared like field.
1001         /// </summary>
1002         public class EventField : Event
1003         {
1004                 abstract class EventFieldAccessor : AEventAccessor
1005                 {
1006                         protected EventFieldAccessor (EventField method, string prefix)
1007                                 : base (method, prefix, null, method.Location)
1008                         {
1009                         }
1010
1011                         protected abstract MethodSpec GetOperation (Location loc);
1012
1013                         public override void Emit (TypeDefinition parent)
1014                         {
1015                                 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
1016                                         block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
1017                                                 IsCompilerGenerated = true
1018                                         };
1019                                         FabricateBodyStatement ();
1020                                 }
1021
1022                                 base.Emit (parent);
1023                         }
1024
1025                         void FabricateBodyStatement ()
1026                         {
1027                                 //
1028                                 // Delegate obj1 = backing_field
1029                                 // do {
1030                                 //   Delegate obj2 = obj1;
1031                                 //   obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
1032                                 // } while ((object)obj1 != (object)obj2)
1033                                 //
1034
1035                                 var field_info = ((EventField) method).backing_field;
1036                                 FieldExpr f_expr = new FieldExpr (field_info, Location);
1037                                 if (!IsStatic)
1038                                         f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
1039
1040                                 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1041                                 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1042
1043                                 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
1044
1045                                 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
1046                                         new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
1047                                         new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
1048
1049                                 var body = new ExplicitBlock (block, Location, Location);
1050                                 block.AddStatement (new Do (body, cond, Location, Location));
1051
1052                                 body.AddStatement (new StatementExpression (
1053                                         new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
1054
1055                                 var args_oper = new Arguments (2);
1056                                 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
1057                                 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
1058
1059                                 var op_method = GetOperation (Location);
1060
1061                                 var args = new Arguments (3);
1062                                 args.Add (new Argument (f_expr, Argument.AType.Ref));
1063                                 args.Add (new Argument (new Cast (
1064                                         new TypeExpression (field_info.MemberType, Location),
1065                                         new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
1066                                         Location)));
1067                                 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
1068
1069                                 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
1070                                 if (cas == null) {
1071                                         if (Module.PredefinedMembers.MonitorEnter_v4.Get () != null || Module.PredefinedMembers.MonitorEnter.Get () != null) {
1072                                                 // Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
1073                                                 body.AddStatement (new Lock (
1074                                                         block.GetParameterReference (0, Location),
1075                                                         new StatementExpression (new SimpleAssign (
1076                                                                 f_expr, args [1].Expr, Location), Location), Location));
1077                                         } else {
1078                                                 Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
1079                                         }
1080                                 } else {
1081                                         body.AddStatement (new StatementExpression (new SimpleAssign (
1082                                                 new LocalVariableReference (obj1, Location),
1083                                                 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
1084                                 }
1085                         }
1086                 }
1087
1088                 sealed class AddDelegateMethod: EventFieldAccessor
1089                 {
1090                         public AddDelegateMethod (EventField method):
1091                                 base (method, AddPrefix)
1092                         {
1093                         }
1094
1095                         protected override MethodSpec GetOperation (Location loc)
1096                         {
1097                                 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1098                         }
1099                 }
1100
1101                 sealed class RemoveDelegateMethod: EventFieldAccessor
1102                 {
1103                         public RemoveDelegateMethod (EventField method):
1104                                 base (method, RemovePrefix)
1105                         {
1106                         }
1107
1108                         protected override MethodSpec GetOperation (Location loc)
1109                         {
1110                                 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1111                         }
1112                 }
1113
1114
1115                 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1116                 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1117
1118                 Expression initializer;
1119                 Field backing_field;
1120                 List<FieldDeclarator> declarators;
1121
1122                 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1123                         : base (parent, type, mod_flags, name, attrs)
1124                 {
1125                         Add = new AddDelegateMethod (this);
1126                         Remove = new RemoveDelegateMethod (this);
1127                 }
1128
1129                 #region Properties
1130
1131                 public List<FieldDeclarator> Declarators {
1132                         get {
1133                                 return this.declarators;
1134                         }
1135                 }
1136
1137                 bool HasBackingField {
1138                         get {
1139                                 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1140                         }
1141                 }
1142
1143                 public Expression Initializer {
1144                         get {
1145                                 return initializer;
1146                         }
1147                         set {
1148                                 initializer = value;
1149                         }
1150                 }
1151
1152                 public override string[] ValidAttributeTargets {
1153                         get {
1154                                 return HasBackingField ? attribute_targets : attribute_targets_interface;
1155                         }
1156                 }
1157
1158                 #endregion
1159
1160                 
1161                 public override void Accept (StructuralVisitor visitor)
1162                 {
1163                         visitor.Visit (this);
1164                 }
1165
1166                 public void AddDeclarator (FieldDeclarator declarator)
1167                 {
1168                         if (declarators == null)
1169                                 declarators = new List<FieldDeclarator> (2);
1170
1171                         declarators.Add (declarator);
1172
1173                         Parent.AddNameToContainer (this, declarator.Name.Value);
1174                 }
1175
1176                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1177                 {
1178                         if (a.Target == AttributeTargets.Field) {
1179                                 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1180                                 return;
1181                         }
1182
1183                         if (a.Target == AttributeTargets.Method) {
1184                                 int errors = Report.Errors;
1185                                 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1186                                 if (errors == Report.Errors)
1187                                         Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1188                                 return;
1189                         }
1190
1191                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1192                 }
1193
1194                 public override bool Define()
1195                 {
1196                         var mod_flags_src = ModFlags;
1197
1198                         if (!base.Define ())
1199                                 return false;
1200
1201                         if (declarators != null) {
1202                                 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1203                                         mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1204
1205                                 var t = new TypeExpression (MemberType, TypeExpression.Location);
1206                                 foreach (var d in declarators) {
1207                                         var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1208
1209                                         if (d.Initializer != null)
1210                                                 ef.initializer = d.Initializer;
1211
1212                                         ef.Define ();
1213                                         Parent.PartialContainer.Members.Add (ef);
1214                                 }
1215                         }
1216
1217                         if (!HasBackingField) {
1218                                 SetIsUsed ();
1219                                 return true;
1220                         }
1221
1222                         backing_field = new Field (Parent,
1223                                 new TypeExpression (MemberType, Location),
1224                                 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1225                                 MemberName, null);
1226
1227                         Parent.PartialContainer.Members.Add (backing_field);
1228                         backing_field.Initializer = Initializer;
1229
1230                         // Call define because we passed fields definition
1231                         backing_field.Define ();
1232
1233                         // Set backing field for event fields
1234                         spec.BackingField = backing_field.Spec;
1235
1236                         return true;
1237                 }
1238         }
1239
1240         public abstract class Event : PropertyBasedMember
1241         {
1242                 public abstract class AEventAccessor : AbstractPropertyEventMethod
1243                 {
1244                         protected readonly Event method;
1245                         readonly ParametersCompiled parameters;
1246
1247                         static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1248
1249                         public const string AddPrefix = "add_";
1250                         public const string RemovePrefix = "remove_";
1251
1252                         protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1253                                 : base (method, prefix, attrs, loc)
1254                         {
1255                                 this.method = method;
1256                                 this.ModFlags = method.ModFlags;
1257                                 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1258                         }
1259
1260                         public bool IsInterfaceImplementation {
1261                                 get { return method_data.implementing != null; }
1262                         }
1263
1264                         public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1265                         {
1266                                 if (a.Type == pa.MethodImpl) {
1267                                         method.is_external_implementation = a.IsInternalCall ();
1268                                 }
1269
1270                                 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1271                         }
1272
1273                         protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1274                         {
1275                                 if (a.Target == AttributeTargets.Parameter) {
1276                                         parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1277                                         return;
1278                                 }
1279
1280                                 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1281                         }
1282
1283                         public override AttributeTargets AttributeTargets {
1284                                 get {
1285                                         return AttributeTargets.Method;
1286                                 }
1287                         }
1288
1289                         public override bool IsClsComplianceRequired ()
1290                         {
1291                                 return method.IsClsComplianceRequired ();
1292                         }
1293
1294                         public virtual void Define (TypeContainer parent)
1295                         {
1296                                 // Fill in already resolved event type to speed things up and
1297                                 // avoid confusing duplicate errors
1298                                 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1299                                 parameters.Types = new TypeSpec[] { method.member_type };
1300
1301                                 method_data = new MethodData (method, method.ModFlags,
1302                                         method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1303
1304                                 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1305                                         return;
1306
1307                                 if (Compiler.Settings.WriteMetadataOnly)
1308                                         block = null;
1309
1310                                 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1311                                 Spec.IsAccessor = true;
1312                         }
1313
1314                         public override TypeSpec ReturnType {
1315                                 get {
1316                                         return Parent.Compiler.BuiltinTypes.Void;
1317                                 }
1318                         }
1319
1320                         public override ObsoleteAttribute GetAttributeObsolete ()
1321                         {
1322                                 return method.GetAttributeObsolete ();
1323                         }
1324
1325                         public MethodData MethodData {
1326                                 get {
1327                                         return method_data;
1328                                 }
1329                         }
1330
1331                         public override string[] ValidAttributeTargets {
1332                                 get {
1333                                         return attribute_targets;
1334                                 }
1335                         }
1336
1337                         public override ParametersCompiled ParameterInfo {
1338                                 get {
1339                                         return parameters;
1340                                 }
1341                         }
1342                 }
1343
1344                 AEventAccessor add, remove;
1345                 EventBuilder EventBuilder;
1346                 protected EventSpec spec;
1347
1348                 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1349                         : base (parent, type, mod_flags,
1350                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1351                                 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1352                                 AllowedModifiersClass,
1353                                 name, attrs)
1354                 {
1355                 }
1356
1357                 #region Properties
1358
1359                 public override AttributeTargets AttributeTargets {
1360                         get {
1361                                 return AttributeTargets.Event;
1362                         }
1363                 }
1364
1365                 public AEventAccessor Add {
1366                         get {
1367                                 return this.add;
1368                         }
1369                         set {
1370                                 add = value;
1371                                 Parent.AddNameToContainer (value, value.MemberName.Basename);
1372                         }
1373                 }
1374
1375                 public override Variance ExpectedMemberTypeVariance {
1376                         get {
1377                                 return Variance.Contravariant;
1378                         }
1379                 }
1380
1381                 public AEventAccessor Remove {
1382                         get {
1383                                 return this.remove;
1384                         }
1385                         set {
1386                                 remove = value;
1387                                 Parent.AddNameToContainer (value, value.MemberName.Basename);
1388                         }
1389                 }
1390                 #endregion
1391
1392                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1393                 {
1394                         if ((a.HasSecurityAttribute)) {
1395                                 a.Error_InvalidSecurityParent ();
1396                                 return;
1397                         }
1398
1399                         EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1400                 }
1401
1402                 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1403                 {
1404                         var ok = base.CheckOverrideAgainstBase (base_member);
1405
1406                         if (!CheckAccessModifiers (this, base_member)) {
1407                                 Error_CannotChangeAccessModifiers (this, base_member);
1408                                 ok = false;
1409                         }
1410
1411                         return ok;
1412                 }
1413
1414                 public override bool Define ()
1415                 {
1416                         if (!base.Define ())
1417                                 return false;
1418
1419                         if (!MemberType.IsDelegate) {
1420                                 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1421                         }
1422
1423                         if (!CheckBase ())
1424                                 return false;
1425
1426                         //
1427                         // Now define the accessors
1428                         //
1429                         add.Define (Parent);
1430                         remove.Define (Parent);
1431
1432                         EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1433
1434                         spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1435
1436                         Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1437                         Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1438                         Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1439
1440                         return true;
1441                 }
1442
1443                 public override void Emit ()
1444                 {
1445                         CheckReservedNameConflict (null, add.Spec);
1446                         CheckReservedNameConflict (null, remove.Spec);
1447
1448                         if (OptAttributes != null) {
1449                                 OptAttributes.Emit ();
1450                         }
1451
1452                         ConstraintChecker.Check (this, member_type, type_expr.Location);
1453
1454                         Add.Emit (Parent);
1455                         Remove.Emit (Parent);
1456
1457                         base.Emit ();
1458                 }
1459
1460                 public override void PrepareEmit ()
1461                 {
1462                         base.PrepareEmit ();
1463
1464                         add.PrepareEmit ();
1465                         remove.PrepareEmit ();
1466
1467                         EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1468                         EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
1469                 }
1470
1471                 public override void WriteDebugSymbol (MonoSymbolFile file)
1472                 {
1473                         add.WriteDebugSymbol (file);
1474                         remove.WriteDebugSymbol (file);
1475                 }
1476
1477                 //
1478                 //   Represents header string for documentation comment.
1479                 //
1480                 public override string DocCommentHeader {
1481                         get { return "E:"; }
1482                 }
1483         }
1484
1485         public class EventSpec : MemberSpec, IInterfaceMemberSpec
1486         {
1487                 MethodSpec add, remove;
1488                 FieldSpec backing_field;
1489
1490                 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1491                         : base (MemberKind.Event, declaringType, definition, modifiers)
1492                 {
1493                         this.AccessorAdd = add;
1494                         this.AccessorRemove = remove;
1495                         this.MemberType = eventType;
1496                 }
1497
1498                 #region Properties
1499
1500                 public MethodSpec AccessorAdd { 
1501                         get {
1502                                 return add;
1503                         }
1504                         set {
1505                                 add = value;
1506                         }
1507                 }
1508
1509                 public MethodSpec AccessorRemove {
1510                         get {
1511                                 return remove;
1512                         }
1513                         set {
1514                                 remove = value;
1515                         }
1516                 }
1517
1518                 public FieldSpec BackingField {
1519                         get {
1520                                 return backing_field;
1521                         }
1522                         set {
1523                                 backing_field = value;
1524                         }
1525                 }
1526
1527                 public TypeSpec MemberType { get; private set; }
1528
1529                 #endregion
1530
1531                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1532                 {
1533                         var es = (EventSpec) base.InflateMember (inflator);
1534                         es.MemberType = inflator.Inflate (MemberType);
1535
1536                         if (backing_field != null)
1537                                 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1538
1539                         return es;
1540                 }
1541
1542                 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1543                 {
1544                         return MemberType.ResolveMissingDependencies (this);
1545                 }
1546         }
1547  
1548         public class Indexer : PropertyBase, IParametersMember
1549         {
1550                 public class GetIndexerMethod : GetMethod, IParametersMember
1551                 {
1552                         ParametersCompiled parameters;
1553
1554                         public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1555                                 : base (property, modifiers, attrs, loc)
1556                         {
1557                                 this.parameters = parameters;
1558                         }
1559
1560                         public override void Define (TypeContainer parent)
1561                         {
1562                                 // Disable reporting, parameters are resolved twice
1563                                 Report.DisableReporting ();
1564                                 try {
1565                                         parameters.Resolve (this);
1566                                 } finally {
1567                                         Report.EnableReporting ();
1568                                 }
1569
1570                                 base.Define (parent);
1571                         }
1572
1573                         public override ParametersCompiled ParameterInfo {
1574                                 get {
1575                                         return parameters;
1576                                 }
1577                         }
1578
1579                         #region IParametersMember Members
1580
1581                         AParametersCollection IParametersMember.Parameters {
1582                                 get {
1583                                         return parameters;
1584                                 }
1585                         }
1586
1587                         TypeSpec IInterfaceMemberSpec.MemberType {
1588                                 get {
1589                                         return ReturnType;
1590                                 }
1591                         }
1592
1593                         #endregion
1594                 }
1595
1596                 public class SetIndexerMethod : SetMethod, IParametersMember
1597                 {
1598                         public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1599                                 : base (property, modifiers, parameters, attrs, loc)
1600                         {
1601                         }
1602
1603                         #region IParametersMember Members
1604
1605                         AParametersCollection IParametersMember.Parameters {
1606                                 get {
1607                                         return parameters;
1608                                 }
1609                         }
1610
1611                         TypeSpec IInterfaceMemberSpec.MemberType {
1612                                 get {
1613                                         return ReturnType;
1614                                 }
1615                         }
1616
1617                         #endregion
1618                 }
1619
1620                 const Modifiers AllowedModifiers =
1621                         Modifiers.NEW |
1622                         Modifiers.PUBLIC |
1623                         Modifiers.PROTECTED |
1624                         Modifiers.INTERNAL |
1625                         Modifiers.PRIVATE |
1626                         Modifiers.VIRTUAL |
1627                         Modifiers.SEALED |
1628                         Modifiers.OVERRIDE |
1629                         Modifiers.UNSAFE |
1630                         Modifiers.EXTERN |
1631                         Modifiers.ABSTRACT;
1632
1633                 const Modifiers AllowedInterfaceModifiers =
1634                         Modifiers.NEW;
1635
1636                 readonly ParametersCompiled parameters;
1637
1638                 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1639                         : base (parent, type, mod,
1640                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1641                                 name, attrs)
1642                 {
1643                         this.parameters = parameters;
1644                 }
1645
1646                 #region Properties
1647
1648                 AParametersCollection IParametersMember.Parameters {
1649                         get {
1650                                 return parameters;
1651                         }
1652                 }
1653
1654                 public ParametersCompiled ParameterInfo {
1655                         get {
1656                                 return parameters;
1657                         }
1658                 }
1659
1660                 #endregion
1661
1662                 
1663                 public override void Accept (StructuralVisitor visitor)
1664                 {
1665                         visitor.Visit (this);
1666                 }
1667
1668                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1669                 {
1670                         if (a.Type == pa.IndexerName) {
1671                                 // Attribute was copied to container
1672                                 return;
1673                         }
1674
1675                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1676                 }
1677
1678                 protected override bool CheckForDuplications ()
1679                 {
1680                         return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1681                 }
1682                 
1683                 public override bool Define ()
1684                 {
1685                         if (!base.Define ())
1686                                 return false;
1687
1688                         if (!DefineParameters (parameters))
1689                                 return false;
1690
1691                         if (OptAttributes != null) {
1692                                 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1693                                 if (indexer_attr != null) {
1694                                         var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1695                                         if (compiling != null)
1696                                                 compiling.Define ();
1697
1698                                         if (IsExplicitImpl) {
1699                                                 Report.Error (415, indexer_attr.Location,
1700                                                         "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1701                                                         indexer_attr.Type.GetSignatureForError ());
1702                                         } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1703                                                 Report.Error (609, indexer_attr.Location,
1704                                                         "Cannot set the `IndexerName' attribute on an indexer marked override");
1705                                         } else {
1706                                                 string name = indexer_attr.GetIndexerAttributeValue ();
1707
1708                                                 if (!string.IsNullOrEmpty (name)) {
1709                                                         SetMemberName (new MemberName (MemberName.Left, name, Location));
1710                                                 }
1711                                         }
1712                                 }
1713                         }
1714
1715                         if (InterfaceType != null) {
1716                                 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1717                                 if (base_IndexerName != ShortName) {
1718                                         SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1719                                 }
1720                         }
1721
1722                         Parent.AddNameToContainer (this, MemberName.Basename);
1723
1724                         flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1725                         
1726                         if (!DefineAccessors ())
1727                                 return false;
1728
1729                         if (!CheckBase ())
1730                                 return false;
1731
1732                         DefineBuilders (MemberKind.Indexer, parameters);
1733                         return true;
1734                 }
1735
1736                 public override bool EnableOverloadChecks (MemberCore overload)
1737                 {
1738                         if (overload is Indexer) {
1739                                 caching_flags |= Flags.MethodOverloadsExist;
1740                                 return true;
1741                         }
1742
1743                         return base.EnableOverloadChecks (overload);
1744                 }
1745
1746                 public override void Emit ()
1747                 {
1748                         parameters.CheckConstraints (this);
1749
1750                         base.Emit ();
1751                 }
1752
1753                 public override string GetSignatureForError ()
1754                 {
1755                         StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1756                         if (MemberName.ExplicitInterface != null) {
1757                                 sb.Append (".");
1758                                 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1759                         }
1760
1761                         sb.Append (".this");
1762                         sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1763                         return sb.ToString ();
1764                 }
1765
1766                 public override string GetSignatureForDocumentation ()
1767                 {
1768                         return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1769                 }
1770
1771                 public override void PrepareEmit ()
1772                 {
1773                         base.PrepareEmit ();
1774                         parameters.ResolveDefaultValues (this);
1775                 }
1776
1777                 protected override bool VerifyClsCompliance ()
1778                 {
1779                         if (!base.VerifyClsCompliance ())
1780                                 return false;
1781
1782                         parameters.VerifyClsCompliance (this);
1783                         return true;
1784                 }
1785         }
1786
1787         public class IndexerSpec : PropertySpec, IParametersMember
1788         {
1789                 AParametersCollection parameters;
1790
1791                 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1792                         : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1793                 {
1794                         this.parameters = parameters;
1795                 }
1796
1797                 #region Properties
1798                 public AParametersCollection Parameters {
1799                         get {
1800                                 return parameters;
1801                         }
1802                 }
1803                 #endregion
1804
1805                 public static ParametersImported CreateParametersFromSetter (MethodSpec setter, int set_param_count)
1806                 {
1807                         //
1808                         // Creates indexer parameters based on setter method parameters (the last parameter has to be removed)
1809                         //
1810                         var data = new IParameterData [set_param_count];
1811                         var types = new TypeSpec [set_param_count];
1812                         Array.Copy (setter.Parameters.FixedParameters, data, set_param_count);
1813                         Array.Copy (setter.Parameters.Types, types, set_param_count);
1814                         return new ParametersImported (data, types, setter.Parameters.HasParams);
1815                 }
1816
1817                 public override string GetSignatureForDocumentation ()
1818                 {
1819                         return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1820                 }
1821
1822                 public override string GetSignatureForError ()
1823                 {
1824                         return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1825                 }
1826
1827                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1828                 {
1829                         var spec = (IndexerSpec) base.InflateMember (inflator);
1830                         spec.parameters = parameters.Inflate (inflator);
1831                         return spec;
1832                 }
1833
1834                 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1835                 {
1836                         var missing = base.ResolveMissingDependencies (caller);
1837
1838                         foreach (var pt in parameters.Types) {
1839                                 var m = pt.GetMissingDependencies (caller);
1840                                 if (m == null)
1841                                         continue;
1842
1843                                 if (missing == null)
1844                                         missing = new List<MissingTypeSpecReference> ();
1845
1846                                 missing.AddRange (m);
1847                         }
1848
1849                         return missing;
1850                 }
1851         }
1852 }