AbstractAddParameterCodeFixProvider.cs 33.5 KB
Newer Older
C
CyrusNajmabadi 已提交
1 2 3 4
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
C
CyrusNajmabadi 已提交
5
using System.Collections.Immutable;
C
CyrusNajmabadi 已提交
6
using System.Linq;
7
using System.Threading;
C
CyrusNajmabadi 已提交
8
using System.Threading.Tasks;
9
using Microsoft.CodeAnalysis.CodeActions;
C
CyrusNajmabadi 已提交
10
using Microsoft.CodeAnalysis.CodeFixes;
11 12
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
13
using Microsoft.CodeAnalysis.FindSymbols;
14
using Microsoft.CodeAnalysis.Formatting;
15
using Microsoft.CodeAnalysis.LanguageServices;
T
Tomas Matousek 已提交
16
using Microsoft.CodeAnalysis.PooledObjects;
17 18 19
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
C
CyrusNajmabadi 已提交
20 21 22

namespace Microsoft.CodeAnalysis.AddParameter
{
23
#pragma warning disable RS1016 // Code fix providers should provide FixAll support. https://github.com/dotnet/roslyn/issues/23528
24
    internal abstract class AbstractAddParameterCodeFixProvider<
25
#pragma warning restore RS1016 // Code fix providers should provide FixAll support.
26 27 28 29 30
        TArgumentSyntax,
        TAttributeArgumentSyntax,
        TArgumentListSyntax,
        TAttributeArgumentListSyntax,
        TInvocationExpressionSyntax,
31
        TObjectCreationExpressionSyntax> : CodeFixProvider
32 33 34 35 36
        where TArgumentSyntax : SyntaxNode
        where TArgumentListSyntax : SyntaxNode
        where TAttributeArgumentListSyntax : SyntaxNode
        where TInvocationExpressionSyntax : SyntaxNode
        where TObjectCreationExpressionSyntax : SyntaxNode
C
CyrusNajmabadi 已提交
37
    {
C
CyrusNajmabadi 已提交
38
        protected abstract ImmutableArray<string> TooManyArgumentsDiagnosticIds { get; }
39
        protected abstract ImmutableArray<string> CannotConvertDiagnosticIds { get; }
C
CyrusNajmabadi 已提交
40

41 42 43
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var cancellationToken = context.CancellationToken;
C
CyrusNajmabadi 已提交
44
            var diagnostic = context.Diagnostics.First();
45 46 47 48

            var document = context.Document;
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

C
CyrusNajmabadi 已提交
49
            var initialNode = root.FindNode(diagnostic.Location.SourceSpan);
50 51

            for (var node = initialNode; node != null; node = node.Parent)
52 53 54
            {
                if (node is TObjectCreationExpressionSyntax objectCreation)
                {
C
CyrusNajmabadi 已提交
55
                    var argumentOpt = TryGetRelevantArgument(initialNode, node, diagnostic);
56
                    await HandleObjectCreationExpressionAsync(context, objectCreation, argumentOpt).ConfigureAwait(false);
57 58 59 60
                    return;
                }
                else if (node is TInvocationExpressionSyntax invocationExpression)
                {
C
CyrusNajmabadi 已提交
61
                    var argumentOpt = TryGetRelevantArgument(initialNode, node, diagnostic);
62
                    await HandleInvocationExpressionAsync(context, invocationExpression, argumentOpt).ConfigureAwait(false);
63 64 65 66 67
                    return;
                }
            }
        }

68 69 70 71 72
        /// <summary>
        /// If the diagnostic is on a argument, the argument is considered to be the argument to fix.
        /// There are some exceptions to this rule. Returning null indicates that the fixer needs
        /// to find the relevant argument by itself.
        /// </summary>
C
CyrusNajmabadi 已提交
73 74
        private TArgumentSyntax TryGetRelevantArgument(
            SyntaxNode initialNode, SyntaxNode node, Diagnostic diagnostic)
75
        {
C
CyrusNajmabadi 已提交
76 77 78 79 80
            if (this.TooManyArgumentsDiagnosticIds.Contains(diagnostic.Id))
            {
                return null;
            }

81 82 83 84 85
            if (this.CannotConvertDiagnosticIds.Contains(diagnostic.Id))
            {
                return null;
            }

86
            return initialNode.GetAncestorsOrThis<TArgumentSyntax>()
87
                              .LastOrDefault(a => a.AncestorsAndSelf().Contains(node));
88 89
        }

90
        private async Task HandleInvocationExpressionAsync(
91
            CodeFixContext context, TInvocationExpressionSyntax invocationExpression, TArgumentSyntax argumentOpt)
92
        {
93 94 95 96 97 98
            var document = context.Document;
            var cancellationToken = context.CancellationToken;
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();

            var expression = syntaxFacts.GetExpressionOfInvocationExpression(invocationExpression);
99

100 101
            var symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken);
            var candidates = symbolInfo.CandidateSymbols.OfType<IMethodSymbol>().ToImmutableArray();
102

103
            var arguments = (SeparatedSyntaxList<TArgumentSyntax>)syntaxFacts.GetArgumentsOfInvocationExpression(invocationExpression);
M
Martin Strecker 已提交
104 105
            var argumentInsertPositionInMethodCandidates = GetArgumentInsertPositionForMethodCandidates(
                argumentOpt, semanticModel, syntaxFacts, arguments, candidates);
106
            RegisterFixForMethodOverloads(context, arguments, argumentInsertPositionInMethodCandidates);
107 108 109 110
        }

        private async Task HandleObjectCreationExpressionAsync(
            CodeFixContext context,
111 112
            TObjectCreationExpressionSyntax objectCreation,
            TArgumentSyntax argumentOpt)
113 114 115 116 117 118
        {
            var document = context.Document;
            var cancellationToken = context.CancellationToken;
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();

C
CyrusNajmabadi 已提交
119
            // Not supported if this is "new { ... }" (as there are no parameters at all.
120 121 122 123 124 125
            var typeNode = syntaxFacts.GetObjectCreationType(objectCreation);
            if (typeNode == null)
            {
                return;
            }

C
CyrusNajmabadi 已提交
126 127
            // If we can't figure out the type being created, or the type isn't in source,
            // then there's nothing we can do.
128
            var type = semanticModel.GetSymbolInfo(typeNode, cancellationToken).GetAnySymbol() as INamedTypeSymbol;
C
CyrusNajmabadi 已提交
129 130 131 132 133 134
            if (type == null)
            {
                return;
            }

            if (!type.IsNonImplicitAndFromSource())
135 136 137 138 139
            {
                return;
            }

            var arguments = (SeparatedSyntaxList<TArgumentSyntax>)syntaxFacts.GetArgumentsOfObjectCreationExpression(objectCreation);
140
            var methodCandidates = type.InstanceConstructors;
141

142 143
            var insertionData = GetArgumentInsertPositionForMethodCandidates(
                argumentOpt, semanticModel, syntaxFacts, arguments, methodCandidates);
144

M
Martin Strecker 已提交
145
            RegisterFixForMethodOverloads(context, arguments, insertionData);
146 147
        }

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        private ImmutableArray<ArgumentInsertPositionData<TArgumentSyntax>> GetArgumentInsertPositionForMethodCandidates(
            TArgumentSyntax argumentOpt,
            SemanticModel semanticModel,
            ISyntaxFactsService syntaxFacts,
            SeparatedSyntaxList<TArgumentSyntax> arguments,
            ImmutableArray<IMethodSymbol> methodCandidates)
        {
            var comparer = syntaxFacts.StringComparer;
            var methodsAndArgumentToAdd = ArrayBuilder<ArgumentInsertPositionData<TArgumentSyntax>>.GetInstance();

            foreach (var method in methodCandidates.OrderBy(m => m.Parameters.Length))
            {
                if (method.IsNonImplicitAndFromSource())
                {
                    var isNamedArgument = !string.IsNullOrWhiteSpace(syntaxFacts.GetNameForArgument(argumentOpt));

                    if (isNamedArgument || NonParamsParameterCount(method) < arguments.Count)
                    {
                        var argumentToAdd = DetermineFirstArgumentToAdd(
M
Martin Strecker 已提交
167 168
                            semanticModel, syntaxFacts, comparer, method,
                            arguments, argumentOpt);
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

                        if (argumentToAdd != null)
                        {
                            if (argumentOpt != null && argumentToAdd != argumentOpt)
                            {
                                // We were trying to fix a specific argument, but the argument we want
                                // to fix is something different.  That means there was an error earlier
                                // than this argument.  Which means we're looking at a non-viable 
                                // constructor or method.  Skip this one.
                                continue;
                            }

                            methodsAndArgumentToAdd.Add(new ArgumentInsertPositionData<TArgumentSyntax>(
                                method, argumentToAdd, arguments.IndexOf(argumentToAdd)));
                        }
                    }
                }
            }

            return methodsAndArgumentToAdd.ToImmutableAndFree();
        }

        private int NonParamsParameterCount(IMethodSymbol method)
            => method.IsParams() ? method.Parameters.Length - 1 : method.Parameters.Length;

M
Martin Strecker 已提交
194 195 196 197
        private void RegisterFixForMethodOverloads(
            CodeFixContext context,
            SeparatedSyntaxList<TArgumentSyntax> arguments,
            ImmutableArray<ArgumentInsertPositionData<TArgumentSyntax>> methodsAndArgumentsToAdd)
198 199 200 201
        {
            // Order by the furthest argument index to the nearest argument index.  The ones with
            // larger argument indexes mean that we matched more earlier arguments (and thus are
            // likely to be the correct match).
M
Martin Strecker 已提交
202
            foreach (var argumentInsertPositionData in methodsAndArgumentsToAdd.OrderByDescending(t => t.ArgumentInsertionIndex))
203
            {
M
Martin Strecker 已提交
204 205 206
                var methodToUpdate = argumentInsertPositionData.MethodToUpdate;
                var argumentToInsert = argumentInsertPositionData.ArgumentToInsert;
                var parameters = methodToUpdate.Parameters.Select(p => p.ToDisplayString(SimpleFormat));
M
Martin Strecker 已提交
207

M
Martin Strecker 已提交
208
                var title = GetCodeFixTitle(FeaturesResources.Add_parameter_to_0, methodToUpdate, parameters);
209
                var hasCascadingDeclarations = HasCascadingDeclarations(methodToUpdate);
M
Martin Strecker 已提交
210
                CodeAction codeAction = new MyCodeAction(title,
211
                    c => FixAsync(context.Document, methodToUpdate, argumentToInsert, arguments, fixAllReferences: false, c));
212 213
                if (hasCascadingDeclarations)
                {
M
Martin Strecker 已提交
214
                    // Offer another alternative code action. Wrap both options so the IDE can collapse them.
215 216
                    var titleForCascadingFix = GetCodeFixTitle(
                        FeaturesResources.Add_parameter_to_0_including_overrides_implementations, methodToUpdate, parameters);
M
Martin Strecker 已提交
217 218 219 220 221
                    codeAction = new CodeAction.CodeActionWithNestedActions(
                        title: title,
                        isInlinable: true,
                        nestedActions: ImmutableArray.Create<CodeAction>(
                            codeAction,
M
Martin Strecker 已提交
222
                            new MyCodeAction(titleForCascadingFix,
M
Martin Strecker 已提交
223
                                c => FixAsync(context.Document, methodToUpdate, argumentToInsert, arguments, fixAllReferences: true, c))));
224
                }
M
Martin Strecker 已提交
225 226

                context.RegisterCodeFix(codeAction, context.Diagnostics);
227 228 229
            }
        }

230
        /// <summary>
231
        /// Checks if there are indications that there might be more than one declarations that need to be fixed.
232 233 234 235
        /// The check does not look-up if there are other declarations (this is done later in the CodeAction).
        /// </summary>
        private bool HasCascadingDeclarations(IMethodSymbol method)
        {
236 237 238 239 240 241
            // Don't cascade constructors
            if (method.IsConstructor())
            {
                return false;
            }

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
            // Virtual methods of all kinds might have overrides somewhere else that need to be fixed.
            if (method.IsVirtual || method.IsOverride || method.IsAbstract)
            {
                return true;
            }

            // If interfaces are involved we will fix those too
            // Explicit interface implementations are easy
            if (method.ExplicitInterfaceImplementations.Length > 0)
            {
                return true;
            }

            // For implicit interface implementations lets check if the characteristic of the method
            // allows it to implicit implement an interface member.
            if (method.DeclaredAccessibility == Accessibility.Private || method.DeclaredAccessibility == Accessibility.NotApplicable)
            {
                return false;
            }

            if (method.IsStatic)
            {
                return false;
            }

            // Now check if the method does implement an interface member
268 269 270 271 272 273
            if (method.ExplicitOrImplicitInterfaceImplementations().Length > 0)
            {
                return true;
            }

            return false;
274 275
        }

M
Martin Strecker 已提交
276
        private static string GetCodeFixTitle(string resourceString, IMethodSymbol methodToUpdate, IEnumerable<string> parameters)
277
        {
M
Martin Strecker 已提交
278 279 280
            var methodPrefix = methodToUpdate.IsConstructor()
                ? ""
                : $"{methodToUpdate.ContainingType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)}.";
281
            var signature = $"{methodPrefix}{methodToUpdate.Name}({string.Join(", ", parameters)})";
M
Martin Strecker 已提交
282
            var title = string.Format(resourceString, signature);
283 284 285
            return title;
        }

286
        private async Task<Solution> FixAsync(
H
Heejae Chang 已提交
287
            Document invocationDocument,
288 289 290
            IMethodSymbol method,
            TArgumentSyntax argument,
            SeparatedSyntaxList<TArgumentSyntax> argumentList,
291
            bool fixAllReferences,
292 293
            CancellationToken cancellationToken)
        {
294 295
            var solution = invocationDocument.Project.Solution;
            var argumentType = await GetArgumentTypeAsync(invocationDocument, argument, cancellationToken).ConfigureAwait(false);
296 297 298 299 300 301

            // The argumentNameSuggestion is the base for the parameter name.
            // For each method declaration the name is made unique to avoid name collisions.
            var (argumentNameSuggestion, isNamedArgument) = await GetNameSuggestionForArgumentAsync(
                invocationDocument, argument, cancellationToken).ConfigureAwait(false);

302 303 304
            var referencedSymbols = fixAllReferences
                ? await FindMethodDeclarationReferences(invocationDocument, method, cancellationToken).ConfigureAwait(false)
                : method.GetAllMethodSymbolsOfPartialParts();
305

306 307
            var anySymbolReferencesNotInSource = referencedSymbols.Any(symbol => !symbol.IsFromSource());
            var locationsInSource = referencedSymbols.Where(symbol => symbol.IsFromSource());
308 309 310

            // Indexing Locations[0] is valid because IMethodSymbols have one location at most
            // and IsFromSource() tests if there is at least one location.
311
            var locationsByDocument = locationsInSource.ToLookup(declarationLocation
312
                => solution.GetDocument(declarationLocation.Locations[0].SourceTree));
313

314 315 316 317 318
            foreach (var documentLookup in locationsByDocument)
            {
                var document = documentLookup.Key;
                var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
                var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
319
                var editor = new SyntaxEditor(syntaxRoot, solution.Workspace);
320
                var generator = editor.Generator;
321
                foreach (var methodDeclaration in documentLookup)
322
                {
323
                    var methodNode = syntaxRoot.FindNode(methodDeclaration.Locations[0].SourceSpan);
324
                    var parameterSymbol = CreateParameterSymbol(
325
                        methodDeclaration, argumentType, argumentNameSuggestion);
326

327 328
                    var parameterDeclaration = generator.ParameterDeclaration(parameterSymbol)
                                                        .WithAdditionalAnnotations(Formatter.Annotation);
329 330 331
                    if (anySymbolReferencesNotInSource && methodDeclaration == method)
                    {
                        parameterDeclaration = parameterDeclaration.WithAdditionalAnnotations(
M
Martin Strecker 已提交
332
                            ConflictAnnotation.Create(FeaturesResources.Related_method_signatures_found_in_metadata_will_not_be_updated));
333
                    }
334 335 336 337
                    var existingParameters = generator.GetParameters(methodNode);
                    var insertionIndex = isNamedArgument
                        ? existingParameters.Count
                        : argumentList.IndexOf(argument);
338

339 340 341 342
                    if (method.IsExtensionMethod)
                    {
                        insertionIndex++;
                    }
343

344 345 346
                    AddParameter(
                        syntaxFacts, editor, methodNode, argument,
                        insertionIndex, parameterDeclaration, cancellationToken);
C
CyrusNajmabadi 已提交
347

348 349
                }
                var newRoot = editor.GetChangedRoot();
350
                solution = solution.WithDocumentSyntaxRoot(document.Id, newRoot);
351
            }
352 353 354 355 356 357 358 359 360 361 362

            return solution;
        }

        private static async Task<ITypeSymbol> GetArgumentTypeAsync(Document invocationDocument, TArgumentSyntax argument, CancellationToken cancellationToken)
        {
            var syntaxFacts = invocationDocument.GetLanguageService<ISyntaxFactsService>();
            var semanticModel = await invocationDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var argumentExpression = syntaxFacts.GetExpressionOfArgument(argument);
            var argumentType = semanticModel.GetTypeInfo(argumentExpression).Type ?? semanticModel.Compilation.ObjectType;
            return argumentType;
363
        }
364

365 366
        private static async Task<ImmutableArray<IMethodSymbol>> FindMethodDeclarationReferences(
            Document invocationDocument, IMethodSymbol method, CancellationToken cancellationToken)
367 368 369 370 371 372 373 374 375
        {
            var progress = new StreamingProgressCollector(StreamingFindReferencesProgress.Instance);

            await SymbolFinder.FindReferencesAsync(
                symbolAndProjectId: SymbolAndProjectId.Create(method, invocationDocument.Project.Id),
                solution: invocationDocument.Project.Solution,
                documents: null,
                progress: progress,
                cancellationToken: cancellationToken).ConfigureAwait(false);
376 377
            var referencedSymbols = progress.GetReferencedSymbols();
            return referencedSymbols.Select(referencedSymbol => referencedSymbol.Definition).OfType<IMethodSymbol>().ToImmutableArray();
378
        }
379

380 381
        private async Task<(string argumentNameSuggestion, bool isNamed)> GetNameSuggestionForArgumentAsync(
            Document invocationDocument, TArgumentSyntax argument, CancellationToken cancellationToken)
382
        {
383
            var syntaxFacts = invocationDocument.GetLanguageService<ISyntaxFactsService>();
384

385
            var argumentName = syntaxFacts.GetNameForArgument(argument);
386 387
            if (!string.IsNullOrWhiteSpace(argumentName))
            {
388
                return (argumentNameSuggestion: argumentName, isNamed: true);
389 390 391
            }
            else
            {
392
                var semanticModel = await invocationDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
393 394 395
                var expression = syntaxFacts.GetExpressionOfArgument(argument);
                var semanticFacts = invocationDocument.GetLanguageService<ISemanticFactsService>();
                argumentName = semanticFacts.GenerateNameForExpression(
396
                    semanticModel, expression, capitalize: false, cancellationToken: cancellationToken);
397 398 399
                return (argumentNameSuggestion: argumentName, isNamed: false);
            }
        }
400

401 402 403 404 405 406 407
        private IParameterSymbol CreateParameterSymbol(
            IMethodSymbol method,
            ITypeSymbol parameterType,
            string argumentNameSuggestion)
        {
            var uniqueName = NameGenerator.EnsureUniqueness(argumentNameSuggestion, method.Parameters.Select(p => p.Name));
            var newParameterSymbol = CodeGenerationSymbolFactory.CreateParameterSymbol(
408
                    attributes: default, refKind: RefKind.None, isParams: false, type: parameterType, name: uniqueName);
409
            return newParameterSymbol;
410 411 412 413 414 415 416
        }

        private static void AddParameter(
            ISyntaxFactsService syntaxFacts,
            SyntaxEditor editor,
            SyntaxNode declaration,
            TArgumentSyntax argument,
C
CyrusNajmabadi 已提交
417
            int insertionIndex,
418 419 420
            SyntaxNode parameterDeclaration,
            CancellationToken cancellationToken)
        {
C
CyrusNajmabadi 已提交
421
            var sourceText = declaration.SyntaxTree.GetText(cancellationToken);
422 423 424 425 426
            var generator = editor.Generator;

            var existingParameters = generator.GetParameters(declaration);
            var placeOnNewLine = ShouldPlaceParametersOnNewLine(existingParameters, cancellationToken);

427 428 429 430 431 432 433
            if (!placeOnNewLine)
            {
                // Trivial case.  Just let the stock editor impl handle this for us.
                editor.InsertParameter(declaration, insertionIndex, parameterDeclaration);
                return;
            }

C
CyrusNajmabadi 已提交
434
            if (insertionIndex == existingParameters.Count)
435
            {
436 437 438
                // Placing the last parameter on its own line.  Get the indentation of the 
                // curent last parameter and give the new last parameter the same indentation.
                var leadingIndentation = GetDesiredLeadingIndentation(
H
Heejae Chang 已提交
439
                    generator, syntaxFacts, existingParameters[existingParameters.Count - 1], includeLeadingNewLine: true);
440 441 442
                parameterDeclaration = parameterDeclaration.WithPrependedLeadingTrivia(leadingIndentation)
                                                            .WithAdditionalAnnotations(Formatter.Annotation);

443 444
                editor.AddParameter(declaration, parameterDeclaration);
            }
445
            else if (insertionIndex == 0)
446
            {
447 448 449 450 451 452
                // Inserting into the start of the list.  The existing first parameter might
                // be on the same line as the parameter list, or it might be on the next line.
                var firstParameter = existingParameters[0];
                var previousToken = firstParameter.GetFirstToken().GetPreviousToken();

                if (sourceText.AreOnSameLine(previousToken, firstParameter.GetFirstToken()))
453
                {
454
                    // First parameter is on hte same line as the method.  
455

456 457 458 459 460 461 462 463 464 465 466 467 468
                    // We want to insert the parameter at the front of the exsiting parameter
                    // list.  That means we need to move the current first parameter to a new
                    // line.  Give the current first parameter the indentation of the second
                    // parameter in the list.
                    editor.InsertParameter(declaration, insertionIndex, parameterDeclaration);
                    var nextParameter = existingParameters[insertionIndex];

                    var nextLeadingIndentation = GetDesiredLeadingIndentation(
                        generator, syntaxFacts, existingParameters[insertionIndex + 1], includeLeadingNewLine: true);
                    editor.ReplaceNode(
                        nextParameter,
                        nextParameter.WithPrependedLeadingTrivia(nextLeadingIndentation)
                                     .WithAdditionalAnnotations(Formatter.Annotation));
469 470 471
                }
                else
                {
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
                    // First parameter is on its own line.  No need to adjust its indentation.
                    // Just copy its indentation over to the parameter we're inserting, and
                    // make sure the current first parameter gets a newline so it stays on 
                    // its own line.

                    // We want to insert the parameter at the front of the exsiting parameter
                    // list.  That means we need to move the current first parameter to a new
                    // line.  Give the current first parameter the indentation of the second
                    // parameter in the list.
                    var firstLeadingIndentation = GetDesiredLeadingIndentation(
                        generator, syntaxFacts, existingParameters[0], includeLeadingNewLine: false);

                    editor.InsertParameter(declaration, insertionIndex,
                        parameterDeclaration.WithLeadingTrivia(firstLeadingIndentation));
                    var nextParameter = existingParameters[insertionIndex];

                    editor.ReplaceNode(
                        nextParameter,
                        nextParameter.WithPrependedLeadingTrivia(generator.ElasticCarriageReturnLineFeed)
                                     .WithAdditionalAnnotations(Formatter.Annotation));
492 493
                }
            }
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
            else
            {
                // We're inserting somewhere after the start (but not at the end). Because 
                // we've set placeOnNewLine, we know that the current comma we'll be placed
                // after already have a newline following it.  So all we need for this new 
                // parameter is to get the indentation of the following parameter.
                // Because we're going to 'steal' the existing comma from that parameter,
                // ensure that the next parameter has a new-line added to it so that it will
                // still stay on a new line.
                var nextParameter = existingParameters[insertionIndex];
                var leadingIndentation = GetDesiredLeadingIndentation(
                    generator, syntaxFacts, existingParameters[insertionIndex], includeLeadingNewLine: false);
                parameterDeclaration = parameterDeclaration.WithPrependedLeadingTrivia(leadingIndentation);

                editor.InsertParameter(declaration, insertionIndex, parameterDeclaration);
                editor.ReplaceNode(
                    nextParameter,
                    nextParameter.WithPrependedLeadingTrivia(generator.ElasticCarriageReturnLineFeed)
                                 .WithAdditionalAnnotations(Formatter.Annotation));
            }
514 515 516
        }

        private static List<SyntaxTrivia> GetDesiredLeadingIndentation(
H
Heejae Chang 已提交
517
            SyntaxGenerator generator, ISyntaxFactsService syntaxFacts,
518 519 520 521 522 523 524 525
            SyntaxNode node, bool includeLeadingNewLine)
        {
            var triviaList = new List<SyntaxTrivia>();
            if (includeLeadingNewLine)
            {
                triviaList.Add(generator.ElasticCarriageReturnLineFeed);
            }

H
Heejae Chang 已提交
526 527
            var lastWhitespace = default(SyntaxTrivia);
            foreach (var trivia in node.GetLeadingTrivia().Reverse())
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
            {
                if (syntaxFacts.IsWhitespaceTrivia(trivia))
                {
                    lastWhitespace = trivia;
                }
                else if (syntaxFacts.IsEndOfLineTrivia(trivia))
                {
                    break;
                }
            }

            if (lastWhitespace.RawKind != 0)
            {
                triviaList.Add(lastWhitespace);
            }

            return triviaList;
        }
546

547 548 549 550 551 552
        private static bool ShouldPlaceParametersOnNewLine(
            IReadOnlyList<SyntaxNode> parameters, CancellationToken cancellationToken)
        {
            if (parameters.Count <= 1)
            {
                return false;
553
            }
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

            var text = parameters[0].SyntaxTree.GetText(cancellationToken);
            for (int i = 1, n = parameters.Count; i < n; i++)
            {
                var lastParameter = parameters[i - 1];
                var thisParameter = parameters[i];

                if (text.AreOnSameLine(lastParameter.GetLastToken(), thisParameter.GetFirstToken()))
                {
                    return false;
                }
            }

            // All parameters are on different lines.  Place the new parameter on a new line as well.
            return true;
569 570 571 572 573 574 575 576 577 578
        }

        private static readonly SymbolDisplayFormat SimpleFormat =
                    new SymbolDisplayFormat(
                        typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
                        genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
                        parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType,
                        miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);

        private TArgumentSyntax DetermineFirstArgumentToAdd(
579 580 581 582
            SemanticModel semanticModel,
            ISyntaxFactsService syntaxFacts,
            StringComparer comparer,
            IMethodSymbol method,
583 584
            SeparatedSyntaxList<TArgumentSyntax> arguments,
            TArgumentSyntax argumentOpt)
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
        {
            var methodParameterNames = new HashSet<string>(comparer);
            methodParameterNames.AddRange(method.Parameters.Select(p => p.Name));

            for (int i = 0, n = arguments.Count; i < n; i++)
            {
                var argument = arguments[i];
                var argumentName = syntaxFacts.GetNameForArgument(argument);

                if (!string.IsNullOrWhiteSpace(argumentName))
                {
                    // If the user provided an argument-name and we don't have any parameters that
                    // match, then this is the argument we want to add a parameter for.
                    if (!methodParameterNames.Contains(argumentName))
                    {
                        return argument;
                    }
                }
                else
                {
                    // Positional argument.  If the position is beyond what the method supports,
                    // then this definitely is an argument we could add.
                    if (i >= method.Parameters.Length)
                    {
609 610 611 612 613 614
                        if (method.Parameters.LastOrDefault()?.IsParams == true)
                        {
                            // Last parameter is a params.  We can't place any parameters past it.
                            return null;
                        }

615 616 617
                        return argument;
                    }

C
CyrusNajmabadi 已提交
618 619
                    // Now check the type of the argument versus the type of the parameter.  If they
                    // don't match, then this is the argument we should make the parameter for.
620 621 622 623 624 625 626 627
                    var expressionOfArgument = syntaxFacts.GetExpressionOfArgument(argument);
                    if (expressionOfArgument is null)
                    {
                        return null;
                    }
                    var argumentTypeInfo = semanticModel.GetTypeInfo(expressionOfArgument);
                    var isNullLiteral = syntaxFacts.IsNullLiteralExpression(expressionOfArgument);
                    var isDefaultLiteral = syntaxFacts.IsDefaultLiteralExpression(expressionOfArgument);
C
CyrusNajmabadi 已提交
628

C
CyrusNajmabadi 已提交
629 630 631
                    if (argumentTypeInfo.Type == null && argumentTypeInfo.ConvertedType == null)
                    {
                        // Didn't know the type of the argument.  We shouldn't assume it doesn't
632 633
                        // match a parameter.  However, if the user wrote 'null' and it didn't
                        // match anything, then this is the problem argument.
C
CyrusNajmabadi 已提交
634
                        if (!isNullLiteral && !isDefaultLiteral)
635 636 637
                        {
                            continue;
                        }
C
CyrusNajmabadi 已提交
638 639
                    }

640 641
                    var parameter = method.Parameters[i];

C
CyrusNajmabadi 已提交
642
                    if (!TypeInfoMatchesType(argumentTypeInfo, parameter.Type, isNullLiteral, isDefaultLiteral))
643
                    {
C
CyrusNajmabadi 已提交
644
                        if (TypeInfoMatchesWithParamsExpansion(argumentTypeInfo, parameter, isNullLiteral, isDefaultLiteral))
645
                        {
C
CyrusNajmabadi 已提交
646 647 648 649
                            // The argument matched if we expanded out the params-parameter.
                            // As the params-parameter has to be last, there's nothing else to 
                            // do here.
                            return null;
650 651
                        }

652 653 654 655 656 657 658
                        return argument;
                    }
                }
            }

            return null;
        }
C
CyrusNajmabadi 已提交
659

C
CyrusNajmabadi 已提交
660
        private bool TypeInfoMatchesWithParamsExpansion(
661
            TypeInfo argumentTypeInfo, IParameterSymbol parameter,
C
CyrusNajmabadi 已提交
662
            bool isNullLiteral, bool isDefaultLiteral)
C
CyrusNajmabadi 已提交
663 664 665
        {
            if (parameter.IsParams && parameter.Type is IArrayTypeSymbol arrayType)
            {
C
CyrusNajmabadi 已提交
666
                if (TypeInfoMatchesType(argumentTypeInfo, arrayType.ElementType, isNullLiteral, isDefaultLiteral))
C
CyrusNajmabadi 已提交
667 668 669 670 671 672 673 674
                {
                    return true;
                }
            }

            return false;
        }

C
CyrusNajmabadi 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
        private bool TypeInfoMatchesType(
            TypeInfo argumentTypeInfo, ITypeSymbol type,
            bool isNullLiteral, bool isDefaultLiteral)
        {
            if (type.Equals(argumentTypeInfo.Type) || type.Equals(argumentTypeInfo.ConvertedType))
            {
                return true;
            }

            if (isDefaultLiteral)
            {
                return true;
            }

            if (isNullLiteral)
            {
                return type.IsReferenceType || type.IsNullable();
            }

694 695 696 697 698
            if (type.Kind == SymbolKind.TypeParameter)
            {
                return true;
            }

C
CyrusNajmabadi 已提交
699 700
            return false;
        }
701

702
        private class MyCodeAction : CodeAction.SolutionChangeAction
C
CyrusNajmabadi 已提交
703
        {
704
            public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution)
705
                : base(title, createChangedSolution)
706 707
            {
            }
C
CyrusNajmabadi 已提交
708 709
        }
    }
T
Tomas Matousek 已提交
710
}