CSharpGenerateConstructorService.cs 14.4 KB
Newer Older
S
Sam Harwell 已提交
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
2 3

using System.Collections.Generic;
C
CyrusNajmabadi 已提交
4
using System.Collections.Immutable;
5 6 7 8 9 10
using System.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
11
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
12 13 14
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
15
using Microsoft.CodeAnalysis.Utilities;
16

17
namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor
18 19 20 21
{
    [ExportLanguageService(typeof(IGenerateConstructorService), LanguageNames.CSharp), Shared]
    internal class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ArgumentSyntax, AttributeArgumentSyntax>
    {
22
        private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
23

24 25 26 27 28
        [ImportingConstructor]
        public CSharpGenerateConstructorService()
        {
        }

29
        protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
C
CyrusNajmabadi 已提交
30
            => node is SimpleNameSyntax;
31 32

        protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken)
C
CyrusNajmabadi 已提交
33
            => node is ConstructorInitializerSyntax;
34

35 36
        protected override bool TryInitializeConstructorInitializerGeneration(
            SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken,
C
CyrusNajmabadi 已提交
37
            out SyntaxToken token, out ImmutableArray<ArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn)
38 39 40 41 42 43
        {
            var constructorInitializer = (ConstructorInitializerSyntax)node;

            if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing)
            {
                token = constructorInitializer.ThisOrBaseKeyword;
C
CyrusNajmabadi 已提交
44
                arguments = constructorInitializer.ArgumentList.Arguments.ToImmutableArray();
45 46 47 48 49 50 51 52 53

                var semanticModel = document.SemanticModel;
                var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken);
                typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer)
                    ? currentType
                    : currentType.BaseType.OriginalDefinition;
                return typeToGenerateIn != null;
            }

54 55
            token = default;
            arguments = default;
56 57 58 59 60 61 62 63 64
            typeToGenerateIn = null;
            return false;
        }

        protected override bool TryInitializeSimpleNameGenerationState(
            SemanticDocument document,
            SyntaxNode node,
            CancellationToken cancellationToken,
            out SyntaxToken token,
C
CyrusNajmabadi 已提交
65
            out ImmutableArray<ArgumentSyntax> arguments,
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
            out INamedTypeSymbol typeToGenerateIn)
        {
            var simpleName = (SimpleNameSyntax)node;
            var fullName = simpleName.IsRightSideOfQualifiedName()
                ? (NameSyntax)simpleName.Parent
                : simpleName;

            if (fullName.Parent is ObjectCreationExpressionSyntax)
            {
                var objectCreationExpression = (ObjectCreationExpressionSyntax)fullName.Parent;
                if (objectCreationExpression.ArgumentList != null &&
                    !objectCreationExpression.ArgumentList.CloseParenToken.IsMissing)
                {
                    var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken);
                    token = simpleName.Identifier;
C
CyrusNajmabadi 已提交
81
                    arguments = objectCreationExpression.ArgumentList.Arguments.ToImmutableArray();
82 83 84 85 86
                    typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol;
                    return typeToGenerateIn != null;
                }
            }

87 88
            token = default;
            arguments = default;
89 90 91 92 93 94 95 96 97
            typeToGenerateIn = null;
            return false;
        }

        protected override bool TryInitializeSimpleAttributeNameGenerationState(
            SemanticDocument document,
            SyntaxNode node,
            CancellationToken cancellationToken,
            out SyntaxToken token,
C
CyrusNajmabadi 已提交
98 99
            out ImmutableArray<ArgumentSyntax> arguments,
            out ImmutableArray<AttributeArgumentSyntax> attributeArguments,
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
            out INamedTypeSymbol typeToGenerateIn)
        {
            var simpleName = (SimpleNameSyntax)node;
            var fullName = simpleName.IsRightSideOfQualifiedName()
                ? (NameSyntax)simpleName.Parent
                : simpleName;

            if (fullName.Parent is AttributeSyntax)
            {
                var attribute = (AttributeSyntax)fullName.Parent;
                if (attribute.ArgumentList != null &&
                    !attribute.ArgumentList.CloseParenToken.IsMissing)
                {
                    var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken);
                    if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty)
                    {
116
                        token = simpleName.Identifier;
C
CyrusNajmabadi 已提交
117 118 119 120
                        attributeArguments = attribute.ArgumentList.Arguments.ToImmutableArray();
                        arguments = attributeArguments.Select(
                            x => SyntaxFactory.Argument(
                                x.NameColon ?? (x.NameEquals != null ? SyntaxFactory.NameColon(x.NameEquals.Name) : null),
121
                                default, x.Expression)).ToImmutableArray();
122 123 124 125 126 127 128

                        typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol;
                        return typeToGenerateIn != null;
                    }
                }
            }

129 130 131
            token = default;
            arguments = default;
            attributeArguments = default;
132 133 134 135
            typeToGenerateIn = null;
            return false;
        }

C
CyrusNajmabadi 已提交
136
        protected override ImmutableArray<ParameterName> GenerateParameterNames(
137 138
            SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames, NamingRule parameterNamingRule, CancellationToken cancellationToken)
            => semanticModel.GenerateParameterNames(arguments, reservedNames, parameterNamingRule, cancellationToken);
139

C
CyrusNajmabadi 已提交
140
        protected override ImmutableArray<ParameterName> GenerateParameterNames(
141 142
            SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames, NamingRule parameterNamingRule, CancellationToken cancellationToken)
            => semanticModel.GenerateParameterNames(arguments, reservedNames, parameterNamingRule, cancellationToken);
143

144 145
        protected override string GenerateNameForArgument(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
            => semanticModel.GenerateNameForArgument(argument, cancellationToken);
146

147 148
        protected override string GenerateNameForArgument(SemanticModel semanticModel, AttributeArgumentSyntax argument, CancellationToken cancellationToken)
            => semanticModel.GenerateNameForArgument(argument, cancellationToken);
149 150

        protected override RefKind GetRefKind(ArgumentSyntax argument)
151
            => argument.GetRefKind();
152 153 154 155 156 157 158 159 160

        protected override bool IsNamedArgument(ArgumentSyntax argument)
        {
            return argument.NameColon != null;
        }

        protected override ITypeSymbol GetArgumentType(
            SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
        {
161
            return argument.DetermineParameterType(semanticModel, cancellationToken);
162 163 164 165 166 167 168 169 170 171
        }

        protected override ITypeSymbol GetAttributeArgumentType(
            SemanticModel semanticModel, AttributeArgumentSyntax argument, CancellationToken cancellationToken)
        {
            return semanticModel.GetType(argument.Expression, cancellationToken);
        }

        protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
        {
172
            return compilation.ClassifyConversion(sourceType.WithoutNullability(), targetType.WithoutNullability()).IsImplicit;
173 174
        }

175 176
        internal override IMethodSymbol GetDelegatingConstructor(
            State state,
177 178 179 180
            SemanticDocument document,
            int argumentCount,
            INamedTypeSymbol namedType,
            ISet<IMethodSymbol> candidates,
181
            CancellationToken cancellationToken)
182 183 184 185 186 187 188 189
        {
            var oldToken = state.Token;
            var tokenKind = oldToken.Kind();

            if (state.IsConstructorInitializerGeneration)
            {
                SyntaxToken thisOrBaseKeyword;
                SyntaxKind newCtorInitializerKind;
190
                if (tokenKind != SyntaxKind.BaseKeyword && Equals(state.TypeToGenerateIn, namedType))
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
                {
                    thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.ThisKeyword);
                    newCtorInitializerKind = SyntaxKind.ThisConstructorInitializer;
                }
                else
                {
                    thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.BaseKeyword);
                    newCtorInitializerKind = SyntaxKind.BaseConstructorInitializer;
                }

                var ctorInitializer = (ConstructorInitializerSyntax)oldToken.Parent;
                var oldArgumentList = ctorInitializer.ArgumentList;
                var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount);

                var newCtorInitializer = SyntaxFactory.ConstructorInitializer(newCtorInitializerKind, ctorInitializer.ColonToken, thisOrBaseKeyword, newArgumentList);
C
CyrusNajmabadi 已提交
206
                if (document.SemanticModel.TryGetSpeculativeSemanticModel(ctorInitializer.Span.Start, newCtorInitializer, out var speculativeModel))
207 208
                {
                    var symbolInfo = speculativeModel.GetSymbolInfo(newCtorInitializer, cancellationToken);
V
Victor Zaytsev 已提交
209
                    var delegatingConstructor = GenerateConstructorHelpers.GetDelegatingConstructor(
210
                        document, symbolInfo, candidates, namedType, state.ParameterTypes);
V
Victor Zaytsev 已提交
211 212 213 214 215 216 217

                    if (delegatingConstructor == null || thisOrBaseKeyword.IsKind(SyntaxKind.BaseKeyword))
                    {
                        return delegatingConstructor;
                    }

                    return CanDelegeteThisConstructor(state, document, delegatingConstructor, cancellationToken) ? delegatingConstructor : null;
218 219 220 221 222 223 224 225 226 227 228
                }
            }
            else
            {
                var oldNode = oldToken.Parent
                    .AncestorsAndSelf(ascendOutOfTrivia: false)
                    .Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node))
                    .LastOrDefault();

                var typeNameToReplace = (TypeSyntax)oldToken.Parent;
                TypeSyntax newTypeName;
229
                if (!Equals(namedType, state.TypeToGenerateIn))
230 231 232
                {
                    while (true)
                    {
C
Cyrus Najmabadi 已提交
233
                        if (!(typeNameToReplace.Parent is TypeSyntax parentType))
234 235 236 237 238 239 240
                        {
                            break;
                        }

                        typeNameToReplace = parentType;
                    }

241
                    newTypeName = namedType.GenerateTypeSyntax().WithAdditionalAnnotations(s_annotation);
242 243 244
                }
                else
                {
245
                    newTypeName = typeNameToReplace.WithAdditionalAnnotations(s_annotation);
246 247 248
                }

                var newNode = oldNode.ReplaceNode(typeNameToReplace, newTypeName);
249
                newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
250 251 252 253 254 255 256 257

                var oldArgumentList = (ArgumentListSyntax)newTypeName.Parent.ChildNodes().FirstOrDefault(n => n is ArgumentListSyntax);
                if (oldArgumentList != null)
                {
                    var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount);
                    if (newArgumentList != oldArgumentList)
                    {
                        newNode = newNode.ReplaceNode(oldArgumentList, newArgumentList);
258
                        newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
259 260 261 262 263 264 265
                    }
                }

                var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, document.SemanticModel);
                if (speculativeModel != null)
                {
                    var symbolInfo = speculativeModel.GetSymbolInfo(newTypeName.Parent, cancellationToken);
266 267
                    return GenerateConstructorHelpers.GetDelegatingConstructor(
                        document, symbolInfo, candidates, namedType, state.ParameterTypes);
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
                }
            }

            return null;
        }

        private static ArgumentListSyntax GetNewArgumentList(ArgumentListSyntax oldArgumentList, int argumentCount)
        {
            if (oldArgumentList.IsMissing || oldArgumentList.Arguments.Count == argumentCount)
            {
                return oldArgumentList;
            }

            var newArguments = oldArgumentList.Arguments.Take(argumentCount);
            return SyntaxFactory.ArgumentList(new SeparatedSyntaxList<ArgumentSyntax>().AddRange(newArguments));
        }
V
Victor Zaytsev 已提交
284

V
Victor Zaytsev 已提交
285 286 287 288
        protected override IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
            => semanticModel.GetDeclaredSymbol(token.GetAncestor<ConstructorDeclarationSyntax>(), cancellationToken);

        protected override IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken)
V
Victor Zaytsev 已提交
289
        {
V
Victor Z 已提交
290 291
            if (constructor.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken) is ConstructorDeclarationSyntax constructorDeclarationSyntax &&
                constructorDeclarationSyntax.Initializer.IsKind(SyntaxKind.ThisConstructorInitializer))
V
Victor Zaytsev 已提交
292
            {
V
Victor Zaytsev 已提交
293
                return semanticModel.GetSymbolInfo(constructorDeclarationSyntax.Initializer, cancellationToken).Symbol as IMethodSymbol;
V
Victor Zaytsev 已提交
294 295
            }

V
Victor Zaytsev 已提交
296
            return null;
V
Victor Zaytsev 已提交
297
        }
298 299
    }
}