diff --git a/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/CSharpCommonInterest.cs b/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/CSharpCommonInterest.cs index 497469f95..bf159a90e 100644 --- a/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/CSharpCommonInterest.cs +++ b/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/CSharpCommonInterest.cs @@ -22,6 +22,7 @@ internal static class CSharpCommonInterest SyntaxKind.AnonymousMethodExpression, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression, + SyntaxKind.LocalFunctionStatement, SyntaxKind.GetAccessorDeclaration, SyntaxKind.SetAccessorDeclaration, SyntaxKind.AddAccessorDeclaration, diff --git a/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/VSTHRD010MainThreadUsageAnalyzer.cs b/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/VSTHRD010MainThreadUsageAnalyzer.cs index 26b9a5af0..80d113abe 100644 --- a/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/VSTHRD010MainThreadUsageAnalyzer.cs +++ b/src/Microsoft.VisualStudio.Threading.Analyzers.CSharp/VSTHRD010MainThreadUsageAnalyzer.cs @@ -301,7 +301,8 @@ public CallInfo(IMethodSymbol methodSymbol, SyntaxNode invocationSyntax) private class MethodAnalyzer { - private ImmutableDictionary methodDeclarationNodes = ImmutableDictionary.Empty; + private readonly object methodDeclarationNodesSyncObject = new object(); + private ImmutableDictionary> methodDeclarationNodes = ImmutableDictionary>.Empty; public MethodAnalyzer( ImmutableArray mainThreadAssertingMethods, @@ -360,7 +361,6 @@ internal void AnalyzeInvocation(SyntaxNodeAnalysisContext context) } } - this.methodDeclarationNodes = this.methodDeclarationNodes.SetItem(methodDeclaration, ThreadingContext.MainThread); return; } } @@ -476,7 +476,7 @@ private bool AnalyzeMemberWithinContext(ITypeSymbol type, ISymbol? symbol, Synta SyntaxNode? methodDeclaration = context.Node.FirstAncestorOrSelf(n => CSharpCommonInterest.MethodSyntaxKinds.Contains(n.Kind())); if (methodDeclaration is object) { - threadingContext = this.methodDeclarationNodes.GetValueOrDefault(methodDeclaration); + threadingContext = this.GetThreadingContext(methodDeclaration, context.Node.SpanStart, context.SemanticModel, context.CancellationToken); } if (threadingContext != ThreadingContext.MainThread) @@ -492,5 +492,86 @@ private bool AnalyzeMemberWithinContext(ITypeSymbol type, ISymbol? symbol, Synta return false; } + + private ThreadingContext GetThreadingContext(SyntaxNode methodDeclaration, int position, SemanticModel semanticModel, CancellationToken cancellationToken) + { + ImmutableArray transitions; + lock (this.methodDeclarationNodesSyncObject) + { + transitions = this.methodDeclarationNodes.GetValueOrDefault(methodDeclaration); + if (transitions.IsDefault) + { + transitions = this.GetThreadingContextTransitions(methodDeclaration, semanticModel, cancellationToken); + this.methodDeclarationNodes = this.methodDeclarationNodes.SetItem(methodDeclaration, transitions); + } + } + + for (int i = transitions.Length - 1; i >= 0; i--) + { + if (transitions[i].Position <= position) + { + return transitions[i].Context; + } + } + + return ThreadingContext.Unknown; + } + + private ImmutableArray GetThreadingContextTransitions(SyntaxNode methodDeclaration, SemanticModel semanticModel, CancellationToken cancellationToken) + { + ImmutableArray.Builder transitions = ImmutableArray.CreateBuilder(); + foreach (SyntaxNode node in methodDeclaration.DescendantNodes().Where(node => node.FirstAncestorOrSelf(ancestor => CSharpCommonInterest.MethodSyntaxKinds.Contains(ancestor.Kind())) == methodDeclaration)) + { + if (node is InvocationExpressionSyntax invocation + && semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol is IMethodSymbol invokedMethod + && (this.MainThreadAssertingMethods.Contains(invokedMethod) || this.MainThreadSwitchingMethods.Contains(invokedMethod))) + { + transitions.Add(new ThreadingContextTransition(invocation.Span.End, ThreadingContext.MainThread)); + } + else if (node is AwaitExpressionSyntax awaitExpression && InvalidatesMainThreadContext(awaitExpression.Expression)) + { + transitions.Add(new ThreadingContextTransition(awaitExpression.Span.End, ThreadingContext.Unknown)); + } + } + + return transitions.OrderBy(transition => transition.Position).ToImmutableArray(); + + bool InvalidatesMainThreadContext(ExpressionSyntax awaitedExpression) + { + while (awaitedExpression is ParenthesizedExpressionSyntax parenthesizedExpression) + { + awaitedExpression = parenthesizedExpression.Expression; + } + + ISymbol? awaitedSymbol = semanticModel.GetSymbolInfo(awaitedExpression, cancellationToken).Symbol; + if (awaitedSymbol is IPropertySymbol { Name: "Default", ContainingType.Name: "TaskScheduler", ContainingType: { } containingType } + && containingType.BelongsToNamespace(Namespaces.SystemThreadingTasks)) + { + return true; + } + + if (awaitedExpression is InvocationExpressionSyntax { ArgumentList.Arguments: [{ Expression: { } continueOnCapturedContext }] } invocation + && semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol is IMethodSymbol { Name: "ConfigureAwait", Parameters: [{ Type.SpecialType: SpecialType.System_Boolean }] }) + { + Optional constantValue = semanticModel.GetConstantValue(continueOnCapturedContext, cancellationToken); + return constantValue.HasValue && constantValue.Value is false; + } + + return false; + } + } + + private readonly struct ThreadingContextTransition + { + internal ThreadingContextTransition(int position, ThreadingContext context) + { + this.Position = position; + this.Context = context; + } + + internal int Position { get; } + + internal ThreadingContext Context { get; } + } } } diff --git a/test/Microsoft.VisualStudio.Threading.Analyzers.Tests/VSTHRD010MainThreadUsageAnalyzerTests.cs b/test/Microsoft.VisualStudio.Threading.Analyzers.Tests/VSTHRD010MainThreadUsageAnalyzerTests.cs index a8a74b77b..be4f8eb14 100644 --- a/test/Microsoft.VisualStudio.Threading.Analyzers.Tests/VSTHRD010MainThreadUsageAnalyzerTests.cs +++ b/test/Microsoft.VisualStudio.Threading.Analyzers.Tests/VSTHRD010MainThreadUsageAnalyzerTests.cs @@ -444,7 +444,7 @@ void VerifyOnUIThread() { await CSVerify.VerifyAnalyzerAsync(test, expected); } - [Fact(Skip = "Not yet supported. See https://github.com/microsoft/vs-threading/issues/542")] + [Fact] public async Task InvokeVsSolutionAfterUIThreadAssertionAndSwitchToThreadPool() { var test = @" @@ -471,7 +471,7 @@ void VerifyOnUIThread() { await CSVerify.VerifyAnalyzerAsync(test, expected); } - [Fact(Skip = "Not yet supported. See https://github.com/microsoft/vs-threading/issues/542")] + [Fact] public async Task InvokeVsSolutionAfterUIThreadAssertionAndConfigureAwaitFalse() { var test = @" @@ -500,6 +500,119 @@ void VerifyOnUIThread() { await CSVerify.VerifyAnalyzerAsync(test, expected); } + [Fact] + public async Task InvokeVsSolutionAfterUIThreadAssertionAndParenthesizedConfigureAwaitFalse() + { + var test = @" +using System; +using System.Threading.Tasks; +using Microsoft.VisualStudio.Shell.Interop; +using Microsoft.VisualStudio.Threading; + +class Test { + async Task F() { + IVsSolution sln = null; + VerifyOnUIThread(); + + await (SomeAsync().ConfigureAwait(false)); + + sln.SetProperty(1000, null); + } + + void VerifyOnUIThread() { + } + + async Task SomeAsync() => await Task.Yield(); +} +"; + DiagnosticResult expected = CSVerify.Diagnostic(DescriptorAsync).WithSpan(14, 13, 14, 24).WithArguments("IVsSolution", "JoinableTaskFactory.SwitchToMainThreadAsync"); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task InvokeVsSolutionWithinAndAfterConfigureAwaitFalseOperand() + { + var test = @" +using System.Threading.Tasks; +using Microsoft.VisualStudio.Shell.Interop; +using Microsoft.VisualStudio.Threading; + +class Test { + async Task F() { + IVsSolution sln = null; + VerifyOnUIThread(); + + await Task.FromResult(sln.SetProperty(1000, null)).ConfigureAwait(false); + + sln.SetProperty(1000, null); + } + + void VerifyOnUIThread() { + } +} +"; + DiagnosticResult expected = CSVerify.Diagnostic(DescriptorAsync).WithSpan(13, 13, 13, 24).WithArguments("IVsSolution", "JoinableTaskFactory.SwitchToMainThreadAsync"); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task InvokeVsSolutionAfterUIThreadAssertionAndCustomConfigureAwaitFalseReportsWarning() + { + var test = @" +using System.Runtime.CompilerServices; +using Microsoft.VisualStudio.Shell.Interop; + +class Test { + async void F() { + IVsSolution sln = null; + VerifyOnUIThread(); + + await new CustomAwaitable().ConfigureAwait(false); + + sln.SetProperty(1000, null); + } + + void VerifyOnUIThread() { + } +} + +class CustomAwaitable { + public CustomAwaitable ConfigureAwait(bool continueOnCapturedContext) => this; + + public TaskAwaiter GetAwaiter() => default; +} +"; + DiagnosticResult expected = CSVerify.Diagnostic(DescriptorAsync).WithSpan(12, 13, 12, 24).WithArguments("IVsSolution", "JoinableTaskFactory.SwitchToMainThreadAsync"); + await CSVerify.VerifyAnalyzerAsync(test, expected); + } + + [Fact] + public async Task WorkerTransitionInLocalFunctionDoesNotAffectContainingMethod() + { + var test = @" +using System.Threading.Tasks; +using Microsoft.VisualStudio.Shell.Interop; +using Microsoft.VisualStudio.Threading; + +class Test { + void F() { + IVsSolution sln = null; + VerifyOnUIThread(); + + async Task LocalAsync() { + await TaskScheduler.Default; + } + + sln.SetProperty(1000, null); + } + + void VerifyOnUIThread() { + } +} +"; + await CSVerify.VerifyAnalyzerAsync(test); + } + [Fact(Skip = "Not yet supported. See https://github.com/Microsoft/vs-threading/issues/38")] public async Task InvokeVsSolutionAfterUIThreadAssertionAndConditionalSwitchToThreadPool() {