folder rename
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
@@ -0,0 +1,13 @@
|
||||
using System.Linq;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace Speckle.InterfaceGenerator;
|
||||
|
||||
internal static class AttributeDataExtensions
|
||||
{
|
||||
public static string? GetNamedParamValue(this AttributeData attributeData, string paramName)
|
||||
{
|
||||
var pair = attributeData.NamedArguments.FirstOrDefault(x => x.Key == paramName);
|
||||
return pair.Value.Value?.ToString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
namespace Speckle.InterfaceGenerator;
|
||||
|
||||
internal class Attributes
|
||||
{
|
||||
public const string AttributesNamespace = "Speckle.InterfaceGenerator";
|
||||
|
||||
public const string GenerateAutoInterfaceClassname = "GenerateAutoInterfaceAttribute";
|
||||
public const string AutoInterfaceIgnoreAttributeClassname = "AutoInterfaceIgnoreAttribute";
|
||||
|
||||
public const string VisibilityModifierPropName = "VisibilityModifier";
|
||||
public const string InterfaceNamePropName = "Name";
|
||||
|
||||
public static readonly string AttributesSourceCode = $@"
|
||||
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
#nullable enable
|
||||
|
||||
namespace {AttributesNamespace}
|
||||
{{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
|
||||
[Conditional(""CodeGeneration"")]
|
||||
internal sealed class {GenerateAutoInterfaceClassname} : Attribute
|
||||
{{
|
||||
public string? {VisibilityModifierPropName} {{ get; init; }}
|
||||
public string? {InterfaceNamePropName} {{ get; init; }}
|
||||
|
||||
public {GenerateAutoInterfaceClassname}()
|
||||
{{
|
||||
}}
|
||||
}}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false)]
|
||||
[Conditional(""CodeGeneration"")]
|
||||
internal sealed class {AutoInterfaceIgnoreAttributeClassname} : Attribute
|
||||
{{
|
||||
}}
|
||||
}}
|
||||
";
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
using System;
|
||||
using System.CodeDom.Compiler;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.Text;
|
||||
|
||||
namespace Speckle.InterfaceGenerator;
|
||||
|
||||
[Generator]
|
||||
public class AutoInterfaceGenerator : ISourceGenerator
|
||||
{
|
||||
private INamedTypeSymbol? _generateAutoInterfaceAttribute;
|
||||
private INamedTypeSymbol? _ignoreAttribute;
|
||||
|
||||
public void Initialize(GeneratorInitializationContext context)
|
||||
{
|
||||
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
|
||||
|
||||
#if DEBUG
|
||||
if (!Debugger.IsAttached)
|
||||
{
|
||||
// sadly this is Windows only so as of now :(
|
||||
Debugger.Launch();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public void Execute(GeneratorExecutionContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
ExecuteCore(context);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
RaiseExceptionDiagnostic(context, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RaiseExceptionDiagnostic(GeneratorExecutionContext context, Exception exception)
|
||||
{
|
||||
var descriptor = new DiagnosticDescriptor(
|
||||
"Speckle.InterfaceGenerator.CriticalError",
|
||||
"Exception thrown in InterfaceGenerator",
|
||||
$"{exception.GetType().FullName} {exception.Message} {exception.StackTrace.Trim()}",
|
||||
"Speckle.InterfaceGenerator",
|
||||
DiagnosticSeverity.Error,
|
||||
true,
|
||||
customTags: WellKnownDiagnosticTags.AnalyzerException);
|
||||
|
||||
var diagnostic = Diagnostic.Create(descriptor, null);
|
||||
|
||||
context.ReportDiagnostic(diagnostic);
|
||||
}
|
||||
|
||||
private void ExecuteCore(GeneratorExecutionContext context)
|
||||
{
|
||||
// setting the culture to invariant prevents errors such as emitting a decimal comma (0,1) instead of
|
||||
// a decimal point (0.1) in certain cultures
|
||||
var prevCulture = Thread.CurrentThread.CurrentCulture;
|
||||
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
|
||||
|
||||
GenerateAttributes(context);
|
||||
GenerateInterfaces(context);
|
||||
|
||||
Thread.CurrentThread.CurrentCulture = prevCulture;
|
||||
}
|
||||
|
||||
private static void GenerateAttributes(GeneratorExecutionContext context)
|
||||
{
|
||||
context.AddSource(
|
||||
Attributes.GenerateAutoInterfaceClassname,
|
||||
SourceText.From(Attributes.AttributesSourceCode, Encoding.UTF8));
|
||||
}
|
||||
|
||||
private void GenerateInterfaces(GeneratorExecutionContext context)
|
||||
{
|
||||
if (context.SyntaxReceiver is not SyntaxReceiver receiver)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var compilation = GetCompilation(context);
|
||||
InitAttributes(compilation);
|
||||
|
||||
var classSymbols = GetImplTypeSymbols(compilation, receiver);
|
||||
|
||||
List<string> classSymbolNames = [];
|
||||
|
||||
foreach (var implTypeSymbol in classSymbols)
|
||||
{
|
||||
if (!implTypeSymbol.TryGetAttribute(_generateAutoInterfaceAttribute ?? throw new NullReferenceException("_generateAutoInterfaceAttribute is null"), out var attributes))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if(classSymbolNames.Contains(implTypeSymbol.GetFullMetadataName(useNameWhenNotFound: true)))
|
||||
{
|
||||
continue; // partial class, already added
|
||||
}
|
||||
|
||||
classSymbolNames.Add(implTypeSymbol.GetFullMetadataName(useNameWhenNotFound: true));
|
||||
|
||||
var attribute = attributes.Single();
|
||||
var source = SourceText.From(GenerateInterfaceCode(implTypeSymbol, attribute), Encoding.UTF8);
|
||||
|
||||
context.AddSource($"{implTypeSymbol.GetFullMetadataName(useNameWhenNotFound: true)}_AutoInterface.g.cs", source);
|
||||
}
|
||||
}
|
||||
|
||||
private static string InferVisibilityModifier(ISymbol implTypeSymbol, AttributeData attributeData)
|
||||
{
|
||||
string? result = attributeData.GetNamedParamValue(Attributes.VisibilityModifierPropName);
|
||||
if (!string.IsNullOrEmpty(result))
|
||||
{
|
||||
return result ?? throw new NullReferenceException("result is null");
|
||||
}
|
||||
|
||||
return implTypeSymbol.DeclaredAccessibility switch
|
||||
{
|
||||
Accessibility.Public => "public",
|
||||
_ => "internal",
|
||||
};
|
||||
}
|
||||
|
||||
private static string InferInterfaceName(ISymbol implTypeSymbol, AttributeData attributeData)
|
||||
{
|
||||
return attributeData.GetNamedParamValue(Attributes.InterfaceNamePropName) ?? $"I{implTypeSymbol.Name}";
|
||||
}
|
||||
|
||||
private string GenerateInterfaceCode(INamedTypeSymbol implTypeSymbol, AttributeData attributeData)
|
||||
{
|
||||
using var stream = new MemoryStream();
|
||||
var streamWriter = new StreamWriter(stream, Encoding.UTF8);
|
||||
var codeWriter = new IndentedTextWriter(streamWriter, " ");
|
||||
|
||||
var namespaceName = implTypeSymbol.ContainingNamespace.ToDisplayString();
|
||||
var interfaceName = InferInterfaceName(implTypeSymbol, attributeData);
|
||||
var visibilityModifier = InferVisibilityModifier(implTypeSymbol, attributeData);
|
||||
|
||||
codeWriter.WriteLine("namespace {0}", namespaceName);
|
||||
codeWriter.WriteLine("{");
|
||||
|
||||
++codeWriter.Indent;
|
||||
WriteSymbolDocsIfPresent(codeWriter, implTypeSymbol);
|
||||
codeWriter.Write("{0} partial interface {1}", visibilityModifier, interfaceName);
|
||||
WriteTypeGenericsIfNeeded(codeWriter, implTypeSymbol);
|
||||
codeWriter.WriteLine();
|
||||
codeWriter.WriteLine("{");
|
||||
|
||||
++codeWriter.Indent;
|
||||
GenerateInterfaceMemberDefinitions(codeWriter, implTypeSymbol);
|
||||
--codeWriter.Indent;
|
||||
|
||||
codeWriter.WriteLine("}");
|
||||
--codeWriter.Indent;
|
||||
|
||||
codeWriter.WriteLine("}");
|
||||
|
||||
codeWriter.Flush();
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8, true);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
private static void WriteTypeGenericsIfNeeded(TextWriter writer, INamedTypeSymbol implTypeSymbol)
|
||||
{
|
||||
if (!implTypeSymbol.IsGenericType)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
writer.Write("<");
|
||||
writer.WriteJoin(", ", implTypeSymbol.TypeParameters.Select(x => x.Name));
|
||||
writer.Write(">");
|
||||
|
||||
WriteTypeParameterConstraints(writer, implTypeSymbol.TypeParameters);
|
||||
}
|
||||
|
||||
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")))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
GenerateInterfaceMemberDefinition(writer, member);
|
||||
}
|
||||
}
|
||||
|
||||
private static void GenerateInterfaceMemberDefinition(TextWriter writer, ISymbol member)
|
||||
{
|
||||
switch (member)
|
||||
{
|
||||
case IPropertySymbol propertySymbol:
|
||||
GeneratePropertyDefinition(writer, propertySymbol);
|
||||
break;
|
||||
case IMethodSymbol methodSymbol:
|
||||
GenerateMethodDefinition(writer, methodSymbol);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteSymbolDocsIfPresent(TextWriter writer, ISymbol symbol)
|
||||
{
|
||||
var xml = symbol.GetDocumentationCommentXml();
|
||||
if (string.IsNullOrWhiteSpace(xml))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// omit the fist and last lines to skip the <member> tag
|
||||
|
||||
var reader = new StringReader(xml);
|
||||
var lines = new List<string>();
|
||||
|
||||
while (true)
|
||||
{
|
||||
var line = reader.ReadLine();
|
||||
if (line is null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
lines.Add(line);
|
||||
}
|
||||
|
||||
for (int i = 1; i < lines.Count - 1; i++)
|
||||
{
|
||||
var line = lines[i].TrimStart(); // for some reason, 4 spaces are inserted to the beginning of the line
|
||||
writer.WriteLine("/// {0}", line);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsPublicOrInternal(ISymbol symbol)
|
||||
{
|
||||
return symbol.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal;
|
||||
}
|
||||
|
||||
private static void GeneratePropertyDefinition(TextWriter writer, IPropertySymbol propertySymbol)
|
||||
{
|
||||
if (propertySymbol.IsStatic)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool hasPublicGetter = propertySymbol.GetMethod is not null &&
|
||||
IsPublicOrInternal(propertySymbol.GetMethod);
|
||||
|
||||
bool hasPublicSetter = propertySymbol.SetMethod is not null &&
|
||||
IsPublicOrInternal(propertySymbol.SetMethod);
|
||||
|
||||
if (!hasPublicGetter && !hasPublicSetter)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
WriteSymbolDocsIfPresent(writer, propertySymbol);
|
||||
|
||||
if (propertySymbol.IsIndexer)
|
||||
{
|
||||
writer.Write("{0} this[", propertySymbol.Type);
|
||||
writer.WriteJoin(", ", propertySymbol.Parameters, WriteMethodParam);
|
||||
writer.Write("] ");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.Write("{0} {1} ", propertySymbol.Type, propertySymbol.Name); // ex. int Foo
|
||||
}
|
||||
|
||||
writer.Write("{ ");
|
||||
|
||||
if (hasPublicGetter)
|
||||
{
|
||||
writer.Write("get; ");
|
||||
}
|
||||
|
||||
if (hasPublicSetter)
|
||||
{
|
||||
if (propertySymbol.SetMethod?.IsInitOnly ?? false)
|
||||
{
|
||||
writer.Write("init; ");
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.Write("set; ");
|
||||
}
|
||||
}
|
||||
|
||||
writer.WriteLine("}");
|
||||
}
|
||||
|
||||
private static void GenerateMethodDefinition(TextWriter writer, IMethodSymbol methodSymbol)
|
||||
{
|
||||
if (methodSymbol.MethodKind != MethodKind.Ordinary || methodSymbol.IsStatic)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (methodSymbol.IsImplicitlyDeclared && methodSymbol.Name != "Deconstruct")
|
||||
{
|
||||
// omit methods that are auto generated by the compiler (eg. record's methods),
|
||||
// except for the record Deconstruct method
|
||||
return;
|
||||
}
|
||||
|
||||
WriteSymbolDocsIfPresent(writer, methodSymbol);
|
||||
|
||||
writer.Write("{0} {1}", methodSymbol.ReturnType, methodSymbol.Name); // ex. int Foo
|
||||
|
||||
if (methodSymbol.IsGenericMethod)
|
||||
{
|
||||
writer.Write("<");
|
||||
writer.WriteJoin(", ", methodSymbol.TypeParameters.Select(x => x.Name));
|
||||
writer.Write(">");
|
||||
}
|
||||
|
||||
writer.Write("(");
|
||||
writer.WriteJoin(", ", methodSymbol.Parameters, WriteMethodParam);
|
||||
|
||||
writer.Write(")");
|
||||
|
||||
if (methodSymbol.IsGenericMethod)
|
||||
{
|
||||
WriteTypeParameterConstraints(writer, methodSymbol.TypeParameters);
|
||||
}
|
||||
|
||||
writer.WriteLine(";");
|
||||
}
|
||||
|
||||
private static void WriteMethodParam(TextWriter writer, IParameterSymbol param)
|
||||
{
|
||||
if (param.IsParams)
|
||||
{
|
||||
writer.Write("params ");
|
||||
}
|
||||
|
||||
switch (param.RefKind)
|
||||
{
|
||||
case RefKind.Ref:
|
||||
writer.Write("ref ");
|
||||
break;
|
||||
case RefKind.Out:
|
||||
writer.Write("out ");
|
||||
break;
|
||||
case RefKind.In:
|
||||
writer.Write("in ");
|
||||
break;
|
||||
}
|
||||
|
||||
writer.Write(param.Type);
|
||||
writer.Write(" ");
|
||||
|
||||
if (StringExtensions.IsCSharpKeyword(param.Name))
|
||||
{
|
||||
writer.Write("@");
|
||||
}
|
||||
|
||||
writer.Write(param.Name);
|
||||
|
||||
if (param.HasExplicitDefaultValue)
|
||||
{
|
||||
WriteParamExplicitDefaultValue(writer, param);
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteParamExplicitDefaultValue(TextWriter writer, IParameterSymbol param)
|
||||
{
|
||||
if (param.ExplicitDefaultValue is null)
|
||||
{
|
||||
writer.Write(" = default");
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (param.Type.Name)
|
||||
{
|
||||
case nameof(String):
|
||||
writer.Write(" = \"{0}\"", param.ExplicitDefaultValue);
|
||||
break;
|
||||
case nameof(Single):
|
||||
writer.Write(" = {0}f", param.ExplicitDefaultValue);
|
||||
break;
|
||||
case nameof(Double):
|
||||
writer.Write(" = {0}d", param.ExplicitDefaultValue);
|
||||
break;
|
||||
case nameof(Decimal):
|
||||
writer.Write(" = {0}m", param.ExplicitDefaultValue);
|
||||
break;
|
||||
case nameof(Boolean):
|
||||
writer.Write(" = {0}", param.ExplicitDefaultValue.ToString().ToLower());
|
||||
break;
|
||||
case nameof(Nullable<bool>):
|
||||
writer.Write(" = {0}", param.ExplicitDefaultValue.ToString().ToLower());
|
||||
break;
|
||||
default:
|
||||
writer.Write(" = {0}", param.ExplicitDefaultValue);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteTypeParameterConstraints(
|
||||
TextWriter writer,
|
||||
IEnumerable<ITypeParameterSymbol> typeParameters)
|
||||
{
|
||||
foreach (var typeParameter in typeParameters)
|
||||
{
|
||||
var constraints = typeParameter.EnumGenericConstraints().ToList();
|
||||
if (constraints.Count == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
writer.Write(" where {0} : ", typeParameter.Name);
|
||||
writer.WriteJoin(", ", constraints);
|
||||
}
|
||||
}
|
||||
|
||||
private void InitAttributes(Compilation compilation)
|
||||
{
|
||||
_generateAutoInterfaceAttribute = compilation.GetTypeByMetadataName(
|
||||
$"{Attributes.AttributesNamespace}.{Attributes.GenerateAutoInterfaceClassname}");
|
||||
|
||||
_ignoreAttribute = compilation.GetTypeByMetadataName(
|
||||
$"{Attributes.AttributesNamespace}.{Attributes.AutoInterfaceIgnoreAttributeClassname}");
|
||||
}
|
||||
|
||||
private static IEnumerable<INamedTypeSymbol> GetImplTypeSymbols(Compilation compilation, SyntaxReceiver receiver)
|
||||
{
|
||||
return receiver.CandidateTypes.Select(candidate => GetTypeSymbol(compilation, candidate)).Where(x => x != null).Cast<INamedTypeSymbol>();
|
||||
}
|
||||
|
||||
private static INamedTypeSymbol? GetTypeSymbol(Compilation compilation, SyntaxNode type)
|
||||
{
|
||||
var model = compilation.GetSemanticModel(type.SyntaxTree);
|
||||
var typeSymbol = model.GetDeclaredSymbol(type);
|
||||
return typeSymbol as INamedTypeSymbol;
|
||||
}
|
||||
|
||||
private static Compilation GetCompilation(GeneratorExecutionContext context)
|
||||
{
|
||||
var options = context.Compilation.SyntaxTrees.First().Options as CSharpParseOptions;
|
||||
|
||||
var compilation = context.Compilation.AddSyntaxTrees(
|
||||
CSharpSyntaxTree.ParseText(
|
||||
SourceText.From(Attributes.AttributesSourceCode, Encoding.UTF8), options));
|
||||
|
||||
return compilation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2</TargetFramework>
|
||||
<LangVersion>Latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<PackageVersion>0.9.0</PackageVersion>
|
||||
|
||||
<developmentDependency>true</developmentDependency>
|
||||
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
|
||||
<IncludeBuildOutput>false</IncludeBuildOutput>
|
||||
<NoPackageAnalysis>true</NoPackageAnalysis>
|
||||
<RootNamespace>Speckle.InterfaceGenerator</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<Title>Speckle.InterfaceGenerator</Title>
|
||||
<Description>A source generator that creates interfaces from implementations</Description>
|
||||
<PackageProjectUrl>https://github.com/specklesystems/InterfaceGenerator</PackageProjectUrl>
|
||||
<PackageLicenseUrl>https://github.com/specklesystems/InterfaceGenerator/blob/master/LICENSE</PackageLicenseUrl>
|
||||
<RepositoryUrl>https://github.com/specklesystems/InterfaceGenerator</RepositoryUrl>
|
||||
<RepositoryType>git</RepositoryType>
|
||||
</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" >
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,124 @@
|
||||
namespace Speckle.InterfaceGenerator;
|
||||
|
||||
internal static class StringExtensions
|
||||
{
|
||||
public static bool IsCSharpKeyword(string? name)
|
||||
{
|
||||
switch (name)
|
||||
{
|
||||
case "abstract":
|
||||
case "add":
|
||||
case "alias":
|
||||
case "as":
|
||||
case "ascending":
|
||||
case "async":
|
||||
case "await":
|
||||
case "base":
|
||||
case "bool":
|
||||
case "break":
|
||||
case "by":
|
||||
case "byte":
|
||||
case "case":
|
||||
case "catch":
|
||||
case "char":
|
||||
case "checked":
|
||||
case "class":
|
||||
case "const":
|
||||
case "continue":
|
||||
case "decimal":
|
||||
case "default":
|
||||
case "delegate":
|
||||
case "descending":
|
||||
case "do":
|
||||
case "double":
|
||||
case "dynamic":
|
||||
case "else":
|
||||
case "enum":
|
||||
case "equals":
|
||||
case "event":
|
||||
case "explicit":
|
||||
case "extern":
|
||||
case "false":
|
||||
case "finally":
|
||||
case "fixed":
|
||||
case "float":
|
||||
case "for":
|
||||
case "foreach":
|
||||
case "from":
|
||||
case "get":
|
||||
case "global":
|
||||
case "goto":
|
||||
// `group` is a contextual to linq queries that we don't generate
|
||||
//case "group":
|
||||
case "if":
|
||||
case "implicit":
|
||||
case "in":
|
||||
case "int":
|
||||
case "interface":
|
||||
case "internal":
|
||||
case "into":
|
||||
case "is":
|
||||
case "join":
|
||||
case "let":
|
||||
case "lock":
|
||||
case "long":
|
||||
case "nameof":
|
||||
case "namespace":
|
||||
case "new":
|
||||
case "null":
|
||||
case "object":
|
||||
case "on":
|
||||
case "operator":
|
||||
// `orderby` is a contextual to linq queries that we don't generate
|
||||
//case "orderby":
|
||||
case "out":
|
||||
case "override":
|
||||
case "params":
|
||||
case "partial":
|
||||
case "private":
|
||||
case "protected":
|
||||
case "public":
|
||||
case "readonly":
|
||||
case "ref":
|
||||
case "remove":
|
||||
case "return":
|
||||
case "sbyte":
|
||||
case "sealed":
|
||||
// `select` is a contextual to linq queries that we don't generate
|
||||
// case "select":
|
||||
case "set":
|
||||
case "short":
|
||||
case "sizeof":
|
||||
case "stackalloc":
|
||||
case "static":
|
||||
case "string":
|
||||
case "struct":
|
||||
case "switch":
|
||||
case "this":
|
||||
case "throw":
|
||||
case "true":
|
||||
case "try":
|
||||
case "typeof":
|
||||
case "uint":
|
||||
case "ulong":
|
||||
case "unchecked":
|
||||
case "unmanaged":
|
||||
case "unsafe":
|
||||
case "ushort":
|
||||
case "using":
|
||||
// `value` is a contextual to getters that we don't generate
|
||||
// case "value":
|
||||
case "var":
|
||||
case "virtual":
|
||||
case "void":
|
||||
case "volatile":
|
||||
case "when":
|
||||
case "where":
|
||||
case "while":
|
||||
case "yield":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace Speckle.InterfaceGenerator;
|
||||
|
||||
internal static class SymbolExtensions
|
||||
{
|
||||
public static bool TryGetAttribute(
|
||||
this ISymbol symbol,
|
||||
INamedTypeSymbol attributeType,
|
||||
out IEnumerable<AttributeData> attributes)
|
||||
{
|
||||
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()
|
||||
.Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeType));
|
||||
}
|
||||
|
||||
//Ref: https://stackoverflow.com/questions/27105909/get-fully-qualified-metadata-name-in-roslyn
|
||||
public static string GetFullMetadataName(this ISymbol symbol, bool useNameWhenNotFound = false)
|
||||
{
|
||||
if (IsRootNamespace(symbol))
|
||||
{
|
||||
return useNameWhenNotFound ? symbol.Name : string.Empty;
|
||||
}
|
||||
|
||||
var stringBuilder = new StringBuilder(symbol.MetadataName);
|
||||
var last = symbol;
|
||||
|
||||
symbol = symbol.ContainingSymbol;
|
||||
|
||||
while (!IsRootNamespace(symbol))
|
||||
{
|
||||
if (symbol is ITypeSymbol && last is ITypeSymbol)
|
||||
{
|
||||
stringBuilder.Insert(0, '+');
|
||||
}
|
||||
else
|
||||
{
|
||||
stringBuilder.Insert(0, '.');
|
||||
}
|
||||
|
||||
stringBuilder.Insert(0, symbol.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
|
||||
symbol = symbol.ContainingSymbol;
|
||||
}
|
||||
|
||||
var retVal = stringBuilder.ToString();
|
||||
if (string.IsNullOrWhiteSpace(retVal) && useNameWhenNotFound)
|
||||
{
|
||||
return symbol.Name;
|
||||
}
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
private static bool IsRootNamespace(ISymbol symbol)
|
||||
{
|
||||
return symbol is INamespaceSymbol { IsGlobalNamespace: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace Speckle.InterfaceGenerator;
|
||||
|
||||
internal class SyntaxReceiver : ISyntaxReceiver
|
||||
{
|
||||
public IList<TypeDeclarationSyntax> CandidateTypes { get; } = new List<TypeDeclarationSyntax>();
|
||||
|
||||
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
|
||||
{
|
||||
if (syntaxNode is TypeDeclarationSyntax typeDeclarationSyntax &&
|
||||
IsClassOrRecord(typeDeclarationSyntax) &&
|
||||
typeDeclarationSyntax.AttributeLists.Count > 0)
|
||||
{
|
||||
CandidateTypes.Add(typeDeclarationSyntax);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsClassOrRecord(TypeDeclarationSyntax typeDeclarationSyntax)
|
||||
{
|
||||
return typeDeclarationSyntax is ClassDeclarationSyntax || typeDeclarationSyntax is RecordDeclarationSyntax;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace Speckle.InterfaceGenerator;
|
||||
|
||||
internal static class TextWriterExtensions
|
||||
{
|
||||
|
||||
public static void WriteJoin<T>(
|
||||
this TextWriter writer,
|
||||
string separator,
|
||||
IEnumerable<T> values)
|
||||
{
|
||||
writer.WriteJoin(separator, values, (w, x) => w.Write(x));
|
||||
}
|
||||
|
||||
public static void WriteJoin<T>(
|
||||
this TextWriter writer,
|
||||
string separator,
|
||||
IEnumerable<T> values,
|
||||
Action<TextWriter, T> writeAction)
|
||||
{
|
||||
using var enumerator = values.GetEnumerator();
|
||||
|
||||
if (!enumerator.MoveNext())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
writeAction(writer, enumerator.Current);
|
||||
|
||||
if (!enumerator.MoveNext())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
do
|
||||
{
|
||||
writer.Write(separator);
|
||||
writeAction(writer, enumerator.Current);
|
||||
} while (enumerator.MoveNext());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace Speckle.InterfaceGenerator;
|
||||
|
||||
internal static class TypeParameterSymbolExtensions
|
||||
{
|
||||
public static IEnumerable<string> EnumGenericConstraints(this ITypeParameterSymbol symbol)
|
||||
{
|
||||
// the class/struct/unmanaged/notnull constraint has to be the last
|
||||
if (symbol.HasNotNullConstraint)
|
||||
{
|
||||
yield return "notnull";
|
||||
}
|
||||
|
||||
if (symbol.HasValueTypeConstraint)
|
||||
{
|
||||
yield return "struct";
|
||||
}
|
||||
|
||||
if (symbol.HasUnmanagedTypeConstraint)
|
||||
{
|
||||
yield return "unmanaged";
|
||||
}
|
||||
|
||||
if (symbol.HasReferenceTypeConstraint)
|
||||
{
|
||||
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)
|
||||
{
|
||||
yield return "new()";
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user