< Summary

Information
Class: Lattice.Analyzers.InlineHintAnalyzer
Assembly: Lattice.Analyzers
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/Tools/Lattice.Analyzers/InlineHintAnalyzer.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 131
Coverable lines: 131
Total lines: 275
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 60
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
get_SupportedDiagnostics()100%210%
Initialize(...)100%210%
AnalyzeMethod(...)0%342180%
AnalyzeProperty(...)0%210140%
AnalyzeOperator(...)0%2040%
HasAggressiveInlining(...)100%210%
HasAggressiveInlining(...)0%2040%
HasAggressiveInlining(...)100%210%
IsAggressiveInliningAttribute(...)0%2040%
IsFPOrVectorType(...)0%4260%
GetStatementCount(...)0%110100%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/Tools/Lattice.Analyzers/InlineHintAnalyzer.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4using System.Collections.Immutable;
 5using System.Linq;
 6using Microsoft.CodeAnalysis;
 7using Microsoft.CodeAnalysis.CSharp;
 8using Microsoft.CodeAnalysis.CSharp.Syntax;
 9using Microsoft.CodeAnalysis.Diagnostics;
 10
 11namespace Lattice.Analyzers
 12{
 13    /// <summary>
 14    /// 检测热路径方法是否缺少 AggressiveInlining 的 Analyzer
 15    /// </summary>
 16    [DiagnosticAnalyzer(LanguageNames.CSharp)]
 17    public class InlineHintAnalyzer : DiagnosticAnalyzer
 18    {
 19        // P0: 必须内联(简单属性、运算符)
 20        public const string RequiredId = "LATTICE001";
 021        private static readonly DiagnosticDescriptor RequiredRule = new(
 022            RequiredId,
 023            "热路径方法必须添加 AggressiveInlining",
 024            "方法 '{0}' 是简单的 FP 操作,必须添加 [MethodImpl(MethodImplOptions.AggressiveInlining)] 以确保性能",
 025            "Performance",
 026            DiagnosticSeverity.Error,
 027            isEnabledByDefault: true,
 028            description: "简单的 FP/FPVector 属性访问器和运算符应该使用 AggressiveInlining 来避免方法调用开销。",
 029            helpLinkUri: "https://docs.lattice.dev/analyzers/LATTICE001");
 30
 31        // P1: 建议内联(小型数学方法)
 32        public const string RecommendedId = "LATTICE002";
 033        private static readonly DiagnosticDescriptor RecommendedRule = new(
 034            RecommendedId,
 035            "建议添加 AggressiveInlining",
 036            "方法 '{0}' 可能是热路径,建议添加 [MethodImpl(MethodImplOptions.AggressiveInlining)]",
 037            "Performance",
 038            DiagnosticSeverity.Warning,
 039            isEnabledByDefault: true,
 040            description: "小型数学方法(≤3 行)建议内联以减少调用开销。",
 041            helpLinkUri: "https://docs.lattice.dev/analyzers/LATTICE002");
 42
 43        // P2: 考虑内联
 44        public const string ConsiderId = "LATTICE003";
 045        private static readonly DiagnosticDescriptor ConsiderRule = new(
 046            ConsiderId,
 047            "考虑添加 AggressiveInlining",
 048            "方法 '{0}' 返回 FP/FPVector,考虑添加 [MethodImpl(MethodImplOptions.AggressiveInlining)]",
 049            "Performance",
 050            DiagnosticSeverity.Info,
 051            isEnabledByDefault: true,
 052            description: "如果此方法是热路径,考虑添加 AggressiveInlining。",
 053            helpLinkUri: "https://docs.lattice.dev/analyzers/LATTICE003");
 54
 55        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
 056            ImmutableArray.Create(RequiredRule, RecommendedRule, ConsiderRule);
 57
 58        public override void Initialize(AnalysisContext context)
 59        {
 060            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
 061            context.EnableConcurrentExecution();
 062            context.RegisterSyntaxNodeAction(AnalyzeMethod, SyntaxKind.MethodDeclaration);
 063            context.RegisterSyntaxNodeAction(AnalyzeProperty, SyntaxKind.PropertyDeclaration);
 064            context.RegisterSyntaxNodeAction(AnalyzeOperator, SyntaxKind.OperatorDeclaration);
 065        }
 66
 67        private void AnalyzeMethod(SyntaxNodeAnalysisContext context)
 68        {
 069            var method = (MethodDeclarationSyntax)context.Node;
 70
 71            // 跳过已有 AggressiveInlining 的方法
 072            if (HasAggressiveInlining(method))
 73            {
 074                return;
 75            }
 76
 77            // 检查返回类型
 078            var returnType = method.ReturnType.ToString();
 079            bool returnsFP = IsFPOrVectorType(returnType);
 080            bool returnsBoolOrInt = returnType == "bool" || returnType == "int" || returnType == "long";
 81
 82            // 计算方法体大小
 083            int statementCount = GetStatementCount(method);
 084            bool isSimple = statementCount <= 1;
 085            bool isSmall = statementCount <= 3;
 86
 87            // 运算符由 OperatorDeclarationSyntax 单独处理
 88
 89            // P0: 简单方法(如 FP.Abs, FP.Min)必须内联
 090            if (returnsFP && isSimple && method.ParameterList.Parameters.Count <= 2)
 91            {
 092                context.ReportDiagnostic(Diagnostic.Create(
 093                    RequiredRule,
 094                    method.Identifier.GetLocation(),
 095                    method.Identifier.Text));
 096                return;
 97            }
 98
 99            // P1: 小型数学方法建议内联
 0100            if (returnsFP && isSmall)
 101            {
 0102                context.ReportDiagnostic(Diagnostic.Create(
 0103                    RecommendedRule,
 0104                    method.Identifier.GetLocation(),
 0105                    method.Identifier.Text));
 0106                return;
 107            }
 108
 109            // P1: 比较方法建议内联
 0110            if (returnsBoolOrInt && isSimple && method.Identifier.Text.Contains("Compare"))
 111            {
 0112                context.ReportDiagnostic(Diagnostic.Create(
 0113                    RecommendedRule,
 0114                    method.Identifier.GetLocation(),
 0115                    method.Identifier.Text));
 0116                return;
 117            }
 118
 119            // P2: 其他返回 FP 的方法考虑内联
 0120            if (returnsFP)
 121            {
 0122                context.ReportDiagnostic(Diagnostic.Create(
 0123                    ConsiderRule,
 0124                    method.Identifier.GetLocation(),
 0125                    method.Identifier.Text));
 126            }
 0127        }
 128
 129        private void AnalyzeProperty(SyntaxNodeAnalysisContext context)
 130        {
 0131            var property = (PropertyDeclarationSyntax)context.Node;
 132
 133            // 跳过已有 AggressiveInlining 的属性
 0134            if (HasAggressiveInlining(property))
 135            {
 0136                return;
 137            }
 138
 139            // 检查返回类型
 0140            var returnType = property.Type.ToString();
 0141            if (!IsFPOrVectorType(returnType))
 142            {
 0143                return;
 144            }
 145
 146            // 检查是否是简单的 getter-only 属性
 0147            if (property.AccessorList == null)
 148            {
 0149                return;
 150            }
 151
 0152            var getter = property.AccessorList.Accessors
 0153                .FirstOrDefault(a => a.Keyword.IsKind(SyntaxKind.GetKeyword));
 154
 0155            if (getter == null)
 156            {
 0157                return;
 158            }
 159
 160            // 简单的表达式体或单行 getter
 0161            bool isSimple = getter.ExpressionBody != null ||
 0162                            (getter.Body?.Statements.Count ?? 0) <= 1;
 163
 0164            if (isSimple)
 165            {
 0166                context.ReportDiagnostic(Diagnostic.Create(
 0167                    RequiredRule,
 0168                    property.Identifier.GetLocation(),
 0169                    property.Identifier.Text));
 170            }
 0171        }
 172
 173        private void AnalyzeOperator(SyntaxNodeAnalysisContext context)
 174        {
 0175            var op = (OperatorDeclarationSyntax)context.Node;
 176
 177            // 跳过已有 AggressiveInlining 的运算符
 0178            if (HasAggressiveInlining(op))
 179            {
 0180                return;
 181            }
 182
 183            // 检查返回类型
 0184            var returnType = op.ReturnType.ToString();
 0185            if (!IsFPOrVectorType(returnType))
 186            {
 0187                return;
 188            }
 189
 190            // 所有 FP/FPVector 运算符必须内联
 0191            context.ReportDiagnostic(Diagnostic.Create(
 0192                RequiredRule,
 0193                op.OperatorToken.GetLocation(),
 0194                "operator " + op.OperatorToken.Text));
 0195        }
 196
 197        private static bool HasAggressiveInlining(MethodDeclarationSyntax method)
 198        {
 0199            return method.AttributeLists
 0200                .SelectMany(a => a.Attributes)
 0201                .Any(IsAggressiveInliningAttribute);
 202        }
 203
 204        private static bool HasAggressiveInlining(PropertyDeclarationSyntax property)
 205        {
 0206            if (property.AttributeLists
 0207                .SelectMany(a => a.Attributes)
 0208                .Any(IsAggressiveInliningAttribute))
 209            {
 0210                return true;
 211            }
 212
 0213            if (property.AccessorList == null)
 214            {
 0215                return false;
 216            }
 217
 0218            return property.AccessorList.Accessors
 0219                .SelectMany(accessor => accessor.AttributeLists)
 0220                .SelectMany(attributeList => attributeList.Attributes)
 0221                .Any(IsAggressiveInliningAttribute);
 222        }
 223
 224        private static bool HasAggressiveInlining(OperatorDeclarationSyntax op)
 225        {
 0226            return op.AttributeLists
 0227                .SelectMany(a => a.Attributes)
 0228                .Any(IsAggressiveInliningAttribute);
 229        }
 230
 231        private static bool IsAggressiveInliningAttribute(AttributeSyntax attribute)
 232        {
 0233            var name = attribute.Name.ToString();
 0234            return name.Contains("MethodImpl") &&
 0235                   attribute.ArgumentList?.ToString().Contains("AggressiveInlining") == true;
 236        }
 237
 238        private static bool IsFPOrVectorType(string typeName)
 239        {
 0240            return typeName == "FP" ||
 0241                   typeName == "FPVector2" ||
 0242                   typeName == "FPVector3" ||
 0243                   typeName.Contains("FP");
 244        }
 245
 246        private static int GetStatementCount(MethodDeclarationSyntax method)
 247        {
 248            // 表达式体
 0249            if (method.ExpressionBody != null)
 250            {
 0251                return 1;
 252            }
 253
 254            // 语句体
 0255            if (method.Body == null)
 256            {
 0257                return 0;
 258            }
 259
 0260            int count = method.Body.Statements.Count;
 261
 262            // 忽略 #if DEBUG 块
 0263            foreach (var stmt in method.Body.Statements)
 264            {
 0265                if (stmt is IfStatementSyntax ifStmt &&
 0266                    ifStmt.Condition.ToString().Contains("DEBUG"))
 267                {
 0268                    count--;
 269                }
 270            }
 271
 0272            return count;
 273        }
 274    }
 275}