Skip to content

Add support for primary constructors when checking for contextual loggers #130

@IDDesigns

Description

@IDDesigns

The constructor analyzer does not work with primary constructors, looking at the code I wonder if it is as simple as adding this:

using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Util;

using ReSharper.Structured.Logging.Extensions;
using ReSharper.Structured.Logging.Highlighting;

namespace ReSharper.Structured.Logging.Analyzer
{
    [ElementProblemAnalyzer(typeof(IPrimaryConstructorDeclaration))]
    public class ContextualLoggerPrimaryConstructorAnalyzer : ElementProblemAnalyzer<IPrimaryConstructorDeclaration>
    {
        // ReSharper disable once CognitiveComplexity
        protected override void Run(IPrimaryConstructorDeclaration element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            if (element.Params?.ParameterDeclarations == null)
            {
                return;
            }

            foreach (var declaration in element.Params.ParameterDeclarations)
            {
                if (!(declaration.Type is IDeclaredType declaredType))
                {
                    continue;
                }

                if (!declaredType.IsGenericMicrosoftExtensionsLogger())
                {
                    continue;
                }

                var argumentType = declaredType.GetFirstGenericArgumentType();
                if (argumentType == null)
                {
                    continue;
                }

                var containingType = element.DeclaredElement?.GetContainingType();
                var className = containingType?.GetClrName().FullName;
                if (className == null)
                {
                    continue;
                }

                if (className.Equals(argumentType.GetClassType()?.GetClrName().FullName))
                {
                    continue;
                }

                consumer.AddHighlighting(new ContextualLoggerWarning(declaration.TypeUsage.GetDocumentRange()));
            }
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions