update and format

This commit is contained in:
Adam Hathcock
2024-05-17 11:58:54 +01:00
parent c0c79ef240
commit 6945bae955
21 changed files with 305 additions and 228 deletions
+12
View File
@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"csharpier": {
"version": "0.28.2",
"commands": [
"dotnet-csharpier"
]
}
}
}
@@ -1,4 +1,5 @@
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using FluentAssertions;
using FluentAssertions.Common;
@@ -18,7 +19,11 @@ public class AccessorsGenerationTests
[Fact]
public void GetSetIndexer_IsImplemented()
{
var indexer = typeof(IAccessorsTestsService).GetIndexerByParameterTypes(new[] { typeof(string) });
var indexer = typeof(IAccessorsTestsService)
.GetProperties()
.First(x =>
x.GetIndexParameters().Select(x => x.ParameterType).Contains(typeof(string))
);
indexer.Should().NotBeNull();
@@ -32,8 +37,10 @@ public class AccessorsGenerationTests
[Fact]
public void PublicProperty_IsImplemented()
{
var prop = typeof(IAccessorsTestsService)
.GetProperty(nameof(IAccessorsTestsService.PublicProperty)) ?? throw new InvalidOperationException();
var prop =
typeof(IAccessorsTestsService).GetProperty(
nameof(IAccessorsTestsService.PublicProperty)
) ?? throw new InvalidOperationException();
prop.Should().NotBeNull();
@@ -47,15 +54,19 @@ public class AccessorsGenerationTests
[Fact]
public void InitProperty_IsImplemented()
{
var prop = typeof(IAccessorsTestsService)
.GetProperty(nameof(IAccessorsTestsService.InitOnlyProperty)) ?? throw new InvalidOperationException();
var prop =
typeof(IAccessorsTestsService).GetProperty(
nameof(IAccessorsTestsService.InitOnlyProperty)
) ?? throw new InvalidOperationException();
prop.Should().NotBeNull();
prop.GetMethod.Should().NotBeNull();
prop.SetMethod.Should().NotBeNull();
prop.SetMethod?.ReturnParameter?.GetRequiredCustomModifiers().Should().Contain(typeof(IsExternalInit));
prop.SetMethod?.ReturnParameter?.GetRequiredCustomModifiers()
.Should()
.Contain(typeof(IsExternalInit));
var _ = _sut.InitOnlyProperty;
}
@@ -63,8 +74,10 @@ public class AccessorsGenerationTests
[Fact]
public void PrivateSetter_IsOmitted()
{
var prop = typeof(IAccessorsTestsService)
.GetProperty(nameof(IAccessorsTestsService.PropertyWithPrivateSetter)) ?? throw new InvalidOperationException();
var prop =
typeof(IAccessorsTestsService).GetProperty(
nameof(IAccessorsTestsService.PropertyWithPrivateSetter)
) ?? throw new InvalidOperationException();
prop.Should().NotBeNull();
@@ -77,8 +90,10 @@ public class AccessorsGenerationTests
[Fact]
public void PrivateGetter_IsOmitted()
{
var prop = typeof(IAccessorsTestsService)
.GetProperty(nameof(IAccessorsTestsService.PropertyWithPrivateGetter)) ?? throw new InvalidOperationException();
var prop =
typeof(IAccessorsTestsService).GetProperty(
nameof(IAccessorsTestsService.PropertyWithPrivateGetter)
) ?? throw new InvalidOperationException();
prop.Should().NotBeNull();
@@ -91,8 +106,10 @@ public class AccessorsGenerationTests
[Fact]
public void ProtectedSetter_IsOmitted()
{
var prop = typeof(IAccessorsTestsService)
.GetProperty(nameof(IAccessorsTestsService.PropertyWithProtectedSetter)) ?? throw new InvalidOperationException();
var prop =
typeof(IAccessorsTestsService).GetProperty(
nameof(IAccessorsTestsService.PropertyWithProtectedSetter)
) ?? throw new InvalidOperationException();
prop.Should().NotBeNull();
@@ -105,8 +122,10 @@ public class AccessorsGenerationTests
[Fact]
public void ProtectedGetter_IsOmitted()
{
var prop = typeof(IAccessorsTestsService)
.GetProperty(nameof(IAccessorsTestsService.PropertyWithProtectedGetter)) ?? throw new InvalidOperationException();
var prop =
typeof(IAccessorsTestsService).GetProperty(
nameof(IAccessorsTestsService.PropertyWithProtectedGetter)
) ?? throw new InvalidOperationException();
prop.Should().NotBeNull();
@@ -119,8 +138,9 @@ public class AccessorsGenerationTests
[Fact]
public void IgnoredProperty_IsOmitted()
{
var prop = typeof(IAccessorsTestsService)
.GetProperty(nameof(AccessorsTestsService.IgnoredProperty));
var prop = typeof(IAccessorsTestsService).GetProperty(
nameof(AccessorsTestsService.IgnoredProperty)
);
prop.Should().BeNull();
}
@@ -128,8 +148,9 @@ public class AccessorsGenerationTests
[Fact]
public void StaticProperty_IsOmitted()
{
var prop = typeof(IAccessorsTestsService)
.GetProperty(nameof(AccessorsTestsService.StaticProperty));
var prop = typeof(IAccessorsTestsService).GetProperty(
nameof(AccessorsTestsService.StaticProperty)
);
prop.Should().BeNull();
}
@@ -142,9 +163,7 @@ internal class AccessorsTestsService : IAccessorsTestsService
public int this[string x]
{
get => 0;
set
{
}
set { }
}
public string PublicProperty { get; set; }
@@ -159,7 +178,8 @@ internal class AccessorsTestsService : IAccessorsTestsService
public string PropertyWithProtectedGetter { protected get; set; }
[AutoInterfaceIgnore] public string IgnoredProperty { get; set; }
[AutoInterfaceIgnore]
public string IgnoredProperty { get; set; }
public static string StaticProperty { get; set; }
}
@@ -18,12 +18,15 @@ public class GenericInterfaceTests
genericArgs[0].IsClass.Should().BeTrue();
genericArgs[0]
.GenericParameterAttributes
.Should()
.GenericParameterAttributes.Should()
.HaveFlag(GenericParameterAttributes.DefaultConstructorConstraint);
var iEquatableOfTx = typeof(IEquatable<>).MakeGenericType(genericArgs[0]);
genericArgs[0].GetGenericParameterConstraints().Should().HaveCount(1).And.Contain(iEquatableOfTx);
genericArgs[0]
.GetGenericParameterConstraints()
.Should()
.HaveCount(1)
.And.Contain(iEquatableOfTx);
genericArgs[1].IsValueType.Should().BeTrue();
}
@@ -33,6 +36,4 @@ public class GenericInterfaceTests
// ReSharper disable once UnusedType.Global
internal class GenericInterfaceTestsService<TX, TY> : IGenericInterfaceTestsService<TX, TY>
where TX : class, IEquatable<TX>, new()
where TY : struct
{
}
where TY : struct { }
@@ -19,8 +19,9 @@ public class MethodGenerationTests
[Fact]
public void VoidMethod_IsImplemented()
{
var method = typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethod)) ?? throw new InvalidOperationException();
var method =
typeof(IMethodsTestService).GetMethod(nameof(MethodsTestService.VoidMethod))
?? throw new InvalidOperationException();
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
@@ -34,8 +35,10 @@ public class MethodGenerationTests
[Fact]
public void VoidMethodWithKeywordParam_IsImplemented()
{
var method = typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithKeywordParam)) ?? throw new InvalidOperationException();
var method =
typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithKeywordParam)
) ?? throw new InvalidOperationException();
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
@@ -52,9 +55,11 @@ public class MethodGenerationTests
[Fact]
public void VoidMethodWithParams_IsImplemented()
{
var method = typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithParams),
[typeof(string), typeof(string)]) ?? throw new InvalidOperationException();
var method =
typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithParams),
[typeof(string), typeof(string)]
) ?? throw new InvalidOperationException();
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
@@ -69,15 +74,20 @@ public class MethodGenerationTests
[Fact]
public void VoidMethodWithOutParam_IsImplemented()
{
var method = typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithOutParam),
[typeof(string).MakeByRefType()]) ?? throw new InvalidOperationException();
var method =
typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithOutParam),
[typeof(string).MakeByRefType()]
) ?? throw new InvalidOperationException();
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
var parameters = method.GetParameters();
parameters.Select(x => x.ParameterType).Should().AllBeEquivalentTo(typeof(string).MakeByRefType());
parameters
.Select(x => x.ParameterType)
.Should()
.AllBeEquivalentTo(typeof(string).MakeByRefType());
parameters.Should().HaveCount(1);
parameters[0].IsOut.Should().BeTrue();
@@ -87,15 +97,20 @@ public class MethodGenerationTests
[Fact]
public void VoidMethodWithInParam_IsImplemented()
{
var method = typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithInParam),
[typeof(string).MakeByRefType()]) ?? throw new InvalidOperationException();
var method =
typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithInParam),
[typeof(string).MakeByRefType()]
) ?? throw new InvalidOperationException();
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
var parameters = method.GetParameters();
parameters.Select(x => x.ParameterType).Should().AllBeEquivalentTo(typeof(string).MakeByRefType());
parameters
.Select(x => x.ParameterType)
.Should()
.AllBeEquivalentTo(typeof(string).MakeByRefType());
parameters.Should().HaveCount(1);
parameters[0].IsIn.Should().BeTrue();
@@ -106,15 +121,20 @@ public class MethodGenerationTests
[Fact]
public void VoidMethodWithRefParam_IsImplemented()
{
var method = typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithRefParam),
[typeof(string).MakeByRefType()]) ?? throw new InvalidOperationException();
var method =
typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.VoidMethodWithRefParam),
[typeof(string).MakeByRefType()]
) ?? throw new InvalidOperationException();
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
var parameters = method.GetParameters();
parameters.Select(x => x.ParameterType).Should().AllBeEquivalentTo(typeof(string).MakeByRefType());
parameters
.Select(x => x.ParameterType)
.Should()
.AllBeEquivalentTo(typeof(string).MakeByRefType());
parameters.Should().HaveCount(1);
parameters[0].IsIn.Should().BeFalse();
parameters[0].IsOut.Should().BeFalse();
@@ -126,8 +146,9 @@ public class MethodGenerationTests
[Fact]
public void StringMethod_IsImplemented()
{
var method = typeof(IMethodsTestService).GetMethod(
nameof(MethodsTestService.StringMethod)) ?? throw new InvalidOperationException();
var method =
typeof(IMethodsTestService).GetMethod(nameof(MethodsTestService.StringMethod))
?? throw new InvalidOperationException();
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(string));
@@ -142,8 +163,8 @@ public class MethodGenerationTests
public void GenericVoidMethod_IsImplemented()
{
var method = typeof(IMethodsTestService)
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.GenericVoidMethod));
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.GenericVoidMethod));
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
@@ -160,8 +181,8 @@ public class MethodGenerationTests
public void GenericVoidMethodWithGenericParam_IsImplemented()
{
var method = typeof(IMethodsTestService)
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.GenericVoidMethodWithGenericParam));
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.GenericVoidMethodWithGenericParam));
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
@@ -180,8 +201,8 @@ public class MethodGenerationTests
public void GenericVoidMethodWithConstraints_IsImplemented()
{
var method = typeof(IMethodsTestService)
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.GenericVoidMethodWithConstraints));
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.GenericVoidMethodWithConstraints));
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
@@ -206,8 +227,8 @@ public class MethodGenerationTests
public void VoidMethodWithOptionalParams_IsImplemented()
{
var method = typeof(IMethodsTestService)
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.VoidMethodWithOptionalParams));
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.VoidMethodWithOptionalParams));
method.Should().NotBeNull();
method.ReturnType.Should().Be(typeof(void));
@@ -234,8 +255,8 @@ public class MethodGenerationTests
public void VoidMethodWithExpandingParam_IsImplemented()
{
var method = typeof(IMethodsTestService)
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.VoidMethodWithExpandingParam));
.GetMethods()
.First(x => x.Name == nameof(MethodsTestService.VoidMethodWithExpandingParam));
method.ReturnType.Should().Be(typeof(void));
@@ -249,8 +270,8 @@ public class MethodGenerationTests
public void IgnoreMethod_IsOmitted()
{
var method = typeof(IMethodsTestService)
.GetMethods()
.FirstOrDefault(x => x.Name == nameof(MethodsTestService.IgnoredMethod));
.GetMethods()
.FirstOrDefault(x => x.Name == nameof(MethodsTestService.IgnoredMethod));
method.Should().BeNull();
}
@@ -259,8 +280,8 @@ public class MethodGenerationTests
public void StaticMethod_IsOmitted()
{
var method = typeof(IMethodsTestService)
.GetMethods()
.FirstOrDefault(x => x.Name == nameof(MethodsTestService.StaticMethod));
.GetMethods()
.FirstOrDefault(x => x.Name == nameof(MethodsTestService.StaticMethod));
method.Should().BeNull();
}
@@ -271,49 +292,33 @@ internal class MethodsTestService : IMethodsTestService
{
public const string StringConstant = "Const";
public void VoidMethod()
{
}
public void VoidMethod() { }
public void VoidMethodWithParams(string a, string b)
{
}
public void VoidMethodWithParams(string a, string b) { }
public void VoidMethodWithKeywordParam(string @void)
{
}
public void VoidMethodWithKeywordParam(string @void) { }
public void VoidMethodWithOutParam(out string a)
{
a = default;
}
public void VoidMethodWithRefParam(ref string a)
{
}
public void VoidMethodWithRefParam(ref string a) { }
public void VoidMethodWithInParam(in string a)
{
}
public void VoidMethodWithInParam(in string a) { }
public string StringMethod()
{
return string.Empty;
}
public void GenericVoidMethod<TX, TY>()
{
}
public void GenericVoidMethod<TX, TY>() { }
public void GenericVoidMethodWithGenericParam<TX, TY>(TX a)
{
}
public void GenericVoidMethodWithGenericParam<TX, TY>(TX a) { }
public void GenericVoidMethodWithConstraints<TX, TY>()
where TX : class
where TY : class, TX, new()
{
}
where TY : class, TX, new() { }
public void VoidMethodWithOptionalParams(
string stringLiteral = "cGFyYW0=",
@@ -325,25 +330,17 @@ internal class MethodsTestService : IMethodsTestService
bool falseLiteral = false,
bool? nullableTrueLiteral = true,
bool? nullableFalseLiteral = false,
bool? nullableNullBoolLiteral = null)
{
}
bool? nullableNullBoolLiteral = null
) { }
public void VoidMethodWithExpandingParam(params string[] strings)
{
}
public void VoidMethodWithExpandingParam(params string[] strings) { }
[AutoInterfaceIgnore]
public void IgnoredMethod()
{
}
public void IgnoredMethod() { }
public static void StaticMethod()
{
}
public static void StaticMethod() { }
}
[GenerateAutoInterface]
internal class MethodsTestServiceGeneric<T> : IMethodsTestServiceGeneric<T> where T : class
{
}
internal class MethodsTestServiceGeneric<T> : IMethodsTestServiceGeneric<T>
where T : class { }
@@ -1,7 +1,4 @@
namespace Speckle.InterfaceGenerator.Tests.Partial;
[GenerateAutoInterface]
internal partial class PartialClass : IPartialClass
{
}
internal partial class PartialClass : IPartialClass { }
@@ -2,7 +2,5 @@ namespace Speckle.InterfaceGenerator.Tests.Partial;
internal partial class PartialClass
{
public void SomeMethodThatShouldGenerate()
{
}
public void SomeMethodThatShouldGenerate() { }
}
@@ -10,6 +10,9 @@ public class PartialClassTests
public void GeneratesMethodFromOtherParts()
{
var tInterface = typeof(IPartialClass);
tInterface.GetMethods().Should().Contain(x => x.Name == nameof(PartialClass.SomeMethodThatShouldGenerate));
tInterface
.GetMethods()
.Should()
.Contain(x => x.Name == nameof(PartialClass.SomeMethodThatShouldGenerate));
}
}
@@ -17,14 +17,17 @@ public class RecordInterfaceGenerationTests
[Fact]
public void RecordProperty_IsGenerated()
{
var prop = typeof(ITestRecord)
.GetProperty(nameof(TestRecord.RecordProperty)) ?? throw new InvalidOperationException();
var prop =
typeof(ITestRecord).GetProperty(nameof(TestRecord.RecordProperty))
?? throw new InvalidOperationException();
prop.Should().NotBeNull();
prop.GetMethod.Should().NotBeNull();
prop.SetMethod.Should().NotBeNull();
prop.SetMethod?.ReturnParameter?.GetRequiredCustomModifiers().Should().Contain(typeof(IsExternalInit));
prop.SetMethod?.ReturnParameter?.GetRequiredCustomModifiers()
.Should()
.Contain(typeof(IsExternalInit));
_sut.RecordProperty.Should().Be(420);
}
@@ -32,8 +35,7 @@ public class RecordInterfaceGenerationTests
[Fact]
public void RecordMethod_IsGenerated()
{
var method = typeof(ITestRecord).GetMethod(
nameof(TestRecord.RecordMethod));
var method = typeof(ITestRecord).GetMethod(nameof(TestRecord.RecordMethod));
method.Should().NotBeNull();
method?.ReturnType.Should().Be(typeof(void));
@@ -47,13 +49,12 @@ public class RecordInterfaceGenerationTests
[Fact]
public void Deconstruct_IsGenerated()
{
var method = typeof(ITestRecord).GetMethod(
nameof(TestRecord.Deconstruct));
var method = typeof(ITestRecord).GetMethod(nameof(TestRecord.Deconstruct));
method.Should().NotBeNull();
method?.ReturnType.Should().Be(typeof(void));
var parameters = method?.GetParameters() ?? throw new InvalidOperationException();
var parameters = method?.GetParameters() ?? throw new InvalidOperationException();
parameters.Length.Should().Be(1);
var parameter = parameters[0];
@@ -65,7 +66,5 @@ public class RecordInterfaceGenerationTests
[GenerateAutoInterface]
internal record TestRecord(int RecordProperty) : ITestRecord
{
public void RecordMethod()
{
}
public void RecordMethod() { }
}
@@ -9,7 +9,4 @@ namespace InterfaceGenerator.Tests.SameName_1;
/// qualified names.
/// </summary>
[GenerateAutoInterface]
internal class SameNameClass : ISameNameClass
{
}
internal class SameNameClass : ISameNameClass { }
@@ -5,7 +5,4 @@ using Speckle.InterfaceGenerator;
namespace InterfaceGenerator.Tests.SameName_2;
[GenerateAutoInterface]
internal class SameNameClass : ISameNameClass
{
}
internal class SameNameClass : ISameNameClass { }
@@ -7,14 +7,14 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="xunit" Version="2.8.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\InterfaceGenerator\Speckle.InterfaceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\Speckle.InterfaceGenerator\Speckle.InterfaceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
</Project>
@@ -36,21 +36,13 @@ public class VisibilityModifierTests
}
[GenerateAutoInterface(VisibilityModifier = "public")]
internal class ExplicitlyPublicService : IExplicitlyPublicService
{
}
internal class ExplicitlyPublicService : IExplicitlyPublicService { }
[GenerateAutoInterface(VisibilityModifier = "internal")]
public class ExplicitlyInternalService : IExplicitlyInternalService
{
}
public class ExplicitlyInternalService : IExplicitlyInternalService { }
[GenerateAutoInterface]
public class ImplicitlyPublicService : IImplicitlyPublicService
{
}
public class ImplicitlyPublicService : IImplicitlyPublicService { }
[GenerateAutoInterface]
internal class ImplicitlyInternalService : IImplicitlyInternalService
{
}
internal class ImplicitlyInternalService : IImplicitlyInternalService { }
+2 -1
View File
@@ -10,7 +10,8 @@ internal class Attributes
public const string VisibilityModifierPropName = "VisibilityModifier";
public const string InterfaceNamePropName = "Name";
public static readonly string AttributesSourceCode = $@"
public static readonly string AttributesSourceCode =
$@"
using System;
using System.Diagnostics;
@@ -44,7 +44,10 @@ public class AutoInterfaceGenerator : ISourceGenerator
}
}
private static void RaiseExceptionDiagnostic(GeneratorExecutionContext context, Exception exception)
private static void RaiseExceptionDiagnostic(
GeneratorExecutionContext context,
Exception exception
)
{
var descriptor = new DiagnosticDescriptor(
"Speckle.InterfaceGenerator.CriticalError",
@@ -53,7 +56,8 @@ public class AutoInterfaceGenerator : ISourceGenerator
"Speckle.InterfaceGenerator",
DiagnosticSeverity.Error,
true,
customTags: WellKnownDiagnosticTags.AnalyzerException);
customTags: WellKnownDiagnosticTags.AnalyzerException
);
var diagnostic = Diagnostic.Create(descriptor, null);
@@ -77,7 +81,8 @@ public class AutoInterfaceGenerator : ISourceGenerator
{
context.AddSource(
Attributes.GenerateAutoInterfaceClassname,
SourceText.From(Attributes.AttributesSourceCode, Encoding.UTF8));
SourceText.From(Attributes.AttributesSourceCode, Encoding.UTF8)
);
}
private void GenerateInterfaces(GeneratorExecutionContext context)
@@ -96,12 +101,24 @@ public class AutoInterfaceGenerator : ISourceGenerator
foreach (var implTypeSymbol in classSymbols)
{
if (!implTypeSymbol.TryGetAttribute(_generateAutoInterfaceAttribute ?? throw new NullReferenceException("_generateAutoInterfaceAttribute is null"), out var attributes))
if (
!implTypeSymbol.TryGetAttribute(
_generateAutoInterfaceAttribute
?? throw new NullReferenceException(
"_generateAutoInterfaceAttribute is null"
),
out var attributes
)
)
{
continue;
}
if(classSymbolNames.Contains(implTypeSymbol.GetFullMetadataName(useNameWhenNotFound: true)))
if (
classSymbolNames.Contains(
implTypeSymbol.GetFullMetadataName(useNameWhenNotFound: true)
)
)
{
continue; // partial class, already added
}
@@ -109,13 +126,22 @@ public class AutoInterfaceGenerator : ISourceGenerator
classSymbolNames.Add(implTypeSymbol.GetFullMetadataName(useNameWhenNotFound: true));
var attribute = attributes.Single();
var source = SourceText.From(GenerateInterfaceCode(implTypeSymbol, attribute), Encoding.UTF8);
var source = SourceText.From(
GenerateInterfaceCode(implTypeSymbol, attribute),
Encoding.UTF8
);
context.AddSource($"{implTypeSymbol.GetFullMetadataName(useNameWhenNotFound: true)}_AutoInterface.g.cs", source);
context.AddSource(
$"{implTypeSymbol.GetFullMetadataName(useNameWhenNotFound: true)}_AutoInterface.g.cs",
source
);
}
}
private static string InferVisibilityModifier(ISymbol implTypeSymbol, AttributeData attributeData)
private static string InferVisibilityModifier(
ISymbol implTypeSymbol,
AttributeData attributeData
)
{
string? result = attributeData.GetNamedParamValue(Attributes.VisibilityModifierPropName);
if (!string.IsNullOrEmpty(result))
@@ -126,16 +152,20 @@ public class AutoInterfaceGenerator : ISourceGenerator
return implTypeSymbol.DeclaredAccessibility switch
{
Accessibility.Public => "public",
_ => "internal",
_ => "internal",
};
}
private static string InferInterfaceName(ISymbol implTypeSymbol, AttributeData attributeData)
{
return attributeData.GetNamedParamValue(Attributes.InterfaceNamePropName) ?? $"I{implTypeSymbol.Name}";
return attributeData.GetNamedParamValue(Attributes.InterfaceNamePropName)
?? $"I{implTypeSymbol.Name}";
}
private string GenerateInterfaceCode(INamedTypeSymbol implTypeSymbol, AttributeData attributeData)
private string GenerateInterfaceCode(
INamedTypeSymbol implTypeSymbol,
AttributeData attributeData
)
{
using var stream = new MemoryStream();
var streamWriter = new StreamWriter(stream, Encoding.UTF8);
@@ -179,7 +209,10 @@ public class AutoInterfaceGenerator : ISourceGenerator
return reader.ReadToEnd();
}
private static void WriteTypeGenericsIfNeeded(TextWriter writer, INamedTypeSymbol implTypeSymbol)
private static void WriteTypeGenericsIfNeeded(
TextWriter writer,
INamedTypeSymbol implTypeSymbol
)
{
if (!implTypeSymbol.IsGenericType)
{
@@ -193,12 +226,19 @@ public class AutoInterfaceGenerator : ISourceGenerator
WriteTypeParameterConstraints(writer, implTypeSymbol.TypeParameters);
}
private void GenerateInterfaceMemberDefinitions(TextWriter writer, INamespaceOrTypeSymbol implTypeSymbol)
private void GenerateInterfaceMemberDefinitions(
TextWriter writer,
INamespaceOrTypeSymbol implTypeSymbol
)
{
foreach (var member in implTypeSymbol.GetMembers())
{
if (member.DeclaredAccessibility != Accessibility.Public ||
member.HasAttribute(_ignoreAttribute ?? throw new NullReferenceException("_ignoreAttribute is null")))
if (
member.DeclaredAccessibility != Accessibility.Public
|| member.HasAttribute(
_ignoreAttribute ?? throw new NullReferenceException("_ignoreAttribute is null")
)
)
{
continue;
}
@@ -256,18 +296,21 @@ public class AutoInterfaceGenerator : ISourceGenerator
return symbol.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal;
}
private static void GeneratePropertyDefinition(TextWriter writer, IPropertySymbol propertySymbol)
private static void GeneratePropertyDefinition(
TextWriter writer,
IPropertySymbol propertySymbol
)
{
if (propertySymbol.IsStatic)
{
return;
}
bool hasPublicGetter = propertySymbol.GetMethod is not null &&
IsPublicOrInternal(propertySymbol.GetMethod);
bool hasPublicGetter =
propertySymbol.GetMethod is not null && IsPublicOrInternal(propertySymbol.GetMethod);
bool hasPublicSetter = propertySymbol.SetMethod is not null &&
IsPublicOrInternal(propertySymbol.SetMethod);
bool hasPublicSetter =
propertySymbol.SetMethod is not null && IsPublicOrInternal(propertySymbol.SetMethod);
if (!hasPublicGetter && !hasPublicSetter)
{
@@ -420,7 +463,8 @@ public class AutoInterfaceGenerator : ISourceGenerator
private static void WriteTypeParameterConstraints(
TextWriter writer,
IEnumerable<ITypeParameterSymbol> typeParameters)
IEnumerable<ITypeParameterSymbol> typeParameters
)
{
foreach (var typeParameter in typeParameters)
{
@@ -438,15 +482,23 @@ public class AutoInterfaceGenerator : ISourceGenerator
private void InitAttributes(Compilation compilation)
{
_generateAutoInterfaceAttribute = compilation.GetTypeByMetadataName(
$"{Attributes.AttributesNamespace}.{Attributes.GenerateAutoInterfaceClassname}");
$"{Attributes.AttributesNamespace}.{Attributes.GenerateAutoInterfaceClassname}"
);
_ignoreAttribute = compilation.GetTypeByMetadataName(
$"{Attributes.AttributesNamespace}.{Attributes.AutoInterfaceIgnoreAttributeClassname}");
$"{Attributes.AttributesNamespace}.{Attributes.AutoInterfaceIgnoreAttributeClassname}"
);
}
private static IEnumerable<INamedTypeSymbol> GetImplTypeSymbols(Compilation compilation, SyntaxReceiver receiver)
private static IEnumerable<INamedTypeSymbol> GetImplTypeSymbols(
Compilation compilation,
SyntaxReceiver receiver
)
{
return receiver.CandidateTypes.Select(candidate => GetTypeSymbol(compilation, candidate)).Where(x => x != null).Cast<INamedTypeSymbol>();
return receiver
.CandidateTypes.Select(candidate => GetTypeSymbol(compilation, candidate))
.Where(x => x != null)
.Cast<INamedTypeSymbol>();
}
private static INamedTypeSymbol? GetTypeSymbol(Compilation compilation, SyntaxNode type)
@@ -462,7 +514,10 @@ public class AutoInterfaceGenerator : ISourceGenerator
var compilation = context.Compilation.AddSyntaxTrees(
CSharpSyntaxTree.ParseText(
SourceText.From(Attributes.AttributesSourceCode, Encoding.UTF8), options));
SourceText.From(Attributes.AttributesSourceCode, Encoding.UTF8),
options
)
);
return compilation;
}
@@ -10,6 +10,7 @@
<IncludeBuildOutput>false</IncludeBuildOutput>
<NoPackageAnalysis>true</NoPackageAnalysis>
<RootNamespace>Speckle.InterfaceGenerator</RootNamespace>
<EnforoceExtendedAnalyzerRules>true</EnforoceExtendedAnalyzerRules>
</PropertyGroup>
<PropertyGroup>
@@ -22,9 +23,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="4.2.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.2.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" >
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="4.9.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
+12 -4
View File
@@ -10,16 +10,19 @@ internal static class SymbolExtensions
public static bool TryGetAttribute(
this ISymbol symbol,
INamedTypeSymbol attributeType,
out IEnumerable<AttributeData> attributes)
out IEnumerable<AttributeData> attributes
)
{
attributes = symbol.GetAttributes()
attributes = symbol
.GetAttributes()
.Where(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeType));
return attributes.Any();
}
public static bool HasAttribute(this ISymbol symbol, INamedTypeSymbol attributeType)
{
return symbol.GetAttributes()
return symbol
.GetAttributes()
.Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeType));
}
@@ -47,7 +50,12 @@ internal static class SymbolExtensions
stringBuilder.Insert(0, '.');
}
stringBuilder.Insert(0, symbol.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
stringBuilder.Insert(
0,
symbol.OriginalDefinition.ToDisplayString(
SymbolDisplayFormat.MinimallyQualifiedFormat
)
);
symbol = symbol.ContainingSymbol;
}
+7 -4
View File
@@ -10,9 +10,11 @@ internal class SyntaxReceiver : ISyntaxReceiver
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is TypeDeclarationSyntax typeDeclarationSyntax &&
IsClassOrRecord(typeDeclarationSyntax) &&
typeDeclarationSyntax.AttributeLists.Count > 0)
if (
syntaxNode is TypeDeclarationSyntax typeDeclarationSyntax
&& IsClassOrRecord(typeDeclarationSyntax)
&& typeDeclarationSyntax.AttributeLists.Count > 0
)
{
CandidateTypes.Add(typeDeclarationSyntax);
}
@@ -20,6 +22,7 @@ internal class SyntaxReceiver : ISyntaxReceiver
private static bool IsClassOrRecord(TypeDeclarationSyntax typeDeclarationSyntax)
{
return typeDeclarationSyntax is ClassDeclarationSyntax || typeDeclarationSyntax is RecordDeclarationSyntax;
return typeDeclarationSyntax is ClassDeclarationSyntax
|| typeDeclarationSyntax is RecordDeclarationSyntax;
}
}
@@ -6,11 +6,7 @@ namespace Speckle.InterfaceGenerator;
internal static class TextWriterExtensions
{
public static void WriteJoin<T>(
this TextWriter writer,
string separator,
IEnumerable<T> values)
public static void WriteJoin<T>(this TextWriter writer, string separator, IEnumerable<T> values)
{
writer.WriteJoin(separator, values, (w, x) => w.Write(x));
}
@@ -19,7 +15,8 @@ internal static class TextWriterExtensions
this TextWriter writer,
string separator,
IEnumerable<T> values,
Action<TextWriter, T> writeAction)
Action<TextWriter, T> writeAction
)
{
using var enumerator = values.GetEnumerator();
@@ -25,19 +25,18 @@ internal static class TypeParameterSymbolExtensions
if (symbol.HasReferenceTypeConstraint)
{
yield return symbol.ReferenceTypeConstraintNullableAnnotation == NullableAnnotation.Annotated
yield return symbol.ReferenceTypeConstraintNullableAnnotation
== NullableAnnotation.Annotated
? "class?"
: "class";
}
// types go in the middle
foreach (var constraintType in symbol.ConstraintTypes)
{
yield return constraintType.ToDisplayString();
}
// the new() constraint has to be the last
if (symbol.HasConstructorConstraint)
{