|
| 1 | +using System.Diagnostics; |
| 2 | +using Microsoft.CodeAnalysis; |
| 3 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 4 | +using Microsoft.CodeAnalysis.Operations; |
| 5 | +using Pretender.SourceGenerator.Parser; |
| 6 | + |
| 7 | +namespace Pretender.SourceGenerator |
| 8 | +{ |
| 9 | + internal class PretendInvocation |
| 10 | + { |
| 11 | + public PretendInvocation(ITypeSymbol pretendType, Location location, bool fillExisting) |
| 12 | + { |
| 13 | + PretendType = pretendType; |
| 14 | + Location = location; |
| 15 | + FillExisting = fillExisting; |
| 16 | + } |
| 17 | + |
| 18 | + public ITypeSymbol PretendType { get; } |
| 19 | + public Location Location { get; } |
| 20 | + public bool FillExisting { get; } |
| 21 | + |
| 22 | + public static bool IsCandidateSyntaxNode(SyntaxNode node) |
| 23 | + { |
| 24 | + // Pretend.That<T>(); |
| 25 | + if (node is InvocationExpressionSyntax |
| 26 | + { |
| 27 | + Expression: MemberAccessExpressionSyntax |
| 28 | + { |
| 29 | + // TODO: Will this work with a using static Pretender.Pretend |
| 30 | + // ... |
| 31 | + // That<IInterface>(); |
| 32 | + Expression: IdentifierNameSyntax { Identifier.ValueText: "Pretend" }, |
| 33 | + Name: GenericNameSyntax { Identifier.ValueText: "That", TypeArgumentList.Arguments.Count: 1 }, |
| 34 | + } |
| 35 | + }) |
| 36 | + { |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + // TODO: Also do Attribute |
| 41 | + |
| 42 | + return false; |
| 43 | + } |
| 44 | + |
| 45 | + public static PretendInvocation? Create(GeneratorSyntaxContext context, CancellationToken cancellationToken) |
| 46 | + { |
| 47 | + Debug.Assert(IsCandidateSyntaxNode(context.Node)); |
| 48 | + var operation = context.SemanticModel.GetOperation(context.Node, cancellationToken); |
| 49 | + if (operation is IInvocationOperation invocation) |
| 50 | + { |
| 51 | + cancellationToken.ThrowIfCancellationRequested(); |
| 52 | + return CreateFromGeneric(invocation); |
| 53 | + } |
| 54 | + // TODO: Support attribute |
| 55 | + |
| 56 | + return null; |
| 57 | + } |
| 58 | + |
| 59 | + private static PretendInvocation? CreateFromGeneric(IInvocationOperation operation) |
| 60 | + { |
| 61 | + if (operation.TargetMethod is not IMethodSymbol |
| 62 | + { |
| 63 | + Name: "That", |
| 64 | + ContainingType: INamedTypeSymbol namedTypeSymbol, |
| 65 | + TypeArguments.Length: 1, |
| 66 | + } || !KnownTypeSymbols.IsPretend(namedTypeSymbol)) |
| 67 | + { |
| 68 | + return null; |
| 69 | + } |
| 70 | + |
| 71 | + return new PretendInvocation(operation.TargetMethod.TypeArguments[0], operation.Syntax.GetLocation(), false); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments