Merge pull request #3583 from xmcclure/test-418-checked
[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
826                         //
827                         // Create get block but we careful with location to
828                         // emit only single sequence point per accessor. This allow
829                         // to set a breakpoint on it even with no user code
830                         //
831                         Get.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location.Null);
832                         Return r = new Return (fe, Get.Location);
833                         Get.Block.AddStatement (r);
834                         Get.ModFlags |= Modifiers.COMPILER_GENERATED;
835
836                         // Create set block
837                         if (Set != null) {
838                                 Set.Block = new ToplevelBlock (Compiler, Set.ParameterInfo, Location.Null);
839                                 Assign a = new SimpleAssign (fe, new SimpleName ("value", Location.Null), Location.Null);
840                                 Set.Block.AddStatement (new StatementExpression (a, Set.Location));
841                                 Set.ModFlags |= Modifiers.COMPILER_GENERATED;
842                         }
843                 }
844
845                 public override bool Define ()
846                 {
847                         if (!base.Define ())
848                                 return false;
849
850                         flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
851
852                         bool auto = AccessorFirst.Block == null && (AccessorSecond == null || AccessorSecond.Block == null) &&
853                                 (ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0;
854
855                         if (Initializer != null) {
856                                 if (!auto)
857                                         Report.Error (8050, Location, "`{0}': Only auto-implemented properties can have initializers",
858                                                 GetSignatureForError ());
859
860                                 if (IsInterface)
861                                         Report.Error (8052, Location, "`{0}': Properties inside interfaces cannot have initializers",
862                                                 GetSignatureForError ());
863
864                                 if (Compiler.Settings.Version < LanguageVersion.V_6)
865                                         Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented property initializer");
866                         }
867
868                         if (auto) {
869                                 ModFlags |= Modifiers.AutoProperty;
870                                 if (Get == null) {
871                                         Report.Error (8051, Location, "Auto-implemented property `{0}' must have get accessor",
872                                                 GetSignatureForError ());
873                                         return false;
874                                 }
875
876                                 if (Compiler.Settings.Version < LanguageVersion.V_3 && Initializer == null)
877                                         Report.FeatureIsNotAvailable (Compiler, Location, "auto-implemented properties");
878
879                                 CreateAutomaticProperty ();
880                         }
881
882                         if (!DefineAccessors ())
883                                 return false;
884
885                         if (AccessorSecond == null) {
886                                 PropertyMethod pm;
887                                 if (AccessorFirst is GetMethod)
888                                         pm = new SetMethod (this, 0, ParametersCompiled.EmptyReadOnlyParameters, null, Location);
889                                 else
890                                         pm = new GetMethod (this, 0, null, Location);
891
892                                 Parent.AddNameToContainer (pm, pm.MemberName.Basename);
893                         }
894
895                         if (!CheckBase ())
896                                 return false;
897
898                         DefineBuilders (MemberKind.Property, ParametersCompiled.EmptyReadOnlyParameters);
899                         return true;
900                 }
901
902                 public override void Emit ()
903                 {
904                         if ((AccessorFirst.ModFlags & (Modifiers.STATIC | Modifiers.AutoProperty)) == Modifiers.AutoProperty && Parent.PartialContainer.HasExplicitLayout) {
905                                 Report.Error (842, Location,
906                                         "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
907                                         GetSignatureForError ());
908                         }
909
910                         base.Emit ();
911                 }
912
913                 public override string[] ValidAttributeTargets {
914                         get {
915                                 return Get != null && ((Get.ModFlags & Modifiers.COMPILER_GENERATED) != 0) ?
916                                         attribute_target_auto : base.ValidAttributeTargets;
917                         }
918                 }
919         }
920
921         /// <summary>
922         /// For case when event is declared like property (with add and remove accessors).
923         /// </summary>
924         public class EventProperty: Event {
925                 public abstract class AEventPropertyAccessor : AEventAccessor
926                 {
927                         protected AEventPropertyAccessor (EventProperty method, string prefix, Attributes attrs, Location loc)
928                                 : base (method, prefix, attrs, loc)
929                         {
930                         }
931
932                         public override void Define (TypeContainer ds)
933                         {
934                                 CheckAbstractAndExtern (block != null);
935                                 base.Define (ds);
936                         }
937                         
938                         public override string GetSignatureForError ()
939                         {
940                                 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
941                         }
942                 }
943
944                 public sealed class AddDelegateMethod: AEventPropertyAccessor
945                 {
946                         public AddDelegateMethod (EventProperty method, Attributes attrs, Location loc)
947                                 : base (method, AddPrefix, attrs, loc)
948                         {
949                         }
950                 }
951
952                 public sealed class RemoveDelegateMethod: AEventPropertyAccessor
953                 {
954                         public RemoveDelegateMethod (EventProperty method, Attributes attrs, Location loc)
955                                 : base (method, RemovePrefix, attrs, loc)
956                         {
957                         }
958                 }
959
960                 static readonly string[] attribute_targets = new string [] { "event" };
961
962                 public EventProperty (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
963                         : base (parent, type, mod_flags, name, attrs)
964                 {
965                 }
966
967                 public override void Accept (StructuralVisitor visitor)
968                 {
969                         visitor.Visit (this);
970                 }
971                 
972                 public override bool Define()
973                 {
974                         if (!base.Define ())
975                                 return false;
976
977                         SetIsUsed ();
978                         return true;
979                 }
980
981                 public override string[] ValidAttributeTargets {
982                         get {
983                                 return attribute_targets;
984                         }
985                 }
986         }
987
988         /// <summary>
989         /// Event is declared like field.
990         /// </summary>
991         public class EventField : Event
992         {
993                 abstract class EventFieldAccessor : AEventAccessor
994                 {
995                         protected EventFieldAccessor (EventField method, string prefix)
996                                 : base (method, prefix, null, method.Location)
997                         {
998                         }
999
1000                         protected abstract MethodSpec GetOperation (Location loc);
1001
1002                         public override void Emit (TypeDefinition parent)
1003                         {
1004                                 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 && !Compiler.Settings.WriteMetadataOnly) {
1005                                         block = new ToplevelBlock (Compiler, ParameterInfo, Location) {
1006                                                 IsCompilerGenerated = true
1007                                         };
1008                                         FabricateBodyStatement ();
1009                                 }
1010
1011                                 base.Emit (parent);
1012                         }
1013
1014                         void FabricateBodyStatement ()
1015                         {
1016                                 //
1017                                 // Delegate obj1 = backing_field
1018                                 // do {
1019                                 //   Delegate obj2 = obj1;
1020                                 //   obj1 = Interlocked.CompareExchange (ref backing_field, Delegate.Combine|Remove(obj2, value), obj1);
1021                                 // } while ((object)obj1 != (object)obj2)
1022                                 //
1023
1024                                 var field_info = ((EventField) method).backing_field;
1025                                 FieldExpr f_expr = new FieldExpr (field_info, Location);
1026                                 if (!IsStatic)
1027                                         f_expr.InstanceExpression = new CompilerGeneratedThis (Parent.CurrentType, Location);
1028
1029                                 var obj1 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1030                                 var obj2 = LocalVariable.CreateCompilerGenerated (field_info.MemberType, block, Location);
1031
1032                                 block.AddStatement (new StatementExpression (new SimpleAssign (new LocalVariableReference (obj1, Location), f_expr)));
1033
1034                                 var cond = new BooleanExpression (new Binary (Binary.Operator.Inequality,
1035                                         new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj1, Location), Location),
1036                                         new Cast (new TypeExpression (Module.Compiler.BuiltinTypes.Object, Location), new LocalVariableReference (obj2, Location), Location)));
1037
1038                                 var body = new ExplicitBlock (block, Location, Location);
1039                                 block.AddStatement (new Do (body, cond, Location, Location));
1040
1041                                 body.AddStatement (new StatementExpression (
1042                                         new SimpleAssign (new LocalVariableReference (obj2, Location), new LocalVariableReference (obj1, Location))));
1043
1044                                 var args_oper = new Arguments (2);
1045                                 args_oper.Add (new Argument (new LocalVariableReference (obj2, Location)));
1046                                 args_oper.Add (new Argument (block.GetParameterReference (0, Location)));
1047
1048                                 var op_method = GetOperation (Location);
1049
1050                                 var args = new Arguments (3);
1051                                 args.Add (new Argument (f_expr, Argument.AType.Ref));
1052                                 args.Add (new Argument (new Cast (
1053                                         new TypeExpression (field_info.MemberType, Location),
1054                                         new Invocation (MethodGroupExpr.CreatePredefined (op_method, op_method.DeclaringType, Location), args_oper),
1055                                         Location)));
1056                                 args.Add (new Argument (new LocalVariableReference (obj1, Location)));
1057
1058                                 var cas = Module.PredefinedMembers.InterlockedCompareExchange_T.Get ();
1059                                 if (cas == null) {
1060                                         if (Module.PredefinedMembers.MonitorEnter_v4.Get () != null || Module.PredefinedMembers.MonitorEnter.Get () != null) {
1061                                                 // Workaround for cripled (e.g. microframework) mscorlib without CompareExchange
1062                                                 body.AddStatement (new Lock (
1063                                                         block.GetParameterReference (0, Location),
1064                                                         new StatementExpression (new SimpleAssign (
1065                                                                 f_expr, args [1].Expr, Location), Location), Location));
1066                                         } else {
1067                                                 Module.PredefinedMembers.InterlockedCompareExchange_T.Resolve (Location);
1068                                         }
1069                                 } else {
1070                                         body.AddStatement (new StatementExpression (new SimpleAssign (
1071                                                 new LocalVariableReference (obj1, Location),
1072                                                 new Invocation (MethodGroupExpr.CreatePredefined (cas, cas.DeclaringType, Location), args))));
1073                                 }
1074                         }
1075                 }
1076
1077                 sealed class AddDelegateMethod: EventFieldAccessor
1078                 {
1079                         public AddDelegateMethod (EventField method):
1080                                 base (method, AddPrefix)
1081                         {
1082                         }
1083
1084                         protected override MethodSpec GetOperation (Location loc)
1085                         {
1086                                 return Module.PredefinedMembers.DelegateCombine.Resolve (loc);
1087                         }
1088                 }
1089
1090                 sealed class RemoveDelegateMethod: EventFieldAccessor
1091                 {
1092                         public RemoveDelegateMethod (EventField method):
1093                                 base (method, RemovePrefix)
1094                         {
1095                         }
1096
1097                         protected override MethodSpec GetOperation (Location loc)
1098                         {
1099                                 return Module.PredefinedMembers.DelegateRemove.Resolve (loc);
1100                         }
1101                 }
1102
1103
1104                 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
1105                 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
1106
1107                 Expression initializer;
1108                 Field backing_field;
1109                 List<FieldDeclarator> declarators;
1110
1111                 public EventField (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1112                         : base (parent, type, mod_flags, name, attrs)
1113                 {
1114                         Add = new AddDelegateMethod (this);
1115                         Remove = new RemoveDelegateMethod (this);
1116                 }
1117
1118                 #region Properties
1119
1120                 public List<FieldDeclarator> Declarators {
1121                         get {
1122                                 return this.declarators;
1123                         }
1124                 }
1125
1126                 bool HasBackingField {
1127                         get {
1128                                 return !IsInterface && (ModFlags & Modifiers.ABSTRACT) == 0;
1129                         }
1130                 }
1131
1132                 public Expression Initializer {
1133                         get {
1134                                 return initializer;
1135                         }
1136                         set {
1137                                 initializer = value;
1138                         }
1139                 }
1140
1141                 public override string[] ValidAttributeTargets {
1142                         get {
1143                                 return HasBackingField ? attribute_targets : attribute_targets_interface;
1144                         }
1145                 }
1146
1147                 #endregion
1148
1149                 
1150                 public override void Accept (StructuralVisitor visitor)
1151                 {
1152                         visitor.Visit (this);
1153                 }
1154
1155                 public void AddDeclarator (FieldDeclarator declarator)
1156                 {
1157                         if (declarators == null)
1158                                 declarators = new List<FieldDeclarator> (2);
1159
1160                         declarators.Add (declarator);
1161
1162                         Parent.AddNameToContainer (this, declarator.Name.Value);
1163                 }
1164
1165                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1166                 {
1167                         if (a.Target == AttributeTargets.Field) {
1168                                 backing_field.ApplyAttributeBuilder (a, ctor, cdata, pa);
1169                                 return;
1170                         }
1171
1172                         if (a.Target == AttributeTargets.Method) {
1173                                 int errors = Report.Errors;
1174                                 Add.ApplyAttributeBuilder (a, ctor, cdata, pa);
1175                                 if (errors == Report.Errors)
1176                                         Remove.ApplyAttributeBuilder (a, ctor, cdata, pa);
1177                                 return;
1178                         }
1179
1180                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1181                 }
1182
1183                 public override bool Define()
1184                 {
1185                         var mod_flags_src = ModFlags;
1186
1187                         if (!base.Define ())
1188                                 return false;
1189
1190                         if (declarators != null) {
1191                                 if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0)
1192                                         mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFIER);
1193
1194                                 var t = new TypeExpression (MemberType, TypeExpression.Location);
1195                                 foreach (var d in declarators) {
1196                                         var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
1197
1198                                         if (d.Initializer != null)
1199                                                 ef.initializer = d.Initializer;
1200
1201                                         ef.Define ();
1202                                         Parent.PartialContainer.Members.Add (ef);
1203                                 }
1204                         }
1205
1206                         if (!HasBackingField) {
1207                                 SetIsUsed ();
1208                                 return true;
1209                         }
1210
1211                         backing_field = new Field (Parent,
1212                                 new TypeExpression (MemberType, Location),
1213                                 Modifiers.BACKING_FIELD | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
1214                                 MemberName, null);
1215
1216                         Parent.PartialContainer.Members.Add (backing_field);
1217                         backing_field.Initializer = Initializer;
1218
1219                         // Call define because we passed fields definition
1220                         backing_field.Define ();
1221
1222                         // Set backing field for event fields
1223                         spec.BackingField = backing_field.Spec;
1224
1225                         return true;
1226                 }
1227         }
1228
1229         public abstract class Event : PropertyBasedMember
1230         {
1231                 public abstract class AEventAccessor : AbstractPropertyEventMethod
1232                 {
1233                         protected readonly Event method;
1234                         readonly ParametersCompiled parameters;
1235
1236                         static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
1237
1238                         public const string AddPrefix = "add_";
1239                         public const string RemovePrefix = "remove_";
1240
1241                         protected AEventAccessor (Event method, string prefix, Attributes attrs, Location loc)
1242                                 : base (method, prefix, attrs, loc)
1243                         {
1244                                 this.method = method;
1245                                 this.ModFlags = method.ModFlags;
1246                                 this.parameters = ParametersCompiled.CreateImplicitParameter (method.TypeExpression, loc);
1247                         }
1248
1249                         public bool IsInterfaceImplementation {
1250                                 get { return method_data.implementing != null; }
1251                         }
1252
1253                         public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1254                         {
1255                                 if (a.Type == pa.MethodImpl) {
1256                                         method.is_external_implementation = a.IsInternalCall ();
1257                                 }
1258
1259                                 base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1260                         }
1261
1262                         protected override void ApplyToExtraTarget (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1263                         {
1264                                 if (a.Target == AttributeTargets.Parameter) {
1265                                         parameters[0].ApplyAttributeBuilder (a, ctor, cdata, pa);
1266                                         return;
1267                                 }
1268
1269                                 base.ApplyToExtraTarget (a, ctor, cdata, pa);
1270                         }
1271
1272                         public override AttributeTargets AttributeTargets {
1273                                 get {
1274                                         return AttributeTargets.Method;
1275                                 }
1276                         }
1277
1278                         public override bool IsClsComplianceRequired ()
1279                         {
1280                                 return method.IsClsComplianceRequired ();
1281                         }
1282
1283                         public virtual void Define (TypeContainer parent)
1284                         {
1285                                 // Fill in already resolved event type to speed things up and
1286                                 // avoid confusing duplicate errors
1287                                 ((Parameter) parameters.FixedParameters[0]).Type = method.member_type;
1288                                 parameters.Types = new TypeSpec[] { method.member_type };
1289
1290                                 method_data = new MethodData (method, method.ModFlags,
1291                                         method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
1292
1293                                 if (!method_data.Define (parent.PartialContainer, method.GetFullName (MemberName)))
1294                                         return;
1295
1296                                 if (Compiler.Settings.WriteMetadataOnly)
1297                                         block = null;
1298
1299                                 Spec = new MethodSpec (MemberKind.Method, parent.PartialContainer.Definition, this, ReturnType, ParameterInfo, method.ModFlags);
1300                                 Spec.IsAccessor = true;
1301                         }
1302
1303                         public override TypeSpec ReturnType {
1304                                 get {
1305                                         return Parent.Compiler.BuiltinTypes.Void;
1306                                 }
1307                         }
1308
1309                         public override ObsoleteAttribute GetAttributeObsolete ()
1310                         {
1311                                 return method.GetAttributeObsolete ();
1312                         }
1313
1314                         public MethodData MethodData {
1315                                 get {
1316                                         return method_data;
1317                                 }
1318                         }
1319
1320                         public override string[] ValidAttributeTargets {
1321                                 get {
1322                                         return attribute_targets;
1323                                 }
1324                         }
1325
1326                         public override ParametersCompiled ParameterInfo {
1327                                 get {
1328                                         return parameters;
1329                                 }
1330                         }
1331                 }
1332
1333                 AEventAccessor add, remove;
1334                 EventBuilder EventBuilder;
1335                 protected EventSpec spec;
1336
1337                 protected Event (TypeDefinition parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs)
1338                         : base (parent, type, mod_flags,
1339                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedModifiersInterface :
1340                                 parent.PartialContainer.Kind == MemberKind.Struct ? AllowedModifiersStruct :
1341                                 AllowedModifiersClass,
1342                                 name, attrs)
1343                 {
1344                 }
1345
1346                 #region Properties
1347
1348                 public override AttributeTargets AttributeTargets {
1349                         get {
1350                                 return AttributeTargets.Event;
1351                         }
1352                 }
1353
1354                 public AEventAccessor Add {
1355                         get {
1356                                 return this.add;
1357                         }
1358                         set {
1359                                 add = value;
1360                                 Parent.AddNameToContainer (value, value.MemberName.Basename);
1361                         }
1362                 }
1363
1364                 public override Variance ExpectedMemberTypeVariance {
1365                         get {
1366                                 return Variance.Contravariant;
1367                         }
1368                 }
1369
1370                 public AEventAccessor Remove {
1371                         get {
1372                                 return this.remove;
1373                         }
1374                         set {
1375                                 remove = value;
1376                                 Parent.AddNameToContainer (value, value.MemberName.Basename);
1377                         }
1378                 }
1379                 #endregion
1380
1381                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1382                 {
1383                         if ((a.HasSecurityAttribute)) {
1384                                 a.Error_InvalidSecurityParent ();
1385                                 return;
1386                         }
1387
1388                         EventBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
1389                 }
1390
1391                 protected override bool CheckOverrideAgainstBase (MemberSpec base_member)
1392                 {
1393                         var ok = base.CheckOverrideAgainstBase (base_member);
1394
1395                         if (!CheckAccessModifiers (this, base_member)) {
1396                                 Error_CannotChangeAccessModifiers (this, base_member);
1397                                 ok = false;
1398                         }
1399
1400                         return ok;
1401                 }
1402
1403                 public override bool Define ()
1404                 {
1405                         if (!base.Define ())
1406                                 return false;
1407
1408                         if (!MemberType.IsDelegate) {
1409                                 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
1410                         }
1411
1412                         if (!CheckBase ())
1413                                 return false;
1414
1415                         //
1416                         // Now define the accessors
1417                         //
1418                         add.Define (Parent);
1419                         remove.Define (Parent);
1420
1421                         EventBuilder = Parent.TypeBuilder.DefineEvent (GetFullName (MemberName), EventAttributes.None, MemberType.GetMetaInfo ());
1422
1423                         spec = new EventSpec (Parent.Definition, this, MemberType, ModFlags, Add.Spec, remove.Spec);
1424
1425                         Parent.MemberCache.AddMember (this, GetFullName (MemberName), spec);
1426                         Parent.MemberCache.AddMember (this, Add.Spec.Name, Add.Spec);
1427                         Parent.MemberCache.AddMember (this, Remove.Spec.Name, remove.Spec);
1428
1429                         return true;
1430                 }
1431
1432                 public override void Emit ()
1433                 {
1434                         CheckReservedNameConflict (null, add.Spec);
1435                         CheckReservedNameConflict (null, remove.Spec);
1436
1437                         if (OptAttributes != null) {
1438                                 OptAttributes.Emit ();
1439                         }
1440
1441                         ConstraintChecker.Check (this, member_type, type_expr.Location);
1442
1443                         Add.Emit (Parent);
1444                         Remove.Emit (Parent);
1445
1446                         base.Emit ();
1447                 }
1448
1449                 public override void PrepareEmit ()
1450                 {
1451                         base.PrepareEmit ();
1452
1453                         add.PrepareEmit ();
1454                         remove.PrepareEmit ();
1455
1456                         EventBuilder.SetAddOnMethod (add.MethodData.MethodBuilder);
1457                         EventBuilder.SetRemoveOnMethod (remove.MethodData.MethodBuilder);
1458                 }
1459
1460                 public override void WriteDebugSymbol (MonoSymbolFile file)
1461                 {
1462                         add.WriteDebugSymbol (file);
1463                         remove.WriteDebugSymbol (file);
1464                 }
1465
1466                 //
1467                 //   Represents header string for documentation comment.
1468                 //
1469                 public override string DocCommentHeader {
1470                         get { return "E:"; }
1471                 }
1472         }
1473
1474         public class EventSpec : MemberSpec, IInterfaceMemberSpec
1475         {
1476                 MethodSpec add, remove;
1477                 FieldSpec backing_field;
1478
1479                 public EventSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec eventType, Modifiers modifiers, MethodSpec add, MethodSpec remove)
1480                         : base (MemberKind.Event, declaringType, definition, modifiers)
1481                 {
1482                         this.AccessorAdd = add;
1483                         this.AccessorRemove = remove;
1484                         this.MemberType = eventType;
1485                 }
1486
1487                 #region Properties
1488
1489                 public MethodSpec AccessorAdd { 
1490                         get {
1491                                 return add;
1492                         }
1493                         set {
1494                                 add = value;
1495                         }
1496                 }
1497
1498                 public MethodSpec AccessorRemove {
1499                         get {
1500                                 return remove;
1501                         }
1502                         set {
1503                                 remove = value;
1504                         }
1505                 }
1506
1507                 public FieldSpec BackingField {
1508                         get {
1509                                 return backing_field;
1510                         }
1511                         set {
1512                                 backing_field = value;
1513                         }
1514                 }
1515
1516                 public TypeSpec MemberType { get; private set; }
1517
1518                 #endregion
1519
1520                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1521                 {
1522                         var es = (EventSpec) base.InflateMember (inflator);
1523                         es.MemberType = inflator.Inflate (MemberType);
1524
1525                         if (backing_field != null)
1526                                 es.backing_field = (FieldSpec) backing_field.InflateMember (inflator);
1527
1528                         return es;
1529                 }
1530
1531                 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1532                 {
1533                         return MemberType.ResolveMissingDependencies (this);
1534                 }
1535         }
1536  
1537         public class Indexer : PropertyBase, IParametersMember
1538         {
1539                 public class GetIndexerMethod : GetMethod, IParametersMember
1540                 {
1541                         ParametersCompiled parameters;
1542
1543                         public GetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1544                                 : base (property, modifiers, attrs, loc)
1545                         {
1546                                 this.parameters = parameters;
1547                         }
1548
1549                         public override void Define (TypeContainer parent)
1550                         {
1551                                 // Disable reporting, parameters are resolved twice
1552                                 Report.DisableReporting ();
1553                                 try {
1554                                         parameters.Resolve (this);
1555                                 } finally {
1556                                         Report.EnableReporting ();
1557                                 }
1558
1559                                 base.Define (parent);
1560                         }
1561
1562                         public override ParametersCompiled ParameterInfo {
1563                                 get {
1564                                         return parameters;
1565                                 }
1566                         }
1567
1568                         #region IParametersMember Members
1569
1570                         AParametersCollection IParametersMember.Parameters {
1571                                 get {
1572                                         return parameters;
1573                                 }
1574                         }
1575
1576                         TypeSpec IInterfaceMemberSpec.MemberType {
1577                                 get {
1578                                         return ReturnType;
1579                                 }
1580                         }
1581
1582                         #endregion
1583                 }
1584
1585                 public class SetIndexerMethod : SetMethod, IParametersMember
1586                 {
1587                         public SetIndexerMethod (PropertyBase property, Modifiers modifiers, ParametersCompiled parameters, Attributes attrs, Location loc)
1588                                 : base (property, modifiers, parameters, attrs, loc)
1589                         {
1590                         }
1591
1592                         #region IParametersMember Members
1593
1594                         AParametersCollection IParametersMember.Parameters {
1595                                 get {
1596                                         return parameters;
1597                                 }
1598                         }
1599
1600                         TypeSpec IInterfaceMemberSpec.MemberType {
1601                                 get {
1602                                         return ReturnType;
1603                                 }
1604                         }
1605
1606                         #endregion
1607                 }
1608
1609                 const Modifiers AllowedModifiers =
1610                         Modifiers.NEW |
1611                         Modifiers.PUBLIC |
1612                         Modifiers.PROTECTED |
1613                         Modifiers.INTERNAL |
1614                         Modifiers.PRIVATE |
1615                         Modifiers.VIRTUAL |
1616                         Modifiers.SEALED |
1617                         Modifiers.OVERRIDE |
1618                         Modifiers.UNSAFE |
1619                         Modifiers.EXTERN |
1620                         Modifiers.ABSTRACT;
1621
1622                 const Modifiers AllowedInterfaceModifiers =
1623                         Modifiers.NEW;
1624
1625                 readonly ParametersCompiled parameters;
1626
1627                 public Indexer (TypeDefinition parent, FullNamedExpression type, MemberName name, Modifiers mod, ParametersCompiled parameters, Attributes attrs)
1628                         : base (parent, type, mod,
1629                                 parent.PartialContainer.Kind == MemberKind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
1630                                 name, attrs)
1631                 {
1632                         this.parameters = parameters;
1633                 }
1634
1635                 #region Properties
1636
1637                 AParametersCollection IParametersMember.Parameters {
1638                         get {
1639                                 return parameters;
1640                         }
1641                 }
1642
1643                 public ParametersCompiled ParameterInfo {
1644                         get {
1645                                 return parameters;
1646                         }
1647                 }
1648
1649                 #endregion
1650
1651                 
1652                 public override void Accept (StructuralVisitor visitor)
1653                 {
1654                         visitor.Visit (this);
1655                 }
1656
1657                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
1658                 {
1659                         if (a.Type == pa.IndexerName) {
1660                                 // Attribute was copied to container
1661                                 return;
1662                         }
1663
1664                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
1665                 }
1666
1667                 protected override bool CheckForDuplications ()
1668                 {
1669                         return Parent.MemberCache.CheckExistingMembersOverloads (this, parameters);
1670                 }
1671                 
1672                 public override bool Define ()
1673                 {
1674                         if (!base.Define ())
1675                                 return false;
1676
1677                         if (!DefineParameters (parameters))
1678                                 return false;
1679
1680                         if (OptAttributes != null) {
1681                                 Attribute indexer_attr = OptAttributes.Search (Module.PredefinedAttributes.IndexerName);
1682                                 if (indexer_attr != null) {
1683                                         var compiling = indexer_attr.Type.MemberDefinition as TypeContainer;
1684                                         if (compiling != null)
1685                                                 compiling.Define ();
1686
1687                                         if (IsExplicitImpl) {
1688                                                 Report.Error (415, indexer_attr.Location,
1689                                                         "The `{0}' attribute is valid only on an indexer that is not an explicit interface member declaration",
1690                                                         indexer_attr.Type.GetSignatureForError ());
1691                                         } else if ((ModFlags & Modifiers.OVERRIDE) != 0) {
1692                                                 Report.Error (609, indexer_attr.Location,
1693                                                         "Cannot set the `IndexerName' attribute on an indexer marked override");
1694                                         } else {
1695                                                 string name = indexer_attr.GetIndexerAttributeValue ();
1696
1697                                                 if (!string.IsNullOrEmpty (name)) {
1698                                                         SetMemberName (new MemberName (MemberName.Left, name, Location));
1699                                                 }
1700                                         }
1701                                 }
1702                         }
1703
1704                         if (InterfaceType != null) {
1705                                 string base_IndexerName = InterfaceType.MemberDefinition.GetAttributeDefaultMember ();
1706                                 if (base_IndexerName != ShortName) {
1707                                         SetMemberName (new MemberName (MemberName.Left, base_IndexerName, new TypeExpression (InterfaceType, Location), Location));
1708                                 }
1709                         }
1710
1711                         Parent.AddNameToContainer (this, MemberName.Basename);
1712
1713                         flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
1714                         
1715                         if (!DefineAccessors ())
1716                                 return false;
1717
1718                         if (!CheckBase ())
1719                                 return false;
1720
1721                         DefineBuilders (MemberKind.Indexer, parameters);
1722                         return true;
1723                 }
1724
1725                 public override bool EnableOverloadChecks (MemberCore overload)
1726                 {
1727                         if (overload is Indexer) {
1728                                 caching_flags |= Flags.MethodOverloadsExist;
1729                                 return true;
1730                         }
1731
1732                         return base.EnableOverloadChecks (overload);
1733                 }
1734
1735                 public override void Emit ()
1736                 {
1737                         parameters.CheckConstraints (this);
1738
1739                         base.Emit ();
1740                 }
1741
1742                 public override string GetSignatureForError ()
1743                 {
1744                         StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
1745                         if (MemberName.ExplicitInterface != null) {
1746                                 sb.Append (".");
1747                                 sb.Append (MemberName.ExplicitInterface.GetSignatureForError ());
1748                         }
1749
1750                         sb.Append (".this");
1751                         sb.Append (parameters.GetSignatureForError ("[", "]", parameters.Count));
1752                         return sb.ToString ();
1753                 }
1754
1755                 public override string GetSignatureForDocumentation ()
1756                 {
1757                         return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1758                 }
1759
1760                 public override void PrepareEmit ()
1761                 {
1762                         base.PrepareEmit ();
1763                         parameters.ResolveDefaultValues (this);
1764                 }
1765
1766                 protected override bool VerifyClsCompliance ()
1767                 {
1768                         if (!base.VerifyClsCompliance ())
1769                                 return false;
1770
1771                         parameters.VerifyClsCompliance (this);
1772                         return true;
1773                 }
1774         }
1775
1776         public class IndexerSpec : PropertySpec, IParametersMember
1777         {
1778                 AParametersCollection parameters;
1779
1780                 public IndexerSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, AParametersCollection parameters, PropertyInfo info, Modifiers modifiers)
1781                         : base (MemberKind.Indexer, declaringType, definition, memberType, info, modifiers)
1782                 {
1783                         this.parameters = parameters;
1784                 }
1785
1786                 #region Properties
1787                 public AParametersCollection Parameters {
1788                         get {
1789                                 return parameters;
1790                         }
1791                 }
1792                 #endregion
1793
1794                 public override string GetSignatureForDocumentation ()
1795                 {
1796                         return base.GetSignatureForDocumentation () + parameters.GetSignatureForDocumentation ();
1797                 }
1798
1799                 public override string GetSignatureForError ()
1800                 {
1801                         return DeclaringType.GetSignatureForError () + ".this" + parameters.GetSignatureForError ("[", "]", parameters.Count);
1802                 }
1803
1804                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1805                 {
1806                         var spec = (IndexerSpec) base.InflateMember (inflator);
1807                         spec.parameters = parameters.Inflate (inflator);
1808                         return spec;
1809                 }
1810
1811                 public override List<MissingTypeSpecReference> ResolveMissingDependencies (MemberSpec caller)
1812                 {
1813                         var missing = base.ResolveMissingDependencies (caller);
1814
1815                         foreach (var pt in parameters.Types) {
1816                                 var m = pt.GetMissingDependencies (caller);
1817                                 if (m == null)
1818                                         continue;
1819
1820                                 if (missing == null)
1821                                         missing = new List<MissingTypeSpecReference> ();
1822
1823                                 missing.AddRange (m);
1824                         }
1825
1826                         return missing;
1827                 }
1828         }
1829 }