Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DotNetWorker.sln
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Worker.Extensions.Kafka", "
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sdk.Analyzers", "sdk\Sdk.Analyzers\Sdk.Analyzers.csproj", "{055D602D-D2B3-416B-AC59-1972D832032A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sdk.Analyzers.Tests", "test\Sdk.Analyzers.Tests\Sdk.Analyzers.Tests\Sdk.Analyzers.Tests.csproj", "{A75EA1E1-2801-460C-87C0-DE6A82D30851}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sdk.Analyzers.Tests", "test\Sdk.Analyzers.Tests\Sdk.Analyzers.Tests.csproj", "{A75EA1E1-2801-460C-87C0-DE6A82D30851}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{083592CA-7DAB-44CE-8979-44FAFA46AEC3}"
EndProject
Expand Down
5 changes: 4 additions & 1 deletion sdk/Sdk.Analyzers/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ internal static class Types
{
public const string WorkerFunctionAttribute = "Microsoft.Azure.Functions.Worker.FunctionAttribute";
public const string WebJobsBindingAttribute = "Microsoft.Azure.WebJobs.Description.BindingAttribute";

public const string SupportsDeferredBindingAttribute = "Microsoft.Azure.Functions.Worker.Extensions.Abstractions.SupportsDeferredBindingAttribute";
public const string InputBindingAttribute = "Microsoft.Azure.Functions.Worker.Extensions.Abstractions.InputBindingAttribute";
public const string TriggerBindingAttribute = "Microsoft.Azure.Functions.Worker.Extensions.Abstractions.TriggerBindingAttribute";

// System types
internal const string TaskType = "System.Threading.Tasks.Task";
}
Expand Down
58 changes: 58 additions & 0 deletions sdk/Sdk.Analyzers/DeferredBindingAttributeNotSupported.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace Microsoft.Azure.Functions.Worker.Sdk.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class DeferredBindingAttributeNotSupported : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DiagnosticDescriptors.DeferredBindingAttributeNotSupported); } }

public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
context.RegisterSymbolAction(AnalyzeMethod, SymbolKind.NamedType);
}

private static void AnalyzeMethod(SymbolAnalysisContext symbolAnalysisContext)
{
var symbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol;

var attributes = symbol.GetAttributes();

if (attributes.IsEmpty)
{
return;
}

foreach (var attribute in attributes)
{
if (attribute.IsSupportsDeferredBindingAttribute() && !IsInputOrTriggerBinding(symbol))
{
var location = Location.Create(attribute.ApplicationSyntaxReference.SyntaxTree, attribute.ApplicationSyntaxReference.Span);
var diagnostic = Diagnostic.Create(DiagnosticDescriptors.DeferredBindingAttributeNotSupported, location, attribute.AttributeClass.Name);
symbolAnalysisContext.ReportDiagnostic(diagnostic);
}
}
}

private static bool IsInputOrTriggerBinding(INamedTypeSymbol symbol)
{
var baseType = symbol.BaseType?.ToDisplayString();

if (string.Equals(baseType,Constants.Types.InputBindingAttribute, StringComparison.Ordinal)
|| string.Equals(baseType,Constants.Types.TriggerBindingAttribute, StringComparison.Ordinal))
{
return true;
}

return false;
}
}
}
11 changes: 6 additions & 5 deletions sdk/Sdk.Analyzers/DiagnosticDescriptors.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.CodeAnalysis;

namespace Microsoft.Azure.Functions.Worker.Sdk.Analyzers
Expand All @@ -16,13 +13,17 @@ private static DiagnosticDescriptor Create(string id, string title,string messag
return new DiagnosticDescriptor(id, title, messageFormat, category, severity, isEnabledByDefault: true, helpLinkUri: helpLink);
}

public static DiagnosticDescriptor WebJobsAttributesAreNotSuppoted { get; }
public static DiagnosticDescriptor WebJobsAttributesAreNotSupported { get; }
= Create(id: "AZFW0001", title: "Invalid binding attributes", messageFormat: "The attribute '{0}' is a WebJobs attribute and not supported in the .NET Worker (Isolated Process).",
category: Constants.DiagnosticsCategories.Usage, severity: DiagnosticSeverity.Error);

public static DiagnosticDescriptor AsyncVoidReturnType { get; }
= Create(id: "AZFW0002", title: "Avoid async void methods", messageFormat: "Do not use void as the return type for async methods. Use Task instead.",
category: Constants.DiagnosticsCategories.Usage, severity: DiagnosticSeverity.Error);

public static DiagnosticDescriptor DeferredBindingAttributeNotSupported{ get; }
= Create(id: "AZFW0003", title: "Invalid class attribute", messageFormat: "The attribute '{0}' can only be used on trigger and input binding attributes.",
Comment thread
liliankasem marked this conversation as resolved.
category: Constants.DiagnosticsCategories.Usage, severity: DiagnosticSeverity.Error);

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static bool IsWebJobAttribute(this AttributeData attributeData)
{
return false;
}

foreach (var attribute in attributeAttributes)
{
if (string.Equals(attribute.AttributeClass?.ToDisplayString(), Constants.Types.WebJobsBindingAttribute,
Expand All @@ -34,4 +34,21 @@ public static bool IsWebJobAttribute(this AttributeData attributeData)

return false;
}

/// <summary>
/// Checks if an attribute is the SupportsDeferredBinding attribute.
/// </summary>
/// <param name="attributeData">The attribute to check.</param>
/// <returns>A boolean value indicating whether the attribute is a SupportsDeferredBinding attribute.</returns>
public static bool IsSupportsDeferredBindingAttribute(this AttributeData attributeData)
{
if (string.Equals(attributeData.AttributeClass?.ToDisplayString(),
Constants.Types.SupportsDeferredBindingAttribute,
StringComparison.Ordinal))
{
return true;
}

return false;
}
}
4 changes: 2 additions & 2 deletions sdk/Sdk.Analyzers/WebJobsAttributesNotSupported.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ namespace Microsoft.Azure.Functions.Worker.Sdk.Analyzers
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class WebJobsAttributesNotSupported : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DiagnosticDescriptors.WebJobsAttributesAreNotSuppoted); } }
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(DiagnosticDescriptors.WebJobsAttributesAreNotSupported); } }

public override void Initialize(AnalysisContext context)
{
Expand All @@ -34,7 +34,7 @@ public override void Initialize(AnalysisContext context)
foreach (var attribute in webjobsAttributes)
{
var location = Location.Create(attribute.ApplicationSyntaxReference.SyntaxTree, attribute.ApplicationSyntaxReference.Span);
c.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.WebJobsAttributesAreNotSuppoted, location, attribute.AttributeClass.Name));
c.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.WebJobsAttributesAreNotSupported, location, attribute.AttributeClass.Name));
}
}
}, SymbolKind.Method);
Expand Down
2 changes: 2 additions & 0 deletions sdk/release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
<!-- Please add your release notes in the following format:
- My change description (#PR/#issue)
-->

- Add analyzer for SupportsDeferredBindingAttribute #1367
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using Xunit;
using AnalizerTest = Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerTest<Microsoft.Azure.Functions.Worker.Sdk.Analyzers.AsyncVoidAnalyzer, Microsoft.CodeAnalysis.Testing.Verifiers.XUnitVerifier>;
using AnalyzerTest = Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerTest<Microsoft.Azure.Functions.Worker.Sdk.Analyzers.AsyncVoidAnalyzer, Microsoft.CodeAnalysis.Testing.Verifiers.XUnitVerifier>;
using AnalyzerVerifier = Microsoft.CodeAnalysis.CSharp.Testing.XUnit.AnalyzerVerifier<Microsoft.Azure.Functions.Worker.Sdk.Analyzers.AsyncVoidAnalyzer>;
using CodeFixTest = Microsoft.CodeAnalysis.CSharp.Testing.CSharpCodeFixTest<Microsoft.Azure.Functions.Worker.Sdk.Analyzers.AsyncVoidAnalyzer, Microsoft.Azure.Functions.Worker.Sdk.Analyzers.AsyncVoidCodeFixProvider, Microsoft.CodeAnalysis.Testing.Verifiers.XUnitVerifier>;
using CodeFixVerifier = Microsoft.CodeAnalysis.CSharp.Testing.CSharpCodeFixVerifier<Microsoft.Azure.Functions.Worker.Sdk.Analyzers.AsyncVoidAnalyzer, Microsoft.Azure.Functions.Worker.Sdk.Analyzers.AsyncVoidCodeFixProvider, Microsoft.CodeAnalysis.Testing.Verifiers.XUnitVerifier>;
Expand Down Expand Up @@ -35,7 +35,7 @@ public static async void Run([QueueTrigger(""myqueue-items"")] string myQueueIte
}
}
}";
var test = new AnalizerTest
var test = new AnalyzerTest
{
ReferenceAssemblies = LoadRequiredDependencyAssemblies(),
TestCode = inputCode
Expand Down Expand Up @@ -72,15 +72,15 @@ public static async Task Run([QueueTrigger(""myqueue-items"")] string myQueueIte
}
}
}";
var test = new AnalizerTest
var test = new AnalyzerTest
{
ReferenceAssemblies = LoadRequiredDependencyAssemblies(),
TestCode = inputCode
};

await test.RunAsync();
}

[Fact]
public async Task AnalyzerDoesNotReportForNonAsyncCode()
{
Expand All @@ -100,7 +100,7 @@ public static void Run([QueueTrigger(""myqueue-items"")] string myQueueItem, Fun
}
}
}";
var test = new AnalizerTest
var test = new AnalyzerTest
{
ReferenceAssemblies = LoadRequiredDependencyAssemblies(),
TestCode = inputCode
Expand Down Expand Up @@ -165,7 +165,7 @@ public static async Task Run([QueueTrigger(""myqueue-items"")] string myQueueIte
test.ExpectedDiagnostics.AddRange(new[] { expectedDiagnosticResult });
await test.RunAsync(CancellationToken.None);
}

private static ReferenceAssemblies LoadRequiredDependencyAssemblies()
{
var referenceAssemblies = ReferenceAssemblies.Net.Net50.WithPackages(ImmutableArray.Create(
Expand Down
134 changes: 134 additions & 0 deletions test/Sdk.Analyzers.Tests/DeferredBindingAttributeNotSupportedTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using Xunit;
using AnalyzerTest = Microsoft.CodeAnalysis.CSharp.Testing.CSharpAnalyzerTest<Microsoft.Azure.Functions.Worker.Sdk.Analyzers.DeferredBindingAttributeNotSupported, Microsoft.CodeAnalysis.Testing.Verifiers.XUnitVerifier>;
using Verify = Microsoft.CodeAnalysis.CSharp.Testing.XUnit.AnalyzerVerifier<Microsoft.Azure.Functions.Worker.Sdk.Analyzers.DeferredBindingAttributeNotSupported>;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using System.Collections.Immutable;

namespace Sdk.Analyzers.Tests
{
public class DeferredBindingAttributeNotSupportedTests
{
[Fact]
public async Task TriggerBindingClass_SupportsDeferredBindingAttribute_Diagnostics_NotExpected()
{
string testCode = @"
using Microsoft.Azure.Functions.Worker.Extensions.Abstractions;

namespace TestBindings
{
[SupportsDeferredBinding]
public sealed class BlobTriggerAttribute : TriggerBindingAttribute
{
}
}";

var test = new AnalyzerTest
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50.WithPackages(ImmutableArray.Create(
new PackageIdentity("Microsoft.Azure.Functions.Worker", "1.12.1-preview1"),
new PackageIdentity("Microsoft.Azure.Functions.Worker.Sdk", "1.9.0-preview1"),
new PackageIdentity("Microsoft.Azure.Functions.Worker.Extensions.Abstractions", "1.2.0-preview1"))),

TestCode = testCode
};

// test.ExpectedDiagnostics is an empty collection.

await test.RunAsync();
}

[Fact]
public async Task InputBindingClass_SupportsDeferredBindingAttribute_Diagnostics_NotExpected()
{
string testCode = @"
using Microsoft.Azure.Functions.Worker.Extensions.Abstractions;

namespace TestBindings
{
[SupportsDeferredBinding]
public sealed class BlobInputAttribute : InputBindingAttribute
{
}
}";

var test = new AnalyzerTest
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50.WithPackages(ImmutableArray.Create(
new PackageIdentity("Microsoft.Azure.Functions.Worker", "1.12.1-preview1"),
new PackageIdentity("Microsoft.Azure.Functions.Worker.Sdk", "1.9.0-preview1"),
new PackageIdentity("Microsoft.Azure.Functions.Worker.Extensions.Abstractions", "1.2.0-preview1"))),

TestCode = testCode
};

// test.ExpectedDiagnostics is an empty collection.

await test.RunAsync();
}

[Fact]
public async Task OutputBindingClass_SupportsDeferredBindingAttribute_Diagnostic_Expected()
{
string testCode = @"
using Microsoft.Azure.Functions.Worker.Extensions.Abstractions;

namespace TestBindings
{
[SupportsDeferredBinding]
public sealed class BlobOutputAttribute : OutputBindingAttribute
{
}
}";

var test = new AnalyzerTest
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50.WithPackages(ImmutableArray.Create(
new PackageIdentity("Microsoft.Azure.Functions.Worker", "1.12.1-preview1"),
new PackageIdentity("Microsoft.Azure.Functions.Worker.Sdk", "1.9.0-preview1"),
new PackageIdentity("Microsoft.Azure.Functions.Worker.Extensions.Abstractions", "1.2.0-preview1"))),

TestCode = testCode
};

test.ExpectedDiagnostics.Add(Verify.Diagnostic()
.WithSeverity(Microsoft.CodeAnalysis.DiagnosticSeverity.Error)
.WithSpan(6, 22, 6, 45)
.WithArguments("SupportsDeferredBindingAttribute"));

await test.RunAsync();
}

[Fact]
public async Task ClassWithoutBase_SupportsDeferredBindingAttribute_Diagnostic_Expected()
{
string testCode = @"
using Microsoft.Azure.Functions.Worker.Extensions.Abstractions;

namespace TestBindings
{
[SupportsDeferredBinding]
public sealed class JustAnotherClass
{
}
}";

var test = new AnalyzerTest
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50.WithPackages(ImmutableArray.Create(
new PackageIdentity("Microsoft.Azure.Functions.Worker", "1.12.1-preview1"),
new PackageIdentity("Microsoft.Azure.Functions.Worker.Sdk", "1.9.0-preview1"),
new PackageIdentity("Microsoft.Azure.Functions.Worker.Extensions.Abstractions", "1.2.0-preview1"))),

TestCode = testCode
};

test.ExpectedDiagnostics.Add(Verify.Diagnostic()
.WithSeverity(Microsoft.CodeAnalysis.DiagnosticSeverity.Error)
.WithSpan(6, 22, 6, 45)
.WithArguments("SupportsDeferredBindingAttribute"));

await test.RunAsync();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\extensions\Worker.Extensions.Abstractions\src\Worker.Extensions.Abstractions.csproj" />
<ProjectReference Include="..\..\..\sdk\Sdk.Analyzers\Sdk.Analyzers.csproj" />
<ProjectReference Include="..\..\..\src\DotNetWorker\DotNetWorker.csproj" />
<ProjectReference Include="..\..\extensions\Worker.Extensions.Abstractions\src\Worker.Extensions.Abstractions.csproj" />
<ProjectReference Include="..\..\sdk\Sdk.Analyzers\Sdk.Analyzers.csproj" />
<ProjectReference Include="..\..\src\DotNetWorker\DotNetWorker.csproj" />
</ItemGroup>

</Project>
Loading