Skip to content

Addition for your project. #5

@IceReaper

Description

@IceReaper

Im basicaly coding using a "enable everything"-setup. Using the stock and stylecop analyzers. One thing which happens often, ist that CA2000 informs you that godot objects implement IDisposable and should be disposed. However this will cause errors as objects inheriting from GodotObject are engine managed. I wrote a small analyzer to fix this just for GodotObject classes. Thought you might find this useful. Take if you want :)

using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

/// <summary>Suppressor for CA2000 diagnostics related to Godot.Object.</summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class GodotObjectCa2000Suppressor : DiagnosticSuppressor
{
    private static readonly SuppressionDescriptor Rule = new("GOD0001", "CA2000", "Do not dispose engine managed objects.");

    /// <inheritdoc />
    public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => [Rule];

    /// <inheritdoc />
    public override void ReportSuppressions(SuppressionAnalysisContext context)
    {
        foreach (Diagnostic? diagnostic in context.ReportedDiagnostics.Where(diagnostic => diagnostic.Id == "CA2000"))
        {
            SyntaxNode? syntax = diagnostic.Location.SourceTree?.GetRoot().FindNode(diagnostic.Location.SourceSpan);

            if (syntax == null)
            {
                continue;
            }

            SemanticModel semanticModel = context.GetSemanticModel(syntax.SyntaxTree);
            ITypeSymbol? type = semanticModel.GetTypeInfo(syntax).Type;
            INamedTypeSymbol? godotObjectType = semanticModel.Compilation.GetTypeByMetadataName("Godot.GodotObject");

            if (godotObjectType != null && InheritsFromOrEquals(type, godotObjectType))
            {
                context.ReportSuppression(Suppression.Create(Rule, diagnostic));
            }
        }
    }

    private static bool InheritsFromOrEquals(ITypeSymbol? type, ITypeSymbol baseType)
    {
        while (type != null)
        {
            if (SymbolEqualityComparer.Default.Equals(type, baseType))
            {
                return true;
            }

            type = type.BaseType;
        }

        return false;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions