コード例 #1
0
            protected ImmutableArray <IParameterSymbol> CreateMethodParameters()
            {
                var parameters = ArrayBuilder <IParameterSymbol> .GetInstance();

                var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root);

                foreach (var parameter in AnalyzerResult.MethodParameters)
                {
                    if (!isLocalFunction || !parameter.CanBeCapturedByLocalFunction)
                    {
                        var refKind = GetRefKind(parameter.ParameterModifier);
                        var type    = parameter.GetVariableType(SemanticDocument);

                        parameters.Add(
                            CodeGenerationSymbolFactory.CreateParameterSymbol(
                                attributes: ImmutableArray <AttributeData> .Empty,
                                refKind: refKind,
                                isParams: false,
                                type: type,
                                name: parameter.Name));
                    }
                }

                return(parameters.ToImmutableAndFree());
            }
コード例 #2
0
        private static IMethodSymbol RemoveAttributesCore(
            this IMethodSymbol method, Func <AttributeData, bool> shouldRemoveAttribute,
            IList <SyntaxNode> statements, IList <SyntaxNode> handlesExpressions)
        {
            var methodHasAttribute = method.GetAttributes().Any(shouldRemoveAttribute);

            var someParameterHasAttribute = method.Parameters
                                            .Any(m => m.GetAttributes().Any(shouldRemoveAttribute));

            var returnTypeHasAttribute = method.GetReturnTypeAttributes().Any(shouldRemoveAttribute);

            if (!methodHasAttribute && !someParameterHasAttribute && !returnTypeHasAttribute)
            {
                return(method);
            }

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       method.ContainingType,
                       method.GetAttributes().Where(a => !shouldRemoveAttribute(a)).ToList(),
                       method.DeclaredAccessibility,
                       method.GetSymbolModifiers(),
                       method.ReturnType,
                       method.ExplicitInterfaceImplementations.FirstOrDefault(),
                       method.Name,
                       method.TypeParameters,
                       method.Parameters.Select(p =>
                                                CodeGenerationSymbolFactory.CreateParameterSymbol(
                                                    p.GetAttributes().Where(a => !shouldRemoveAttribute(a)).ToList(),
                                                    p.RefKind, p.IsParams, p.Type, p.Name, p.IsOptional,
                                                    p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null)).ToList(),
                       statements,
                       handlesExpressions,
                       method.GetReturnTypeAttributes().Where(a => !shouldRemoveAttribute(a)).ToList()));
        }
コード例 #3
0
            private async Task AddOperatorsAsync(
                ArrayBuilder <IMethodSymbol> members,
                CancellationToken cancellationToken
                )
            {
                var compilation = await _document.Project
                                  .GetRequiredCompilationAsync(cancellationToken)
                                  .ConfigureAwait(false);

                var generator = _document.GetRequiredLanguageService <SyntaxGenerator>();

                // add nullable annotation to the parameter reference type, so that (in)equality operator implementations allow comparison against null
                var parameters = ImmutableArray.Create(
                    CodeGenerationSymbolFactory.CreateParameterSymbol(
                        _containingType.IsValueType
                          ? _containingType
                          : _containingType.WithNullableAnnotation(NullableAnnotation.Annotated),
                        LeftName
                        ),
                    CodeGenerationSymbolFactory.CreateParameterSymbol(
                        _containingType.IsValueType
                          ? _containingType
                          : _containingType.WithNullableAnnotation(NullableAnnotation.Annotated),
                        RightName
                        )
                    );

                members.Add(CreateEqualityOperator(compilation, generator, parameters));
                members.Add(CreateInequalityOperator(compilation, generator, parameters));
            }
コード例 #4
0
        public static IMethodSymbol RemoveInaccessibleAttributesAndAttributesOfTypes(
            this IMethodSymbol method, ISymbol accessibleWithin,
            params INamedTypeSymbol[] removeAttributeTypes)
        {
            var methodHasAttribute = method.GetAttributes().Any(shouldRemoveAttribute);

            var someParameterHasAttribute = method.Parameters
                                            .Any(m => m.GetAttributes().Any(shouldRemoveAttribute));

            var returnTypeHasAttribute = method.GetReturnTypeAttributes().Any(shouldRemoveAttribute);

            if (!methodHasAttribute && !someParameterHasAttribute && !returnTypeHasAttribute)
            {
                return(method);
            }

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       method,
                       containingType: method.ContainingType,
                       explicitInterfaceImplementations: method.ExplicitInterfaceImplementations,
                       attributes: method.GetAttributes().WhereAsArray(a => !shouldRemoveAttribute(a)),
                       parameters: method.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)),
                       returnTypeAttributes: method.GetReturnTypeAttributes().WhereAsArray(a => !shouldRemoveAttribute(a))));

            bool shouldRemoveAttribute(AttributeData a) =>
            removeAttributeTypes.Any(attr => attr.Equals(a.AttributeClass)) ||
            a.AttributeClass?.IsAccessibleWithin(accessibleWithin) == false;
        }
コード例 #5
0
        public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, IList <string> newNames)
        {
            if (method.TypeParameters.Select(t => t.Name).SequenceEqual(newNames))
            {
                return(method);
            }

            var typeGenerator         = new TypeGenerator();
            var updatedTypeParameters = RenameTypeParameters(
                method.TypeParameters, newNames, typeGenerator);

            // The use of AllNullabilityIgnoringSymbolComparer is tracked by https://github.com/dotnet/roslyn/issues/36093
            var mapping = new Dictionary <ITypeSymbol, ITypeSymbol>(AllNullabilityIgnoringSymbolComparer.Instance);

            for (var i = 0; i < method.TypeParameters.Length; i++)
            {
                mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
            }

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       method.ContainingType,
                       method.GetAttributes(),
                       method.DeclaredAccessibility,
                       method.GetSymbolModifiers(),
                       method.GetReturnTypeWithAnnotatedNullability().SubstituteTypes(mapping, typeGenerator),
                       method.RefKind,
                       method.ExplicitInterfaceImplementations,
                       method.Name,
                       updatedTypeParameters,
                       method.Parameters.SelectAsArray(p =>
                                                       CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.GetTypeWithAnnotatedNullability().SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
                                                                                                         p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null))));
        }
コード例 #6
0
        private static async Task <ISymbol?> TryRehydrateAsync(Document document, CompletionItem item, CancellationToken cancellationToken)
        {
            // If we're need to rehydrate the conversion, pull out the necessary parts.
            if (item.Properties.ContainsKey(RehydrateName))
            {
                var symbols = await SymbolCompletionItem.GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false);

                if (symbols.Length == 3 &&
                    symbols[0] is INamedTypeSymbol containingType &&
                    symbols[1] is ITypeSymbol fromType &&
                    symbols[2] is ITypeSymbol toType)
                {
                    return(CodeGenerationSymbolFactory.CreateConversionSymbol(
                               toType: toType,
                               fromType: CodeGenerationSymbolFactory.CreateParameterSymbol(fromType, "value"),
                               containingType: containingType,
                               documentationCommentXml: item.Properties[DocumentationCommentXmlName]));
                }

                return(null);
            }
            else
            {
                // Otherwise, just go retrieve the conversion directly.
                var symbols = await SymbolCompletionItem.GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false);

                return(symbols.Length == 1 ? symbols.Single() : null);
            }
        }
コード例 #7
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));
        }
コード例 #8
0
        public static IMethodSymbol RenameTypeParameters(this IMethodSymbol method, ImmutableArray <string> newNames)
        {
            if (method.TypeParameters.Select(t => t.Name).SequenceEqual(newNames))
            {
                return(method);
            }

            var typeGenerator         = new TypeGenerator();
            var updatedTypeParameters = RenameTypeParameters(
                method.TypeParameters, newNames, typeGenerator);

            var mapping = new Dictionary <ITypeSymbol, ITypeSymbol>(SymbolEqualityComparer.Default);

            for (var i = 0; i < method.TypeParameters.Length; i++)
            {
                mapping[method.TypeParameters[i]] = updatedTypeParameters[i];
            }

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       method.ContainingType,
                       method.GetAttributes(),
                       method.DeclaredAccessibility,
                       method.GetSymbolModifiers(),
                       method.ReturnType.SubstituteTypes(mapping, typeGenerator),
                       method.RefKind,
                       method.ExplicitInterfaceImplementations,
                       method.Name,
                       updatedTypeParameters,
                       method.Parameters.SelectAsArray(p =>
                                                       CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type.SubstituteTypes(mapping, typeGenerator), p.Name, p.IsOptional,
                                                                                                         p.HasExplicitDefaultValue, p.HasExplicitDefaultValue ? p.ExplicitDefaultValue : null))));
        }
コード例 #9
0
            private void GetParameters(
                IList <TArgumentSyntax> arguments,
                IList <TAttributeArgumentSyntax> attributeArguments,
                IList <ITypeSymbol> parameterTypes,
                IList <string> parameterNames,
                out Dictionary <string, ISymbol> parameterToExistingFieldMap,
                out Dictionary <string, string> parameterToNewFieldMap,
                out List <IParameterSymbol> parameters)
            {
                parameterToExistingFieldMap = new Dictionary <string, ISymbol>();
                parameterToNewFieldMap      = new Dictionary <string, string>();
                parameters = new List <IParameterSymbol>();

                for (var i = 0; i < parameterNames.Count; i++)
                {
                    // See if there's a matching field we can use.  First test in a case sensitive
                    // manner, then case insensitively.
                    if (!TryFindMatchingField(arguments, attributeArguments, parameterNames, parameterTypes, i, parameterToExistingFieldMap, parameterToNewFieldMap, caseSentitive: true))
                    {
                        if (!TryFindMatchingField(arguments, attributeArguments, parameterNames, parameterTypes, i, parameterToExistingFieldMap, parameterToNewFieldMap, caseSentitive: false))
                        {
                            parameterToNewFieldMap[parameterNames[i]] = parameterNames[i];
                        }
                    }

                    parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
                                       attributes: null,
                                       refKind: service.GetRefKind(arguments[i]),
                                       isParams: false,
                                       type: parameterTypes[i],
                                       name: parameterNames[i]));
                }
            }
コード例 #10
0
        public static IMethodSymbol CreateEqualsMethod(
            this SyntaxGenerator factory,
            Compilation compilation,
            INamedTypeSymbol containingType,
            ImmutableArray <ISymbol> symbols,
            SyntaxAnnotation statementAnnotation,
            CancellationToken cancellationToken)
        {
            var statements = CreateEqualsMethodStatements(
                factory, compilation, containingType, symbols, cancellationToken);

            statements = statements.SelectAsArray(s => s.WithAdditionalAnnotations(statementAnnotation));

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       attributes: default(ImmutableArray <AttributeData>),
                       accessibility: Accessibility.Public,
                       modifiers: new DeclarationModifiers(isOverride: true),
                       returnType: compilation.GetSpecialType(SpecialType.System_Boolean),
                       returnsByRef: false,
                       explicitInterfaceSymbol: null,
                       name: EqualsName,
                       typeParameters: default(ImmutableArray <ITypeParameterSymbol>),
                       parameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(compilation.GetSpecialType(SpecialType.System_Object), ObjName)),
                       statements: statements));
        }
コード例 #11
0
        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));
        }
コード例 #12
0
            private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken)
            {
                var parameters = ParameterTypes
                                 .Zip(
                    _parameterRefKinds,
                    (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")
                    )
                                 .ToImmutableArray();
                var expressions          = _arguments.SelectAsArray(a => a.Expression);
                var delegatedConstructor = FindConstructorToDelegateTo(
                    parameters,
                    expressions,
                    cancellationToken
                    );

                if (delegatedConstructor == null)
                {
                    return(false);
                }

                // Map the first N parameters to the other constructor in this type.  Then
                // try to map any further parameters to existing fields.  Finally, generate
                // new fields if no such parameters exist.

                // Find the names of the parameters that will follow the parameters we're
                // delegating.
                var argumentCount           = delegatedConstructor.Parameters.Length;
                var remainingArguments      = _arguments.Skip(argumentCount).ToImmutableArray();
                var remainingParameterNames = _service.GenerateParameterNames(
                    _document,
                    remainingArguments,
                    delegatedConstructor.Parameters.Select(p => p.Name).ToList(),
                    _parameterNamingRule,
                    cancellationToken
                    );

                // Can't generate the constructor if the parameter names we're copying over forcibly
                // conflict with any names we generated.
                if (
                    delegatedConstructor.Parameters
                    .Select(p => p.Name)
                    .Intersect(remainingParameterNames.Select(n => n.BestNameForParameter))
                    .Any()
                    )
                {
                    return(false);
                }

                var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray();

                _delegatedConstructor = delegatedConstructor;
                GetParameters(
                    remainingArguments,
                    remainingParameterTypes,
                    remainingParameterNames,
                    cancellationToken
                    );
                return(true);
            }
            private void AddFieldDelegatingConstructor(
                IList <TArgumentSyntax> argumentList, ArrayBuilder <ISymbol> members, GenerateTypeOptionsResult options = null)
            {
                var factory            = _document.Project.LanguageServices.GetService <SyntaxGenerator>();
                var syntaxFactsService = _document.Project.LanguageServices.GetService <ISyntaxFactsService>();

                var availableTypeParameters = _service.GetAvailableTypeParameters(_state, _document.SemanticModel, _intoNamespace, _cancellationToken);
                var parameterTypes          = GetArgumentTypes(argumentList);
                var parameterNames          = _service.GenerateParameterNames(_document.SemanticModel, argumentList, _cancellationToken);
                var parameters = ArrayBuilder <IParameterSymbol> .GetInstance();

                var parameterToExistingFieldMap = new Dictionary <string, ISymbol>();
                var parameterToNewFieldMap      = new Dictionary <string, string>();

                var syntaxFacts = _document.Project.LanguageServices.GetService <ISyntaxFactsService>();

                for (var i = 0; i < parameterNames.Count; i++)
                {
                    var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]);

                    var parameterName = parameterNames[i];
                    var parameterType = parameterTypes[i];
                    parameterType = parameterType.RemoveUnavailableTypeParameters(
                        _document.SemanticModel.Compilation, availableTypeParameters);

                    if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: true))
                    {
                        if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: false))
                        {
                            parameterToNewFieldMap[parameterName.BestNameForParameter] = parameterName.NameBasedOnArgument;
                        }
                    }

                    parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
                                       attributes: default(ImmutableArray <AttributeData>),
                                       refKind: refKind,
                                       isParams: false,
                                       type: parameterType,
                                       name: parameterName.BestNameForParameter));
                }

                // Empty Constructor for Struct is not allowed
                if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure)))
                {
                    members.AddRange(factory.CreateFieldDelegatingConstructor(
                                         _document.SemanticModel.Compilation,
                                         DetermineName(), null, parameters.ToImmutable(),
                                         parameterToExistingFieldMap, parameterToNewFieldMap,
                                         addNullChecks: false, preferThrowExpression: false,
                                         cancellationToken: _cancellationToken));
                }

                parameters.Free();
            }
コード例 #14
0
            private async Task AddOperatorsAsync(List <IMethodSymbol> members, CancellationToken cancellationToken)
            {
                var compilation = await _document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

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

                var parameters = ImmutableArray.Create(
                    CodeGenerationSymbolFactory.CreateParameterSymbol(_containingType, LeftName),
                    CodeGenerationSymbolFactory.CreateParameterSymbol(_containingType, RightName));

                members.Add(CreateEqualityOperator(compilation, generator, parameters));
                members.Add(CreateInequalityOperator(compilation, generator, parameters));
            }
 public static IMethodSymbol CreateEqualsMethod(this Compilation compilation, ImmutableArray <SyntaxNode> statements)
 {
     return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                attributes: default(ImmutableArray <AttributeData>),
                accessibility: Accessibility.Public,
                modifiers: new DeclarationModifiers(isOverride: true),
                returnType: compilation.GetSpecialType(SpecialType.System_Boolean),
                returnsByRef: false,
                explicitInterfaceSymbol: null,
                name: EqualsName,
                typeParameters: default(ImmutableArray <ITypeParameterSymbol>),
                parameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(compilation.GetSpecialType(SpecialType.System_Object), ObjName)),
                statements: statements));
 }
コード例 #16
0
 public static IParameterSymbol WithAttributes(this IParameterSymbol parameter, ImmutableArray <AttributeData> attributes)
 {
     return(parameter.GetAttributes() == attributes
         ? parameter
         : CodeGenerationSymbolFactory.CreateParameterSymbol(
                attributes,
                parameter.RefKind,
                parameter.IsParams,
                parameter.Type,
                parameter.Name,
                parameter.IsOptional,
                parameter.HasExplicitDefaultValue,
                parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null));
 }
コード例 #17
0
 public static IParameterSymbol RenameParameter(this IParameterSymbol parameter, string parameterName)
 {
     return(parameter.Name == parameterName
         ? parameter
         : CodeGenerationSymbolFactory.CreateParameterSymbol(
                parameter.GetAttributes(),
                parameter.RefKind,
                parameter.IsParams,
                parameter.Type,
                parameterName,
                parameter.IsOptional,
                parameter.HasExplicitDefaultValue,
                parameter.HasExplicitDefaultValue ? parameter.ExplicitDefaultValue : null));
 }
コード例 #18
0
            private void AddFieldDelegatingConstructor(
                IList <TArgumentSyntax> argumentList, IList <ISymbol> members, GenerateTypeOptionsResult options = null)
            {
                var factory            = document.Project.LanguageServices.GetService <SyntaxGenerator>();
                var syntaxFactsService = document.Project.LanguageServices.GetService <ISyntaxFactsService>();

                var availableTypeParameters = service.GetAvailableTypeParameters(state, document.SemanticModel, intoNamespace, cancellationToken);
                var parameterTypes          = GetArgumentTypes(argumentList);
                var parameterNames          = service.GenerateParameterNames(document.SemanticModel, argumentList);
                var parameters = new List <IParameterSymbol>();

                var parameterToExistingFieldMap = new Dictionary <string, ISymbol>();
                var parameterToNewFieldMap      = new Dictionary <string, string>();

                var syntaxFacts = document.Project.LanguageServices.GetService <ISyntaxFactsService>();

                for (var i = 0; i < parameterNames.Count; i++)
                {
                    var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]);

                    var parameterName = parameterNames[i];
                    var parameterType = (ITypeSymbol)parameterTypes[i];
                    parameterType = parameterType.RemoveUnavailableTypeParameters(
                        this.document.SemanticModel.Compilation, availableTypeParameters);

                    if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: true))
                    {
                        if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: false))
                        {
                            parameterToNewFieldMap[parameterName] = parameterName;
                        }
                    }

                    parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
                                       attributes: null,
                                       refKind: refKind,
                                       isParams: false,
                                       type: parameterType,
                                       name: parameterName));
                }

                // Empty Constructor for Struct is not allowed
                if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure)))
                {
                    members.AddRange(factory.CreateFieldDelegatingConstructor(
                                         DetermineName(), null, parameters, parameterToExistingFieldMap, parameterToNewFieldMap, cancellationToken));
                }
            }
コード例 #19
0
        private static SyntaxNode GetNewMethodDeclaration(
            IMethodSymbol method,
            TArgumentSyntax argument,
            SeparatedSyntaxList <TArgumentSyntax> argumentList,
            SyntaxGenerator generator,
            SyntaxNode declaration,
            ISemanticFactsService semanticFacts,
            string argumentName,
            SyntaxNode expression,
            SemanticModel semanticModel,
            ITypeSymbol parameterType,
            CancellationToken cancellationToken)
        {
            if (!string.IsNullOrWhiteSpace(argumentName))
            {
                var newParameterSymbol = CodeGenerationSymbolFactory.CreateParameterSymbol(
                    attributes: default(ImmutableArray <AttributeData>),
                    refKind: RefKind.None,
                    isParams: false,
                    type: parameterType,
                    name: argumentName);

                var newParameterDeclaration = generator.ParameterDeclaration(newParameterSymbol);
                return(generator.AddParameters(declaration, new[] { newParameterDeclaration }));
            }
            else
            {
                var name = semanticFacts.GenerateNameForExpression(
                    semanticModel, expression, capitalize: false, cancellationToken: cancellationToken);
                var uniqueName = NameGenerator.EnsureUniqueness(name, method.Parameters.Select(p => p.Name));

                var newParameterSymbol = CodeGenerationSymbolFactory.CreateParameterSymbol(
                    attributes: default(ImmutableArray <AttributeData>),
                    refKind: RefKind.None,
                    isParams: false,
                    type: parameterType,
                    name: uniqueName);

                var argumentIndex           = argumentList.IndexOf(argument);
                var newParameterDeclaration = generator.ParameterDeclaration(newParameterSymbol);
                return(generator.InsertParameters(
                           declaration, argumentIndex, new[] { newParameterDeclaration }));
            }
        }
コード例 #20
0
        protected override async Task <ISymbol> GenerateMemberAsync(ISymbol member, INamedTypeSymbol containingType, Document document, CompletionItem item, CancellationToken cancellationToken)
        {
            var syntaxFactory = document.GetLanguageService <SyntaxGenerator>();
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            var method = (IMethodSymbol)member;

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       attributes: ImmutableArray <AttributeData> .Empty,
                       accessibility: Accessibility.NotApplicable,
                       modifiers: MemberInsertionCompletionItem.GetModifiers(item),
                       returnType: semanticModel.Compilation.GetSpecialType(SpecialType.System_Void),
                       returnsByRef: method.ReturnsByRef,
                       explicitInterfaceSymbol: null,
                       name: member.Name,
                       typeParameters: method.TypeParameters,
                       parameters: method.Parameters.SelectAsArray(p => CodeGenerationSymbolFactory.CreateParameterSymbol(p.GetAttributes(), p.RefKind, p.IsParams, p.Type, p.Name)),
                       statements: syntaxFactory.CreateThrowNotImplementedStatementBlock(semanticModel.Compilation)));
        }
コード例 #21
0
        private static IMethodSymbol GenerateMethodSymbol(INamedTypeSymbol typeToGenerateIn, INamedTypeSymbol parameterSymbol)
        {
            // Remove any generic parameters
            if (typeToGenerateIn.IsGenericType)
            {
                typeToGenerateIn = typeToGenerateIn.ConstructUnboundGenericType().ConstructedFrom;
            }

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       attributes: SpecializedCollections.EmptyList <AttributeData>(),
                       accessibility: default(Accessibility),
                       modifiers: default(DeclarationModifiers),
                       returnType: typeToGenerateIn,
                       explicitInterfaceSymbol: null,
                       name: null,
                       typeParameters: SpecializedCollections.EmptyList <ITypeParameterSymbol>(),
                       parameters: new[] { CodeGenerationSymbolFactory.CreateParameterSymbol(parameterSymbol, "v") },
                       methodKind: MethodKind.Conversion));
        }
コード例 #22
0
        internal static IMethodSymbol GenerateSetPropertyMethod(Compilation compilation)
        {
            var body = SyntaxFactory.ParseStatement(
                @"if (!System.Collections.Generic.EqualityComparer<T>.Default.Equals(field, value))
{
    field = value;

    var handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new System.ComponentModel.PropertyChangedEventArgs(name));
    }
}");

            body = body.WithAdditionalAnnotations(Simplifier.Annotation);

            var stringType = compilation.GetSpecialType(SpecialType.System_String);
            var voidType   = compilation.GetSpecialType(SpecialType.System_Void);

            var typeParameter = CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T");

            var parameter1 = CodeGenerationSymbolFactory.CreateParameterSymbol(
                attributes: null,
                refKind: RefKind.Ref,
                isParams: false,
                type: typeParameter,
                name: "field");

            var parameter2 = CodeGenerationSymbolFactory.CreateParameterSymbol(typeParameter, "value");
            var parameter3 = CodeGenerationSymbolFactory.CreateParameterSymbol(stringType, "name");

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       attributes: null,
                       accessibility: Microsoft.CodeAnalysis.Accessibility.Private,
                       modifiers: new SymbolModifiers(),
                       returnType: voidType,
                       explicitInterfaceSymbol: null,
                       name: "SetProperty",
                       typeParameters: new[] { typeParameter },
                       parameters: new[] { parameter1, parameter2, parameter3 },
                       statements: new[] { body }));
        }
コード例 #23
0
            protected ImmutableArray <IParameterSymbol> CreateMethodParameters()
            {
                var parameters = ArrayBuilder <IParameterSymbol> .GetInstance();

                foreach (var parameter in this.AnalyzerResult.MethodParameters)
                {
                    var refKind = GetRefKind(parameter.ParameterModifier);
                    var type    = parameter.GetVariableType(this.SemanticDocument);

                    parameters.Add(
                        CodeGenerationSymbolFactory.CreateParameterSymbol(
                            attributes: ImmutableArray <AttributeData> .Empty,
                            refKind: refKind,
                            isParams: false,
                            type: type,
                            name: parameter.Name));
                }

                return(parameters.ToImmutableAndFree());
            }
コード例 #24
0
            protected IList <IParameterSymbol> CreateMethodParameters()
            {
                var parameters = new List <IParameterSymbol>();

                foreach (var parameter in this.AnalyzerResult.MethodParameters)
                {
                    var refKind = GetRefKind(parameter.ParameterModifier);
                    var type    = parameter.GetVariableType(this.SemanticDocument);

                    parameters.Add(
                        CodeGenerationSymbolFactory.CreateParameterSymbol(
                            attributes: SpecializedCollections.EmptyList <AttributeData>(),
                            refKind: refKind,
                            isParams: false,
                            type: type,
                            name: parameter.Name));
                }

                return(parameters);
            }
        private IEnumerable <CodeAction> CreateCodeActions(Document document, State state)
        {
            var lastParameter = state.DelegatedConstructor.Parameters.Last();

            if (!lastParameter.IsOptional)
            {
                yield return(new AddConstructorParametersCodeAction(this, document, state, state.Parameters));
            }

            var parameters = state.Parameters.Select(p => CodeGenerationSymbolFactory.CreateParameterSymbol(
                                                         attributes: null,
                                                         refKind: p.RefKind,
                                                         isParams: p.IsParams,
                                                         type: p.Type,
                                                         name: p.Name,
                                                         isOptional: true,
                                                         hasDefaultValue: true)).ToList();

            yield return(new AddConstructorParametersCodeAction(this, document, state, parameters));
        }
コード例 #26
0
        public static IMethodSymbol CreateEqualsMethod(
            this ISyntaxFactoryService factory,
            Compilation compilation,
            INamedTypeSymbol containingType,
            IList <ISymbol> symbols,
            CancellationToken cancellationToken)
        {
            var statements = CreateEqualsMethodStatements(factory, compilation, containingType, symbols, cancellationToken);

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       attributes: null,
                       accessibility: Accessibility.Public,
                       modifiers: new SymbolModifiers(isOverride: true),
                       returnType: compilation.GetSpecialType(SpecialType.System_Boolean),
                       explicitInterfaceSymbol: null,
                       name: EqualsName,
                       typeParameters: null,
                       parameters: new[] { CodeGenerationSymbolFactory.CreateParameterSymbol(compilation.GetSpecialType(SpecialType.System_Object), ObjName) },
                       statements: statements));
        }
コード例 #27
0
        internal async override Task <Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
        {
            var syntaxFactoryService = document.GetLanguageService <SyntaxGenerator>();

            var symbol = model.GetDeclaredSymbol(nodeToFix);

            // There was no constructor and so the diagnostic was on the type. Generate a serlialization ctor.
            if (symbol.Kind == SymbolKind.NamedType)
            {
                var typeSymbol     = symbol as INamedTypeSymbol;
                var throwStatement = syntaxFactoryService.CreateThrowNotImplementedStatementBlock(model.Compilation);

                var parameters = ImmutableArray.Create(
                    CodeGenerationSymbolFactory.CreateParameterSymbol(WellKnownTypes.SerializationInfo(model.Compilation), "serializationInfo"),
                    CodeGenerationSymbolFactory.CreateParameterSymbol(WellKnownTypes.StreamingContext(model.Compilation), "streamingContext"));

                var ctorSymbol = CodeGenerationSymbolFactory.CreateConstructorSymbol(null,
                                                                                     typeSymbol.IsSealed ? Accessibility.Private : Accessibility.Protected,
                                                                                     new SymbolModifiers(),
                                                                                     typeSymbol.Name,
                                                                                     parameters,
                                                                                     throwStatement);

                return(await CodeGenerator.AddMethodDeclarationAsync(document.Project.Solution, typeSymbol, ctorSymbol).ConfigureAwait(false));
            }
            else if (symbol.Kind == SymbolKind.Method)
            {
                // There is a serialization constructor but with incorrect accessibility. Set that right.
                var methodSymbol = symbol as IMethodSymbol;

                // This would be constructor and can have only one definition.
                Debug.Assert(methodSymbol.IsConstructor() && methodSymbol.DeclaringSyntaxReferences.Count() == 1);
                var declaration = await methodSymbol.DeclaringSyntaxReferences.First().GetSyntaxAsync(cancellationToken);

                var newAccessibility = methodSymbol.ContainingType.IsSealed ? Accessibility.Private : Accessibility.Protected;
                var newDecl          = CodeGenerator.UpdateDeclarationAccessibility(declaration, document.Project.Solution.Workspace, newAccessibility, cancellationToken: cancellationToken);
                return(document.WithSyntaxRoot(root.ReplaceNode(declaration, newDecl)));
            }

            return(document);
        }
コード例 #28
0
        protected ImmutableArray <IParameterSymbol> DetermineParameters(
            ImmutableArray <ISymbol> selectedMembers)
        {
            var parameters = ArrayBuilder <IParameterSymbol> .GetInstance();

            foreach (var symbol in selectedMembers)
            {
                var type = symbol is IFieldSymbol
                    ? ((IFieldSymbol)symbol).Type
                    : ((IPropertySymbol)symbol).Type;

                parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
                                   attributes: default(ImmutableArray <AttributeData>),
                                   refKind: RefKind.None,
                                   isParams: false,
                                   type: type,
                                   name: symbol.Name.ToCamelCase().TrimStart(s_underscore)));
            }

            return(parameters.ToImmutableAndFree());
        }
コード例 #29
0
        private static IMethodSymbol GenerateMethodSymbol(
            INamedTypeSymbol typeToGenerateIn, INamedTypeSymbol parameterSymbol)
        {
            // Remove any generic parameters
            if (typeToGenerateIn.IsGenericType)
            {
                typeToGenerateIn = typeToGenerateIn.ConstructUnboundGenericType().ConstructedFrom;
            }

            return(CodeGenerationSymbolFactory.CreateMethodSymbol(
                       attributes: ImmutableArray <AttributeData> .Empty,
                       accessibility: default(Accessibility),
                       modifiers: default(DeclarationModifiers),
                       returnType: typeToGenerateIn,
                       returnsByRef: false,
                       explicitInterfaceSymbol: null,
                       name: null,
                       typeParameters: ImmutableArray <ITypeParameterSymbol> .Empty,
                       parameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateParameterSymbol(parameterSymbol, "v")),
                       methodKind: MethodKind.Conversion));
        }
コード例 #30
0
        protected List <IParameterSymbol> DetermineParameters(
            IList <ISymbol> selectedMembers)
        {
            var parameters = new List <IParameterSymbol>();

            foreach (var symbol in selectedMembers)
            {
                var type = symbol is IFieldSymbol
                                        ? ((IFieldSymbol)symbol).Type
                                        : ((IPropertySymbol)symbol).Type;

                parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
                                   attributes: null,
                                   refKind: RefKind.None,
                                   isParams: false,
                                   type: type,
                                   name: symbol.Name.ToCamelCase()));
            }

            return(parameters);
        }