-
Notifications
You must be signed in to change notification settings - Fork 6
Implement LuceneDev1007, 1008, 6000 Analyzers & CodeFix with Unit Tests #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
145 changes: 145 additions & 0 deletions
145
...alysis.Dev.CodeFixes/LuceneDev1xxx/LuceneDev1007_1008_DictionaryIndexerCodeFixProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| /* | ||
| * 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 System.Composition; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Lucene.Net.CodeAnalysis.Dev.Utility; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Formatting; | ||
|
|
||
| namespace Lucene.Net.CodeAnalysis.Dev.CodeFixes.LuceneDev1xxx | ||
| { | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(LuceneDev1007_1008_DictionaryIndexerCodeFixProvider)), Shared] | ||
| public sealed class LuceneDev1007_1008_DictionaryIndexerCodeFixProvider : CodeFixProvider | ||
| { | ||
| private const string TitleReturn = "Use TryGetValue and return default on missing key"; | ||
|
|
||
| public override ImmutableArray<string> FixableDiagnosticIds => | ||
| ImmutableArray.Create( | ||
| Descriptors.LuceneDev1007_GenericDictionaryIndexerValueType.Id, | ||
| Descriptors.LuceneDev1008_GenericDictionaryIndexerReferenceType.Id); | ||
|
|
||
| public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| if (root == null) return; | ||
|
|
||
| foreach (var diagnostic in context.Diagnostics) | ||
| { | ||
| var elementAccess = root.FindToken(diagnostic.Location.SourceSpan.Start) | ||
| .Parent? | ||
| .AncestorsAndSelf() | ||
| .OfType<ElementAccessExpressionSyntax>() | ||
| .FirstOrDefault(e => e.Span.Contains(diagnostic.Location.SourceSpan)); | ||
| if (elementAccess == null) | ||
| continue; | ||
|
|
||
| // Only handle the "return dict[key];" pattern automatically. | ||
| if (elementAccess.Parent is not ReturnStatementSyntax returnStmt | ||
| || returnStmt.Expression != elementAccess) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: TitleReturn, | ||
| createChangedDocument: c => ConvertReturnAsync(context.Document, returnStmt, elementAccess, c), | ||
| equivalenceKey: TitleReturn), | ||
| diagnostic); | ||
| } | ||
| } | ||
|
|
||
| private static async Task<Document> ConvertReturnAsync( | ||
| Document document, | ||
| ReturnStatementSyntax returnStmt, | ||
| ElementAccessExpressionSyntax elementAccess, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
| if (root == null) return document; | ||
|
|
||
| var receiver = elementAccess.Expression; | ||
| var keyArg = elementAccess.ArgumentList.Arguments.FirstOrDefault(); | ||
| if (keyArg == null) return document; | ||
|
|
||
| var outName = PickLocalName(returnStmt); | ||
|
|
||
| // receiver.TryGetValue(key, out var <outName>) | ||
| var tryGetValueInvocation = SyntaxFactory.InvocationExpression( | ||
| SyntaxFactory.MemberAccessExpression( | ||
| SyntaxKind.SimpleMemberAccessExpression, | ||
| receiver.WithoutTrivia(), | ||
| SyntaxFactory.IdentifierName("TryGetValue")), | ||
| SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[] | ||
| { | ||
| keyArg.WithoutTrivia(), | ||
| SyntaxFactory.Argument( | ||
| SyntaxFactory.DeclarationExpression( | ||
| SyntaxFactory.IdentifierName( | ||
| SyntaxFactory.Identifier("var")), | ||
| SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier(outName)))) | ||
| .WithRefOrOutKeyword(SyntaxFactory.Token(SyntaxKind.OutKeyword)) | ||
| }))); | ||
|
|
||
| // tryGetValueInvocation ? <outName> : default | ||
| var ternary = SyntaxFactory.ConditionalExpression( | ||
| tryGetValueInvocation, | ||
| SyntaxFactory.IdentifierName(outName), | ||
| SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression, | ||
| SyntaxFactory.Token(SyntaxKind.DefaultKeyword))); | ||
|
|
||
| var newReturn = returnStmt.WithExpression(ternary).WithAdditionalAnnotations(Formatter.Annotation); | ||
|
|
||
| var newRoot = root.ReplaceNode(returnStmt, newReturn); | ||
| return document.WithSyntaxRoot(newRoot); | ||
| } | ||
|
|
||
| private static string PickLocalName(SyntaxNode context) | ||
| { | ||
| // Avoid collisions with identifiers in the enclosing member. | ||
| var member = context.AncestorsAndSelf().OfType<MemberDeclarationSyntax>().FirstOrDefault(); | ||
| var names = member == null | ||
| ? ImmutableHashSet<string>.Empty | ||
| : member.DescendantTokens() | ||
| .Where(t => t.IsKind(SyntaxKind.IdentifierToken)) | ||
| .Select(t => t.ValueText) | ||
| .ToImmutableHashSet(); | ||
|
|
||
| if (!names.Contains("value")) | ||
| return "value"; | ||
| for (int i = 1; i < 100; i++) | ||
| { | ||
| var candidate = "value" + i; | ||
| if (!names.Contains(candidate)) | ||
| return candidate; | ||
| } | ||
| return "value"; | ||
|
paulirwin marked this conversation as resolved.
|
||
| } | ||
| } | ||
| } | ||
55 changes: 55 additions & 0 deletions
55
...e.Net.CodeAnalysis.Dev.Sample/LuceneDev1xxx/LuceneDev1007_1008_DictionaryIndexerSample.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| /* | ||
| * 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; | ||
|
|
||
| namespace Lucene.Net.CodeAnalysis.Dev.Sample.LuceneDev1xxx; | ||
|
|
||
| public class LuceneDev1007_1008_DictionaryIndexerSample | ||
| { | ||
| public int GetIntValue(IDictionary<string, int> dict, string key) | ||
| { | ||
| // LuceneDev1007 (value-type value): indexer may throw KeyNotFoundException. | ||
| return dict[key]; | ||
| } | ||
|
|
||
| public string GetStringValue(IDictionary<string, string> dict, string key) | ||
| { | ||
| // LuceneDev1008 (reference-type value): indexer may throw KeyNotFoundException. | ||
| return dict[key]; | ||
| } | ||
|
|
||
| public void ReadOnlyUsage(IReadOnlyDictionary<string, string> dict, string key) | ||
| { | ||
| // LuceneDev1008: also applies to IReadOnlyDictionary<TKey, TValue>. | ||
| var value = dict[key]; | ||
| } | ||
|
|
||
| public void ConcreteDictionaryUsage(Dictionary<string, string> dict, string key) | ||
| { | ||
| // LuceneDev1008: Dictionary<TKey, TValue> implements IDictionary<TKey, TValue>. | ||
| var value = dict[key]; | ||
| } | ||
|
|
||
| public void AssignmentIsFine(Dictionary<string, int> dict, string key) | ||
| { | ||
| // No diagnostic: indexer setter does not throw. | ||
| dict[key] = 42; | ||
| } | ||
| } |
37 changes: 37 additions & 0 deletions
37
....CodeAnalysis.Dev.Sample/LuceneDev6xxx/LuceneDev6000_NonGenericDictionaryIndexerSample.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| /* | ||
| * 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; | ||
|
|
||
| namespace Lucene.Net.CodeAnalysis.Dev.Sample.LuceneDev6xxx; | ||
|
|
||
| public class LuceneDev6000_NonGenericDictionaryIndexerSample | ||
| { | ||
| public object? GetValue(IDictionary dict, object key) | ||
| { | ||
| // LuceneDev6000 (Info): non-generic IDictionary indexer may return null for missing keys. | ||
| return dict[key]; | ||
| } | ||
|
|
||
| public object? GetValueFromHashtable(Hashtable table, object key) | ||
| { | ||
| // LuceneDev6000: Hashtable implements non-generic IDictionary. | ||
| return table[key]; | ||
| } | ||
| } |
99 changes: 99 additions & 0 deletions
99
...Lucene.Net.CodeAnalysis.Dev/LuceneDev1xxx/LuceneDev1007_1008_DictionaryIndexerAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| /* | ||
| * 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.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
|
|
||
| namespace Lucene.Net.CodeAnalysis.Dev.LuceneDev1xxx | ||
| { | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class LuceneDev1007_1008_DictionaryIndexerAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => | ||
| ImmutableArray.Create( | ||
| Descriptors.LuceneDev1007_GenericDictionaryIndexerValueType, | ||
| Descriptors.LuceneDev1008_GenericDictionaryIndexerReferenceType); | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); | ||
| context.EnableConcurrentExecution(); | ||
| context.RegisterSyntaxNodeAction(AnalyzeElementAccess, SyntaxKind.ElementAccessExpression); | ||
| } | ||
|
|
||
| private static void AnalyzeElementAccess(SyntaxNodeAnalysisContext ctx) | ||
| { | ||
| var elementAccess = (ElementAccessExpressionSyntax)ctx.Node; | ||
|
|
||
| // Skip assignment targets (setter usage does not throw). | ||
| if (IsAssignmentTarget(elementAccess)) | ||
| return; | ||
|
|
||
| var symbolInfo = ctx.SemanticModel.GetSymbolInfo(elementAccess, ctx.CancellationToken); | ||
| var property = symbolInfo.Symbol as IPropertySymbol; | ||
| if (property == null || !property.IsIndexer) | ||
| return; | ||
|
|
||
| var containing = property.ContainingType; | ||
| if (containing == null) | ||
| return; | ||
|
|
||
| if (!DictionaryTypeHelper.IsGenericDictionaryIndexer(property, containing, out var valueType)) | ||
| return; | ||
|
|
||
| var receiverText = elementAccess.Expression.ToString(); | ||
| var keyText = elementAccess.ArgumentList.ToString(); | ||
| var display = receiverText + keyText; | ||
|
|
||
| var descriptor = IsValueTypeForDiagnostic(valueType!) | ||
| ? Descriptors.LuceneDev1007_GenericDictionaryIndexerValueType | ||
| : Descriptors.LuceneDev1008_GenericDictionaryIndexerReferenceType; | ||
|
|
||
| ctx.ReportDiagnostic(Diagnostic.Create(descriptor, elementAccess.GetLocation(), display)); | ||
| } | ||
|
|
||
| private static bool IsAssignmentTarget(ElementAccessExpressionSyntax elementAccess) | ||
| { | ||
| // dict[key] = value -> skip | ||
| if (elementAccess.Parent is AssignmentExpressionSyntax assignment | ||
| && assignment.Left == elementAccess | ||
| && assignment.IsKind(SyntaxKind.SimpleAssignmentExpression)) | ||
| { | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| private static bool IsValueTypeForDiagnostic(ITypeSymbol valueType) | ||
| { | ||
| // Unconstrained type parameters: treat as reference-like (safer — null check may apply). | ||
| if (valueType is ITypeParameterSymbol tp) | ||
| { | ||
| if (tp.HasValueTypeConstraint) | ||
| return true; | ||
| return false; | ||
| } | ||
| return valueType.IsValueType; | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.