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