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