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