“a87c62c351439c2286cd054d87bcff5ee9468f87”上不存在“...CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs”
SourcePropertySymbol.cs 67.5 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4 5 6

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
L
Llewellyn Pritchard 已提交
7
using System.Linq;
8
using System.Runtime.CompilerServices;
P
Pilchie 已提交
9
using System.Threading;
10
using Microsoft.CodeAnalysis.CSharp.Emit;
11
using Microsoft.CodeAnalysis.CSharp.Syntax;
T
Tomas Matousek 已提交
12
using Microsoft.CodeAnalysis.PooledObjects;
13
using Roslyn.Utilities;
P
Pilchie 已提交
14 15 16 17 18 19 20 21 22

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    internal sealed class SourcePropertySymbol : PropertySymbol, IAttributeTargetSymbol
    {
        private const string DefaultIndexerName = "Item";

        // TODO (tomat): consider splitting into multiple subclasses/rare data.

23 24 25 26 27
        private readonly SourceMemberContainerTypeSymbol _containingType;
        private readonly string _name;
        private readonly SyntaxReference _syntaxRef;
        private readonly Location _location;
        private readonly DeclarationModifiers _modifiers;
C
Charles Stoner 已提交
28
        private readonly ImmutableArray<CustomModifier> _refCustomModifiers;
29 30 31 32 33 34 35
        private readonly SourcePropertyAccessorSymbol _getMethod;
        private readonly SourcePropertyAccessorSymbol _setMethod;
        private readonly SynthesizedBackingFieldSymbol _backingField;
        private readonly TypeSymbol _explicitInterfaceType;
        private readonly ImmutableArray<PropertySymbol> _explicitInterfaceImplementations;
        private readonly bool _isExpressionBodied;
        private readonly bool _isAutoProperty;
36
        private readonly RefKind _refKind;
37 38 39

        private SymbolCompletionState _state;
        private ImmutableArray<ParameterSymbol> _lazyParameters;
40
        private TypeSymbolWithAnnotations.Builder _lazyType;
P
Pilchie 已提交
41 42

        /// <summary>
43
        /// Set in constructor, might be changed while decoding <see cref="IndexerNameAttribute"/>.
P
Pilchie 已提交
44
        /// </summary>
45
        private readonly string _sourceName;
P
Pilchie 已提交
46

47
        private string _lazyDocComment;
48 49
        private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers;
        private SynthesizedSealedPropertyAccessor _lazySynthesizedSealedAccessor;
50
        private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag;
P
Pilchie 已提交
51 52 53 54

        // CONSIDER: if the parameters were computed lazily, ParameterCount could be overridden to fall back on the syntax (as in SourceMemberMethodSymbol).

        private SourcePropertySymbol(
55 56 57 58 59 60
           SourceMemberContainerTypeSymbol containingType,
           Binder bodyBinder,
           BasePropertyDeclarationSyntax syntax,
           string name,
           Location location,
           DiagnosticBag diagnostics)
P
Pilchie 已提交
61 62
        {
            // This has the value that IsIndexer will ultimately have, once we've populated the fields of this object.
63
            bool isIndexer = syntax.Kind() == SyntaxKind.IndexerDeclaration;
P
Pilchie 已提交
64 65 66
            var interfaceSpecifier = GetExplicitInterfaceSpecifier(syntax);
            bool isExplicitInterfaceImplementation = (interfaceSpecifier != null);

67 68 69
            _location = location;
            _containingType = containingType;
            _syntaxRef = syntax.GetReference();
V
vsadov 已提交
70
            _refKind = syntax.Type.GetRefKind();
P
Pilchie 已提交
71 72 73 74 75 76

            SyntaxTokenList modifiers = syntax.Modifiers;
            bodyBinder = bodyBinder.WithUnsafeRegionIfNecessary(modifiers);
            bodyBinder = bodyBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);

            bool modifierErrors;
77
            _modifiers = MakeModifiers(modifiers, isExplicitInterfaceImplementation, isIndexer, location, diagnostics, out modifierErrors);
P
Pilchie 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
            this.CheckAccessibility(location, diagnostics);

            this.CheckModifiers(location, isIndexer, diagnostics);

            if (isIndexer && !isExplicitInterfaceImplementation)
            {
                // Evaluate the attributes immediately in case the IndexerNameAttribute has been applied.
                // NOTE: we want IsExplicitInterfaceImplementation, IsOverride, Locations, and the syntax reference
                // to be initialized before we pass this symbol to LoadCustomAttributes.

                // CONSIDER: none of the information from this early binding pass is cached.  Everything will
                // be re-bound when someone calls GetAttributes.  If this gets to be a problem, we could
                // always use the real attribute bag of this symbol and modify LoadAndValidateAttributes to
                // handle partially filled bags.
                CustomAttributesBag<CSharpAttributeData> temp = null;
                LoadAndValidateAttributes(OneOrMany.Create(this.CSharpSyntaxNode.AttributeLists), ref temp, earlyDecodingOnly: true);
                if (temp != null)
                {
                    Debug.Assert(temp.IsEarlyDecodedWellKnownAttributeDataComputed);
                    var propertyData = (PropertyEarlyWellKnownAttributeData)temp.EarlyDecodedWellKnownAttributeData;
                    if (propertyData != null)
                    {
100
                        _sourceName = propertyData.IndexerName;
P
Pilchie 已提交
101 102 103 104 105
                    }
                }
            }

            string aliasQualifierOpt;
106 107 108 109
            string memberName = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, interfaceSpecifier, name, diagnostics, out _explicitInterfaceType, out aliasQualifierOpt);
            _sourceName = _sourceName ?? memberName; //sourceName may have been set while loading attributes
            _name = isIndexer ? ExplicitInterfaceHelpers.GetMemberName(WellKnownMemberNames.Indexer, _explicitInterfaceType, aliasQualifierOpt) : _sourceName;
            _isExpressionBodied = false;
P
Pilchie 已提交
110

111 112
            bool hasAccessorList = syntax.AccessorList != null;
            var propertySyntax = syntax as PropertyDeclarationSyntax;
113
            var arrowExpression = propertySyntax != null
114
                ? propertySyntax.ExpressionBody
115 116
                : ((IndexerDeclarationSyntax)syntax).ExpressionBody;
            bool hasExpressionBody = arrowExpression != null;
117 118
            bool hasInitializer = !isIndexer && propertySyntax.Initializer != null;

119
            bool notRegularProperty = (!IsAbstract && !IsExtern && !isIndexer && hasAccessorList);
P
Pilchie 已提交
120 121
            AccessorDeclarationSyntax getSyntax = null;
            AccessorDeclarationSyntax setSyntax = null;
122
            if (hasAccessorList)
P
Pilchie 已提交
123
            {
124
                foreach (var accessor in syntax.AccessorList.Accessors)
P
Pilchie 已提交
125
                {
126
                    switch (accessor.Kind())
127
                    {
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
                        case SyntaxKind.GetAccessorDeclaration:
                            if (getSyntax == null)
                            {
                                getSyntax = accessor;
                            }
                            else
                            {
                                diagnostics.Add(ErrorCode.ERR_DuplicateAccessor, accessor.Keyword.GetLocation());
                            }
                            break;
                        case SyntaxKind.SetAccessorDeclaration:
                            if (setSyntax == null)
                            {
                                setSyntax = accessor;
                            }
                            else
                            {
                                diagnostics.Add(ErrorCode.ERR_DuplicateAccessor, accessor.Keyword.GetLocation());
                            }
                            break;
                        case SyntaxKind.AddAccessorDeclaration:
                        case SyntaxKind.RemoveAccessorDeclaration:
                            diagnostics.Add(ErrorCode.ERR_GetOrSetExpected, accessor.Keyword.GetLocation());
                            continue;
                        case SyntaxKind.UnknownAccessorDeclaration:
                            // We don't need to report an error here as the parser will already have
                            // done that for us.
                            continue;
                        default:
                            throw ExceptionUtilities.UnexpectedValue(accessor.Kind());
158
                    }
P
Pilchie 已提交
159

160
                    if (accessor.Body != null || accessor.ExpressionBody != null)
161
                    {
162
                        notRegularProperty = false;
163
                    }
P
Pilchie 已提交
164 165
                }
            }
166 167
            else
            {
168
                notRegularProperty = false;
169
            }
P
Pilchie 已提交
170

171
            if (hasInitializer)
172
            {
C
Charles Stoner 已提交
173
                CheckInitializer(notRegularProperty, location, diagnostics);
174 175
            }

176
            if (notRegularProperty || hasInitializer)
P
Pilchie 已提交
177
            {
178
                var hasGetSyntax = getSyntax != null;
179
                _isAutoProperty = notRegularProperty && hasGetSyntax;
180
                bool isReadOnly = hasGetSyntax && setSyntax == null;
181

V
vsadov 已提交
182
                if (_isAutoProperty && !isReadOnly && !IsStatic && ContainingType.IsReadOnly)
183 184 185 186
                {
                    diagnostics.Add(ErrorCode.ERR_AutoPropsInRoStruct, location);
                }

187
                if (_isAutoProperty || hasInitializer)
P
Pilchie 已提交
188
                {
189
                    if (_isAutoProperty)
190 191 192 193
                    {
                        //issue a diagnostic if the compiler generated attribute ctor is not found.
                        Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(bodyBinder.Compilation,
                        WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, diagnostics, syntax: syntax);
194

195
                        if (this._refKind != RefKind.None && !_containingType.IsInterface)
196 197 198
                        {
                            diagnostics.Add(ErrorCode.ERR_AutoPropertyCannotBeRefReturning, location, this);
                        }
199
                    }
P
Pilchie 已提交
200

201 202
                    string fieldName = GeneratedNames.MakeBackingFieldName(_sourceName);
                    _backingField = new SynthesizedBackingFieldSymbol(this,
203 204 205 206
                                                                          fieldName,
                                                                          isReadOnly,
                                                                          this.IsStatic,
                                                                          hasInitializer);
P
Pilchie 已提交
207 208
                }

209 210
                if (notRegularProperty)
                {
211 212 213 214 215
                    Binder.CheckFeatureAvailability(
                        syntax,
                        isReadOnly ? MessageID.IDS_FeatureReadonlyAutoImplementedProperties : MessageID.IDS_FeatureAutoImplementedProperties,
                        diagnostics,
                        location);
216
                }
P
Pilchie 已提交
217 218 219
            }

            PropertySymbol explicitlyImplementedProperty = null;
C
Charles Stoner 已提交
220
            _refCustomModifiers = ImmutableArray<CustomModifier>.Empty;
P
Pilchie 已提交
221 222 223 224 225 226 227 228 229

            // The runtime will not treat the accessors of this property as overrides or implementations
            // of those of another property unless both the signatures and the custom modifiers match.
            // Hence, in the case of overrides and *explicit* implementations, we need to copy the custom
            // modifiers that are in the signatures of the overridden/implemented property accessors.
            // (From source, we know that there can only be one overridden/implemented property, so there
            // are no conflicts.)  This is unnecessary for implicit implementations because, if the custom
            // modifiers don't match, we'll insert bridge methods for the accessors (explicit implementations 
            // that delegate to the implicit implementations) with the correct custom modifiers
C
Charles Stoner 已提交
230
            // (see SourceMemberContainerTypeSymbol.SynthesizeInterfaceMemberImplementation).
P
Pilchie 已提交
231 232 233 234 235 236 237 238 239 240

            // Note: we're checking if the syntax indicates explicit implementation rather,
            // than if explicitInterfaceType is null because we don't want to look for an
            // overridden property if this is supposed to be an explicit implementation.
            if (isExplicitInterfaceImplementation || this.IsOverride)
            {
                // Type and parameters for overrides and explicit implementations cannot be bound
                // lazily since the property name depends on the metadata name of the base property,
                // and the property name is required to add the property to the containing type, and
                // the type and parameters are required to determine the override or implementation.
241 242
                var type = this.ComputeType(bodyBinder, syntax, diagnostics);
                _lazyType.InterlockedInitialize(type);
243
                _lazyParameters = this.ComputeParameters(bodyBinder, syntax, diagnostics);
P
Pilchie 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

                bool isOverride = false;
                PropertySymbol overriddenOrImplementedProperty = null;

                if (!isExplicitInterfaceImplementation)
                {
                    // If this property is an override, we may need to copy custom modifiers from
                    // the overridden property (so that the runtime will recognize it as an override).
                    // We check for this case here, while we can still modify the parameters and
                    // return type without losing the appearance of immutability.
                    isOverride = true;
                    overriddenOrImplementedProperty = this.OverriddenProperty;
                }
                else
                {
                    string interfacePropertyName = isIndexer ? WellKnownMemberNames.Indexer : name;
260
                    explicitlyImplementedProperty = this.FindExplicitlyImplementedProperty(_explicitInterfaceType, interfacePropertyName, interfaceSpecifier, diagnostics);
C
Charles Stoner 已提交
261
                    this.FindExplicitlyImplementedMemberVerification(explicitlyImplementedProperty, diagnostics);
P
Pilchie 已提交
262 263 264 265 266
                    overriddenOrImplementedProperty = explicitlyImplementedProperty;
                }

                if ((object)overriddenOrImplementedProperty != null)
                {
C
Charles Stoner 已提交
267 268
                    _refCustomModifiers = _refKind != RefKind.None ? overriddenOrImplementedProperty.RefCustomModifiers : ImmutableArray<CustomModifier>.Empty;

269
                    TypeSymbolWithAnnotations overriddenPropertyType = overriddenOrImplementedProperty.Type;
P
Pilchie 已提交
270 271 272 273

                    // We do an extra check before copying the type to handle the case where the overriding
                    // property (incorrectly) has a different type than the overridden property.  In such cases,
                    // we want to retain the original (incorrect) type to avoid hiding the type given in source.
274
                    if (type.TypeSymbol.Equals(overriddenPropertyType.TypeSymbol, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamic))
P
Pilchie 已提交
275
                    {
276
                        type = type.WithTypeAndModifiers(
277
                            CustomModifierUtils.CopyTypeCustomModifiers(overriddenPropertyType.TypeSymbol, type.TypeSymbol, this.ContainingAssembly),
278
                            overriddenPropertyType.CustomModifiers);
279 280
                        _lazyType = default;
                        _lazyType.InterlockedInitialize(type);
P
Pilchie 已提交
281 282
                    }

283
                    _lazyParameters = CustomModifierUtils.CopyParameterCustomModifiers(overriddenOrImplementedProperty.Parameters, _lazyParameters, alsoCopyParamsModifier: isOverride);
P
Pilchie 已提交
284 285
                }
            }
O
Omar Tawfik 已提交
286
            else if (_refKind == RefKind.RefReadOnly)
287
            {
288
                var modifierType = bodyBinder.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_InAttribute, diagnostics, syntax.Type);
289

C
Charles Stoner 已提交
290
                _refCustomModifiers = ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType));
291
            }
P
Pilchie 已提交
292

293
            if (!hasAccessorList)
P
Pilchie 已提交
294
            {
295 296
                if (hasExpressionBody)
                {
297 298
                    _isExpressionBodied = true;
                    _getMethod = SourcePropertyAccessorSymbol.CreateAccessorSymbol(
299 300
                        containingType,
                        this,
301 302
                        _modifiers,
                        _sourceName,
303 304 305 306 307 308
                        arrowExpression,
                        explicitlyImplementedProperty,
                        aliasQualifierOpt,
                        diagnostics);
                }
                else
P
Pilchie 已提交
309
                {
310
                    _getMethod = null;
P
Pilchie 已提交
311
                }
312
                _setMethod = null;
313 314 315
            }
            else
            {
316 317
                _getMethod = CreateAccessorSymbol(getSyntax, explicitlyImplementedProperty, aliasQualifierOpt, notRegularProperty, diagnostics);
                _setMethod = CreateAccessorSymbol(setSyntax, explicitlyImplementedProperty, aliasQualifierOpt, notRegularProperty, diagnostics);
318 319

                if ((getSyntax == null) || (setSyntax == null))
P
Pilchie 已提交
320
                {
321
                    if ((getSyntax == null) && (setSyntax == null))
322
                    {
323
                        diagnostics.Add(ErrorCode.ERR_PropertyWithNoAccessors, location, this);
324
                    }
325
                    else if (_refKind != RefKind.None)
326 327 328 329 330 331
                    {
                        if (getSyntax == null)
                        {
                            diagnostics.Add(ErrorCode.ERR_RefPropertyMustHaveGetAccessor, location, this);
                        }
                    }
332
                    else if (notRegularProperty)
333
                    {
334
                        var accessor = _getMethod ?? _setMethod;
335 336 337 338
                        if (getSyntax == null)
                        {
                            diagnostics.Add(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, accessor.Locations[0], accessor);
                        }
339
                    }
P
Pilchie 已提交
340 341
                }

342
                // Check accessor accessibility is more restrictive than property accessibility.
343 344
                CheckAccessibilityMoreRestrictive(_getMethod, diagnostics);
                CheckAccessibilityMoreRestrictive(_setMethod, diagnostics);
P
Pilchie 已提交
345

346
                if (((object)_getMethod != null) && ((object)_setMethod != null))
P
Pilchie 已提交
347
                {
348
                    if (_refKind != RefKind.None)
349
                    {
350 351 352
                        diagnostics.Add(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, _setMethod.Locations[0], _setMethod);
                    }
                    else if ((_getMethod.LocalAccessibility != Accessibility.NotApplicable) &&
353
                        (_setMethod.LocalAccessibility != Accessibility.NotApplicable))
354
                    {
355
                        // Check accessibility is set on at most one accessor.
356 357 358 359 360
                        diagnostics.Add(ErrorCode.ERR_DuplicatePropertyAccessMods, location, this);
                    }
                    else if (this.IsAbstract)
                    {
                        // Check abstract property accessors are not private.
361 362
                        CheckAbstractPropertyAccessorNotPrivate(_getMethod, diagnostics);
                        CheckAbstractPropertyAccessorNotPrivate(_setMethod, diagnostics);
363
                    }
P
Pilchie 已提交
364
                }
365
                else
P
Pilchie 已提交
366
                {
367
                    if (!this.IsOverride)
P
Pilchie 已提交
368
                    {
369
                        var accessor = _getMethod ?? _setMethod;
370
                        if ((object)accessor != null)
P
Pilchie 已提交
371
                        {
372 373 374 375 376
                            // Check accessibility is not set on the one accessor.
                            if (accessor.LocalAccessibility != Accessibility.NotApplicable)
                            {
                                diagnostics.Add(ErrorCode.ERR_AccessModMissingAccessor, location, this);
                            }
P
Pilchie 已提交
377 378 379 380 381 382 383 384 385 386 387
                        }
                    }
                }
            }

            if ((object)explicitlyImplementedProperty != null)
            {
                CheckExplicitImplementationAccessor(this.GetMethod, explicitlyImplementedProperty.GetMethod, explicitlyImplementedProperty, diagnostics);
                CheckExplicitImplementationAccessor(this.SetMethod, explicitlyImplementedProperty.SetMethod, explicitlyImplementedProperty, diagnostics);
            }

388
            _explicitInterfaceImplementations =
P
Pilchie 已提交
389 390
                (object)explicitlyImplementedProperty == null ?
                    ImmutableArray<PropertySymbol>.Empty :
391
                    ImmutableArray.Create(explicitlyImplementedProperty);
A
angocke 已提交
392

393
            // get-only auto property should not override settable properties
394
            if (_isAutoProperty && (object)_setMethod == null && !this.IsReadOnly)
A
angocke 已提交
395 396 397
            {
                diagnostics.Add(ErrorCode.ERR_AutoPropertyMustOverrideSet, location, this);
            }
398

399 400 401 402 403
            if (_isAutoProperty)
            {
                CheckForFieldTargetedAttribute(syntax, diagnostics);
            }

404 405
            CheckForBlockAndExpressionBody(
                syntax.AccessorList, syntax.GetExpressionBodySyntax(), syntax, diagnostics);
P
Pilchie 已提交
406 407
        }

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        private void CheckForFieldTargetedAttribute(BasePropertyDeclarationSyntax syntax, DiagnosticBag diagnostics)
        {
            var languageVersion = this.DeclaringCompilation.LanguageVersion;
            if (languageVersion.AllowAttributesOnBackingFields())
            {
                return;
            }

            foreach (var attribute in syntax.AttributeLists)
            {
                if (attribute.Target?.GetAttributeLocation() == AttributeLocation.Field)
                {
                    diagnostics.Add(
                        new CSDiagnosticInfo(ErrorCode.WRN_AttributesOnBackingFieldsNotAvailable,
                            languageVersion.ToDisplayString(),
                            new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureAttributesOnBackingFields.RequiredVersion())),
                        attribute.Target.Location);
                }
            }
        }

429
        internal bool IsExpressionBodied
430 431 432
        {
            get
            {
433
                return _isExpressionBodied;
434 435 436 437 438 439 440 441
            }
        }

        private void CheckInitializer(
            bool isAutoProperty,
            Location location,
            DiagnosticBag diagnostics)
        {
442
            if (_containingType.IsInterface)
443 444 445 446 447 448 449 450 451
            {
                diagnostics.Add(ErrorCode.ERR_AutoPropertyInitializerInInterface, location, this);
            }
            else if (!isAutoProperty)
            {
                diagnostics.Add(ErrorCode.ERR_InitializerOnNonAutoProperty, location, this);
            }
        }

P
Pilchie 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464
        internal static SourcePropertySymbol Create(SourceMemberContainerTypeSymbol containingType, Binder bodyBinder, PropertyDeclarationSyntax syntax, DiagnosticBag diagnostics)
        {
            var nameToken = syntax.Identifier;
            var location = nameToken.GetLocation();
            return new SourcePropertySymbol(containingType, bodyBinder, syntax, nameToken.ValueText, location, diagnostics);
        }

        internal static SourcePropertySymbol Create(SourceMemberContainerTypeSymbol containingType, Binder bodyBinder, IndexerDeclarationSyntax syntax, DiagnosticBag diagnostics)
        {
            var location = syntax.ThisKeyword.GetLocation();
            return new SourcePropertySymbol(containingType, bodyBinder, syntax, DefaultIndexerName, location, diagnostics);
        }

465
        public override RefKind RefKind
466 467 468
        {
            get
            {
469
                return _refKind;
470 471 472
            }
        }

473
        public override TypeSymbolWithAnnotations Type
P
Pilchie 已提交
474 475 476
        {
            get
            {
477
                if (_lazyType.IsNull)
P
Pilchie 已提交
478 479 480
                {
                    var diagnostics = DiagnosticBag.GetInstance();
                    var binder = this.CreateBinderForTypeAndParameters();
481
                    var syntax = (BasePropertyDeclarationSyntax)_syntaxRef.GetSyntax();
P
Pilchie 已提交
482
                    var result = this.ComputeType(binder, syntax, diagnostics);
483
                    if (_lazyType.InterlockedInitialize(result))
P
Pilchie 已提交
484
                    {
485
                        this.AddDeclarationDiagnostics(diagnostics);
P
Pilchie 已提交
486 487 488 489
                    }
                    diagnostics.Free();
                }

490
                return _lazyType.ToType();
P
Pilchie 已提交
491 492 493 494 495 496 497
            }
        }

        internal bool HasPointerType
        {
            get
            {
498
                if (!_lazyType.IsNull)
P
Pilchie 已提交
499
                {
500
                    return _lazyType.DefaultType.IsPointerType();
P
Pilchie 已提交
501 502
                }

503
                var syntax = (BasePropertyDeclarationSyntax)_syntaxRef.GetSyntax();
504 505 506
                RefKind refKind;
                var typeSyntax = syntax.Type.SkipRef(out refKind);
                return typeSyntax.Kind() == SyntaxKind.PointerType;
P
Pilchie 已提交
507 508 509 510 511 512 513 514 515 516 517 518
            }
        }

        /// <remarks>
        /// To facilitate lookup, all indexer symbols have the same name.
        /// Check the MetadataName property to find the name that will be
        /// emitted (based on IndexerNameAttribute, or the default "Item").
        /// </remarks>
        public override string Name
        {
            get
            {
519
                return _name;
P
Pilchie 已提交
520 521 522 523 524 525 526 527 528
            }
        }

        public override string MetadataName
        {
            get
            {
                // Explicit implementation names may have spaces if the interface
                // is generic (between the type arguments).
529
                return _sourceName.Replace(" ", "");
P
Pilchie 已提交
530 531 532 533 534 535 536
            }
        }

        public override Symbol ContainingSymbol
        {
            get
            {
537
                return _containingType;
P
Pilchie 已提交
538 539 540 541 542 543 544
            }
        }

        public override NamedTypeSymbol ContainingType
        {
            get
            {
545
                return _containingType;
P
Pilchie 已提交
546 547 548 549 550
            }
        }

        internal override LexicalSortKey GetLexicalSortKey()
        {
551
            return new LexicalSortKey(_location, this.DeclaringCompilation);
P
Pilchie 已提交
552 553 554 555 556 557
        }

        public override ImmutableArray<Location> Locations
        {
            get
            {
558
                return ImmutableArray.Create(_location);
P
Pilchie 已提交
559 560 561 562 563 564 565
            }
        }

        internal Location Location
        {
            get
            {
566
                return _location;
P
Pilchie 已提交
567 568 569 570 571 572 573
            }
        }

        public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
        {
            get
            {
574
                return ImmutableArray.Create(_syntaxRef);
P
Pilchie 已提交
575 576 577 578 579
            }
        }

        public override bool IsAbstract
        {
580
            get { return (_modifiers & DeclarationModifiers.Abstract) != 0; }
P
Pilchie 已提交
581 582 583 584
        }

        public override bool IsExtern
        {
585
            get { return (_modifiers & DeclarationModifiers.Extern) != 0; }
P
Pilchie 已提交
586 587 588 589
        }

        public override bool IsStatic
        {
590
            get { return (_modifiers & DeclarationModifiers.Static) != 0; }
P
Pilchie 已提交
591 592 593 594 595 596 597 598 599 600 601 602
        }

        internal bool IsFixed
        {
            get { return false; }
        }

        /// <remarks>
        /// Even though it is declared with an IndexerDeclarationSyntax, an explicit
        /// interface implementation is not an indexer because it will not cause the
        /// containing type to be emitted with a DefaultMemberAttribute (and even if
        /// there is another indexer, the name of the explicit implementation won't
603
        /// match).  This is important for round-tripping.
P
Pilchie 已提交
604 605 606
        /// </remarks>
        public override bool IsIndexer
        {
607
            get { return (_modifiers & DeclarationModifiers.Indexer) != 0; }
P
Pilchie 已提交
608 609 610 611
        }

        public override bool IsOverride
        {
612
            get { return (_modifiers & DeclarationModifiers.Override) != 0; }
P
Pilchie 已提交
613 614 615 616
        }

        public override bool IsSealed
        {
617
            get { return (_modifiers & DeclarationModifiers.Sealed) != 0; }
P
Pilchie 已提交
618 619 620 621
        }

        public override bool IsVirtual
        {
622
            get { return (_modifiers & DeclarationModifiers.Virtual) != 0; }
P
Pilchie 已提交
623 624 625 626
        }

        internal bool IsNew
        {
627
            get { return (_modifiers & DeclarationModifiers.New) != 0; }
P
Pilchie 已提交
628 629 630 631
        }

        public override MethodSymbol GetMethod
        {
632
            get { return _getMethod; }
P
Pilchie 已提交
633 634 635 636
        }

        public override MethodSymbol SetMethod
        {
637
            get { return _setMethod; }
P
Pilchie 已提交
638 639 640 641 642 643 644 645 646 647 648
        }

        internal override Microsoft.Cci.CallingConvention CallingConvention
        {
            get { return (IsStatic ? 0 : Microsoft.Cci.CallingConvention.HasThis); }
        }

        public override ImmutableArray<ParameterSymbol> Parameters
        {
            get
            {
649
                if (_lazyParameters.IsDefault)
P
Pilchie 已提交
650 651 652
                {
                    var diagnostics = DiagnosticBag.GetInstance();
                    var binder = this.CreateBinderForTypeAndParameters();
653
                    var syntax = (BasePropertyDeclarationSyntax)_syntaxRef.GetSyntax();
P
Pilchie 已提交
654
                    var result = this.ComputeParameters(binder, syntax, diagnostics);
655
                    if (ImmutableInterlocked.InterlockedInitialize(ref _lazyParameters, result))
P
Pilchie 已提交
656
                    {
657
                        this.AddDeclarationDiagnostics(diagnostics);
P
Pilchie 已提交
658 659 660 661
                    }
                    diagnostics.Free();
                }

662
                return _lazyParameters;
P
Pilchie 已提交
663 664 665 666 667 668 669 670 671 672
            }
        }

        internal override bool IsExplicitInterfaceImplementation
        {
            get { return this.CSharpSyntaxNode.ExplicitInterfaceSpecifier != null; }
        }

        public override ImmutableArray<PropertySymbol> ExplicitInterfaceImplementations
        {
673
            get { return _explicitInterfaceImplementations; }
P
Pilchie 已提交
674 675
        }

676
        public override ImmutableArray<CustomModifier> RefCustomModifiers
677
        {
C
Charles Stoner 已提交
678
            get { return _refCustomModifiers; }
679 680
        }

P
Pilchie 已提交
681 682 683 684
        public override Accessibility DeclaredAccessibility
        {
            get
            {
685
                return ModifierUtils.EffectiveAccessibility(_modifiers);
P
Pilchie 已提交
686 687 688 689 690
            }
        }

        internal bool IsAutoProperty
        {
691
            get { return _isAutoProperty; }
P
Pilchie 已提交
692 693
        }

694 695 696 697
        /// <summary>
        /// Backing field for automatically implemented property, or
        /// for a property with an initializer.
        /// </summary>
698
        internal SynthesizedBackingFieldSymbol BackingField
P
Pilchie 已提交
699
        {
700
            get { return _backingField; }
P
Pilchie 已提交
701 702 703 704 705 706 707 708 709 710 711
        }

        internal override bool MustCallMethodsDirectly
        {
            get { return false; }
        }

        internal SyntaxReference SyntaxReference
        {
            get
            {
712
                return _syntaxRef;
P
Pilchie 已提交
713 714 715 716 717 718 719
            }
        }

        internal BasePropertyDeclarationSyntax CSharpSyntaxNode
        {
            get
            {
720
                return (BasePropertyDeclarationSyntax)_syntaxRef.GetSyntax();
P
Pilchie 已提交
721 722 723 724 725 726 727
            }
        }

        internal SyntaxTree SyntaxTree
        {
            get
            {
728
                return _syntaxRef.SyntaxTree;
P
Pilchie 已提交
729 730 731 732 733
            }
        }

        internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, DiagnosticBag diagnostics)
        {
734
            Location location = CSharpSyntaxNode.Type.Location;
735

736
            Debug.Assert(location != null);
737

P
Pilchie 已提交
738 739 740 741
            // Check constraints on return type and parameters. Note: Dev10 uses the
            // property name location for any such errors. We'll do the same for return
            // type errors but for parameter errors, we'll use the parameter location.

742
            if ((object)_explicitInterfaceType != null)
P
Pilchie 已提交
743 744
            {
                var explicitInterfaceSpecifier = GetExplicitInterfaceSpecifier(this.CSharpSyntaxNode);
745
                bool includeNullability = DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes);
P
Pilchie 已提交
746
                Debug.Assert(explicitInterfaceSpecifier != null);
747
                _explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, includeNullability, new SourceLocation(explicitInterfaceSpecifier.Name), diagnostics);
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763

                // Note: we delayed nullable-related checks that could pull on NonNullTypes
                PropertySymbol overriddenOrImplementedProperty = null;
                if (this.IsOverride)
                {
                    overriddenOrImplementedProperty = this.OverriddenProperty;
                }
                else if (!_explicitInterfaceImplementations.IsEmpty)
                {
                    overriddenOrImplementedProperty = _explicitInterfaceImplementations[0];
                }

                if (overriddenOrImplementedProperty != null)
                {
                    TypeSymbol.CheckNullableReferenceTypeMismatchOnImplementingMember(this, overriddenOrImplementedProperty, true, diagnostics);
                }
P
Pilchie 已提交
764
            }
765 766 767

            if (_refKind == RefKind.RefReadOnly)
            {
768
                DeclaringCompilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true);
769 770 771 772
            }

            ParameterHelpers.EnsureIsReadOnlyAttributeExists(Parameters, diagnostics, modifyCompilation: true);

773
            if (this.Type.NeedsNullableAttribute())
774
            {
775
                DeclaringCompilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true);
776 777
            }

778
            ParameterHelpers.EnsureNullableAttributeExists(this.Parameters, diagnostics, modifyCompilation: true);
P
Pilchie 已提交
779 780 781 782
        }

        private void CheckAccessibility(Location location, DiagnosticBag diagnostics)
        {
783
            var info = ModifierUtils.CheckAccessibility(_modifiers);
P
Pilchie 已提交
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
            if (info != null)
            {
                diagnostics.Add(new CSDiagnostic(info, location));
            }
        }

        private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, bool isExplicitInterfaceImplementation, bool isIndexer, Location location, DiagnosticBag diagnostics, out bool modifierErrors)
        {
            bool isInterface = this.ContainingType.IsInterface;
            var defaultAccess = isInterface ? DeclarationModifiers.Public : DeclarationModifiers.Private;

            // Check that the set of modifiers is allowed
            var allowedModifiers = DeclarationModifiers.Unsafe;
            if (!isExplicitInterfaceImplementation)
            {
                allowedModifiers |= DeclarationModifiers.New;

                if (!isInterface)
                {
                    allowedModifiers |=
                        DeclarationModifiers.AccessibilityMask |
                        DeclarationModifiers.Sealed |
                        DeclarationModifiers.Abstract |
                        DeclarationModifiers.Virtual |
                        DeclarationModifiers.Override;

                    if (!isIndexer)
                    {
                        allowedModifiers |= DeclarationModifiers.Static;
                    }
                }
            }

            if (!isInterface)
            {
                allowedModifiers |=
                    DeclarationModifiers.Extern;
            }

            var mods = ModifierUtils.MakeAndCheckNontypeMemberModifiers(modifiers, defaultAccess, allowedModifiers, location, diagnostics, out modifierErrors);

            this.CheckUnsafeModifier(mods, diagnostics);

            // Let's overwrite modifiers for interface methods with what they are supposed to be. 
            // Proper errors must have been reported by now.
            if (isInterface)
            {
                mods = (mods & ~DeclarationModifiers.AccessibilityMask) | DeclarationModifiers.Abstract | DeclarationModifiers.Public;
            }

            if (isIndexer)
            {
                mods |= DeclarationModifiers.Indexer;
            }

            return mods;
        }

842
        private static ImmutableArray<ParameterSymbol> MakeParameters(
843
            Binder binder, SourcePropertySymbol owner, BaseParameterListSyntax parameterSyntaxOpt, DiagnosticBag diagnostics, bool addRefReadOnlyModifier)
P
Pilchie 已提交
844 845 846 847 848 849
        {
            if (parameterSyntaxOpt == null)
            {
                return ImmutableArray<ParameterSymbol>.Empty;
            }

850 851 852 853 854
            if (parameterSyntaxOpt.Parameters.Count < 1)
            {
                diagnostics.Add(ErrorCode.ERR_IndexerNeedsParam, parameterSyntaxOpt.GetLastToken().GetLocation());
            }

P
Pilchie 已提交
855
            SyntaxToken arglistToken;
856
            var parameters = ParameterHelpers.MakeParameters(
857 858 859
                binder, owner, parameterSyntaxOpt, out arglistToken,
                allowRefOrOut: false,
                allowThis: false,
860
                addRefReadOnlyModifier: addRefReadOnlyModifier,
861
                diagnostics: diagnostics);
P
Pilchie 已提交
862

863
            if (arglistToken.Kind() != SyntaxKind.None)
P
Pilchie 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
            {
                diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation());
            }

            // There is a special warning for an indexer with exactly one parameter, which is optional.
            // ParameterHelpers already warns for default values on explicit interface implementations.
            if (parameters.Length == 1 && !owner.IsExplicitInterfaceImplementation)
            {
                ParameterSyntax parameterSyntax = parameterSyntaxOpt.Parameters[0];
                if (parameterSyntax.Default != null)
                {
                    SyntaxToken paramNameToken = parameterSyntax.Identifier;
                    diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation, paramNameToken.GetLocation(), paramNameToken.ValueText);
                }
            }

            return parameters;
        }

        private void CheckModifiers(Location location, bool isIndexer, DiagnosticBag diagnostics)
        {
            if (this.DeclaredAccessibility == Accessibility.Private && (IsVirtual || IsAbstract || IsOverride))
            {
                diagnostics.Add(ErrorCode.ERR_VirtualPrivate, location, this);
            }
            else if (IsStatic && (IsOverride || IsVirtual || IsAbstract))
            {
                // A static member '{0}' cannot be marked as override, virtual, or abstract
                diagnostics.Add(ErrorCode.ERR_StaticNotVirtual, location, this);
            }
            else if (IsOverride && (IsNew || IsVirtual))
            {
                // A member '{0}' marked as override cannot be marked as new or virtual
                diagnostics.Add(ErrorCode.ERR_OverrideNotNew, location, this);
            }
            else if (IsSealed && !IsOverride)
            {
                // '{0}' cannot be sealed because it is not an override
                diagnostics.Add(ErrorCode.ERR_SealedNonOverride, location, this);
            }
L
leppie 已提交
904 905 906 907 908 909 910 911 912 913
            else if (IsAbstract && ContainingType.TypeKind == TypeKind.Struct)
            {
                // The modifier '{0}' is not valid for this item
                diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.AbstractKeyword));
            }
            else if (IsVirtual && ContainingType.TypeKind == TypeKind.Struct)
            {
                // The modifier '{0}' is not valid for this item
                diagnostics.Add(ErrorCode.ERR_BadMemberFlag, location, SyntaxFacts.GetText(SyntaxKind.VirtualKeyword));
            }
P
Pilchie 已提交
914 915 916 917 918 919 920 921 922 923
            else if (IsAbstract && IsExtern)
            {
                diagnostics.Add(ErrorCode.ERR_AbstractAndExtern, location, this);
            }
            else if (IsAbstract && IsSealed)
            {
                diagnostics.Add(ErrorCode.ERR_AbstractAndSealed, location, this);
            }
            else if (IsAbstract && IsVirtual)
            {
924
                diagnostics.Add(ErrorCode.ERR_AbstractNotVirtual, location, this.Kind.Localize(), this);
P
Pilchie 已提交
925
            }
926
            else if (ContainingType.IsSealed && this.DeclaredAccessibility.HasProtected() && !this.IsOverride)
P
Pilchie 已提交
927 928 929 930 931 932 933 934 935 936
            {
                diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), location, this);
            }
            else if (ContainingType.IsStatic && !IsStatic)
            {
                ErrorCode errorCode = isIndexer ? ErrorCode.ERR_IndexerInStaticClass : ErrorCode.ERR_InstanceMemberInStaticClass;
                diagnostics.Add(errorCode, location, this);
            }
        }

937
        // Create AccessorSymbol for AccessorDeclarationSyntax
P
Pilchie 已提交
938 939 940 941 942 943 944
        private SourcePropertyAccessorSymbol CreateAccessorSymbol(AccessorDeclarationSyntax syntaxOpt,
            PropertySymbol explicitlyImplementedPropertyOpt, string aliasQualifierOpt, bool isAutoPropertyAccessor, DiagnosticBag diagnostics)
        {
            if (syntaxOpt == null)
            {
                return null;
            }
945
            return SourcePropertyAccessorSymbol.CreateAccessorSymbol(_containingType, this, _modifiers, _sourceName, syntaxOpt,
P
Pilchie 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
                explicitlyImplementedPropertyOpt, aliasQualifierOpt, isAutoPropertyAccessor, diagnostics);
        }

        private void CheckAccessibilityMoreRestrictive(SourcePropertyAccessorSymbol accessor, DiagnosticBag diagnostics)
        {
            if (((object)accessor != null) &&
                !IsAccessibilityMoreRestrictive(this.DeclaredAccessibility, accessor.LocalAccessibility))
            {
                diagnostics.Add(ErrorCode.ERR_InvalidPropertyAccessMod, accessor.Locations[0], accessor, this);
            }
        }

        /// <summary>
        /// Return true if the accessor accessibility is more restrictive
        /// than the property accessibility, otherwise false.
        /// </summary>
        private static bool IsAccessibilityMoreRestrictive(Accessibility property, Accessibility accessor)
        {
            if (accessor == Accessibility.NotApplicable)
            {
                return true;
            }
            return (accessor < property) &&
                ((accessor != Accessibility.Protected) || (property != Accessibility.Internal));
        }

        private static void CheckAbstractPropertyAccessorNotPrivate(SourcePropertyAccessorSymbol accessor, DiagnosticBag diagnostics)
        {
            if (accessor.LocalAccessibility == Accessibility.Private)
            {
                diagnostics.Add(ErrorCode.ERR_PrivateAbstractAccessor, accessor.Locations[0], accessor);
            }
        }

        public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken))
        {
982
            return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref _lazyDocComment);
P
Pilchie 已提交
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        }

        // Separate these checks out of FindExplicitlyImplementedProperty because they depend on the accessor symbols,
        // which depend on the explicitly implemented property
        private void CheckExplicitImplementationAccessor(MethodSymbol thisAccessor, MethodSymbol otherAccessor, PropertySymbol explicitlyImplementedProperty, DiagnosticBag diagnostics)
        {
            var thisHasAccessor = (object)thisAccessor != null;
            var otherHasAccessor = (object)otherAccessor != null;

            if (otherHasAccessor && !thisHasAccessor)
            {
                diagnostics.Add(ErrorCode.ERR_ExplicitPropertyMissingAccessor, this.Location, this, otherAccessor);
            }
            else if (!otherHasAccessor && thisHasAccessor)
            {
                diagnostics.Add(ErrorCode.ERR_ExplicitPropertyAddingAccessor, thisAccessor.Locations[0], thisAccessor, explicitlyImplementedProperty);
            }
        }

        internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers
        {
            get
            {
1006
                if (_lazyOverriddenOrHiddenMembers == null)
P
Pilchie 已提交
1007
                {
1008
                    Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null);
P
Pilchie 已提交
1009
                }
1010
                return _lazyOverriddenOrHiddenMembers;
P
Pilchie 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
            }
        }

        /// <summary>
        /// If this property is sealed, then we have to emit both accessors - regardless of whether
        /// they are present in the source - so that they can be marked final. (i.e. sealed).
        /// </summary>
        internal SynthesizedSealedPropertyAccessor SynthesizedSealedAccessorOpt
        {
            get
            {
1022 1023
                bool hasGetter = (object)_getMethod != null;
                bool hasSetter = (object)_setMethod != null;
P
Pilchie 已提交
1024 1025 1026 1027 1028 1029 1030 1031
                if (!this.IsSealed || (hasGetter && hasSetter))
                {
                    return null;
                }

                // This has to be cached because the CCI layer depends on reference equality.
                // However, there's no point in having more than one field, since we don't
                // expect to have to synthesize more than one accessor.
1032
                if ((object)_lazySynthesizedSealedAccessor == null)
P
Pilchie 已提交
1033
                {
1034
                    Interlocked.CompareExchange(ref _lazySynthesizedSealedAccessor, MakeSynthesizedSealedAccessor(), null);
P
Pilchie 已提交
1035
                }
1036
                return _lazySynthesizedSealedAccessor;
P
Pilchie 已提交
1037 1038 1039 1040 1041 1042 1043 1044
            }
        }

        /// <remarks>
        /// Only non-null for sealed properties without both accessors.
        /// </remarks>
        private SynthesizedSealedPropertyAccessor MakeSynthesizedSealedAccessor()
        {
1045
            Debug.Assert(this.IsSealed && ((object)_getMethod == null || (object)_setMethod == null));
P
Pilchie 已提交
1046

1047
            if ((object)_getMethod != null)
P
Pilchie 已提交
1048 1049 1050 1051 1052
            {
                // need to synthesize setter
                MethodSymbol overriddenAccessor = this.GetOwnOrInheritedSetMethod();
                return (object)overriddenAccessor == null ? null : new SynthesizedSealedPropertyAccessor(this, overriddenAccessor);
            }
1053
            else if ((object)_setMethod != null)
P
Pilchie 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
            {
                // need to synthesize getter
                MethodSymbol overriddenAccessor = this.GetOwnOrInheritedGetMethod();
                return (object)overriddenAccessor == null ? null : new SynthesizedSealedPropertyAccessor(this, overriddenAccessor);
            }
            else
            {
                // Arguably, it would be more correct to return an array containing two
                // synthesized accessors, but we're already in an error case, so we'll
                // minimize the cascading error behavior by suppressing synthesis.
                return null;
            }
        }

        #region Attributes

        IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner
        {
            get { return this; }
        }

        AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation
        {
            get { return AttributeLocation.Property; }
        }

        AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations
        {
1082 1083 1084 1085 1086 1087
            get
            {
                return _isAutoProperty
                    ? AttributeLocation.Property | AttributeLocation.Field
                    : AttributeLocation.Property;
            }
P
Pilchie 已提交
1088 1089 1090
        }

        /// <summary>
1091
        /// Returns a bag of custom attributes applied on the property and data decoded from well-known attributes. Returns null if there are no attributes.
P
Pilchie 已提交
1092 1093 1094 1095 1096 1097
        /// </summary>
        /// <remarks>
        /// Forces binding and decoding of attributes.
        /// </remarks>
        private CustomAttributesBag<CSharpAttributeData> GetAttributesBag()
        {
1098
            var bag = _lazyCustomAttributesBag;
P
Pilchie 已提交
1099 1100 1101 1102 1103
            if (bag != null && bag.IsSealed)
            {
                return bag;
            }

1104 1105 1106
            // The property is responsible for completion of the backing field
            _ = _backingField?.GetAttributes();

1107
            if (LoadAndValidateAttributes(OneOrMany.Create(this.CSharpSyntaxNode.AttributeLists), ref _lazyCustomAttributesBag))
P
Pilchie 已提交
1108
            {
1109
                var completed = _state.NotePartComplete(CompletionPart.Attributes);
1110
                Debug.Assert(completed);
P
Pilchie 已提交
1111 1112
            }

1113 1114
            Debug.Assert(_lazyCustomAttributesBag.IsSealed);
            return _lazyCustomAttributesBag;
P
Pilchie 已提交
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
        }

        /// <summary>
        /// Gets the attributes applied on this symbol.
        /// Returns an empty array if there are no attributes.
        /// </summary>
        /// <remarks>
        /// NOTE: This method should always be kept as a sealed override.
        /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method.
        /// </remarks>
        public sealed override ImmutableArray<CSharpAttributeData> GetAttributes()
        {
            return this.GetAttributesBag().Attributes;
        }

        /// <summary>
        /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes.
        /// </summary>
        /// <remarks>
        /// Forces binding and decoding of attributes.
        /// </remarks>
1136
        private CommonPropertyWellKnownAttributeData GetDecodedWellKnownAttributeData()
P
Pilchie 已提交
1137
        {
1138
            var attributesBag = _lazyCustomAttributesBag;
P
Pilchie 已提交
1139 1140 1141 1142 1143
            if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed)
            {
                attributesBag = this.GetAttributesBag();
            }

1144
            return (CommonPropertyWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData;
P
Pilchie 已提交
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
        }

        /// <summary>
        /// Returns data decoded from special early bound well-known attributes applied to the symbol or null if there are no applied attributes.
        /// </summary>
        /// <remarks>
        /// Forces binding and decoding of attributes.
        /// </remarks>
        internal PropertyEarlyWellKnownAttributeData GetEarlyDecodedWellKnownAttributeData()
        {
1155
            var attributesBag = _lazyCustomAttributesBag;
P
Pilchie 已提交
1156 1157 1158 1159 1160 1161 1162 1163
            if (attributesBag == null || !attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed)
            {
                attributesBag = this.GetAttributesBag();
            }

            return (PropertyEarlyWellKnownAttributeData)attributesBag.EarlyDecodedWellKnownAttributeData;
        }

1164
        internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes)
P
Pilchie 已提交
1165
        {
1166
            base.AddSynthesizedAttributes(moduleBuilder, ref attributes);
P
Pilchie 已提交
1167

1168 1169 1170
            var type = this.Type;

            if (type.TypeSymbol.ContainsDynamic())
P
Pilchie 已提交
1171
            {
1172
                AddSynthesizedAttribute(ref attributes,
1173
                    DeclaringCompilation.SynthesizeDynamicAttribute(type.TypeSymbol, type.CustomModifiers.Length + RefCustomModifiers.Length, _refKind));
1174 1175
            }

1176
            if (type.TypeSymbol.ContainsTupleNames())
1177 1178
            {
                AddSynthesizedAttribute(ref attributes,
1179
                    DeclaringCompilation.SynthesizeTupleNamesAttribute(type.TypeSymbol));
P
Pilchie 已提交
1180
            }
1181

1182
            if (type.NeedsNullableAttribute())
1183
            {
1184
                AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttribute(this, type));
1185 1186
            }

1187 1188
            if (this.ReturnsByRefReadonly)
            {
1189
                AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this));
1190
            }
P
Pilchie 已提交
1191 1192
        }

1193 1194 1195
        internal sealed override bool IsDirectlyExcludedFromCodeCoverage =>
            GetDecodedWellKnownAttributeData()?.HasExcludeFromCodeCoverageAttribute == true;

P
Pilchie 已提交
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
        internal override bool HasSpecialName
        {
            get
            {
                var data = GetDecodedWellKnownAttributeData();
                return data != null && data.HasSpecialNameAttribute;
            }
        }

        internal override CSharpAttributeData EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments)
        {
            CSharpAttributeData boundAttribute;
            ObsoleteAttributeData obsoleteData;

C
Charles Stoner 已提交
1210
            if (EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out boundAttribute, out obsoleteData))
P
Pilchie 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
            {
                if (obsoleteData != null)
                {
                    arguments.GetOrCreateData<PropertyEarlyWellKnownAttributeData>().ObsoleteAttributeData = obsoleteData;
                }

                return boundAttribute;
            }

            if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.IndexerNameAttribute))
            {
1222
                bool hasAnyDiagnostics;
P
Pilchie 已提交
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
                boundAttribute = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics);
                if (!boundAttribute.HasErrors)
                {
                    string indexerName = boundAttribute.CommonConstructorArguments[0].DecodeValue<string>(SpecialType.System_String);
                    if (indexerName != null)
                    {
                        arguments.GetOrCreateData<PropertyEarlyWellKnownAttributeData>().IndexerName = indexerName;
                    }

                    if (!hasAnyDiagnostics)
                    {
                        return boundAttribute;
                    }
                }

                return null;
            }

            return base.EarlyDecodeWellKnownAttribute(ref arguments);
        }

        /// <summary>
        /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute.
        /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet.
        /// </summary>
        internal override ObsoleteAttributeData ObsoleteAttributeData
        {
            get
            {
1252
                if (!_containingType.AnyMemberHasAttributes)
P
Pilchie 已提交
1253 1254 1255 1256
                {
                    return null;
                }

1257
                var lazyCustomAttributesBag = _lazyCustomAttributesBag;
P
Pilchie 已提交
1258 1259
                if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed)
                {
1260
                    return ((PropertyEarlyWellKnownAttributeData)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData)?.ObsoleteAttributeData;
P
Pilchie 已提交
1261 1262 1263 1264 1265 1266 1267 1268
                }

                return ObsoleteAttributeData.Uninitialized;
            }
        }

        internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments)
        {
1269
            Debug.Assert(arguments.AttributeSyntaxOpt != null);
P
Pilchie 已提交
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281

            var attribute = arguments.Attribute;
            Debug.Assert(!attribute.HasErrors);
            Debug.Assert(arguments.SymbolPart == AttributeLocation.None);

            if (attribute.IsTargetAttribute(this, AttributeDescription.IndexerNameAttribute))
            {
                //NOTE: decoding was done by EarlyDecodeWellKnownAttribute.
                ValidateIndexerNameAttribute(attribute, arguments.AttributeSyntaxOpt, arguments.Diagnostics);
            }
            else if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute))
            {
1282
                arguments.GetOrCreateData<CommonPropertyWellKnownAttributeData>().HasSpecialNameAttribute = true;
P
Pilchie 已提交
1283
            }
1284 1285
            else if (attribute.IsTargetAttribute(this, AttributeDescription.ExcludeFromCodeCoverageAttribute))
            {
1286
                arguments.GetOrCreateData<CommonPropertyWellKnownAttributeData>().HasExcludeFromCodeCoverageAttribute = true;
1287
            }
P
Pilchie 已提交
1288 1289 1290 1291 1292
            else if (attribute.IsTargetAttribute(this, AttributeDescription.DynamicAttribute))
            {
                // DynamicAttribute should not be set explicitly.
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitDynamicAttr, arguments.AttributeSyntaxOpt.Location);
            }
1293
            else if (attribute.IsTargetAttribute(this, AttributeDescription.IsReadOnlyAttribute))
1294
            {
1295
                // IsReadOnlyAttribute should not be set explicitly.
V
vsadov 已提交
1296
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, AttributeDescription.IsReadOnlyAttribute.FullName);
1297
            }
1298 1299 1300 1301 1302
            else if (attribute.IsTargetAttribute(this, AttributeDescription.IsUnmanagedAttribute))
            {
                // IsUnmanagedAttribute should not be set explicitly.
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, AttributeDescription.IsUnmanagedAttribute.FullName);
            }
V
vsadov 已提交
1303 1304 1305
            else if (attribute.IsTargetAttribute(this, AttributeDescription.IsByRefLikeAttribute))
            {
                // IsByRefLikeAttribute should not be set explicitly.
V
vsadov 已提交
1306
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, AttributeDescription.IsByRefLikeAttribute.FullName);
1307
            }
1308 1309
            else if (attribute.IsTargetAttribute(this, AttributeDescription.TupleElementNamesAttribute))
            {
V
VSadov 已提交
1310
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location);
1311
            }
1312 1313 1314 1315 1316
            else if (attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute))
            {
                // NullableAttribute should not be set explicitly.
                arguments.Diagnostics.Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location);
            }
P
Pilchie 已提交
1317 1318 1319 1320 1321 1322 1323
        }

        internal override void PostDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> boundAttributes, ImmutableArray<AttributeSyntax> allAttributeSyntaxNodes, DiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData)
        {
            Debug.Assert(!boundAttributes.IsDefault);
            Debug.Assert(!allAttributeSyntaxNodes.IsDefault);
            Debug.Assert(boundAttributes.Length == allAttributeSyntaxNodes.Length);
1324 1325
            Debug.Assert(_lazyCustomAttributesBag != null);
            Debug.Assert(_lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed);
P
Pilchie 已提交
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
            Debug.Assert(symbolPart == AttributeLocation.None);

            base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData);
        }

        private void ValidateIndexerNameAttribute(CSharpAttributeData attribute, AttributeSyntax node, DiagnosticBag diagnostics)
        {
            if (!this.IsIndexer || this.IsExplicitInterfaceImplementation)
            {
                diagnostics.Add(ErrorCode.ERR_BadIndexerNameAttr, node.Name.Location, node.GetErrorDisplayName());
            }
            else
            {
                string indexerName = attribute.CommonConstructorArguments[0].DecodeValue<string>(SpecialType.System_String);
                if (indexerName == null || !SyntaxFacts.IsValidIdentifier(indexerName))
                {
                    diagnostics.Add(ErrorCode.ERR_BadArgumentToAttribute, node.ArgumentList.Arguments[0].Location, node.GetErrorDisplayName());
                }
            }
        }

        #endregion

        #region Completion

        internal sealed override bool RequiresCompletion
        {
            get { return true; }
        }

        internal sealed override bool HasComplete(CompletionPart part)
        {
1358
            return _state.HasComplete(part);
P
Pilchie 已提交
1359 1360 1361 1362 1363 1364 1365
        }

        internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
        {
            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
1366
                var incompletePart = _state.NextIncompletePart;
P
Pilchie 已提交
1367 1368 1369 1370 1371 1372
                switch (incompletePart)
                {
                    case CompletionPart.Attributes:
                        GetAttributes();
                        break;

1373 1374
                    case CompletionPart.StartPropertyParameters:
                    case CompletionPart.FinishPropertyParameters:
P
Pilchie 已提交
1375
                        {
1376
                            if (_state.NotePartComplete(CompletionPart.StartPropertyParameters))
P
Pilchie 已提交
1377
                            {
1378 1379 1380 1381 1382
                                var parameters = this.Parameters;
                                if (parameters.Length > 0)
                                {
                                    var diagnostics = DiagnosticBag.GetInstance();
                                    var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary);
1383
                                    bool includeNullability = DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes);
1384 1385 1386
                                    foreach (var parameter in this.Parameters)
                                    {
                                        parameter.ForceComplete(locationOpt, cancellationToken);
1387
                                        parameter.Type.CheckAllConstraints(DeclaringCompilation, conversions, includeNullability, parameter.Locations[0], diagnostics);
1388
                                    }
P
Pilchie 已提交
1389

1390 1391 1392
                                    this.AddDeclarationDiagnostics(diagnostics);
                                    diagnostics.Free();
                                }
P
Pilchie 已提交
1393

1394 1395 1396 1397 1398
                                DeclaringCompilation.SymbolDeclaredEvent(this);
                                var completedOnThisThread = _state.NotePartComplete(CompletionPart.FinishPropertyParameters);
                                Debug.Assert(completedOnThisThread);
                            }
                            else
P
Pilchie 已提交
1399
                            {
1400 1401
                                // StartPropertyParameters was completed by another thread. Wait for it to finish the parameters.
                                _state.SpinWaitComplete(CompletionPart.FinishPropertyParameters, cancellationToken);
P
Pilchie 已提交
1402 1403 1404 1405
                            }
                        }
                        break;

1406 1407
                    case CompletionPart.StartPropertyType:
                    case CompletionPart.FinishPropertyType:
P
Pilchie 已提交
1408
                        {
1409
                            if (_state.NotePartComplete(CompletionPart.StartPropertyType))
P
Pilchie 已提交
1410 1411 1412
                            {
                                var diagnostics = DiagnosticBag.GetInstance();
                                var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary);
1413 1414
                                bool includeNullability = DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes);
                                this.Type.CheckAllConstraints(DeclaringCompilation, conversions, includeNullability, _location, diagnostics);
P
Pilchie 已提交
1415

1416
                                var type = this.Type.TypeSymbol;
1417 1418 1419 1420
                                if (type.IsRestrictedType(ignoreSpanLikeTypes: true))
                                {
                                    diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, this.CSharpSyntaxNode.Type.Location, type);
                                }
1421
                                else if (this.IsAutoProperty && type.IsRefLikeType && (this.IsStatic || !this.ContainingType.IsRefLikeType))
P
Pilchie 已提交
1422
                                {
1423
                                    diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, this.CSharpSyntaxNode.Type.Location, type);
P
Pilchie 已提交
1424 1425
                                }

1426 1427 1428
                                this.AddDeclarationDiagnostics(diagnostics);
                                var completedOnThisThread = _state.NotePartComplete(CompletionPart.FinishPropertyType);
                                Debug.Assert(completedOnThisThread);
P
Pilchie 已提交
1429 1430 1431 1432
                                diagnostics.Free();
                            }
                            else
                            {
1433 1434
                                // StartPropertyType was completed by another thread. Wait for it to finish the type.
                                _state.SpinWaitComplete(CompletionPart.FinishPropertyType, cancellationToken);
P
Pilchie 已提交
1435 1436 1437 1438 1439 1440 1441 1442 1443
                            }
                        }
                        break;

                    case CompletionPart.None:
                        return;

                    default:
                        // any other values are completion parts intended for other kinds of symbols
1444
                        _state.NotePartComplete(CompletionPart.All & ~CompletionPart.PropertySymbolAll);
P
Pilchie 已提交
1445 1446 1447
                        break;
                }

1448
                _state.SpinWaitComplete(incompletePart, cancellationToken);
P
Pilchie 已提交
1449 1450 1451 1452 1453
            }
        }

        #endregion

1454
        private TypeSymbolWithAnnotations ComputeType(Binder binder, BasePropertyDeclarationSyntax syntax, DiagnosticBag diagnostics)
P
Pilchie 已提交
1455
        {
1456 1457 1458
            RefKind refKind;
            var typeSyntax = syntax.Type.SkipRef(out refKind);
            var type = binder.BindType(typeSyntax, diagnostics);
P
Pilchie 已提交
1459 1460 1461 1462 1463 1464
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;

            if (!this.IsNoMoreVisibleThan(type, ref useSiteDiagnostics))
            {
                // "Inconsistent accessibility: indexer return type '{1}' is less accessible than indexer '{0}'"
                // "Inconsistent accessibility: property type '{1}' is less accessible than property '{0}'"
1465
                diagnostics.Add((this.IsIndexer ? ErrorCode.ERR_BadVisIndexerReturn : ErrorCode.ERR_BadVisPropertyType), _location, this, type.TypeSymbol);
P
Pilchie 已提交
1466 1467
            }

1468
            diagnostics.Add(_location, useSiteDiagnostics);
P
Pilchie 已提交
1469 1470 1471 1472

            if (type.SpecialType == SpecialType.System_Void)
            {
                ErrorCode errorCode = this.IsIndexer ? ErrorCode.ERR_IndexerCantHaveVoidType : ErrorCode.ERR_PropertyCantHaveVoidType;
1473
                diagnostics.Add(errorCode, _location, this);
P
Pilchie 已提交
1474 1475 1476 1477 1478 1479 1480 1481
            }

            return type;
        }

        private ImmutableArray<ParameterSymbol> ComputeParameters(Binder binder, BasePropertyDeclarationSyntax syntax, DiagnosticBag diagnostics)
        {
            var parameterSyntaxOpt = GetParameterListSyntax(syntax);
1482
            var parameters = MakeParameters(binder, this, parameterSyntaxOpt, diagnostics, addRefReadOnlyModifier: IsVirtual || IsAbstract);
P
Pilchie 已提交
1483 1484 1485 1486 1487 1488
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;

            foreach (ParameterSymbol param in parameters)
            {
                if (!this.IsNoMoreVisibleThan(param.Type, ref useSiteDiagnostics))
                {
1489
                    diagnostics.Add(ErrorCode.ERR_BadVisIndexerParam, _location, this, param.Type.TypeSymbol);
P
Pilchie 已提交
1490
                }
1491
                else if ((object)_setMethod != null && param.Name == ParameterSymbol.ValueParameterName)
P
Pilchie 已提交
1492
                {
L
Llewellyn Pritchard 已提交
1493
                    diagnostics.Add(ErrorCode.ERR_DuplicateGeneratedName, param.Locations.FirstOrDefault() ?? _location, param.Name);
P
Pilchie 已提交
1494 1495 1496
                }
            }

1497
            diagnostics.Add(_location, useSiteDiagnostics);
P
Pilchie 已提交
1498 1499 1500 1501 1502 1503
            return parameters;
        }

        private Binder CreateBinderForTypeAndParameters()
        {
            var compilation = this.DeclaringCompilation;
1504 1505
            var syntaxTree = _syntaxRef.SyntaxTree;
            var syntax = (BasePropertyDeclarationSyntax)_syntaxRef.GetSyntax();
P
Pilchie 已提交
1506
            var binderFactory = compilation.GetBinderFactory(syntaxTree);
1507
            var binder = binderFactory.GetBinder(syntax, syntax, this);
P
Pilchie 已提交
1508 1509 1510 1511 1512 1513 1514
            SyntaxTokenList modifiers = syntax.Modifiers;
            binder = binder.WithUnsafeRegionIfNecessary(modifiers);
            return binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
        }

        private static ExplicitInterfaceSpecifierSyntax GetExplicitInterfaceSpecifier(BasePropertyDeclarationSyntax syntax)
        {
1515
            switch (syntax.Kind())
P
Pilchie 已提交
1516 1517 1518 1519 1520 1521
            {
                case SyntaxKind.PropertyDeclaration:
                    return ((PropertyDeclarationSyntax)syntax).ExplicitInterfaceSpecifier;
                case SyntaxKind.IndexerDeclaration:
                    return ((IndexerDeclarationSyntax)syntax).ExplicitInterfaceSpecifier;
                default:
1522
                    throw ExceptionUtilities.UnexpectedValue(syntax.Kind());
P
Pilchie 已提交
1523 1524 1525 1526 1527
            }
        }

        private static BaseParameterListSyntax GetParameterListSyntax(BasePropertyDeclarationSyntax syntax)
        {
1528
            return (syntax.Kind() == SyntaxKind.IndexerDeclaration) ? ((IndexerDeclarationSyntax)syntax).ParameterList : null;
P
Pilchie 已提交
1529 1530 1531
        }
    }
}