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