You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@lucenenet.apache.org by "Copilot (via GitHub)" <gi...@apache.org> on 2026/07/03 20:44:21 UTC

Re: [PR] Add TestApiConsistency analyzers for #1359 [lucenenet-codeanalysis-dev]

Copilot commented on code in PR #44:
URL: https://github.com/apache/lucenenet-codeanalysis-dev/pull/44#discussion_r3521789721


##########
src/Lucene.Net.CodeAnalysis.Dev/Utility/FieldNameHelper.cs:
##########
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;

Review Comment:
   FieldNameHelper uses Enumerable.Any() but doesn't import System.Linq, which will fail to compile in this repo (no implicit/global usings in the netstandard2.0 analyzer project).



##########
src/Lucene.Net.CodeAnalysis.Dev/LuceneDev1xxx/LuceneDev1012_MethodReturnsWritableArrayAnalyzer.cs:
##########
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using Lucene.Net.CodeAnalysis.Dev.Utility;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.CSharp.Syntax;
+using Microsoft.CodeAnalysis.Diagnostics;
+
+namespace Lucene.Net.CodeAnalysis.Dev.LuceneDev1xxx
+{
+    /// <summary>
+    /// Ports TestApiConsistency.TestForMethodsThatReturnWritableArray. The original test inspected
+    /// the compiled IL to detect a method body that simply returns a field (so the consumer can
+    /// mutate the array). Because a source analyzer has no IL, this analyzer inspects the method
+    /// body syntax and reports when an array-returning method returns a field reference directly,
+    /// without cloning it (e.g. <c>return m_values;</c>). Methods decorated with [WritableArray]
+    /// are excluded, matching the original test.
+    /// </summary>
+    [DiagnosticAnalyzer(LanguageNames.CSharp)]
+    public sealed class LuceneDev1012_MethodReturnsWritableArrayAnalyzer : DiagnosticAnalyzer
+    {
+        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
+            ImmutableArray.Create(Descriptors.LuceneDev1012_MethodReturnsWritableArray);
+
+        public override void Initialize(AnalysisContext context)
+        {
+            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
+            context.EnableConcurrentExecution();
+            context.RegisterSyntaxNodeAction(AnalyzeMethod, SyntaxKind.MethodDeclaration);
+        }
+
+        private static void AnalyzeMethod(SyntaxNodeAnalysisContext context)
+        {
+            var methodDeclaration = (MethodDeclarationSyntax)context.Node;
+
+            // Must be declared on a class.
+            if (methodDeclaration.Parent is not ClassDeclarationSyntax)
+                return;
+
+            // Return type must be an array.
+            if (methodDeclaration.ReturnType is not ArrayTypeSyntax)
+                return;

Review Comment:
   The early syntax check `methodDeclaration.ReturnType is not ArrayTypeSyntax` skips nullable-annotated array returns (e.g. `int[]?`), even though `methodSymbol.ReturnType.TypeKind` is still Array. This will miss violations for methods returning `T[]?` directly from a field.



##########
src/Lucene.Net.CodeAnalysis.Dev/LuceneDev7xxx/LuceneDev7001_ProtectedFieldNameAnalyzer.cs:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+using System.Collections.Immutable;
+using Lucene.Net.CodeAnalysis.Dev.Utility;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Diagnostics;
+
+namespace Lucene.Net.CodeAnalysis.Dev.LuceneDev7xxx
+{
+    /// <summary>
+    /// Ports TestApiConsistency.TestProtectedFieldNames: protected (or protected internal)
+    /// instance fields of classes must use the 'm_' prefix followed by camelCase, or be an
+    /// UPPER_CASE constant. Fields in the Lucene.Net.Support namespace and the AssemblyKeys
+    /// type are excluded, mirroring the original test.
+    /// </summary>
+    [DiagnosticAnalyzer(LanguageNames.CSharp)]
+    public sealed class LuceneDev7001_ProtectedFieldNameAnalyzer : DiagnosticAnalyzer
+    {
+        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
+            ImmutableArray.Create(Descriptors.LuceneDev7001_ProtectedFieldName);
+
+        public override void Initialize(AnalysisContext context)
+        {
+            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
+            context.EnableConcurrentExecution();
+            context.RegisterSymbolAction(AnalyzeField, SymbolKind.Field);
+        }
+
+        private static void AnalyzeField(SymbolAnalysisContext context)
+        {
+            var field = (IFieldSymbol)context.Symbol;
+            var containingType = field.ContainingType;
+
+            if (containingType?.TypeKind != TypeKind.Class)
+                return;
+
+            if (ApiConventionHelper.IsGeneratedType(containingType))
+                return;
+
+            if (ApiConventionHelper.IsInSupportNamespace(containingType))
+                return;
+
+            if (containingType.Name == "AssemblyKeys")
+                return;
+
+            // Original test binds Instance fields only (static protected fields are not scanned).
+            if (field.IsStatic)
+                return;
+
+            if (field.IsImplicitlyDeclared || ApiConventionHelper.IsCompilerGeneratedName(field.Name))
+                return;
+
+            // Original test condition: field.IsFamily || field.IsFamilyOrAssembly.
+            if (field.DeclaredAccessibility is not (Accessibility.Protected or Accessibility.ProtectedOrInternal))

Review Comment:
   This rule claims to cover "protected" fields, including `private protected` (which still has the `protected` modifier). Roslyn represents `private protected` as Accessibility.ProtectedAndInternal, but it's currently excluded here, so those fields won't be checked.



##########
src/Lucene.Net.CodeAnalysis.Dev.CodeFixes/Utility/FieldRenameHelper.cs:
##########
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System.Globalization;
+
+namespace Lucene.Net.CodeAnalysis.Dev.CodeFixes.Utility;
+
+/// <summary>
+/// Helpers that compute conventional names used by the naming code fixes.
+/// </summary>
+internal static class FieldRenameHelper
+{
+    /// <summary>
+    /// Computes the conventional protected field name ('m_' prefix followed by camelCase) for the
+    /// given field name, or <c>null</c> when a sensible suggestion cannot be produced (e.g. the name
+    /// is an UPPER_CASE constant, which is already an allowed form).
+    /// </summary>
+    public static string? ToProtectedFieldName(string name)
+    {
+        if (string.IsNullOrEmpty(name))
+            return null;
+
+        // Strip any leading underscores and a leading 'm_' if already present.
+        var core = name.TrimStart('_');
+        if (core.StartsWith("m_", System.StringComparison.Ordinal))
+            core = core.Substring(2);
+
+        core = core.TrimStart('_');
+        if (core.Length == 0)
+            return null;
+
+        // camelCase the first letter.
+        var camel = char.ToLower(core[0], CultureInfo.InvariantCulture) + core.Substring(1);
+        return "m_" + camel;
+    }
+
+    /// <summary>
+    /// Computes the conventional interface name (capital 'I' prefix followed by PascalCase) for the
+    /// given interface name, or <c>null</c> when a sensible suggestion cannot be produced.
+    /// </summary>
+    public static string? ToInterfaceName(string name)
+    {
+        if (string.IsNullOrEmpty(name))
+            return null;
+
+        // Drop leading underscores, then PascalCase the first letter.
+        var core = name.TrimStart('_');
+        if (core.Length == 0)
+            return null;
+
+        var pascal = char.ToUpper(core[0], CultureInfo.InvariantCulture) + core.Substring(1);
+
+        // If it already starts with 'I' followed by an uppercase letter it is already valid.
+        if (pascal.Length >= 2 && pascal[0] == 'I' && char.IsUpper(pascal[1]))
+            return null;
+
+        return "I" + pascal;

Review Comment:
   ToInterfaceName() uppercases the first letter and then treats the result as if it were the original name when deciding whether the interface is already valid. For names like `iFoo`, this returns null (no code fix offered) even though the analyzer will correctly report a diagnostic.



##########
src/Lucene.Net.CodeAnalysis.Dev/LuceneDev1xxx/LuceneDev1013_NullableEnumAnalyzer.cs:
##########
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+using System.Collections.Immutable;
+using Lucene.Net.CodeAnalysis.Dev.Utility;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Diagnostics;
+
+namespace Lucene.Net.CodeAnalysis.Dev.LuceneDev1xxx
+{
+    /// <summary>
+    /// Ports TestApiConsistency.TestForPublicMembersWithNullableEnum: reports non-private methods
+    /// (return value and parameters), non-private constructors (parameters), non-private properties,
+    /// and protected fields whose type is a nullable enum (<c>Nullable&lt;TEnum&gt;</c>). Members
+    /// decorated with [ExceptionToNullableEnumConvention] are excluded, matching the original test.
+    /// </summary>
+    [DiagnosticAnalyzer(LanguageNames.CSharp)]
+    public sealed class LuceneDev1013_NullableEnumAnalyzer : DiagnosticAnalyzer
+    {
+        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
+            ImmutableArray.Create(Descriptors.LuceneDev1013_NullableEnum);
+
+        public override void Initialize(AnalysisContext context)
+        {
+            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
+            context.EnableConcurrentExecution();
+            context.RegisterSymbolAction(AnalyzeMethod, SymbolKind.Method);
+            context.RegisterSymbolAction(AnalyzeProperty, SymbolKind.Property);
+            context.RegisterSymbolAction(AnalyzeField, SymbolKind.Field);
+        }
+
+        private static bool IsNullableEnum(ITypeSymbol type)
+        {
+            if (type is INamedTypeSymbol named
+                && named.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T
+                && named.TypeArguments.Length == 1)
+            {
+                return named.TypeArguments[0].TypeKind == TypeKind.Enum;
+            }
+
+            return false;
+        }
+
+        private static bool MemberPreconditions(ISymbol member)
+        {
+            var containingType = member.ContainingType;
+            if (containingType is null || ApiConventionHelper.IsGeneratedType(containingType))
+                return false;
+
+            if (member.IsImplicitlyDeclared || ApiConventionHelper.IsCompilerGeneratedName(member.Name))
+                return false;
+
+            return !ApiConventionHelper.HasAttribute(member, ApiConventionHelper.ExceptionToNullableEnumConventionAttribute);
+        }
+
+        private void AnalyzeMethod(SymbolAnalysisContext context)
+        {
+            var method = (IMethodSymbol)context.Symbol;
+
+            // Original test handles ordinary methods (excluding accessors) and constructors.
+            if (method.MethodKind is not (MethodKind.Ordinary or MethodKind.Constructor))
+                return;
+
+            if (!MemberPreconditions(method))
+                return;
+
+            // Original test only considers non-private methods/constructors.
+            if (method.DeclaredAccessibility == Accessibility.Private)
+                return;
+
+            // Return value (ordinary methods only; constructors have no return type to flag).
+            if (method.MethodKind == MethodKind.Ordinary && IsNullableEnum(method.ReturnType))
+            {
+                ReportSymbol(context, method);
+            }
+
+            foreach (var parameter in method.Parameters)
+            {
+                if (IsNullableEnum(parameter.Type))
+                {
+                    ReportParameter(context, parameter);
+                }
+            }
+        }
+
+        private void AnalyzeProperty(SymbolAnalysisContext context)
+        {
+            var property = (IPropertySymbol)context.Symbol;
+            if (!MemberPreconditions(property))
+                return;
+
+            // Original IsNonPrivateProperty: requires a public getter or setter.
+            if (!ApiConventionHelper.HasPublicAccessor(property))
+                return;
+
+            if (IsNullableEnum(property.Type))
+            {
+                ReportSymbol(context, property);
+            }
+        }
+
+        private void AnalyzeField(SymbolAnalysisContext context)
+        {
+            var field = (IFieldSymbol)context.Symbol;
+            if (!MemberPreconditions(field))
+                return;
+
+            // Original test flags protected (or protected internal) fields.
+            if (field.DeclaredAccessibility is not (Accessibility.Protected or Accessibility.ProtectedOrInternal))
+                return;

Review Comment:
   `private protected` fields are represented as `Accessibility.ProtectedAndInternal` in Roslyn. The original rule targets protected fields, but this filter currently excludes `private protected`, so nullable-enum fields declared that way won't be reported.



##########
src/Lucene.Net.CodeAnalysis.Dev/LuceneDev7xxx/LuceneDev7005_MemberContainsComparerAnalyzer.cs:
##########
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+using System.Collections.Immutable;
+using Lucene.Net.CodeAnalysis.Dev.Utility;
+using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.Diagnostics;
+
+namespace Lucene.Net.CodeAnalysis.Dev.LuceneDev7xxx
+{
+    /// <summary>
+    /// Ports TestApiConsistency.TestForPublicMembersContainingComparer: reports protected fields,
+    /// externally visible types, and members (ordinary methods, properties and events) whose name
+    /// contains the Java term "Comparator". In .NET these should use "Comparer".
+    /// </summary>
+    [DiagnosticAnalyzer(LanguageNames.CSharp)]
+    public sealed class LuceneDev7005_MemberContainsComparerAnalyzer : DiagnosticAnalyzer
+    {
+        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
+            ImmutableArray.Create(Descriptors.LuceneDev7005_MemberContainsComparer);
+
+        public override void Initialize(AnalysisContext context)
+        {
+            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
+            context.EnableConcurrentExecution();
+            context.RegisterSymbolAction(AnalyzeType, SymbolKind.NamedType);
+            context.RegisterSymbolAction(AnalyzeField, SymbolKind.Field);
+            context.RegisterSymbolAction(AnalyzeMethod, SymbolKind.Method);
+            context.RegisterSymbolAction(AnalyzeProperty, SymbolKind.Property);
+            context.RegisterSymbolAction(AnalyzeEvent, SymbolKind.Event);
+        }
+
+        private static bool Matches(string name) => NamingHelper.ContainsComparer.IsMatch(name);
+
+        private void AnalyzeType(SymbolAnalysisContext context)
+        {
+            var type = (INamedTypeSymbol)context.Symbol;
+
+            if (ApiConventionHelper.IsGeneratedType(type))
+                return;
+
+            // Original test: only externally visible types are flagged (t.IsVisible).
+            if (Matches(type.MetadataName) && IsVisible(type))
+                Report(context, type);
+        }
+
+        private void AnalyzeField(SymbolAnalysisContext context)
+        {
+            var field = (IFieldSymbol)context.Symbol;
+            var containingType = field.ContainingType;
+
+            if (containingType?.TypeKind != TypeKind.Class || ApiConventionHelper.IsGeneratedType(containingType))
+                return;
+
+            if (field.IsStatic || field.IsImplicitlyDeclared || ApiConventionHelper.IsCompilerGeneratedName(field.Name))
+                return;
+
+            // Original test scans protected (or protected internal) instance fields.
+            if (field.DeclaredAccessibility is not (Accessibility.Protected or Accessibility.ProtectedOrInternal))
+                return;

Review Comment:
   `private protected` fields (`Accessibility.ProtectedAndInternal`) are still syntactically "protected" and are included by the original intent, but they're currently skipped by this accessibility filter.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscribe@lucenenet.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org