Merge pull request #799 from kebby/master
[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                 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 MethodBuilder 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                                 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
209                                         return null;
210
211                                 method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
212
213                                 return method_data.MethodBuilder;
214                         }
215
216                         public override TypeSpec ReturnType {
217                                 get {
218                                         return method.MemberType;
219                                 }
220                         }
221
222                         public override ParametersCompiled ParameterInfo {
223                                 get {
224                                         return ParametersCompiled.EmptyReadOnlyParameters;
225                                 }
226                         }
227
228                         public override string[] ValidAttributeTargets {
229                                 get {
230                                         return attribute_targets;
231                                 }
232                         }
233                 }
234
235                 public class SetMethod : PropertyMethod {
236
237                         static readonly string[] attribute_targets = new string[] { "method", "param", "return" };
238
239                         internal const string Prefix = "set_";
240
241                         protected ParametersCompiled parameters;
242
243                         public SetMethod (PropertyBase method, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
244                                 : base (method, Prefix, modifiers, attrs, loc)
245                         {
246                                 this.parameters = parameters;
247                         }
248
249                         protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
250                         {
251                                 if (a.Target == AttributeTargets.Parameter) {
252                                         parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
253                                         return;
254                                 }
255
256                                 base.ApplyToExtraTarget (a, ctor, cdata, pa);
257                         }
258
259                         public override ParametersCompiled ParameterInfo {
260                             get {
261                                 return parameters;
262                             }
263                         }
264
265                         public override MethodBuilder Define (TypeContainer parent)
266                         {
267                                 parameters.Resolve (this);
268                                 
269                                 base.Define (parent);
270
271                                 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, ModFlags);
272
273                                 method_data = new MethodData (method, ModFlags, flags, this);
274
275                                 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
276                                         return null;
277
278                                 method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
279
280                                 return method_data.MethodBuilder;
281                         }
282
283                         public override TypeSpec ReturnType {
284                                 get {
285                                         return Parent.Compiler.BuiltinTypes.Void;
286                                 }
287                         }
288
289                         public override string[] ValidAttributeTargets {
290                                 get {
291                                         return attribute_targets;
292                                 }
293                         }
294                 }
295
296                 static readonly string[] attribute_targets = new string[] { "property" };
297
298                 public abstract class PropertyMethod : AbstractPropertyEventMethod
299                 {
300                         const Modifiers AllowedModifiers =
301                                 Modifiers.PUBLIC |
302                                 Modifiers.PROTECTED |
303                                 Modifiers.INTERNAL |
304                                 Modifiers.PRIVATE;
305                 
306                         protected readonly PropertyBase method;
307                         protected MethodAttributes flags;
308
309                         public PropertyMethod (PropertyBase method, string prefix, Modifiers modifiers, Attributes attrs, Location loc)
310                                 : base (method, prefix, attrs, loc)
311                         {
312                                 this.method = method;
313                                 this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, modifiers, 0, loc, Report);
314                                 this.ModFlags |= (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
315                         }
316
317                         public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
318                         {
319                                 if (a.Type == pa.MethodImpl) {
320                                         method.is_external_implementation = a.IsInternalCall ();
321                                 }
322
323                                 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
324                         }
325
326                         public override AttributeTargets AttributeTargets {
327                                 get {
328                                         return AttributeTargets.Method;
329                                 }
330                         }
331
332                         public override bool IsClsComplianceRequired ()
333                         {
334                                 return method.IsClsComplianceRequired ();
335                         }
336
337                         public virtual MethodBuilder Define (TypeContainer parent)
338                         {
339                                 var container = parent.PartialContainer;
340
341                                 //
342                                 // Check for custom access modifier
343                                 //
344                                 if ((ModFlags & Modifiers.AccessibilityMask) == 0) {
345                                         ModFlags |= method.ModFlags;
346                                         flags = method.flags;
347                                 } else {
348                                         if (container.Kind == MemberKind.Interface)
349                                                 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
350                                                         GetSignatureForError ());
351                                         else if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
352                                                 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
353                                         }
354
355                                         CheckModifiers (ModFlags);
356                                         ModFlags |= (method.ModFlags & (~Modifiers.AccessibilityMask));
357                                         ModFlags |= Modifiers.PROPERTY_CUSTOM;
358                                         flags = ModifiersExtensions.MethodAttr (ModFlags);
359                                         flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
360                                 }
361
362                                 CheckAbstractAndExtern (block != null);
363                                 CheckProtectedModifier ();
364
365                                 if (block != null) {
366                                         if (block.IsIterator)
367                                                 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
368
369                                         if (Compiler.Settings.WriteMetadataOnly)
370                                                 block = null;
371                                 }
372
373                                 return null;
374                         }
375
376                         public bool HasCustomAccessModifier {
377                                 get {
378                                         return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
379                                 }
380                         }
381
382                         public PropertyBase Property {
383                                 get {
384                                         return method;
385                                 }
386                         }
387
388                         public override ObsoleteAttribute GetAttributeObsolete ()
389                         {
390                                 return method.GetAttributeObsolete ();
391                         }
392
393                         public override string GetSignatureForError()
394                         {
395                                 return method.GetSignatureForError () + "." + prefix.Substring (0, 3);
396                         }
397
398                         void CheckModifiers (Modifiers modflags)
399                         {
400                                 if (!ModifiersExtensions.IsRestrictedModifier (modflags & Modifiers.AccessibilityMask, method.ModFlags & Modifiers.AccessibilityMask)) {
401                                         Report.Error (273, Location,
402                                                 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
403                                                 GetSignatureForError (), method.GetSignatureForError ());
404                                 }
405                         }
406                 }
407
408                 PropertyMethod get, set, first;
409                 PropertyBuilder PropertyBuilder;
410
411                 protected PropertyBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, Modifiers allowed_mod, MemberName name, Attributes attrs)
412                         : base (parent, type, mod_flags, allowed_mod, name, attrs)
413                 {
414                 }
415
416                 #region Properties
417
418                 public override AttributeTargets AttributeTargets {
419                         get {
420                                 return AttributeTargets.Property;
421                         }
422                 }
423
424                 public PropertyMethod AccessorFirst {
425                         get {
426                                 return first;
427                         }
428                 }
429
430                 public PropertyMethod AccessorSecond {
431                         get {
432                                 return first == get ? set : get;
433                         }
434                 }
435
436                 public override Variance ExpectedMemberTypeVariance {
437                         get {
438                                 return (get != null && set != null) ?
439                                         Variance.None : set == null ?
440                                         Variance.Covariant :
441                                         Variance.Contravariant;
442                         }
443                 }
444
445                 public PropertyMethod Get {
446                         get {
447                                 return get;
448                         }
449                         set {
450                                 get = value;
451                                 if (first == null)
452                                         first = value;
453
454                                 Parent.AddNameToContainer (get, get.MemberName.Basename);
455                         }
456                 }
457
458                 public PropertyMethod Set {
459                         get {
460                                 return set;
461                         }
462                         set {
463                                 set = value;
464                                 if (first == null)
465                                         first = value;
466
467                                 Parent.AddNameToContainer (set, set.MemberName.Basename);
468                         }
469                 }
470
471                 public override string[] ValidAttributeTargets {
472                         get {
473                                 return attribute_targets;
474                         }
475                 }
476
477                 #endregion
478
479                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
480                 {
481                         if (a.HasSecurityAttribute) {
482                                 a.Error_InvalidSecurityParent ();
483                                 return;
484                         }
485
486                         if (a.Type == pa.Dynamic) {
487                                 a.Error_MisusedDynamicAttribute ();
488                                 return;
489                         }
490
491                         PropertyBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
492                 }
493
494                 void CheckMissingAccessor (MemberKind kind, ParametersCompiled parameters, bool get)
495                 {
496                         if (IsExplicitImpl) {
497                                 MemberFilter filter;
498                                 if (kind == MemberKind.Indexer)
499                                         filter = new MemberFilter (MemberCache.IndexerNameAlias, 0, kind, parameters, null);
500                                 else
501                                         filter = new MemberFilter (MemberName.Name, 0, kind, null, null);
502
503                                 var implementing = MemberCache.FindMember (InterfaceType, filter, BindingRestriction.DeclaredOnly) as PropertySpec;
504
505                                 if (implementing == null)
506                                         return;
507
508                                 var accessor = get ? implementing.Get : implementing.Set;
509                                 if (accessor != null) {
510                                         Report.SymbolRelatedToPreviousError (accessor);
511                                         Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
512                                                 GetSignatureForError (), accessor.GetSignatureForError ());
513                                 }
514                         }
515                 }
516
517                 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
518                 {
519                         var ok = base.CheckOverrideAgainstBase (base_member);
520
521                         //
522                         // Check base property accessors conflict
523                         //
524                         var base_prop = (PropertySpec) base_member;
525                         if (Get != null) {
526                                 if (!base_prop.HasGet) {
527                                         if (ok) {
528                                                 Report.SymbolRelatedToPreviousError (base_prop);
529                                                 Report.Error (545, Get.Location,
530                                                         "`{0}': cannot override because `{1}' does not have an overridable get accessor",
531                                                         Get.GetSignatureForError (), base_prop.GetSignatureForError ());
532                                                 ok = false;
533                                         }
534                                 } else if (Get.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
535                                         if (!CheckAccessModifiers (Get, base_prop.Get)) {
536                                                 Error_CannotChangeAccessModifiers (Get, base_prop.Get);
537                                                 ok = false;
538                                         }
539                                 }
540                         }
541
542                         if (Set != null) {
543                                 if (!base_prop.HasSet) {
544                                         if (ok) {
545                                                 Report.SymbolRelatedToPreviousError (base_prop);
546                                                 Report.Error (546, Set.Location,
547                                                         "`{0}': cannot override because `{1}' does not have an overridable set accessor",
548                                                         Set.GetSignatureForError (), base_prop.GetSignatureForError ());
549                                                 ok = false;
550                                         }
551                                 } else if (Set.HasCustomAccessModifier || base_prop.HasDifferentAccessibility) {
552                                         if (!CheckAccessModifiers (Set, base_prop.Set)) {
553                                                 Error_CannotChangeAccessModifiers (Set, base_prop.Set);
554                                                 ok = false;
555                                         }
556                                 }
557                         }
558
559                         if ((Set == null || !Set.HasCustomAccessModifier) && (Get == null || !Get.HasCustomAccessModifier)) {
560                                 if (!CheckAccessModifiers (this, base_prop)) {
561                                         Error_CannotChangeAccessModifiers (this, base_prop);
562                                         ok = false;
563                                 }
564                         }
565
566                         return ok;
567                 }
568
569                 protected override void DoMemberTypeDependentChecks ()
570                 {
571                         base.DoMemberTypeDependentChecks ();
572
573                         IsTypePermitted ();
574
575                         if (MemberType.IsStatic)
576                                 Error_StaticReturnType ();
577                 }
578
579                 protected override void DoMemberTypeIndependentChecks ()
580                 {
581                         base.DoMemberTypeIndependentChecks ();
582
583                         //
584                         // Accessors modifiers check
585                         //
586                         if (AccessorSecond != null) {
587                                 if ((Get.ModFlags & Modifiers.AccessibilityMask) != 0 && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) {
588                                         Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
589                                                 GetSignatureForError ());
590                                 }
591                         } else if ((ModFlags & Modifiers.OVERRIDE) == 0 && 
592                                 (Get == null && (Set.ModFlags & Modifiers.AccessibilityMask) != 0) ||
593                                 (Set == null && (Get.ModFlags & Modifiers.AccessibilityMask) != 0)) {
594                                 Report.Error (276, Location, 
595                                               "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
596                                               GetSignatureForError ());
597                         }
598                 }
599
600                 protected bool DefineAccessors ()
601                 {
602                         first.Define (Parent);
603                         if (AccessorSecond != null)
604                                 AccessorSecond.Define (Parent);
605
606                         return true;
607                 }
608
609                 protected void DefineBuilders (MemberKind kind, ParametersCompiled parameters)
610                 {
611                         PropertyBuilder = Parent.TypeBuilder.DefineProperty (
612                                 GetFullName (MemberName), PropertyAttributes.None,
613 #if !BOOTSTRAP_BASIC    // Requires trunk version mscorlib
614                                 IsStatic ? 0 : CallingConventions.HasThis,
615 #endif
616                                 MemberType.GetMetaInfo (), null, null,
617                                 parameters.GetMetaInfo (), null, null);
618
619                         PropertySpec spec;
620                         if (kind == MemberKind.Indexer)
621                                 spec = new IndexerSpec (Parent.Definition, this, MemberType, parameters, PropertyBuilder, ModFlags);
622                         else
623                                 spec = new PropertySpec (kind, Parent.Definition, this, MemberType, PropertyBuilder, ModFlags);
624
625                         if (Get != null) {
626                                 spec.Get = Get.Spec;
627
628                                 var method = Get.Spec.GetMetaInfo () as MethodBuilder;
629                                 if (method != null) {
630                                         PropertyBuilder.SetGetMethod (method);
631                                         Parent.MemberCache.AddMember (this, method.Name, Get.Spec);
632                                 }
633                         } else {
634                                 CheckMissingAccessor (kind, parameters, true);
635                         }
636
637                         if (Set != null) {
638                                 spec.Set = Set.Spec;
639
640                                 var method = Set.Spec.GetMetaInfo () as MethodBuilder;
641                                 if (method != null) {
642                                         PropertyBuilder.SetSetMethod (method);
643                                         Parent.MemberCache.AddMember (this, method.Name, Set.Spec);
644                                 }
645                         } else {
646                                 CheckMissingAccessor (kind, parameters, false);
647                         }
648
649                         Parent.MemberCache.AddMember (this, PropertyBuilder.Name, spec);
650                 }
651
652                 public override void Emit ()
653                 {
654                         CheckReservedNameConflict (GetMethod.Prefix, get == null ? null : get.Spec);
655                         CheckReservedNameConflict (SetMethod.Prefix, set == null ? null : set.Spec);
656
657                         if (OptAttributes != null)
658                                 OptAttributes.Emit ();
659
660                         if (member_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
661                                 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder);
662                         } else if (member_type.HasDynamicElement) {
663                                 Module.PredefinedAttributes.Dynamic.EmitAttribute (PropertyBuilder, member_type, Location);
664                         }
665
666                         ConstraintChecker.Check (this, member_type, type_expr.Location);
667
668                         first.Emit (Parent);
669                         if (AccessorSecond != null)
670                                 AccessorSecond.Emit (Parent);
671
672                         base.Emit ();
673                 }
674
675                 public override bool IsUsed {
676                         get {
677                                 if (IsExplicitImpl)
678                                         return true;
679
680                                 return Get.IsUsed | Set.IsUsed;
681                         }
682                 }
683
684                 protected override void SetMemberName (MemberName new_name)
685                 {
686                         base.SetMemberName (new_name);
687
688                         if (Get != null)
689                                 Get.UpdateName (this);
690
691                         if (Set != null)
692                                 Set.UpdateName (this);
693                 }
694
695                 public override void WriteDebugSymbol (MonoSymbolFile file)
696                 {
697                         if (get != null)
698                                 get.WriteDebugSymbol (file);
699
700                         if (set != null)
701                                 set.WriteDebugSymbol (file);
702                 }
703
704                 //
705                 //   Represents header string for documentation comment.
706                 //
707                 public override string DocCommentHeader {
708                         get { return "P:"; }
709                 }
710         }
711                         
712         public class Property : PropertyBase
713         {
714                 public sealed class BackingField : Field
715                 {
716                         readonly Property property;
717
718                         public BackingField (Property p)
719                                 : base (p.Parent, p.type_expr,
720                                 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (p.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
721                                 new MemberName ("<" + p.GetFullName (p.MemberName) + ">k__BackingField", p.Location), null)
722                         {
723                                 this.property = p;
724                         }
725
726                         public Property OriginalProperty {
727                                 get {
728                                         return property;
729                                 }
730                         }
731
732                         public override string GetSignatureForError ()
733                         {
734                                 return property.GetSignatureForError ();
735                         }
736                 }
737
738                 static readonly string[] attribute_target_auto = new string[] { "property", "field" };
739
740                 Field backing_field;
741
742                 public Property (TypeDefinition parent, FullNamedExpression type, Modifiers mod,
743                                  MemberName name, Attributes attrs)
744                         : base (parent, type, mod,
745                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
746                                 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
747                                 AllowedModifiersClass,
748                                 name, attrs)
749                 {
750                 }
751
752                 public override void Accept (StructuralVisitor visitor)
753                 {
754                         visitor.Visit (this);
755                 }
756
757                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
758                 {
759                         if (a.Target == AttributeTargets.Field) {
760                                 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
761                                 return;
762                         }
763
764                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
765                 }
766
767                 void CreateAutomaticProperty ()
768                 {
769                         // Create backing field
770                         backing_field = new BackingField (this);
771                         if (!backing_field.Define ())
772                                 return;
773
774                         Parent.PartialContainer.Members.Add (backing_field);
775
776                         FieldExpr fe = new FieldExpr (backing_field, Location);
777                         if ((backing_field.ModFlags & Modifiers.STATIC) == 0)
778                                 fe.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
779
780                         //
781                         // Create get block but we careful with location to
782                         // emit only single sequence point per accessor. This allow
783                         // to set a breakpoint on it even with no user code
784                         //
785                         Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
786                         Return r = new Return (fe, Get.Location);
787                         Get.Block.AddStatement (r);
788
789                         // Create set block
790                         Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
791                         Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
792                         Set.Block.AddStatement (new StatementExpression (a, Set.Location));
793                 }
794
795                 public override bool Define ()
796                 {
797                         if (!base.Define ())
798                                 return false;
799
800                         flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
801
802                         if (!IsInterface && (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
803                                 AccessorSecond != null && Get.Block == null && Set.Block == null) {
804                                 if (Compiler.Settings.Version <= LanguageVersion.ISO_2)
805                                         Report.FeatureIsNotAvailable (Compiler, Location, "automatically implemented properties");
806
807                                 Get.ModFlags |= Modifiers.COMPILER_GENERATED;
808                                 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
809                                 CreateAutomaticProperty ();
810                         }
811
812                         if (!DefineAccessors ())
813                                 return false;
814
815                         if (AccessorSecond == null) {
816                                 PropertyMethod pm;
817                                 if (AccessorFirst is GetMethod)
818                                         pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
819                                 else
820                                         pm = new GetMethod (this, 0, null, Location);
821
822                                 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
823                         }
824
825                         if (!CheckBase ())
826                                 return false;
827
828                         DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
829                         return true;
830                 }
831
832                 public override void Emit ()
833                 {
834                         if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
835                                 Report.Error (842, Location,
836                                         "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
837                                         GetSignatureForError ());
838                         }
839
840                         base.Emit ();
841                 }
842
843                 public override string[] ValidAttributeTargets {
844                         get {
845                                 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
846                                         attribute_target_auto : base.ValidAttributeTargets;
847                         }
848                 }
849         }
850
851         /// <summary>
852         /// For case when event is declared like property (with add and remove accessors).
853         /// </summary>
854         public class EventProperty: Event {
855                 public abstract class AEventPropertyAccessor : AEventAccessor
856                 {
857                         protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
858                                 : base (method, prefix, attrs, loc)
859                         {
860                         }
861
862                         public override MethodBuilder Define (TypeContainer ds)
863                         {
864                                 CheckAbstractAndExtern (block != null);
865                                 return base.Define (ds);
866                         }
867                         
868                         public override string GetSignatureForError ()
869                         {
870                                 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
871                         }
872                 }
873
874                 public sealed class AddDelegateMethod: AEventPropertyAccessor
875                 {
876                         public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
877                                 : base (method, AddPrefix, attrs, loc)
878                         {
879                         }
880                 }
881
882                 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
883                 {
884                         public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
885                                 : base (method, RemovePrefix, attrs, loc)
886                         {
887                         }
888                 }
889
890                 static readonly string[] attribute_targets = new string [] { "event" };
891
892                 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
893                         : base (parent, type, mod_flags, name, attrs)
894                 {
895                 }
896
897                 public override void Accept (StructuralVisitor visitor)
898                 {
899                         visitor.Visit (this);
900                 }
901                 
902                 public override bool Define()
903                 {
904                         if (!base.Define ())
905                                 return false;
906
907                         SetIsUsed ();
908                         return true;
909                 }
910
911                 public override string[] ValidAttributeTargets {
912                         get {
913                                 return attribute_targets;
914                         }
915                 }
916         }
917
918         /// <summary>
919         /// Event is declared like field.
920         /// </summary>
921         public class EventField : Event
922         {
923                 abstract class EventFieldAccessor : AEventAccessor
924                 {
925                         protected EventFieldAccessor (EventField method, string prefix)
926                                 : base (method, prefix, null, method.Location)
927                         {
928                         }
929
930                         protected abstract MethodSpec GetOperation (Location loc);
931
932                         public override void Emit (TypeDefinition parent)
933                         {
934                                 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
935                                         block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
936                                                 IsCompilerGenerated = true
937                                         };
938                                         FabricateBodyStatement ();
939                                 }
940
941                                 base.Emit (parent);
942                         }
943
944                         void FabricateBodyStatement ()
945                         {
946                                 //
947                                 // Delegate obj1 = backing_field
948                                 // do {
949                                 //   Delegate obj2 = obj1;
950                                 //   obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
951                                 // } while ((object)obj1 != (object)obj2)
952                                 //
953
954                                 var field_info = ((EventField) method).backing_field;
955                                 FieldExpr f_expr = new FieldExpr (field_info, Location);
956                                 if (!IsStatic)
957                                         f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
958
959                                 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
960                                 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
961
962                                 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
963
964                                 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
965                                         new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
966                                         new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
967
968                                 var body = new ExplicitBlock (block, Location, Location);
969                                 block.AddStatement (new Do (body, cond, Location, Location));
970
971                                 body.AddStatement (new StatementExpression (
972                                         new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
973
974                                 var args_oper = new Arguments (2);
975                                 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
976                                 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
977
978                                 var op_method = GetOperation (Location);
979
980                                 var args = new Arguments (3);
981                                 args.Add (new Argument (f_expr, Argument.AType.Ref));
982                                 args.Add (new Argument (new Cast (
983                                         new TypeExpression (field_info.MemberType, Location),
984                                         new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
985                                         Location)));
986                                 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
987
988                                 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
989                                 if (cas == null)
990                                         return;
991
992                                 body.AddStatement (new StatementExpression (new SimpleAssign (
993                                         new LocalVariableReference (obj1, Location),
994                                         new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
995                         }
996                 }
997
998                 sealed class AddDelegateMethod: EventFieldAccessor
999                 {
1000                         public AddDelegateMethod (EventField method):
1001                                 base (method, AddPrefix)
1002                         {
1003                         }
1004
1005                         protected override MethodSpec GetOperation (Location loc)
1006                         {
1007                                 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1008                         }
1009                 }
1010
1011                 sealed class RemoveDelegateMethod: EventFieldAccessor
1012                 {
1013                         public RemoveDelegateMethod (EventField method):
1014                                 base (method, RemovePrefix)
1015                         {
1016                         }
1017
1018                         protected override MethodSpec GetOperation (Location loc)
1019                         {
1020                                 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1021                         }
1022                 }
1023
1024
1025                 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1026                 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1027
1028                 Expression initializer;
1029                 Field backing_field;
1030                 List<FieldDeclarator> declarators;
1031
1032                 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1033                         : base (parent, type, mod_flags, name, attrs)
1034                 {
1035                         Add = new AddDelegateMethod (this);
1036                         Remove = new RemoveDelegateMethod (this);
1037                 }
1038
1039                 #region Properties
1040
1041                 public List<FieldDeclarator> Declarators {
1042                         get {
1043                                 return this.declarators;
1044                         }
1045                 }
1046
1047                 bool HasBackingField {
1048                         get {
1049                                 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1050                         }
1051                 }
1052
1053                 public Expression Initializer {
1054                         get {
1055                                 return initializer;
1056                         }
1057                         set {
1058                                 initializer = value;
1059                         }
1060                 }
1061
1062                 public override string[] ValidAttributeTargets {
1063                         get {
1064                                 return HasBackingField ? attribute_targets : attribute_targets_interface;
1065                         }
1066                 }
1067
1068                 #endregion
1069
1070                 
1071                 public override void Accept (StructuralVisitor visitor)
1072                 {
1073                         visitor.Visit (this);
1074                 }
1075
1076                 public void AddDeclarator (FieldDeclarator declarator)
1077                 {
1078                         if (declarators == null)
1079                                 declarators = new List<FieldDeclarator> (2);
1080
1081                         declarators.Add (declarator);
1082
1083                         Parent.AddNameToContainer (this, declarator.Name.Value);
1084                 }
1085
1086                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1087                 {
1088                         if (a.Target == AttributeTargets.Field) {
1089                                 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1090                                 return;
1091                         }
1092
1093                         if (a.Target == AttributeTargets.Method) {
1094                                 int errors = Report.Errors;
1095                                 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1096                                 if (errors == Report.Errors)
1097                                         Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1098                                 return;
1099                         }
1100
1101                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1102                 }
1103
1104                 public override bool Define()
1105                 {
1106                         var mod_flags_src = ModFlags;
1107
1108                         if (!base.Define ())
1109                                 return false;
1110
1111                         if (declarators != null) {
1112                                 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFER) != 0)
1113                                         mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFER);
1114
1115                                 var t = new TypeExpression (MemberType, TypeExpression.Location);
1116                                 foreach (var d in declarators) {
1117                                         var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1118
1119                                         if (d.Initializer != null)
1120                                                 ef.initializer = d.Initializer;
1121
1122                                         ef.Define ();
1123                                         Parent.PartialContainer.Members.Add (ef);
1124                                 }
1125                         }
1126
1127                         if (!HasBackingField) {
1128                                 SetIsUsed ();
1129                                 return true;
1130                         }
1131
1132                         if (Add.IsInterfaceImplementation)
1133                                 SetIsUsed ();
1134
1135                         backing_field = new Field (Parent,
1136                                 new TypeExpression (MemberType, Location),
1137                                 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1138                                 MemberName, null);
1139
1140                         Parent.PartialContainer.Members.Add (backing_field);
1141                         backing_field.Initializer = Initializer;
1142                         backing_field.ModFlags &= ~Modifiers.COMPILER_GENERATED;
1143
1144                         // Call define because we passed fields definition
1145                         backing_field.Define ();
1146
1147                         // Set backing field for event fields
1148                         spec.BackingField = backing_field.Spec;
1149
1150                         return true;
1151                 }
1152         }
1153
1154         public abstract class Event : PropertyBasedMember
1155         {
1156                 public abstract class AEventAccessor : AbstractPropertyEventMethod
1157                 {
1158                         protected readonly Event method;
1159                         readonly ParametersCompiled parameters;
1160
1161                         static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1162
1163                         public const string AddPrefix = "add_";
1164                         public const string RemovePrefix = "remove_";
1165
1166                         protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1167                                 : base (method, prefix, attrs, loc)
1168                         {
1169                                 this.method = method;
1170                                 this.ModFlags = method.ModFlags;
1171                                 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1172                         }
1173
1174                         public bool IsInterfaceImplementation {
1175                                 get { return method_data.implementing != null; }
1176                         }
1177
1178                         public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1179                         {
1180                                 if (a.Type == pa.MethodImpl) {
1181                                         method.is_external_implementation = a.IsInternalCall ();
1182                                 }
1183
1184                                 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1185                         }
1186
1187                         protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1188                         {
1189                                 if (a.Target == AttributeTargets.Parameter) {
1190                                         parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1191                                         return;
1192                                 }
1193
1194                                 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1195                         }
1196
1197                         public override AttributeTargets AttributeTargets {
1198                                 get {
1199                                         return AttributeTargets.Method;
1200                                 }
1201                         }
1202
1203                         public override bool IsClsComplianceRequired ()
1204                         {
1205                                 return method.IsClsComplianceRequired ();
1206                         }
1207
1208                         public virtual MethodBuilder Define (TypeContainer parent)
1209                         {
1210                                 // Fill in already resolved event type to speed things up and
1211                                 // avoid confusing duplicate errors
1212                                 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1213                                 parameters.Types = new TypeSpec[] { method.member_type };
1214
1215                                 method_data = new MethodData (method, method.ModFlags,
1216                                         method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1217
1218                                 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1219                                         return null;
1220
1221                                 method_data.DefineMethodBuilder (parent.PartialContainer, ParameterInfo);
1222
1223                                 if (Compiler.Settings.WriteMetadataOnly)
1224                                         block = null;
1225
1226                                 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1227                                 Spec.IsAccessor = true;
1228
1229                                 return method_data.MethodBuilder;
1230                         }
1231
1232                         public override TypeSpec ReturnType {
1233                                 get {
1234                                         return Parent.Compiler.BuiltinTypes.Void;
1235                                 }
1236                         }
1237
1238                         public override ObsoleteAttribute GetAttributeObsolete ()
1239                         {
1240                                 return method.GetAttributeObsolete ();
1241                         }
1242
1243                         public override string[] ValidAttributeTargets {
1244                                 get {
1245                                         return attribute_targets;
1246                                 }
1247                         }
1248
1249                         public override ParametersCompiled ParameterInfo {
1250                                 get {
1251                                         return parameters;
1252                                 }
1253                         }
1254                 }
1255
1256                 AEventAccessor add, remove;
1257                 EventBuilder EventBuilder;
1258                 protected EventSpec spec;
1259
1260                 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1261                         : base (parent, type, mod_flags,
1262                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1263                                 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1264                                 AllowedModifiersClass,
1265                                 name, attrs)
1266                 {
1267                 }
1268
1269                 #region Properties
1270
1271                 public override AttributeTargets AttributeTargets {
1272                         get {
1273                                 return AttributeTargets.Event;
1274                         }
1275                 }
1276
1277                 public AEventAccessor Add {
1278                         get {
1279                                 return this.add;
1280                         }
1281                         set {
1282                                 add = value;
1283                                 Parent.AddNameToContainer (value, value.MemberName.Basename);
1284                         }
1285                 }
1286
1287                 public override Variance ExpectedMemberTypeVariance {
1288                         get {
1289                                 return Variance.Contravariant;
1290                         }
1291                 }
1292
1293                 public AEventAccessor Remove {
1294                         get {
1295                                 return this.remove;
1296                         }
1297                         set {
1298                                 remove = value;
1299                                 Parent.AddNameToContainer (value, value.MemberName.Basename);
1300                         }
1301                 }
1302                 #endregion
1303
1304                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1305                 {
1306                         if ((a.HasSecurityAttribute)) {
1307                                 a.Error_InvalidSecurityParent ();
1308                                 return;
1309                         }
1310
1311                         EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1312                 }
1313
1314                 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1315                 {
1316                         var ok = base.CheckOverrideAgainstBase (base_member);
1317
1318                         if (!CheckAccessModifiers (this, base_member)) {
1319                                 Error_CannotChangeAccessModifiers (this, base_member);
1320                                 ok = false;
1321                         }
1322
1323                         return ok;
1324                 }
1325
1326                 public override bool Define ()
1327                 {
1328                         if (!base.Define ())
1329                                 return false;
1330
1331                         if (!MemberType.IsDelegate) {
1332                                 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1333                         }
1334
1335                         if (!CheckBase ())
1336                                 return false;
1337
1338                         //
1339                         // Now define the accessors
1340                         //
1341                         var AddBuilder = Add.Define (Parent);
1342                         if (AddBuilder == null)
1343                                 return false;
1344
1345                         var RemoveBuilder = remove.Define (Parent);
1346                         if (RemoveBuilder == null)
1347                                 return false;
1348
1349                         EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1350                         EventBuilder.SetAddOnMethod (AddBuilder);
1351                         EventBuilder.SetRemoveOnMethod (RemoveBuilder);
1352
1353                         spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1354
1355                         Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1356                         Parent.MemberCache.AddMember (this, AddBuilder.Name, Add.Spec);
1357                         Parent.MemberCache.AddMember (this, RemoveBuilder.Name, remove.Spec);
1358
1359                         return true;
1360                 }
1361
1362                 public override void Emit ()
1363                 {
1364                         CheckReservedNameConflict (null, add.Spec);
1365                         CheckReservedNameConflict (null, remove.Spec);
1366
1367                         if (OptAttributes != null) {
1368                                 OptAttributes.Emit ();
1369                         }
1370
1371                         ConstraintChecker.Check (this, member_type, type_expr.Location);
1372
1373                         Add.Emit (Parent);
1374                         Remove.Emit (Parent);
1375
1376                         base.Emit ();
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 MethodBuilder 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                                 return 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 }