public static IPropertySymbol RemoveInaccessibleAttributesAndAttributesOfTypes(
            this IPropertySymbol property, ISymbol accessibleWithin, params INamedTypeSymbol[] attributesToRemove)
        {
            bool shouldRemoveAttribute(AttributeData a) =>
            attributesToRemove.Any(attr => attr.Equals(a.AttributeClass)) || !a.AttributeClass.IsAccessibleWithin(accessibleWithin);

            var someParameterHasAttribute = property.Parameters
                                            .Any(p => p.GetAttributes().Any(shouldRemoveAttribute));

            if (!someParameterHasAttribute)
            {
                return(property);
            }

            return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                       property.ContainingType,
                       property.GetAttributes(),
                       property.DeclaredAccessibility,
                       property.GetSymbolModifiers(),
                       property.Type,
                       property.RefKind,
                       property.ExplicitInterfaceImplementations,
                       property.Name,
                       property.Parameters.SelectAsArray(p =>
                                                         CodeGenerationSymbolFactory.CreateParameterSymbol(
                                                             p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
                                                             p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
                                                             p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)),
                       property.GetMethod,
                       property.SetMethod,
                       property.IsIndexer));
        }
Ejemplo n.º 2
0
 private static ISymbol GetSymbolsToPullUp(MemberAnalysisResult analysisResult)
 {
     if (analysisResult.Member is IPropertySymbol propertySymbol)
     {
         // Property is treated differently since we need to make sure it gives right accessor symbol to ICodeGenerationService,
         // otherwise ICodeGenerationService won't give the expected declaration.
         if (analysisResult.ChangeOriginalToPublic)
         {
             // We are pulling a non-public property, change its getter/setter to public and itself to be public.
             return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                        propertySymbol,
                        accessibility: Accessibility.Public,
                        getMethod: MakePublicAccessor(propertySymbol.GetMethod),
                        setMethod: MakePublicAccessor(propertySymbol.SetMethod)));
         }
         else
         {
             // We are pulling a public property, filter the non-public getter/setter.
             return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                        propertySymbol,
                        getMethod: FilterOutNonPublicAccessor(propertySymbol.GetMethod),
                        setMethod: FilterOutNonPublicAccessor(propertySymbol.SetMethod)));
         }
     }
     else
     {
         // ICodeGenerationService will give the right result if it is method or event
         return(analysisResult.Member);
     }
 }
        public static IPropertySymbol RenameParameters(this IPropertySymbol property, ImmutableArray <string> parameterNames)
        {
            var parameterList = property.Parameters;

            if (parameterList.Select(p => p.Name).SequenceEqual(parameterNames))
            {
                return(property);
            }

            var parameters = parameterList.RenameParameters(parameterNames);

            return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                       property.ContainingType,
                       property.GetAttributes(),
                       property.DeclaredAccessibility,
                       property.GetSymbolModifiers(),
                       property.Type,
                       property.RefKind,
                       property.ExplicitInterfaceImplementations,
                       property.Name,
                       parameters,
                       property.GetMethod,
                       property.SetMethod,
                       property.IsIndexer));
        }
Ejemplo n.º 4
0
        private IPropertySymbol CreateProperty(
            IParameterSymbol parameter, ImmutableArray <NamingRule> rules, List <string> parameterNameParts)
        {
            foreach (var rule in rules)
            {
                if (rule.SymbolSpecification.AppliesTo(SymbolKind.Property, Accessibility.Public))
                {
                    var uniqueName = GenerateUniqueName(parameter, parameterNameParts, rule);

                    var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol(
                        default(ImmutableArray <AttributeData>),
                        Accessibility.Public,
                        default(ImmutableArray <SyntaxNode>));

                    return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                               default(ImmutableArray <AttributeData>),
                               Accessibility.Public,
                               new DeclarationModifiers(),
                               parameter.Type,
                               returnsByRef: false,
                               explicitInterfaceSymbol: null,
                               name: uniqueName,
                               parameters: default(ImmutableArray <IParameterSymbol>),
                               getMethod: getMethod,
                               setMethod: null));
                }
            }

            // We place a special rule in s_builtInRules that matches all properties.  So we should
            // always find a matching rule.
            throw ExceptionUtilities.Unreachable;
        }
Ejemplo n.º 5
0
        private static ISymbol MakeAbstractVersion(ISymbol member)
        {
            if (member.IsAbstract)
            {
                return(member);
            }

            var modifier = DeclarationModifiers.From(member).WithIsAbstract(true);

            if (member is IMethodSymbol methodSymbol)
            {
                return(CodeGenerationSymbolFactory.CreateMethodSymbol(methodSymbol, modifiers: modifier));
            }
            else if (member is IPropertySymbol propertySymbol)
            {
                return(CodeGenerationSymbolFactory.CreatePropertySymbol(propertySymbol, modifiers: modifier, getMethod: propertySymbol.GetMethod, setMethod: propertySymbol.SetMethod));
            }
            else if (member is IEventSymbol eventSymbol)
            {
                return(CodeGenerationSymbolFactory.CreateEventSymbol(eventSymbol, modifiers: modifier));
            }
            else
            {
                throw ExceptionUtilities.UnexpectedValue(member);
            }
        }
        protected IPropertySymbol GenerateProperty(
            string propertyName, string fieldName,
            Accessibility accessibility,
            IFieldSymbol field,
            INamedTypeSymbol containingSymbol,
            SyntaxAnnotation annotation,
            Document document,
            CancellationToken cancellationToken)
        {
            var factory = document.GetLanguageService <SyntaxGenerator>();

            var propertySymbol = annotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreatePropertySymbol(containingType: containingSymbol,
                                                                                                                   attributes: SpecializedCollections.EmptyList <AttributeData>(),
                                                                                                                   accessibility: ComputeAccessibility(accessibility, field.Type),
                                                                                                                   modifiers: new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isUnsafe: field.IsUnsafe()),
                                                                                                                   type: field.Type,
                                                                                                                   returnsByRef: false,
                                                                                                                   explicitInterfaceSymbol: null,
                                                                                                                   name: propertyName,
                                                                                                                   parameters: SpecializedCollections.EmptyList <IParameterSymbol>(),
                                                                                                                   getMethod: CreateGet(fieldName, field, factory),
                                                                                                                   setMethod: field.IsReadOnly || field.IsConst ? null : CreateSet(fieldName, field, factory)));

            return(Simplifier.Annotation.AddAnnotationToSymbol(
                       Formatter.Annotation.AddAnnotationToSymbol(propertySymbol)));
        }
            private IPropertySymbol GenerateProperty(
                IPropertySymbol property,
                DeclarationModifiers modifiers,
                Accessibility accessibility,
                CancellationToken cancellationToken)
            {
                var syntaxFactory = _document.Project.LanguageServices.GetService <SyntaxGenerator>();

                var throwingBody = syntaxFactory.CreateThrowNotImplementedStatementBlock(
                    _model.Compilation);

                var getMethod = ShouldGenerateAccessor(property.GetMethod)
                                        ? CodeGenerationSymbolFactory.CreateAccessorSymbol(
                    property.GetMethod,
                    attributes: null,
                    accessibility: property.GetMethod.ComputeResultantAccessibility(_state.ClassType),
                    statements: throwingBody)
                                        : null;

                var setMethod = ShouldGenerateAccessor(property.SetMethod)
                                        ? CodeGenerationSymbolFactory.CreateAccessorSymbol(
                    property.SetMethod,
                    attributes: null,
                    accessibility: property.SetMethod.ComputeResultantAccessibility(_state.ClassType),
                    statements: throwingBody)
                                        : null;

                return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                           property,
                           accessibility: accessibility,
                           modifiers: modifiers,
                           getMethod: getMethod,
                           setMethod: setMethod));
            }
Ejemplo n.º 8
0
            internal IPropertySymbol GenerateProperty(
                SyntaxGenerator factory,
                bool isAbstract, bool includeSetter,
                CancellationToken cancellationToken)
            {
                var accessibility = DetermineAccessibility(isAbstract);
                var getMethod     = CodeGenerationSymbolFactory.CreateAccessorSymbol(
                    attributes: default(ImmutableArray <AttributeData>),
                    accessibility: accessibility,
                    statements: GenerateStatements(factory, isAbstract, cancellationToken));

                var setMethod = includeSetter ? getMethod : null;

                return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                           attributes: default(ImmutableArray <AttributeData>),
                           accessibility: accessibility,
                           modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract),
                           type: DetermineReturnType(cancellationToken),
                           returnsByRef: DetermineReturnsByRef(cancellationToken),
                           explicitInterfaceSymbol: null,
                           name: this.State.IdentifierToken.ValueText,
                           parameters: DetermineParameters(cancellationToken),
                           getMethod: getMethod,
                           setMethod: setMethod));
            }
Ejemplo n.º 9
0
        public static IPropertySymbol RemoveAttributeFromParameters(
            this IPropertySymbol property, INamedTypeSymbol attributeType)
        {
            if (attributeType == null)
            {
                return(property);
            }

            var someParameterHasAttribute = property.Parameters
                                            .Any(p => p.GetAttributes().Any(a => a.AttributeClass.Equals(attributeType)));

            if (!someParameterHasAttribute)
            {
                return(property);
            }

            return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                       property.ContainingType,
                       property.GetAttributes(),
                       property.DeclaredAccessibility,
                       property.GetSymbolModifiers(),
                       property.Type,
                       property.ExplicitInterfaceImplementations.FirstOrDefault(),
                       property.Name,
                       property.Parameters.Select(p =>
                                                  CodeGenerationSymbolFactory.CreateParameterSymbol(
                                                      p.GetAttributes().Where(a => !a.AttributeClass.Equals(attributeType)).ToList(),
                                                      p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
                                                      p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)).ToList(),
                       property.GetMethod,
                       property.SetMethod,
                       property.IsIndexer));
        }
Ejemplo n.º 10
0
            protected override async Task <Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
            {
                var syntaxTree = await _document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

                var generateUnsafe = _state.TypeMemberType.IsUnsafe() &&
                                     !_state.IsContainedInUnsafeType;

                if (_generateProperty)
                {
                    var getAccessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
                        attributes: null,
                        accessibility: DetermineMaximalAccessibility(_state),
                        statements: null);
                    var setAccessor = _isReadonly ? null : CodeGenerationSymbolFactory.CreateAccessorSymbol(
                        attributes: null,
                        accessibility: DetermineMinimalAccessibility(_state),
                        statements: null);

                    var result = await CodeGenerator.AddPropertyDeclarationAsync(
                        _document.Project.Solution,
                        _state.TypeToGenerateIn,
                        CodeGenerationSymbolFactory.CreatePropertySymbol(
                            attributes: null,
                            accessibility: DetermineMaximalAccessibility(_state),
                            modifiers: new DeclarationModifiers(isStatic: _state.IsStatic, isUnsafe: generateUnsafe),
                            type: _state.TypeMemberType,
                            explicitInterfaceSymbol: null,
                            name: _state.IdentifierToken.ValueText,
                            isIndexer: _state.IsIndexer,
                            parameters: _state.Parameters,
                            getMethod: getAccessor,
                            setMethod: setAccessor),
                        new CodeGenerationOptions(contextLocation : _state.IdentifierToken.GetLocation()),
                        cancellationToken : cancellationToken)
                                 .ConfigureAwait(false);

                    return(result);
                }
                else
                {
                    var result = await CodeGenerator.AddFieldDeclarationAsync(
                        _document.Project.Solution,
                        _state.TypeToGenerateIn,
                        CodeGenerationSymbolFactory.CreateFieldSymbol(
                            attributes: null,
                            accessibility: DetermineMinimalAccessibility(_state),
                            modifiers: _isConstant ?
                            new DeclarationModifiers(isConst: true, isUnsafe: generateUnsafe) :
                            new DeclarationModifiers(isStatic: _state.IsStatic, isReadOnly: _isReadonly, isUnsafe: generateUnsafe),
                            type: _state.TypeMemberType,
                            name: _state.IdentifierToken.ValueText),
                        new CodeGenerationOptions(contextLocation : _state.IdentifierToken.GetLocation()),
                        cancellationToken : cancellationToken)
                                 .ConfigureAwait(false);

                    return(result);
                }
            }
Ejemplo n.º 11
0
        private IList <ISymbol> CreateInterfaceMembers(IEnumerable <ISymbol> includedMembers)
        {
            var interfaceMembers = new List <ISymbol>();

            foreach (var member in includedMembers)
            {
                switch (member.Kind)
                {
                case SymbolKind.Event:
                    var @event = member as IEventSymbol;
                    interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol(
                                             attributes: SpecializedCollections.EmptyList <AttributeData>(),
                                             accessibility: Accessibility.Public,
                                             modifiers: new DeclarationModifiers(isAbstract: true),
                                             type: @event.Type,
                                             explicitInterfaceSymbol: null,
                                             name: @event.Name));
                    break;

                case SymbolKind.Method:
                    var method = member as IMethodSymbol;
                    interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol(
                                             attributes: SpecializedCollections.EmptyList <AttributeData>(),
                                             accessibility: Accessibility.Public,
                                             modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.IsUnsafe()),
                                             returnType: method.ReturnType,
                                             returnsByRef: method.ReturnsByRef,
                                             explicitInterfaceSymbol: null,
                                             name: method.Name,
                                             typeParameters: method.TypeParameters,
                                             parameters: method.Parameters));
                    break;

                case SymbolKind.Property:
                    var property = member as IPropertySymbol;
                    interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol(
                                             attributes: SpecializedCollections.EmptyList <AttributeData>(),
                                             accessibility: Accessibility.Public,
                                             modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.IsUnsafe()),
                                             type: property.Type,
                                             returnsByRef: property.ReturnsByRef,
                                             explicitInterfaceSymbol: null,
                                             name: property.Name,
                                             parameters: property.Parameters,
                                             getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null),
                                             setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null),
                                             isIndexer: property.IsIndexer));
                    break;

                default:
                    Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString()));
                    break;
                }
            }

            return(interfaceMembers);
        }
            private ISymbol GenerateProperty(
                Compilation compilation,
                IPropertySymbol property,
                Accessibility accessibility,
                DeclarationModifiers modifiers,
                bool generateAbstractly,
                bool useExplicitInterfaceSymbol,
                string memberName,
                ImplementTypePropertyGenerationBehavior propertyGenerationBehavior
                )
            {
                var factory            = Document.GetLanguageService <SyntaxGenerator>();
                var attributesToRemove = AttributesToRemove(compilation);

                var getAccessor = GenerateGetAccessor(
                    compilation,
                    property,
                    accessibility,
                    generateAbstractly,
                    useExplicitInterfaceSymbol,
                    propertyGenerationBehavior,
                    attributesToRemove
                    );

                var setAccessor = GenerateSetAccessor(
                    compilation,
                    property,
                    accessibility,
                    generateAbstractly,
                    useExplicitInterfaceSymbol,
                    propertyGenerationBehavior,
                    attributesToRemove
                    );

                var syntaxFacts =
                    Document.Project.LanguageServices.GetRequiredService <ISyntaxFactsService>();

                var parameterNames = NameGenerator.EnsureUniqueness(
                    property.Parameters.SelectAsArray(p => p.Name),
                    isCaseSensitive: syntaxFacts.IsCaseSensitive
                    );

                var updatedProperty = property.RenameParameters(parameterNames);

                updatedProperty = updatedProperty.RemoveInaccessibleAttributesAndAttributesOfTypes(
                    compilation.Assembly,
                    attributesToRemove
                    );

                return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                           updatedProperty,
                           accessibility: accessibility,
                           modifiers: modifiers,
                           explicitInterfaceImplementations: useExplicitInterfaceSymbol
                      ? ImmutableArray.Create(property)
                      : default,
            protected override async Task <Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
            {
                var generateUnsafe = _state.TypeMemberType.IsUnsafe() &&
                                     !_state.IsContainedInUnsafeType;

                if (_generateProperty)
                {
                    var getAccessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
                        attributes: null,
                        accessibility: DetermineMaximalAccessibility(_state),
                        statements: null);
                    var setAccessor = _isReadonly ? null : CodeGenerationSymbolFactory.CreateAccessorSymbol(
                        attributes: null,
                        accessibility: DetermineMinimalAccessibility(_state),
                        statements: null);

                    var result = await ICSharpCode.NRefactory6.CSharp.CodeGenerator.AddPropertyDeclarationAsync(
                        _document.Project.Solution,
                        _state.TypeToGenerateIn,
                        CodeGenerationSymbolFactory.CreatePropertySymbol(
                            attributes: null,
                            accessibility: DetermineMaximalAccessibility(_state),
                            modifiers: DeclarationModifiers.None.WithIsStatic(_state.IsStatic).WithIsUnsafe(generateUnsafe),
                            type: _state.TypeMemberType,
                            explicitInterfaceSymbol: null,
                            name: _state.IdentifierToken.ValueText,
                            isIndexer: _state.IsIndexer,
                            parameters: _state.Parameters,
                            getMethod: getAccessor,
                            setMethod: setAccessor),
                        new CodeGenerationOptions(contextLocation : _state.IdentifierToken.GetLocation(), generateDefaultAccessibility : false),
                        cancellationToken : cancellationToken)
                                 .ConfigureAwait(false);

                    return(await AnnotateInsertionMode(_document.Project.Solution.GetDocument(result.Id), result));
                }
                else
                {
                    var result = await ICSharpCode.NRefactory6.CSharp.CodeGenerator.AddFieldDeclarationAsync(
                        _document.Project.Solution,
                        _state.TypeToGenerateIn,
                        CodeGenerationSymbolFactory.CreateFieldSymbol(
                            attributes: null,
                            accessibility: DetermineMinimalAccessibility(_state),
                            modifiers: _isConstant ?
                            DeclarationModifiers.None.WithIsConst(true).WithIsUnsafe(generateUnsafe) :
                            DeclarationModifiers.None.WithIsStatic(_state.IsStatic).WithIsReadOnly(_isReadonly).WithIsUnsafe(generateUnsafe),
                            type: _state.TypeMemberType,
                            name: _state.IdentifierToken.ValueText),
                        new CodeGenerationOptions(contextLocation : _state.IdentifierToken.GetLocation(), generateDefaultAccessibility : false),
                        cancellationToken : cancellationToken)
                                 .ConfigureAwait(false);

                    return(await AnnotateInsertionMode(_document.Project.Solution.GetDocument(result.Id), result));
                }
            }
Ejemplo n.º 14
0
            private ISymbol GenerateProperty(
                Compilation compilation,
                IPropertySymbol property,
                Accessibility accessibility,
                DeclarationModifiers modifiers,
                bool generateAbstractly,
                bool useExplicitInterfaceSymbol,
                string memberName,
                CancellationToken cancellationToken)
            {
                var factory = this.Document.GetLanguageService <SyntaxGenerator>();
                var comAliasNameAttribute = compilation.ComAliasNameAttributeType();

                var getAccessor = property.GetMethod == null
                    ? null
                    : CodeGenerationSymbolFactory.CreateAccessorSymbol(
                    property.GetMethod.RemoveInaccessibleAttributesAndAttributesOfType(
                        accessibleWithin: this.State.ClassOrStructType,
                        removeAttributeType: comAliasNameAttribute),
                    attributes: null,
                    accessibility: accessibility,
                    explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.GetMethod : null,
                    statements: GetGetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));

                var setAccessor = property.SetMethod == null
                    ? null
                    : CodeGenerationSymbolFactory.CreateAccessorSymbol(
                    property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfType(
                        accessibleWithin: this.State.ClassOrStructType,
                        removeAttributeType: comAliasNameAttribute),
                    attributes: null,
                    accessibility: accessibility,
                    explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property.SetMethod : null,
                    statements: GetSetAccessorStatements(compilation, property, generateAbstractly, cancellationToken));

                var syntaxFacts    = Document.GetLanguageService <ISyntaxFactsService>();
                var parameterNames = NameGenerator.EnsureUniqueness(
                    property.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: syntaxFacts.IsCaseSensitive);

                var updatedProperty = property.RenameParameters(parameterNames);

                updatedProperty = updatedProperty.RemoveAttributeFromParameters(comAliasNameAttribute);

                // TODO(cyrusn): Delegate through throughMember if it's non-null.
                return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                           updatedProperty,
                           accessibility: accessibility,
                           modifiers: modifiers,
                           explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property : null,
                           name: memberName,
                           getMethod: getAccessor,
                           setMethod: setAccessor));
            }
        protected SyntaxNode CreatePropertyDeclaration(SyntaxNode containerNode, string name, bool generateGetter, bool generateSetter, EnvDTE.vsCMAccess access, ITypeSymbol type)
        {
            var destination = CodeModelService.GetDestination(containerNode);

            IMethodSymbol getMethod = null;

            if (generateGetter)
            {
                getMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
                    attributes: default(ImmutableArray <AttributeData>),
                    accessibility: Accessibility.NotApplicable,
                    modifiers: new DeclarationModifiers(),
                    returnType: null,
                    returnsByRef: false,
                    explicitInterfaceSymbol: null,
                    name: "get_" + name,
                    typeParameters: default(ImmutableArray <ITypeParameterSymbol>),
                    parameters: default(ImmutableArray <IParameterSymbol>),
                    statements: ImmutableArray.Create(CodeModelService.CreateReturnDefaultValueStatement(type)));
            }

            IMethodSymbol setMethod = null;

            if (generateSetter)
            {
                setMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
                    attributes: default(ImmutableArray <AttributeData>),
                    accessibility: Accessibility.NotApplicable,
                    modifiers: new DeclarationModifiers(),
                    returnType: null,
                    returnsByRef: false,
                    explicitInterfaceSymbol: null,
                    name: "set_" + name,
                    typeParameters: default(ImmutableArray <ITypeParameterSymbol>),
                    parameters: default(ImmutableArray <IParameterSymbol>));
            }

            var newPropertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol(
                attributes: default(ImmutableArray <AttributeData>),
                accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination),
                modifiers: new DeclarationModifiers(),
                type: type,
                returnsByRef: false,
                explicitInterfaceSymbol: null,
                name: name,
                parameters: default(ImmutableArray <IParameterSymbol>),
                getMethod: getMethod,
                setMethod: setMethod);

            return(CodeGenerationService.CreatePropertyDeclaration(
                       newPropertySymbol, destination,
                       options: GetCodeGenerationOptions(access, containerNode.SyntaxTree.Options)));
        }
Ejemplo n.º 16
0
            protected override Task <Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
            {
                var solution       = _document.Project.Solution;
                var syntaxTree     = _document.SyntaxTree;
                var generateUnsafe = _state.TypeMemberType.IsUnsafe() &&
                                     !_state.IsContainedInUnsafeType;

                var otions = new CodeGenerationOptions(
                    afterThisLocation: _state.AfterThisLocation,
                    beforeThisLocation: _state.BeforeThisLocation,
                    contextLocation: _state.IdentifierToken.GetLocation());

                if (_generateProperty)
                {
                    var getAccessor = CreateAccessor(DetermineMaximalAccessibility(_state), cancellationToken);
                    var setAccessor = _isReadonly || _returnsByRef
                        ? null
                        : CreateAccessor(DetermineMinimalAccessibility(_state), cancellationToken);

                    var propertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol(
                        attributes: default(ImmutableArray <AttributeData>),
                        accessibility: DetermineMaximalAccessibility(_state),
                        modifiers: new DeclarationModifiers(isStatic: _state.IsStatic, isUnsafe: generateUnsafe),
                        type: _state.TypeMemberType,
                        returnsByRef: _returnsByRef,
                        explicitInterfaceSymbol: null,
                        name: _state.IdentifierToken.ValueText,
                        isIndexer: _state.IsIndexer,
                        parameters: _state.Parameters,
                        getMethod: getAccessor,
                        setMethod: setAccessor);

                    return(CodeGenerator.AddPropertyDeclarationAsync(
                               solution, _state.TypeToGenerateIn, propertySymbol, otions, cancellationToken));
                }
                else
                {
                    var fieldSymbol = CodeGenerationSymbolFactory.CreateFieldSymbol(
                        attributes: default(ImmutableArray <AttributeData>),
                        accessibility: DetermineMinimalAccessibility(_state),
                        modifiers: _isConstant
                            ? new DeclarationModifiers(isConst: true, isUnsafe: generateUnsafe)
                            : new DeclarationModifiers(isStatic: _state.IsStatic, isReadOnly: _isReadonly, isUnsafe: generateUnsafe),
                        type: _state.TypeMemberType,
                        name: _state.IdentifierToken.ValueText);

                    return(CodeGenerator.AddFieldDeclarationAsync(
                               solution, _state.TypeToGenerateIn, fieldSymbol, otions, cancellationToken));
                }
            }
Ejemplo n.º 17
0
 private IPropertySymbol CreatePropertySymbol(SimpleNameSyntax propertyName, ITypeSymbol propertyType)
 {
     return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                attributes: SpecializedCollections.EmptyList <AttributeData>(),
                accessibility: Accessibility.Public,
                modifiers: new DeclarationModifiers(),
                explicitInterfaceSymbol: null,
                name: propertyName.ToString(),
                type: propertyType,
                parameters: null,
                getMethod: s_accessor,
                setMethod: s_accessor,
                isIndexer: false));
 }
Ejemplo n.º 18
0
 private IPropertySymbol CreatePropertySymbol(
     SimpleNameSyntax propertyName, ITypeSymbol propertyType)
 {
     return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                attributes: ImmutableArray <AttributeData> .Empty,
                accessibility: Accessibility.Public,
                modifiers: new DeclarationModifiers(),
                explicitInterfaceSymbol: null,
                name: propertyName.Identifier.ValueText,
                type: propertyType,
                returnsByRef: false,
                parameters: default(ImmutableArray <IParameterSymbol>),
                getMethod: s_accessor,
                setMethod: s_accessor,
                isIndexer: false));
 }
            private IPropertySymbol GenerateProperty(
                IPropertySymbol property,
                DeclarationModifiers modifiers,
                Accessibility accessibility,
                ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
                CancellationToken cancellationToken)
            {
                if (property.GetMethod == null)
                {
                    // Can't generate an auto-prop for a setter-only property.
                    propertyGenerationBehavior = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties;
                }

                var syntaxFactory = _document.GetLanguageService <SyntaxGenerator>();

                var accessorBody = propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties
                    ? default
                    : syntaxFactory.CreateThrowNotImplementedStatementBlock(_model.Compilation);

                var getMethod = ShouldGenerateAccessor(property.GetMethod)
                    ? CodeGenerationSymbolFactory.CreateAccessorSymbol(
                    property.GetMethod,
                    attributes: default,
                    accessibility: property.GetMethod.ComputeResultantAccessibility(_state.ClassType),
                    statements: accessorBody)
                    : null;

                var setMethod = ShouldGenerateAccessor(property.SetMethod)
                    ? CodeGenerationSymbolFactory.CreateAccessorSymbol(
                    property.SetMethod,
                    attributes: default,
                    accessibility: property.SetMethod.ComputeResultantAccessibility(_state.ClassType),
                    statements: accessorBody)
                    : null;

                return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                           property,
                           accessibility: accessibility,
                           modifiers: modifiers,
                           getMethod: getMethod,
                           setMethod: setMethod));
            }
        private IPropertySymbol CreateProperty(
            IParameterSymbol parameter, ImmutableArray <NamingRule> rules, List <string> parameterNameParts)
        {
            foreach (var rule in rules)
            {
                if (rule.SymbolSpecification.AppliesTo(SymbolKind.Property, Accessibility.Public))
                {
                    var uniqueName = GenerateUniqueName(parameter, parameterNameParts, rule);

                    var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol(
                        default(ImmutableArray <AttributeData>),
                        Accessibility.Public,
                        default(ImmutableArray <SyntaxNode>));

                    return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                               default(ImmutableArray <AttributeData>),
                               Accessibility.Public,
                               new DeclarationModifiers(),
                               parameter.Type,
                               returnsByRef: false,
                               explicitInterfaceImplementations: default,
            private ISymbol GenerateProperty(
                Compilation compilation,
                IPropertySymbol property,
                Accessibility accessibility,
                DeclarationModifiers modifiers,
                bool generateAbstractly,
                bool useExplicitInterfaceSymbol,
                string memberName,
                ImplementTypePropertyGenerationBehavior propertyGenerationBehavior,
                CancellationToken cancellationToken)
            {
                var factory            = this.Document.GetLanguageService <SyntaxGenerator>();
                var attributesToRemove = AttributesToRemove(compilation);

                var getAccessor = GenerateGetAccessor(
                    compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol,
                    propertyGenerationBehavior, attributesToRemove, cancellationToken);

                var setAccessor = GenerateSetAccessor(
                    compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol,
                    propertyGenerationBehavior, attributesToRemove, cancellationToken);

                var syntaxFacts    = Document.GetLanguageService <ISyntaxFactsService>();
                var parameterNames = NameGenerator.EnsureUniqueness(
                    property.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: syntaxFacts.IsCaseSensitive);

                var updatedProperty = property.RenameParameters(parameterNames);

                updatedProperty = updatedProperty.RemoveAttributeFromParameters(attributesToRemove);

                // TODO(cyrusn): Delegate through throughMember if it's non-null.
                return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                           updatedProperty,
                           accessibility: accessibility,
                           modifiers: modifiers,
                           explicitInterfaceSymbol: useExplicitInterfaceSymbol ? property : null,
                           name: memberName,
                           getMethod: getAccessor,
                           setMethod: setAccessor));
            }
Ejemplo n.º 22
0
        public static IPropertySymbol RemoveAttributeFromParameters(
            this IPropertySymbol property, INamedTypeSymbol[] attributesToRemove)
        {
            if (attributesToRemove == null)
            {
                return(property);
            }

            Func <AttributeData, bool> shouldRemoveAttribute = a =>
                                                               attributesToRemove.Where(attr => attr != null).Any(attr => attr.Equals(a.AttributeClass));

            var someParameterHasAttribute = property.Parameters
                                            .Any(p => p.GetAttributes().Any(shouldRemoveAttribute));

            if (!someParameterHasAttribute)
            {
                return(property);
            }

            return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                       property.ContainingType,
                       property.GetAttributes(),
                       property.DeclaredAccessibility,
                       property.GetSymbolModifiers(),
                       property.Type,
                       property.ReturnsByRef,
                       property.ExplicitInterfaceImplementations,
                       property.Name,
                       property.Parameters.SelectAsArray(p =>
                                                         CodeGenerationSymbolFactory.CreateParameterSymbol(
                                                             p.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
                                                             p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
                                                             p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)),
                       property.GetMethod,
                       property.SetMethod,
                       property.IsIndexer));
        }
Ejemplo n.º 23
0
        internal static async Task TestAddPropertyAsync(
            string initial,
            string expected,
            string name = "P",
            Accessibility defaultAccessibility = Accessibility.Public,
            Accessibility setterAccessibility  = Accessibility.Public,
            DeclarationModifiers modifiers     = default(DeclarationModifiers),
            string getStatements = null,
            string setStatements = null,
            Type type            = null,
            IPropertySymbol explicitInterfaceSymbol = null,
            ImmutableArray <Func <SemanticModel, IParameterSymbol> > parameters = default(ImmutableArray <Func <SemanticModel, IParameterSymbol> >),
            bool isIndexer = false,
            CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions),
            bool ignoreTrivia = true,
            IDictionary <OptionKey, object> options = null)
        {
            // This assumes that tests will not use place holders for get/set statements at the same time
            if (getStatements != null)
            {
                expected = expected.Replace("$$", getStatements);
            }

            if (setStatements != null)
            {
                expected = expected.Replace("$$", setStatements);
            }

            using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia))
            {
                if (options != null)
                {
                    foreach (var kvp in options)
                    {
                        context.Workspace.Options = context.Workspace.Options.WithChangedOption(kvp.Key, kvp.Value);
                    }
                }

                var typeSymbol          = GetTypeSymbol(type)(context.SemanticModel);
                var getParameterSymbols = GetParameterSymbols(parameters, context);
                var setParameterSymbols = getParameterSymbols == null
                    ? default(ImmutableArray <IParameterSymbol>)
                    : getParameterSymbols.Add(Parameter(type, "value")(context.SemanticModel));
                IMethodSymbol getAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol(
                    default(ImmutableArray <AttributeData>),
                    defaultAccessibility,
                    new DeclarationModifiers(isAbstract: getStatements == null),
                    typeSymbol,
                    false,
                    null,
                    "get_" + name,
                    default(ImmutableArray <ITypeParameterSymbol>),
                    getParameterSymbols,
                    statements: context.ParseStatements(getStatements));
                IMethodSymbol setAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol(
                    default(ImmutableArray <AttributeData>),
                    setterAccessibility,
                    new DeclarationModifiers(isAbstract: setStatements == null),
                    GetTypeSymbol(typeof(void))(context.SemanticModel),
                    false,
                    null,
                    "set_" + name,
                    default(ImmutableArray <ITypeParameterSymbol>),
                    setParameterSymbols,
                    statements: context.ParseStatements(setStatements));

                // If get is provided but set isn't, we don't want an accessor for set
                if (getStatements != null && setStatements == null)
                {
                    setAccessor = null;
                }

                // If set is provided but get isn't, we don't want an accessor for get
                if (getStatements == null && setStatements != null)
                {
                    getAccessor = null;
                }

                var property = CodeGenerationSymbolFactory.CreatePropertySymbol(
                    default(ImmutableArray <AttributeData>),
                    defaultAccessibility,
                    modifiers,
                    typeSymbol,
                    false,
                    explicitInterfaceSymbol,
                    name,
                    getParameterSymbols,
                    getAccessor,
                    setAccessor,
                    isIndexer);
                context.Result = await context.Service.AddPropertyAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), property, codeGenerationOptions);
            }
        }
Ejemplo n.º 24
0
        internal static async Task TestAddPropertyAsync(
            string initial,
            string expected,
            string name = "P",
            Accessibility defaultAccessibility = Accessibility.Public,
            Accessibility setterAccessibility  = Accessibility.Public,
            DeclarationModifiers modifiers     = default(DeclarationModifiers),
            string getStatements = null,
            string setStatements = null,
            Type type            = null,
            IPropertySymbol explicitInterfaceSymbol = null,
            IList <Func <SemanticModel, IParameterSymbol> > parameters = null,
            bool isIndexer = false,
            CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions),
            bool compareTokens = true)
        {
            // This assumes that tests will not use place holders for get/set statements at the same time
            if (getStatements != null)
            {
                expected = expected.Replace("$$", getStatements);
            }

            if (setStatements != null)
            {
                expected = expected.Replace("$$", setStatements);
            }

            using (var context = await TestContext.CreateAsync(initial, expected, compareTokens))
            {
                var typeSymbol          = GetTypeSymbol(type)(context.SemanticModel);
                var getParameterSymbols = GetParameterSymbols(parameters, context);
                var setParameterSymbols = getParameterSymbols == null ? null : new List <IParameterSymbol>(getParameterSymbols)
                {
                    Parameter(type, "value")(context.SemanticModel)
                };
                IMethodSymbol getAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol(
                    null,
                    defaultAccessibility,
                    new DeclarationModifiers(isAbstract: getStatements == null),
                    typeSymbol,
                    null,
                    "get_" + name,
                    null,
                    getParameterSymbols,
                    statements: context.ParseStatements(getStatements));
                IMethodSymbol setAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol(
                    null,
                    setterAccessibility,
                    new DeclarationModifiers(isAbstract: setStatements == null),
                    GetTypeSymbol(typeof(void))(context.SemanticModel),
                    null,
                    "set_" + name,
                    null,
                    setParameterSymbols,
                    statements: context.ParseStatements(setStatements));

                // If get is provided but set isn't, we don't want an accessor for set
                if (getStatements != null && setStatements == null)
                {
                    setAccessor = null;
                }

                // If set is provided but get isn't, we don't want an accessor for get
                if (getStatements == null && setStatements != null)
                {
                    getAccessor = null;
                }

                var property = CodeGenerationSymbolFactory.CreatePropertySymbol(
                    null,
                    defaultAccessibility,
                    modifiers,
                    typeSymbol,
                    explicitInterfaceSymbol,
                    name,
                    getParameterSymbols,
                    getAccessor,
                    setAccessor,
                    isIndexer);
                context.Result = await context.Service.AddPropertyAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), property, codeGenerationOptions);
            }
        }
        public static async Task <IPropertySymbol> OverridePropertyAsync(
            this SyntaxGenerator codeFactory,
            IPropertySymbol overriddenProperty,
            DeclarationModifiers modifiers,
            INamedTypeSymbol containingType,
            Document document,
            CancellationToken cancellationToken)
        {
            var getAccessibility = overriddenProperty.GetMethod.ComputeResultantAccessibility(containingType);
            var setAccessibility = overriddenProperty.SetMethod.ComputeResultantAccessibility(containingType);

            SyntaxNode getBody = null;
            SyntaxNode setBody = null;

            // Implement an abstract property by throwing not implemented in accessors.
            if (overriddenProperty.IsAbstract)
            {
                var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                getBody = codeFactory.CreateThrowNotImplementStatement(compilation);
                setBody = getBody;
            }
            else if (overriddenProperty.IsIndexer() && document.Project.Language == LanguageNames.CSharp)
            {
                // Indexer: return or set base[]. Only in C#, since VB must refer to these by name.
                getBody = codeFactory.ReturnStatement(
                    codeFactory.ElementAccessExpression(
                        codeFactory.BaseExpression(),
                        codeFactory.CreateArguments(overriddenProperty.Parameters)));

                setBody = codeFactory.ExpressionStatement(
                    codeFactory.AssignmentStatement(
                        codeFactory.ElementAccessExpression(
                            codeFactory.BaseExpression(),
                            codeFactory.CreateArguments(overriddenProperty.Parameters)),
                        codeFactory.IdentifierName("value")));
            }
            else if (overriddenProperty.GetParameters().Any())
            {
                // Call accessors directly if C# overriding VB
                if (document.Project.Language == LanguageNames.CSharp &&
                    (await SymbolFinder.FindSourceDefinitionAsync(overriddenProperty, document.Project.Solution, cancellationToken).ConfigureAwait(false))
                    .Language == LanguageNames.VisualBasic)
                {
                    var getName = overriddenProperty.GetMethod != null ? overriddenProperty.GetMethod.Name : null;
                    var setName = overriddenProperty.SetMethod != null ? overriddenProperty.SetMethod.Name : null;

                    getBody = getName == null
                        ? null
                        : codeFactory.ReturnStatement(
                        codeFactory.InvocationExpression(
                            codeFactory.MemberAccessExpression(
                                codeFactory.BaseExpression(),
                                codeFactory.IdentifierName(getName)),
                            codeFactory.CreateArguments(overriddenProperty.Parameters)));

                    setBody = setName == null
                        ? null
                        : codeFactory.ExpressionStatement(
                        codeFactory.InvocationExpression(
                            codeFactory.MemberAccessExpression(
                                codeFactory.BaseExpression(),
                                codeFactory.IdentifierName(setName)),
                            codeFactory.CreateArguments(overriddenProperty.SetMethod.GetParameters())));
                }
                else
                {
                    getBody = codeFactory.ReturnStatement(
                        codeFactory.InvocationExpression(
                            codeFactory.MemberAccessExpression(
                                codeFactory.BaseExpression(),
                                codeFactory.IdentifierName(overriddenProperty.Name)), codeFactory.CreateArguments(overriddenProperty.Parameters)));
                    setBody = codeFactory.ExpressionStatement(
                        codeFactory.AssignmentStatement(
                            codeFactory.InvocationExpression(
                                codeFactory.MemberAccessExpression(
                                    codeFactory.BaseExpression(),
                                    codeFactory.IdentifierName(overriddenProperty.Name)), codeFactory.CreateArguments(overriddenProperty.Parameters)),
                            codeFactory.IdentifierName("value")));
                }
            }
            else
            {
                // Regular property: return or set the base property
                getBody = codeFactory.ReturnStatement(
                    codeFactory.MemberAccessExpression(
                        codeFactory.BaseExpression(),
                        codeFactory.IdentifierName(overriddenProperty.Name)));
                setBody = codeFactory.ExpressionStatement(
                    codeFactory.AssignmentStatement(
                        codeFactory.MemberAccessExpression(
                            codeFactory.BaseExpression(),
                            codeFactory.IdentifierName(overriddenProperty.Name)),
                        codeFactory.IdentifierName("value")));
            }

            // Only generate a getter if the base getter is accessible.
            IMethodSymbol accessorGet = null;

            if (overriddenProperty.GetMethod != null && overriddenProperty.GetMethod.IsAccessibleWithin(containingType))
            {
                accessorGet = CodeGenerationSymbolFactory.CreateMethodSymbol(
                    overriddenProperty.GetMethod,
                    accessibility: getAccessibility,
                    statements: new[] { getBody },
                    modifiers: modifiers);
            }

            // Only generate a setter if the base setter is accessible.
            IMethodSymbol accessorSet = null;

            if (overriddenProperty.SetMethod != null &&
                overriddenProperty.SetMethod.IsAccessibleWithin(containingType) &&
                overriddenProperty.SetMethod.DeclaredAccessibility != Accessibility.Private)
            {
                accessorSet = CodeGenerationSymbolFactory.CreateMethodSymbol(
                    overriddenProperty.SetMethod,
                    accessibility: setAccessibility,
                    statements: new[] { setBody },
                    modifiers: modifiers);
            }

            return(CodeGenerationSymbolFactory.CreatePropertySymbol(
                       overriddenProperty,
                       accessibility: overriddenProperty.ComputeResultantAccessibility(containingType),
                       modifiers: modifiers,
                       name: overriddenProperty.Name,
                       isIndexer: overriddenProperty.IsIndexer(),
                       getMethod: accessorGet,
                       setMethod: accessorSet));
        }