|
| 1 | +using Microsoft.CodeAnalysis; |
| 2 | +using Microsoft.CodeAnalysis.Completion; |
| 3 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Linq; |
| 7 | +using System.Text; |
| 8 | +using System.Threading.Tasks; |
| 9 | + |
| 10 | +namespace Mocking.Helpers.NSubstitute |
| 11 | +{ |
| 12 | + [ExportCompletionProvider(nameof(NSubstituteArgAnyCompletion), LanguageNames.CSharp)] |
| 13 | + public class NSubstituteArgAnyCompletion : CompletionProvider |
| 14 | + { |
| 15 | + private NSubstituteProvider _provider; |
| 16 | + |
| 17 | + public NSubstituteArgAnyCompletion() |
| 18 | + { |
| 19 | + this._provider = new NSubstituteProvider(); |
| 20 | + } |
| 21 | + |
| 22 | + internal bool IsSubstituteForMethod(InvocationExpressionSyntax invocation) |
| 23 | + { |
| 24 | + return SyntaxHelpers.IsMethodNamed(invocation, this._provider.MockingMethodName); |
| 25 | + } |
| 26 | + |
| 27 | + public override async Task ProvideCompletionsAsync(CompletionContext context) |
| 28 | + { |
| 29 | + try |
| 30 | + { |
| 31 | + if (!context.Document.SupportsSemanticModel || !context.Document.SupportsSyntaxTree) return; |
| 32 | + |
| 33 | + var hasNSubstituteReferenced = context.Document.Project.MetadataReferences.Any(r => r.Display.Contains(this._provider.AssemblyName)); |
| 34 | + if (!hasNSubstituteReferenced) return; |
| 35 | + |
| 36 | + var syntaxRoot = await context.Document.GetSyntaxRootAsync(); |
| 37 | + var token = SyntaxHelpers.GetSelectedTokens(syntaxRoot, context.Position); |
| 38 | + |
| 39 | + // Not in an opened method |
| 40 | + if (token.Parent == null) return; |
| 41 | + |
| 42 | + var mockedMethodArgumentList = token.Parent as ArgumentListSyntax; |
| 43 | + var mockedMethodInvocation = mockedMethodArgumentList.Ancestors() |
| 44 | + .OfType<InvocationExpressionSyntax>() |
| 45 | + .FirstOrDefault(); |
| 46 | + |
| 47 | + if (mockedMethodInvocation == null) return; |
| 48 | + |
| 49 | + var semanticModel = await context.Document.GetSemanticModelAsync(); |
| 50 | + var matchingMockedMethods = SyntaxHelpers.GetCandidatesMockedMethodSignatures(semanticModel, mockedMethodInvocation); |
| 51 | + |
| 52 | + var completionService = new CompletionService(context, token, semanticModel, this._provider); |
| 53 | + |
| 54 | + foreach (IMethodSymbol matchingMockedMethodSymbol in matchingMockedMethods) |
| 55 | + { |
| 56 | + completionService.AddSuggestionsForMethod(matchingMockedMethodSymbol, mockedMethodArgumentList); |
| 57 | + } |
| 58 | + } |
| 59 | + catch |
| 60 | + { |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
0 commit comments