File: Microsoft.NetCore.Analyzers\Runtime\CSharpForwardCancellationTokenToInvocations.Analyzer.cs
Web Access
Project: src\src\sdk\src\Microsoft.CodeAnalysis.NetAnalyzers\src\Microsoft.CodeAnalysis.CSharp.NetAnalyzers\Microsoft.CodeAnalysis.CSharp.NetAnalyzers.csproj (Microsoft.CodeAnalysis.CSharp.NetAnalyzers)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.CodeAnalysis;
using Microsoft.NetCore.Analyzers.Runtime;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Operations;
using System.Linq;

namespace Microsoft.NetCore.CSharp.Analyzers.Runtime
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public sealed class CSharpForwardCancellationTokenToInvocationsAnalyzer : ForwardCancellationTokenToInvocationsAnalyzer
    {
        protected override SyntaxNode? GetInvocationMethodNameNode(SyntaxNode invocationNode)
        {
            if (invocationNode is InvocationExpressionSyntax invocationExpression)
            {
                if (invocationExpression.Expression is MemberBindingExpressionSyntax memberBindingExpression)
                {
                    // When using nullability features, specifically attempting to dereference possible null references,
                    // the dot becomes part of the member invocation expression, so we need to return just the name,
                    // so that the diagnostic gets properly returned in the method name only.
                    return memberBindingExpression.Name;
                }

                return invocationExpression.Expression;
            }

            return null;
        }
        protected override bool ArgumentsImplicitOrNamed(INamedTypeSymbol cancellationTokenType, ImmutableArray<IArgumentOperation> arguments)
        {
            return arguments.Any(a =>
                (a.IsImplicit && a.Parameter != null && !a.Parameter.Type.Equals(cancellationTokenType)) ||
                (a.Syntax is ArgumentSyntax argumentNode && argumentNode.NameColon != null));
        }
    }
}