背景故事(了解我的问题不是必需的,但某些情况可能会有所帮助)
在我公司,我们使用IResult<T>
类型以功能样式处理错误,而不是引发异常并希望某些客户端捕获异常。 IResult<T>
可以是带有DataResult<T>
的T
或带有ErrorResult<T>
的Error
,但不能同时包含两者。 Error
大致等效于Exception
。因此,典型的函数将返回IResult<T>
以通过返回值传递任何遇到的错误,而不是使用throw
备份堆栈。
我们在IResult<T>
上有扩展方法来组成功能链。主要的两个是Bind
和Let
。Bind
是功能语言中的标准单子(monad)bind
运算符。基本上,如果IResult
有一个值,它将投影该值,否则它将转发错误。这样实现
static IResult<T2> Bind(
this IResult<T1> @this,
Func<T1, IResult<T2>> projection)
{
return @this.HasValue
? projection(@this.Value)
: new ErrorResult<T2>(@this.Error);
}
Let
用于执行副作用,只要在功能链中较早时未遇到错误即可。它被实现为static IResult<T> Let(
this IResult<T> @this,
Action<T> action)
{
if (@this.HasValue) {
action(@this.Value);
}
return @this;
}
我的罗斯林分析仪用例
使用此
IResult<T>
API时常犯的一个错误是调用一个函数,该函数在传递给IResult<T>
的Action<T>
中返回一个Let
。发生这种情况时,如果内部函数返回Error
,则错误将丢失并且执行将继续,就像没有发生任何错误一样。这可能是一个很难跟踪的错误,并且在过去的一年中已经发生过几次。在这些情况下,应改用
Bind
,以便可以传播错误。我想确定对在作为参数传递给
IResult<T>
的lambda表达式内返回Let
的函数的任何调用,并将它们标记为编译器警告。我创建了一个分析器来执行此操作。您可以在此处查看完整的源代码:https://github.com/JamesFaix/NContext.Analyzers这是解决方案中的主要分析器文件:
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace NContext.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class BindInsteadOfLetAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "NContext_0001";
private const string _Category = "Safety";
private const string _Title = "Unsafe use of IServiceResponse<T> inside Let expression";
private const string _MessageFormat = "Unsafe use of IServiceResponse<T> inside Let expression.";
private const string _Description = "If calling any methods that return IServiceResponse<T>, use Bind instead of Let. " +
"Otherwise, any returned ErrorResponses will be lost, execution will continue as if no error occurred, and no error will be logged.";
private static DiagnosticDescriptor _Rule =
new DiagnosticDescriptor(
DiagnosticId,
_Title,
_MessageFormat,
_Category,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: _Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(_Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.InvocationExpression);
}
private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var functionChain = (InvocationExpressionSyntax) context.Node;
//When invoking an extension method, the first child node should be a MemberAccessExpression
var memberAccess = functionChain.ChildNodes().First() as MemberAccessExpressionSyntax;
if (memberAccess == null)
{
return;
}
//When invoking an extension method, the last child node of the member access should be an IdentifierName
var letIdentifier = memberAccess.ChildNodes().Last() as IdentifierNameSyntax;
if (letIdentifier == null)
{
return;
}
//Ignore method invocations that do not have "Let" in the name
if (!letIdentifier.GetText().ToString().Contains("Let"))
{
return;
}
var semanticModel = context.SemanticModel;
var unsafeNestedInvocations = functionChain.ArgumentList
//Get nested method calls
.DescendantNodes().OfType<InvocationExpressionSyntax>()
//Get any identifier names in those calls
.SelectMany(node => node.DescendantNodes().OfType<IdentifierNameSyntax>())
//Get tuples of syntax nodes and the methods they refer to
.Select(node => new
{
Node = node,
Symbol = semanticModel.GetSymbolInfo(node).Symbol as IMethodSymbol
})
//Ignore identifiers that do not refer to methods
.Where(x => x.Symbol != null
//Ignore methods that do not have "IServiceResponse" in the return type
&& x.Symbol.ReturnType.ToDisplayString().Contains("IServiceResponse"));
//Just report the first one to reduce error log clutter
var firstUnsafe = unsafeNestedInvocations.FirstOrDefault();
if (firstUnsafe != null)
{
var diagnostic = Diagnostic.Create(_Rule, firstUnsafe.Node.GetLocation(), firstUnsafe.Node.GetText().ToString());
context.ReportDiagnostic(diagnostic);
}
}
}
}
问题
对于当前打开的任何
*.cs
文件,我的分析仪都可以正常工作。警告已添加到“错误”窗口,并且绿色警告下划线显示在文本编辑器中。但是,如果我关闭包含这些警告的调用站点的文件,则错误将从“错误”窗口中删除。另外,如果我只编译我的解决方案而没有打开任何文件,则不会记录任何警告。在 Debug模式下运行分析器解决方案时,在Visual Studio的调试沙箱实例中没有打开源代码文件时,不会遇到断点。如何使分析仪检查所有文件,甚至关闭的文件?
最佳答案
我从以下问题找到了答案:How can I make my code diagnostic syntax node action work on closed files?
显然,如果您的分析器是作为Visual Studio扩展而不是作为项目级程序包安装的,则默认情况下,它仅分析打开的文件。您可以转到“工具”>“选项”>“文本编辑器”>“C#”>“高级”,然后选中“启用完整解决方案分析”以使其适用于当前解决方案中的任何文件。
多么奇怪的默认行为。 ¯\_(ツ)_/¯
关于c# - Roslyn Analyzer仅针对打开的文件运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49592058/