📄 core/src/MessageLinks.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.Options;

namespace Cfa;

internal sealed class MessageLinks
{
    private readonly MessageOptions options;
    private readonly IReadOnlyCollection<Compilation> compilations;
    private readonly HashSet<SyntaxTree> includedTrees;
    private readonly Solution solution;
    private readonly Dictionary<(MessageRoute Route, string Type, bool Publishers), HashSet<ISymbol>> links = [];
    private readonly Dictionary<(SyntaxTree Tree, TextSpan Span), Registration[]> registrations = [];
    private readonly Dictionary<(MethodSelector Method, int Argument, int? TypeArgument), IMethodSymbol[]> methods = [];
    private readonly IImmutableSet<Document> documents;

    public MessageLinks(
        MessageOptions options,
        IReadOnlyCollection<Compilation> compilations,
        HashSet<SyntaxTree> includedTrees,
        Solution solution
    )
    {
        this.options = options;
        this.compilations = compilations;
        this.includedTrees = includedTrees;
        this.solution = solution;
        documents = includedTrees.Select(solution.GetDocument).OfType<Document>().ToImmutableHashSet();
        // Validate API shapes only; call sites are resolved on demand.
        foreach (var route in options.MessageRoutes)
        {
            Validate(route.Publisher.Method, route.Publisher.MessageArgument);
            foreach (var rule in route.Registrations)
            {
                Validate(rule.Method, rule.HandlerArgument, rule.MessageTypeArgument);
            }
        }
    }

    private sealed record Registration(MessageRoute Route, ITypeSymbol Message, ISymbol Handler, TextSpan Argument);

    public bool IsHandler(ISymbol member) =>
        options.MessageRoutes is not []
        && member is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }
        && member.DeclaringSyntaxReferences.Any(reference =>
            reference
                .GetSyntax()
                .Ancestors()
                .OfType<InvocationExpressionSyntax>()
                .Any(invocation =>
                    Registrations(invocation)
                        .Any(registration => SymbolEqualityComparer.Default.Equals(registration.Handler, member))
                )
        );

    public bool IsRegistrationArgument(SyntaxNode node) =>
        options.MessageRoutes is not []
        && node.AncestorsAndSelf()
            .TakeWhile(ancestor => ancestor is not AnonymousFunctionExpressionSyntax)
            .OfType<ArgumentSyntax>()
            .Any(argument =>
                argument.Parent?.Parent is InvocationExpressionSyntax invocation
                && Registrations(invocation).Any(registration => registration.Argument == argument.Span)
            );

    public async Task<IEnumerable<ISymbol>> Targets(ISymbol member, CancellationToken token)
    {
        var result = new HashSet<ISymbol>(SymbolEqualityComparer.Default);
        if (options.MessageRoutes is [])
        {
            return result;
        }
        foreach (var reference in member.DeclaringSyntaxReferences)
        {
            var syntax = await reference.GetSyntaxAsync(token);
            var model = compilations.GetSemanticModel(syntax.SyntaxTree);
            foreach (
                var invocation in MemberSyntax
                    .ExecutionRoots(member, syntax)
                    .SelectMany(root =>
                        root.DescendantNodesAndSelf(node =>
                            node == root
                            || node is not AnonymousFunctionExpressionSyntax
                            || model.GetSymbolInfo(node, token).Symbol is not { } handler
                            || !IsHandler(handler)
                        )
                    )
                    .OfType<InvocationExpressionSyntax>()
                    .Where(invocation =>
                        options.MessageRoutes.Any(route => route.Publisher.Method.Name == InvocationName(invocation))
                    )
            )
            {
                token.ThrowIfCancellationRequested();
                if (
                    !(member is IMethodSymbol { MethodKind: MethodKind.Constructor } && syntax is TypeDeclarationSyntax)
                        && !SameMember(ContainingMember(model, invocation, token), member)
                    || model.GetOperation(invocation, token) is not IInvocationOperation operation
                )
                {
                    continue;
                }
                foreach (
                    var route in options.MessageRoutes.Where(route =>
                        Matches(operation.TargetMethod, route.Publisher.Method)
                    )
                )
                {
                    if (PublishedMessage(operation, route) is { } message)
                    {
                        result.UnionWith(await Resolve(route, message, publishers: false, token));
                    }
                }
            }
        }
        return result;
    }

    public async Task<IEnumerable<ISymbol>> Callers(
        ISymbol member,
        IEnumerable<ReferencedSymbol> references,
        CancellationToken token
    )
    {
        var result = new HashSet<ISymbol>(SymbolEqualityComparer.Default);
        if (options.MessageRoutes is [])
        {
            return result;
        }
        var candidates = new HashSet<InvocationExpressionSyntax>();
        if (member is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction })
        {
            foreach (var reference in member.DeclaringSyntaxReferences)
            {
                candidates.UnionWith(
                    (await reference.GetSyntaxAsync(token)).Ancestors().OfType<InvocationExpressionSyntax>()
                );
            }
        }
        else
        {
            candidates.UnionWith(await ReferencingInvocations(references, token));
        }
        foreach (
            var registration in candidates
                .SelectMany(Registrations)
                .Where(registration => SameMember(registration.Handler, member))
        )
        {
            result.UnionWith(await Resolve(registration.Route, registration.Message, publishers: true, token));
        }
        return result;
    }

    private Registration[] Registrations(InvocationExpressionSyntax syntax)
    {
        var key = (syntax.SyntaxTree, syntax.Span);
        if (registrations.TryGetValue(key, out var found))
        {
            return found;
        }
        var result = new List<Registration>();
        if (!includedTrees.Contains(syntax.SyntaxTree))
        {
            return [];
        }
        var name = InvocationName(syntax);
        foreach (var route in options.MessageRoutes)
        {
            foreach (var rule in route.Registrations.Where(rule => rule.Method.Name == name))
            {
                var model = compilations.GetSemanticModel(syntax.SyntaxTree);
                if (
                    model.GetOperation(syntax) is not IInvocationOperation operation
                    || !Matches(operation.TargetMethod, rule.Method)
                )
                {
                    continue;
                }
                Validate(rule.Method, rule.HandlerArgument, rule.MessageTypeArgument);
                var callback = operation.Arguments.FirstOrDefault(argument =>
                    argument.Parameter?.Ordinal == rule.HandlerArgument
                );
                if (callback is not { Value: var callbackOperation })
                {
                    continue;
                }
                var handler = Unwrap(callbackOperation) switch
                {
                    IAnonymousFunctionOperation lambda => lambda.Symbol,
                    IMethodReferenceOperation method => method.Method,
                    _ => null,
                };
                if (
                    handler is null
                    || !handler.DeclaringSyntaxReferences.Any(reference => includedTrees.Contains(reference.SyntaxTree))
                )
                {
                    continue;
                }
                var argument = syntax.ArgumentList.Arguments.First(argument =>
                    argument.Span.Contains(callbackOperation.Syntax.Span)
                );
                result.Add(
                    new(route, operation.TargetMethod.TypeArguments[rule.MessageTypeArgument], handler, argument.Span)
                );
            }
        }
        found = [.. result];
        registrations.Add(key, found);
        return found;
    }

    private static string InvocationName(InvocationExpressionSyntax invocation) =>
        invocation.Expression switch
        {
            SimpleNameSyntax simple => simple.Identifier.ValueText,
            MemberAccessExpressionSyntax access => access.Name.Identifier.ValueText,
            MemberBindingExpressionSyntax binding => binding.Name.Identifier.ValueText,
            _ => "",
        };

    private ITypeSymbol? PublishedMessage(IInvocationOperation operation, MessageRoute route)
    {
        Validate(route.Publisher.Method, route.Publisher.MessageArgument);
        var message = Unwrap(
            operation
                .Arguments.FirstOrDefault(argument => argument.Parameter?.Ordinal == route.Publisher.MessageArgument)
                ?.Value
        )?.Type;
        return message is INamedTypeSymbol { IsAbstract: false, TypeKind: TypeKind.Class or TypeKind.Struct }
            ? message
            : null;
    }

    private async Task<HashSet<ISymbol>> Resolve(
        MessageRoute route,
        ITypeSymbol message,
        bool publishers,
        CancellationToken token
    )
    {
        var key = (
            route,
            $"{message.ContainingAssembly.Identity}:{DocumentationCommentId.CreateReferenceId(message)}",
            publishers
        );
        if (links.TryGetValue(key, out var found))
        {
            return found;
        }
        var result = new HashSet<ISymbol>(SymbolEqualityComparer.Default);
        if (publishers)
        {
            foreach (var method in Validate(route.Publisher.Method, route.Publisher.MessageArgument))
            {
                foreach (var invocation in await ReferencingInvocations(method, token))
                {
                    var model = compilations.GetSemanticModel(invocation.SyntaxTree);
                    if (
                        model.GetOperation(invocation, token) is not IInvocationOperation operation
                        || !Matches(operation.TargetMethod, route.Publisher.Method)
                        || PublishedMessage(operation, route) is not { } published
                        || !SameMessageType(published, message)
                    )
                    {
                        continue;
                    }
                    var caller = ContainingMember(model, invocation, token);
                    if (caller is IMethodSymbol or IPropertySymbol)
                    {
                        result.Add(caller);
                    }
                }
            }
        }
        else
        {
            foreach (var rule in route.Registrations)
            {
                Validate(rule.Method, rule.HandlerArgument, rule.MessageTypeArgument);
            }
            // Search references to this message type, rather than every registration API call.
            foreach (var invocation in await ReferencingInvocations(message.OriginalDefinition, token))
            {
                foreach (var registration in Registrations(invocation))
                {
                    if (registration.Route == route && SameMessageType(message, registration.Message))
                    {
                        result.Add(registration.Handler);
                    }
                }
            }
        }
        links.Add(key, result);
        return result;
    }

    private ISymbol? ContainingMember(
        SemanticModel model,
        InvocationExpressionSyntax invocation,
        CancellationToken token
    )
    {
        var caller = model.GetEnclosingSymbol(invocation.SpanStart, token);
        while (caller is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } && !IsHandler(caller))
        {
            caller = caller.ContainingSymbol;
        }
        return caller is IMethodSymbol { AssociatedSymbol: IPropertySymbol property } ? property : caller;
    }

    private async Task<HashSet<InvocationExpressionSyntax>> ReferencingInvocations(
        ISymbol symbol,
        CancellationToken token
    ) =>
        await ReferencingInvocations(await SymbolFinder.FindReferencesAsync(symbol, solution, documents, token), token);

    private static async Task<HashSet<InvocationExpressionSyntax>> ReferencingInvocations(
        IEnumerable<ReferencedSymbol> references,
        CancellationToken token
    )
    {
        var result = new HashSet<InvocationExpressionSyntax>();
        foreach (var reference in references)
        {
            foreach (var location in reference.Locations)
            {
                token.ThrowIfCancellationRequested();
                var root = await location.Document.GetSyntaxRootAsync(token);
                result.UnionWith(
                    root!.FindNode(location.Location.SourceSpan).AncestorsAndSelf().OfType<InvocationExpressionSyntax>()
                );
            }
        }
        return result;
    }

    private static bool SameMessageType(ITypeSymbol left, ITypeSymbol right) =>
        SymbolEqualityComparer.Default.Equals(left, right)
        // A referenced project's type can be represented by a metadata symbol.
        || left.ContainingAssembly.Identity.Equals(right.ContainingAssembly.Identity)
            && DocumentationCommentId.CreateReferenceId(left) is { } id
            && id == DocumentationCommentId.CreateReferenceId(right);

    private static bool SameMember(ISymbol? left, ISymbol right) =>
        SymbolEqualityComparer.Default.Equals(left?.OriginalDefinition, right.OriginalDefinition)
        // Retargeted symbols from another project still represent the same source declaration.
        || left is not null
            && left.ContainingAssembly.Identity.Equals(right.ContainingAssembly.Identity)
            && left.OriginalDefinition.GetDocumentationCommentId() is { } id
            && id == right.OriginalDefinition.GetDocumentationCommentId();

    private static IOperation? Unwrap(IOperation? operation) =>
        operation switch
        {
            IConversionOperation { IsImplicit: true } conversion => Unwrap(conversion.Operand),
            IDelegateCreationOperation creation => Unwrap(creation.Target),
            _ => operation,
        };

    private static bool Matches(IMethodSymbol method, MethodSelector selector)
    {
        for (var member = method; member is not null; member = member.OverriddenMethod)
        {
            if (MatchesDefinition(member, selector))
            {
                return true;
            }
        }
        foreach (
            var contract in method.ContainingType.AllInterfaces.Where(contract =>
                MetadataName(contract) == selector.Type
            )
        )
        {
            foreach (
                var member in contract
                    .GetMembers(selector.Name)
                    .OfType<IMethodSymbol>()
                    .Where(member => MatchesDefinition(member, selector))
            )
            {
                if (
                    SymbolEqualityComparer.Default.Equals(
                        method.ContainingType.FindImplementationForInterfaceMember(member)?.OriginalDefinition,
                        method.OriginalDefinition
                    )
                )
                {
                    return true;
                }
            }
        }
        return false;
    }

    private static bool MatchesDefinition(IMethodSymbol method, MethodSelector selector) =>
        method.Name == selector.Name
        && MetadataName(method.ContainingType) == selector.Type
        && (selector.GenericArity is null || method.Arity == selector.GenericArity)
        && (selector.ParameterCount is null || method.Parameters.Length == selector.ParameterCount);

    private static string MetadataName(INamedTypeSymbol type) =>
        type.ContainingType is { } parent ? $"{MetadataName(parent)}+{type.MetadataName}"
        : type.ContainingNamespace.IsGlobalNamespace ? type.MetadataName
        : $"{type.ContainingNamespace}.{type.MetadataName}";

    private IMethodSymbol[] Validate(MethodSelector selector, int argument, int? typeArgument = null)
    {
        var key = (selector, argument, typeArgument);
        if (methods.TryGetValue(key, out var found))
        {
            return found;
        }
        found =
        [
            .. compilations
                .Select(compilation => compilation.GetTypeByMetadataName(selector.Type))
                .OfType<INamedTypeSymbol>()
                .SelectMany(type => type.GetMembers(selector.Name))
                .OfType<IMethodSymbol>()
                .Where(method => MatchesDefinition(method, selector))
                .GroupBy(method => (method.ContainingAssembly.Identity, method.GetDocumentationCommentId()))
                .Select(group =>
                    group.FirstOrDefault(method => method.DeclaringSyntaxReferences is not []) ?? group.First()
                ),
        ];
        if (
            found is []
            || found.Any(method =>
                argument < 0
                || argument >= method.Parameters.Length
                || typeArgument is { } index && (index < 0 || index >= method.Arity)
                || typeArgument is not null && method.Parameters[argument].Type.TypeKind != TypeKind.Delegate
            )
        )
        {
            throw new OptionsValidationException(
                nameof(MessageOptions),
                typeof(MessageOptions),
                [
                    $"Message method '{selector.Type}.{selector.Name}' was not found or its configured argument indices are invalid.",
                ]
            );
        }
        methods.Add(key, found);
        return found;
    }
}