From b523a2bb2ae272c0d9766b2f499b753ea900a597 Mon Sep 17 00:00:00 2001
From: DismissedLight <1686188646@qq.com>
Date: Tue, 28 Nov 2023 22:05:02 +0800
Subject: [PATCH] 1.8.3 package
---
.gitignore | 4 +-
.../Automation/AttributeGenerator.cs | 167 -----
.../Automation/CommandGenerator.cs | 98 ---
.../Automation/ConstructorGenerator.cs | 193 ------
.../Automation/DependencyPropertyGenerator.cs | 130 ----
.../Automation/SaltConstantGenerator.cs | 72 --
.../CodeAnalysis/NotNullWhenAttribute.cs | 18 -
.../HttpClientGenerator.cs | 145 ----
.../DependencyInjection/InjectionGenerator.cs | 145 ----
.../DependencyInjection/ServiceAnalyzer.cs | 78 ---
.../Enum/LocalizedEnumGenerator.cs | 136 ----
.../GlobalSuppressions.cs | 8 -
.../Identity/IdentityGenerator.cs | 202 ------
.../Snap.Hutao.SourceGeneration/JsonParser.cs | 439 ------------
.../Primitive/AttributeDataExtension.cs | 32 -
.../Primitive/EnumerableExtension.cs | 41 --
.../Primitive/GeneratorSyntaxContext2.cs | 77 ---
.../GeneratorSyntaxContextExtension.cs | 18 -
.../Primitive/SymbolDisplayFormats.cs | 21 -
.../Primitive/SyntaxExtension.cs | 20 -
.../Primitive/TypeSymbolExtension.cs | 28 -
.../Resx/ResxGenerator.cs | 629 ------------------
.../Resx/StringExtensions.cs | 27 -
.../Snap.Hutao.SourceGeneration.csproj | 19 -
.../UniversalAnalyzer.cs | 302 ---------
.../Snap.Hutao.SourceGeneration/stylecop.json | 23 -
src/Snap.Hutao/Snap.Hutao.sln | 28 +-
.../Snap.Hutao/Package.appxmanifest | 2 +-
.../Package.development.appxmanifest | 2 +-
.../PublishProfiles/FolderProfile.pubxml | 19 +
src/Snap.Hutao/Snap.Hutao/Snap.Hutao.csproj | 20 +-
31 files changed, 43 insertions(+), 3100 deletions(-)
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/AttributeGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/CommandGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/ConstructorGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/DependencyPropertyGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/SaltConstantGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/CodeAnalysis/NotNullWhenAttribute.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/HttpClientGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/InjectionGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/ServiceAnalyzer.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Enum/LocalizedEnumGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/GlobalSuppressions.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Identity/IdentityGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/JsonParser.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Primitive/AttributeDataExtension.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Primitive/EnumerableExtension.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Primitive/GeneratorSyntaxContext2.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Primitive/GeneratorSyntaxContextExtension.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Primitive/SymbolDisplayFormats.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Primitive/SyntaxExtension.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Primitive/TypeSymbolExtension.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Resx/ResxGenerator.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Resx/StringExtensions.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/Snap.Hutao.SourceGeneration.csproj
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/UniversalAnalyzer.cs
delete mode 100644 src/Snap.Hutao/Snap.Hutao.SourceGeneration/stylecop.json
create mode 100644 src/Snap.Hutao/Snap.Hutao/Properties/PublishProfiles/FolderProfile.pubxml
diff --git a/.gitignore b/.gitignore
index 2f91f8dc..130e1dc2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,6 @@
desktop.ini
*.csproj.user
-*.pubxml
*.DotSettings.user
.vs/
@@ -20,4 +19,5 @@ src/Snap.Hutao/Snap.Hutao.SourceGeneration/bin/
src/Snap.Hutao/Snap.Hutao.SourceGeneration/obj/
src/Snap.Hutao/Snap.Hutao.Test/bin/
-src/Snap.Hutao/Snap.Hutao.Test/obj/
\ No newline at end of file
+src/Snap.Hutao/Snap.Hutao.Test/obj/
+src/Snap.Hutao/Snap.Hutao/Properties/PublishProfiles/FolderProfile.pubxml.user
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/AttributeGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/AttributeGenerator.cs
deleted file mode 100644
index 80e068fe..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/AttributeGenerator.cs
+++ /dev/null
@@ -1,167 +0,0 @@
-// Copyright (c) DGP Studio. All rights reserved.
-// Licensed under the MIT license.
-
-using Microsoft.CodeAnalysis;
-
-namespace Snap.Hutao.SourceGeneration.Automation;
-
-[Generator(LanguageNames.CSharp)]
-internal sealed class AttributeGenerator : IIncrementalGenerator
-{
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- context.RegisterPostInitializationOutput(GenerateAllAttributes);
- }
-
- public static void GenerateAllAttributes(IncrementalGeneratorPostInitializationContext context)
- {
- string coreAnnotations = """
- using System.Diagnostics;
-
- namespace Snap.Hutao.Core.Annotation;
-
- [AttributeUsage(AttributeTargets.Method, Inherited = false)]
- internal sealed class CommandAttribute : Attribute
- {
- public CommandAttribute(string name)
- {
- }
-
- public bool AllowConcurrentExecutions { get; set; }
- }
-
- [AttributeUsage(AttributeTargets.Class, Inherited = false)]
- internal sealed class ConstructorGeneratedAttribute : Attribute
- {
- public ConstructorGeneratedAttribute()
- {
- }
-
- public bool CallBaseConstructor { get; set; }
- public bool ResolveHttpClient { get; set; }
- }
-
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
- internal sealed class DependencyPropertyAttribute : Attribute
- {
- public DependencyPropertyAttribute(string name, Type type)
- {
- }
-
- public DependencyPropertyAttribute(string name, Type type, object defaultValue)
- {
- }
-
- public DependencyPropertyAttribute(string name, Type type, object defaultValue, string valueChangedCallbackName)
- {
- }
-
- public bool IsAttached { get; set; }
- public Type AttachedType { get; set; } = default;
- }
-
- [AttributeUsage(AttributeTargets.All, Inherited = false)]
- [Conditional("DEBUG")]
- internal sealed class HighQualityAttribute : Attribute
- {
- }
- """;
- context.AddSource("Snap.Hutao.Core.Annotation.Attributes.g.cs", coreAnnotations);
-
- string coreDependencyInjectionAnnotationHttpClients = """
- namespace Snap.Hutao.Core.DependencyInjection.Annotation.HttpClient;
-
- [AttributeUsage(AttributeTargets.Class, Inherited = false)]
- internal sealed class HttpClientAttribute : Attribute
- {
- public HttpClientAttribute(HttpClientConfiguration configuration)
- {
- }
-
- public HttpClientAttribute(HttpClientConfiguration configuration, Type interfaceType)
- {
- }
- }
-
- internal enum HttpClientConfiguration
- {
- ///
- /// 默认配置
- ///
- Default,
-
- ///
- /// 米游社请求配置
- ///
- XRpc,
-
- ///
- /// 米游社登录请求配置
- ///
- XRpc2,
-
- ///
- /// Hoyolab app
- ///
- XRpc3,
- }
-
- [AttributeUsage(AttributeTargets.Class, Inherited = false)]
- internal sealed class PrimaryHttpMessageHandlerAttribute : Attribute
- {
- ///
- public int MaxConnectionsPerServer { get; set; }
-
- ///
- ///
- ///
- public bool UseCookies { get; set; }
- }
- """;
- context.AddSource("Snap.Hutao.Core.DependencyInjection.Annotation.HttpClient.Attributes.g.cs", coreDependencyInjectionAnnotationHttpClients);
-
- string coreDependencyInjectionAnnotations = """
- namespace Snap.Hutao.Core.DependencyInjection.Annotation;
-
- internal enum InjectAs
- {
- Singleton,
- Transient,
- Scoped,
- }
-
- [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
- internal sealed class InjectionAttribute : Attribute
- {
- public InjectionAttribute(InjectAs injectAs)
- {
- }
-
- public InjectionAttribute(InjectAs injectAs, Type interfaceType)
- {
- }
-
- public object Key { get; set; }
- }
- """;
- context.AddSource("Snap.Hutao.Core.DependencyInjection.Annotation.Attributes.g.cs", coreDependencyInjectionAnnotations);
-
- string resourceLocalization = """
- namespace Snap.Hutao.Resource.Localization;
-
- [AttributeUsage(AttributeTargets.Enum)]
- internal sealed class LocalizationAttribute : Attribute
- {
- }
-
- [AttributeUsage(AttributeTargets.Field)]
- internal sealed class LocalizationKeyAttribute : Attribute
- {
- public LocalizationKeyAttribute(string key)
- {
- }
- }
- """;
- context.AddSource("Snap.Hutao.Resource.Localization.Attributes.g.cs", resourceLocalization);
- }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/CommandGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/CommandGenerator.cs
deleted file mode 100644
index 83b1d206..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/CommandGenerator.cs
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright (c) DGP Studio. All rights reserved.
-// Licensed under the MIT license.
-
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Snap.Hutao.SourceGeneration.Primitive;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Threading;
-
-namespace Snap.Hutao.SourceGeneration.Automation;
-
-[Generator(LanguageNames.CSharp)]
-internal sealed class CommandGenerator : IIncrementalGenerator
-{
- public const string AttributeName = "Snap.Hutao.Core.Annotation.CommandAttribute";
-
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- IncrementalValueProvider>> commands =
- context.SyntaxProvider.CreateSyntaxProvider(FilterAttributedMethods, CommandMethod)
- .Where(GeneratorSyntaxContext2.NotNull)
- .Collect();
-
- context.RegisterImplementationSourceOutput(commands, GenerateCommandImplementations);
- }
-
- private static bool FilterAttributedMethods(SyntaxNode node, CancellationToken token)
- {
- return node is MethodDeclarationSyntax methodDeclarationSyntax
- && methodDeclarationSyntax.Parent is ClassDeclarationSyntax classDeclarationSyntax
- && classDeclarationSyntax.Modifiers.Count > 1
- && methodDeclarationSyntax.HasAttributeLists();
- }
-
- private static GeneratorSyntaxContext2 CommandMethod(GeneratorSyntaxContext context, CancellationToken token)
- {
- if (context.TryGetDeclaredSymbol(token, out IMethodSymbol? methodSymbol))
- {
- ImmutableArray attributes = methodSymbol.GetAttributes();
- if (attributes.Any(data => data.AttributeClass!.ToDisplayString() == AttributeName))
- {
- return new(context, methodSymbol, attributes);
- }
- }
-
- return default;
- }
-
- private static void GenerateCommandImplementations(SourceProductionContext production, ImmutableArray> context2s)
- {
- foreach (GeneratorSyntaxContext2 context2 in context2s.DistinctBy(c => c.Symbol.ToDisplayString()))
- {
- GenerateCommandImplementation(production, context2);
- }
- }
-
- private static void GenerateCommandImplementation(SourceProductionContext production, GeneratorSyntaxContext2 context2)
- {
- INamedTypeSymbol classSymbol = context2.Symbol.ContainingType;
-
- AttributeData commandInfo = context2.SingleAttribute(AttributeName);
- string commandName = (string)commandInfo.ConstructorArguments[0].Value!;
-
- string commandType = context2.Symbol.ReturnType.IsOrInheritsFrom("System.Threading.Tasks.Task")
- ? "AsyncRelayCommand"
- : "RelayCommand";
-
- string genericParameter = context2.Symbol.Parameters.ElementAtOrDefault(0) is IParameterSymbol parameter
- ? $"<{parameter.Type.ToDisplayString(SymbolDisplayFormats.FullyQualifiedNonNullableFormat)}>"
- : string.Empty;
-
- string concurrentExecution = commandInfo.HasNamedArgumentWith("AllowConcurrentExecutions", value => value)
- ? ", AsyncRelayCommandOptions.AllowConcurrentExecutions"
- : string.Empty;
-
- string className = classSymbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
-
- string code = $$"""
- using CommunityToolkit.Mvvm.Input;
-
- namespace {{classSymbol.ContainingNamespace}};
-
- partial class {{className}}
- {
- private ICommand _{{commandName}};
-
- public ICommand {{commandName}}
- {
- get => _{{commandName}} ??= new {{commandType}}{{genericParameter}}({{context2.Symbol.Name}}{{concurrentExecution}});
- }
- }
- """;
-
- string normalizedClassName = classSymbol.ToDisplayString().Replace('<', '{').Replace('>', '}');
- production.AddSource($"{normalizedClassName}.{commandName}.g.cs", code);
- }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/ConstructorGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/ConstructorGenerator.cs
deleted file mode 100644
index 0d005188..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/ConstructorGenerator.cs
+++ /dev/null
@@ -1,193 +0,0 @@
-// Copyright (c) DGP Studio. All rights reserved.
-// Licensed under the MIT license.
-
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Snap.Hutao.SourceGeneration.Primitive;
-using System;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Text;
-using System.Threading;
-
-namespace Snap.Hutao.SourceGeneration.Automation;
-
-[Generator(LanguageNames.CSharp)]
-internal sealed class ConstructorGenerator : IIncrementalGenerator
-{
- private const string AttributeName = "Snap.Hutao.Core.Annotation.ConstructorGeneratedAttribute";
- private const string CompilerGenerated = "System.Runtime.CompilerServices.CompilerGeneratedAttribute";
-
- //private static readonly DiagnosticDescriptor genericTypeNotSupportedDescriptor = new("SH102", "Generic type is not supported to generate .ctor", "Type [{0}] is not supported", "Quality", DiagnosticSeverity.Error, true);
-
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- IncrementalValueProvider> injectionClasses =
- context.SyntaxProvider.CreateSyntaxProvider(FilterAttributedClasses, ConstructorGeneratedClass)
- .Where(GeneratorSyntaxContext2.NotNull)
- .Collect();
-
- context.RegisterSourceOutput(injectionClasses, GenerateConstructorImplementations);
- }
-
- private static bool FilterAttributedClasses(SyntaxNode node, CancellationToken token)
- {
- return node is ClassDeclarationSyntax classDeclarationSyntax
- && classDeclarationSyntax.Modifiers.Count > 1
- && classDeclarationSyntax.HasAttributeLists();
- }
-
- private static GeneratorSyntaxContext2 ConstructorGeneratedClass(GeneratorSyntaxContext context, CancellationToken token)
- {
- if (context.TryGetDeclaredSymbol(token, out INamedTypeSymbol? classSymbol))
- {
- ImmutableArray attributes = classSymbol.GetAttributes();
- if (attributes.Any(data => data.AttributeClass!.ToDisplayString() == AttributeName))
- {
- return new(context, classSymbol, attributes);
- }
- }
-
- return default;
- }
-
- private static void GenerateConstructorImplementations(SourceProductionContext production, ImmutableArray context2s)
- {
- foreach (GeneratorSyntaxContext2 context2 in context2s.DistinctBy(c => c.Symbol.ToDisplayString()))
- {
- GenerateConstructorImplementation(production, context2);
- }
- }
-
- private static void GenerateConstructorImplementation(SourceProductionContext production, GeneratorSyntaxContext2 context2)
- {
- AttributeData constructorInfo = context2.SingleAttribute(AttributeName);
-
- bool resolveHttpClient = constructorInfo.HasNamedArgumentWith("ResolveHttpClient", value => value);
- bool callBaseConstructor = constructorInfo.HasNamedArgumentWith("CallBaseConstructor", value => value);
- string httpclient = resolveHttpClient ? ", System.Net.Http.HttpClient httpClient" : string.Empty;
-
- FieldValueAssignmentOptions options = new(resolveHttpClient, callBaseConstructor);
-
- StringBuilder sourceBuilder = new StringBuilder().Append($$"""
- namespace {{context2.Symbol.ContainingNamespace}};
-
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{nameof(ConstructorGenerator)}}", "1.0.0.0")]
- partial class {{context2.Symbol.ToDisplayString(SymbolDisplayFormats.QualifiedNonNullableFormat)}}
- {
- public {{context2.Symbol.Name}}(System.IServiceProvider serviceProvider{{httpclient}}){{(options.CallBaseConstructor ? " : base(serviceProvider)" : string.Empty)}}
- {
-
- """);
-
- FillUpWithFieldValueAssignment(sourceBuilder, context2, options);
-
- sourceBuilder.Append("""
- }
- }
- """);
-
- string normalizedClassName = context2.Symbol.ToDisplayString().Replace('<', '{').Replace('>', '}');
- production.AddSource($"{normalizedClassName}.ctor.g.cs", sourceBuilder.ToString());
- }
-
- private static void FillUpWithFieldValueAssignment(StringBuilder builder, GeneratorSyntaxContext2 context2, FieldValueAssignmentOptions options)
- {
- IEnumerable fields = context2.Symbol.GetMembers()
- .Where(m => m.Kind == SymbolKind.Field)
- .OfType();
-
- foreach (IFieldSymbol fieldSymbol in fields)
- {
- if (fieldSymbol.Name.AsSpan()[0] is '<')
- {
- continue;
- }
-
- bool shoudSkip = false;
- foreach (SyntaxReference syntaxReference in fieldSymbol.DeclaringSyntaxReferences)
- {
- if (syntaxReference.GetSyntax() is VariableDeclaratorSyntax declarator)
- {
- if (declarator.Initializer is not null)
- {
- // Skip field with initializer
- builder.Append(" // Skip field with initializer: ").AppendLine(fieldSymbol.Name);
- shoudSkip = true;
- break;
- }
- }
- }
-
- if (shoudSkip)
- {
- continue;
- }
-
- if (fieldSymbol.IsReadOnly && !fieldSymbol.IsStatic)
- {
- switch (fieldSymbol.Type.ToDisplayString())
- {
- case "System.IServiceProvider":
- builder
- .Append(" this.")
- .Append(fieldSymbol.Name)
- .AppendLine(" = serviceProvider;");
- break;
-
- case "System.Net.Http.HttpClient":
- if (options.ResolveHttpClient)
- {
- builder
- .Append(" this.")
- .Append(fieldSymbol.Name)
- .AppendLine(" = httpClient;");
- }
- else
- {
- builder
- .Append(" this.")
- .Append(fieldSymbol.Name)
- .Append(" = serviceProvider.GetRequiredService().CreateClient(nameof(")
- .Append(context2.Symbol.Name)
- .AppendLine("));");
- }
- break;
-
- default:
- builder
- .Append(" this.")
- .Append(fieldSymbol.Name)
- .Append(" = serviceProvider.GetRequiredService<")
- .Append(fieldSymbol.Type)
- .AppendLine(">();");
- break;
- }
- }
- }
-
- foreach (INamedTypeSymbol interfaceSymbol in context2.Symbol.Interfaces)
- {
- if (interfaceSymbol.Name == "IRecipient")
- {
- builder
- .Append(" CommunityToolkit.Mvvm.Messaging.IMessengerExtensions.Register<")
- .Append(interfaceSymbol.TypeArguments[0])
- .AppendLine(">(serviceProvider.GetRequiredService(), this);");
- }
- }
- }
-
- private readonly struct FieldValueAssignmentOptions
- {
- public readonly bool ResolveHttpClient;
- public readonly bool CallBaseConstructor;
-
- public FieldValueAssignmentOptions(bool resolveHttpClient, bool callBaseConstructor)
- {
- ResolveHttpClient = resolveHttpClient;
- CallBaseConstructor = callBaseConstructor;
- }
- }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/DependencyPropertyGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/DependencyPropertyGenerator.cs
deleted file mode 100644
index 8d0d7748..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/DependencyPropertyGenerator.cs
+++ /dev/null
@@ -1,130 +0,0 @@
-// Copyright (c) DGP Studio. All rights reserved.
-// Licensed under the MIT license.
-
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Snap.Hutao.SourceGeneration.Primitive;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Threading;
-
-namespace Snap.Hutao.SourceGeneration.Automation;
-
-[Generator(LanguageNames.CSharp)]
-internal sealed class DependencyPropertyGenerator : IIncrementalGenerator
-{
- private const string AttributeName = "Snap.Hutao.Core.Annotation.DependencyPropertyAttribute";
-
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- IncrementalValueProvider> commands =
- context.SyntaxProvider.CreateSyntaxProvider(FilterAttributedClasses, CommandMethod)
- .Where(GeneratorSyntaxContext2.NotNull)
- .Collect();
-
- context.RegisterImplementationSourceOutput(commands, GenerateDependencyPropertyImplementations);
- }
-
- private static bool FilterAttributedClasses(SyntaxNode node, CancellationToken token)
- {
- return node is ClassDeclarationSyntax classDeclarationSyntax
- && classDeclarationSyntax.Modifiers.Count > 1
- && classDeclarationSyntax.HasAttributeLists();
- }
-
- private static GeneratorSyntaxContext2 CommandMethod(GeneratorSyntaxContext context, CancellationToken token)
- {
- if (context.TryGetDeclaredSymbol(token, out INamedTypeSymbol? methodSymbol))
- {
- ImmutableArray attributes = methodSymbol.GetAttributes();
- if (attributes.Any(data => data.AttributeClass!.ToDisplayString() == AttributeName))
- {
- return new(context, methodSymbol, attributes);
- }
- }
-
- return default;
- }
-
- private static void GenerateDependencyPropertyImplementations(SourceProductionContext production, ImmutableArray context2s)
- {
- foreach (GeneratorSyntaxContext2 context2 in context2s.DistinctBy(c => c.Symbol.ToDisplayString()))
- {
- GenerateDependencyPropertyImplementation(production, context2);
- }
- }
-
- private static void GenerateDependencyPropertyImplementation(SourceProductionContext production, GeneratorSyntaxContext2 context2)
- {
- foreach (AttributeData propertyInfo in context2.Attributes.Where(attr => attr.AttributeClass!.ToDisplayString() == AttributeName))
- {
- string owner = context2.Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
- Dictionary namedArguments = propertyInfo.NamedArguments.ToDictionary();
- bool isAttached = namedArguments.TryGetValue("IsAttached", out TypedConstant constant) && (bool)constant.Value!;
- string register = isAttached ? "RegisterAttached" : "Register";
-
- ImmutableArray arguments = propertyInfo.ConstructorArguments;
-
- string propertyName = (string)arguments[0].Value!;
- string propertyType = arguments[1].Value!.ToString();
- string defaultValue = arguments.ElementAtOrDefault(2).ToCSharpString() ?? "default";
- defaultValue = defaultValue == "null" ? "default" : defaultValue;
- string propertyChangedCallback = arguments.ElementAtOrDefault(3) is { IsNull: false } arg3 ? $", {arg3.Value}" : string.Empty;
-
- string code;
- if (isAttached)
- {
- string objType = namedArguments.TryGetValue("AttachedType", out TypedConstant attachedType)
- ? attachedType.Value!.ToString()
- : "object";
-
- code = $$"""
- using Microsoft.UI.Xaml;
-
- namespace {{context2.Symbol.ContainingNamespace}};
-
- partial class {{owner}}
- {
- private static readonly DependencyProperty {{propertyName}}Property =
- DependencyProperty.RegisterAttached("{{propertyName}}", typeof({{propertyType}}), typeof({{owner}}), new PropertyMetadata(({{propertyType}}){{defaultValue}}{{propertyChangedCallback}}));
-
- public static {{propertyType}} Get{{propertyName}}({{objType}} obj)
- {
- return ({{propertyType}})obj?.GetValue({{propertyName}}Property);
- }
-
- public static void Set{{propertyName}}({{objType}} obj, {{propertyType}} value)
- {
- obj.SetValue({{propertyName}}Property, value);
- }
- }
- """;
- }
- else
- {
- code = $$"""
- using Microsoft.UI.Xaml;
-
- namespace {{context2.Symbol.ContainingNamespace}};
-
- partial class {{owner}}
- {
- private static readonly DependencyProperty {{propertyName}}Property =
- DependencyProperty.Register(nameof({{propertyName}}), typeof({{propertyType}}), typeof({{owner}}), new PropertyMetadata(({{propertyType}}){{defaultValue}}{{propertyChangedCallback}}));
-
- public {{propertyType}} {{propertyName}}
- {
- get => ({{propertyType}})GetValue({{propertyName}}Property);
- set => SetValue({{propertyName}}Property, value);
- }
- }
- """;
- }
-
- string normalizedClassName = context2.Symbol.ToDisplayString().Replace('<', '{').Replace('>', '}');
- production.AddSource($"{normalizedClassName}.{propertyName}.g.cs", code);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/SaltConstantGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/SaltConstantGenerator.cs
deleted file mode 100644
index 86967884..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Automation/SaltConstantGenerator.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) DGP Studio. All rights reserved.
-// Licensed under the MIT license.
-
-using Microsoft.CodeAnalysis;
-using System;
-using System.Net.Http;
-using System.Runtime.Serialization;
-
-namespace Snap.Hutao.SourceGeneration.Automation;
-
-[Generator(LanguageNames.CSharp)]
-internal sealed class SaltConstantGenerator : IIncrementalGenerator
-{
- private static readonly HttpClient httpClient;
- private static readonly Lazy> lazySaltInfo;
-
- static SaltConstantGenerator()
- {
- httpClient = new();
- lazySaltInfo = new Lazy>(() =>
- {
- string body = httpClient.GetStringAsync("https://internal.snapgenshin.cn/Archive/Salt/Latest").GetAwaiter().GetResult();
- return JsonParser.FromJson>(body)!;
- });
- }
-
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- context.RegisterPostInitializationOutput(GenerateSaltContstants);
- }
-
- private static void GenerateSaltContstants(IncrementalGeneratorPostInitializationContext context)
- {
- Response saltInfo = lazySaltInfo.Value;
- string code = $$"""
- namespace Snap.Hutao.Web.Hoyolab;
-
- internal sealed class SaltConstants
- {
- public const string CNVersion = "{{saltInfo.Data.CNVersion}}";
- public const string CNK2 = "{{saltInfo.Data.CNK2}}";
- public const string CNLK2 = "{{saltInfo.Data.CNLK2}}";
-
- public const string OSVersion = "{{saltInfo.Data.OSVersion}}";
- public const string OSK2 = "{{saltInfo.Data.OSK2}}";
- public const string OSLK2 = "{{saltInfo.Data.OSLK2}}";
- }
- """;
- context.AddSource("SaltConstants.g.cs", code);
- }
-
- private sealed class Response
- {
- [DataMember(Name = "data")]
- public T Data { get; set; } = default!;
- }
-
- internal sealed class SaltLatest
- {
- public string CNVersion { get; set; } = default!;
-
- public string CNK2 { get; set; } = default!;
-
- public string CNLK2 { get; set; } = default!;
-
- public string OSVersion { get; set; } = default!;
-
- public string OSK2 { get; set; } = default!;
-
- public string OSLK2 { get; set; } = default!;
- }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/CodeAnalysis/NotNullWhenAttribute.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/CodeAnalysis/NotNullWhenAttribute.cs
deleted file mode 100644
index 3a2eb152..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/CodeAnalysis/NotNullWhenAttribute.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-namespace System.Diagnostics.CodeAnalysis;
-
-/// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it.
-[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
-internal sealed class NotNullWhenAttribute : Attribute
-{
- /// Initializes the attribute with the specified return value condition.
- ///
- /// The return value condition. If the method returns this value, the associated parameter will not be null.
- ///
- public NotNullWhenAttribute(bool returnValue)
- {
- ReturnValue = returnValue;
- }
-
- /// Gets the return value condition.
- public bool ReturnValue { get; }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/HttpClientGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/HttpClientGenerator.cs
deleted file mode 100644
index 5df9b4c1..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/HttpClientGenerator.cs
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright (c) DGP Studio. All rights reserved.
-// Licensed under the MIT license.
-
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Snap.Hutao.SourceGeneration.Primitive;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Text;
-using System.Threading;
-
-namespace Snap.Hutao.SourceGeneration.DependencyInjection;
-
-[Generator(LanguageNames.CSharp)]
-internal sealed class HttpClientGenerator : IIncrementalGenerator
-{
- private const string AttributeName = "Snap.Hutao.Core.DependencyInjection.Annotation.HttpClient.HttpClientAttribute";
-
- private const string HttpClientConfiguration = "Snap.Hutao.Core.DependencyInjection.Annotation.HttpClient.HttpClientConfiguration.";
- private const string PrimaryHttpMessageHandlerAttributeName = "Snap.Hutao.Core.DependencyInjection.Annotation.HttpClient.PrimaryHttpMessageHandlerAttribute";
- private const string CRLF = "\r\n";
-
- private static readonly DiagnosticDescriptor injectionShouldOmitDescriptor = new("SH201", "Injection 特性可以省略", "HttpClient 特性已将 {0} 注册为 Transient 服务", "Quality", DiagnosticSeverity.Warning, true);
-
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- IncrementalValueProvider> injectionClasses = context.SyntaxProvider
- .CreateSyntaxProvider(FilterAttributedClasses, HttpClientClass)
- .Where(GeneratorSyntaxContext2.NotNull)
- .Collect();
-
- context.RegisterImplementationSourceOutput(injectionClasses, GenerateAddHttpClientsImplementation);
- }
-
- private static bool FilterAttributedClasses(SyntaxNode node, CancellationToken token)
- {
- return node is ClassDeclarationSyntax classDeclarationSyntax
- && classDeclarationSyntax.HasAttributeLists();
- }
-
- private static GeneratorSyntaxContext2 HttpClientClass(GeneratorSyntaxContext context, CancellationToken token)
- {
- if (context.TryGetDeclaredSymbol(token, out INamedTypeSymbol? classSymbol))
- {
- ImmutableArray attributes = classSymbol.GetAttributes();
- if (attributes.Any(data => data.AttributeClass!.ToDisplayString() == AttributeName))
- {
- return new(context, classSymbol, attributes);
- }
- }
-
- return default;
- }
-
- private static void GenerateAddHttpClientsImplementation(SourceProductionContext context, ImmutableArray context2s)
- {
- StringBuilder sourceBuilder = new StringBuilder().Append($$"""
- // Copyright (c) DGP Studio. All rights reserved.
- // Licensed under the MIT license.
-
- using System.Net.Http;
-
- namespace Snap.Hutao.Core.DependencyInjection;
-
- internal static partial class IocHttpClientConfiguration
- {
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{nameof(HttpClientGenerator)}}", "1.0.0.0")]
- public static partial IServiceCollection AddHttpClients(this IServiceCollection services)
- {
- """);
-
- FillUpWithAddHttpClient(sourceBuilder, context, context2s);
-
- sourceBuilder.Append("""
-
- return services;
- }
- }
- """);
-
- context.AddSource("IocHttpClientConfiguration.g.cs", sourceBuilder.ToString());
- }
-
- private static void FillUpWithAddHttpClient(StringBuilder sourceBuilder, SourceProductionContext production, ImmutableArray contexts)
- {
- List lines = [];
- StringBuilder lineBuilder = new();
-
- foreach (GeneratorSyntaxContext2 context in contexts.DistinctBy(c => c.Symbol.ToDisplayString()))
- {
- if (context.SingleOrDefaultAttribute(InjectionGenerator.AttributeName) is AttributeData injectionData)
- {
- if (injectionData.ConstructorArguments[0].ToCSharpString() == InjectionGenerator.InjectAsTransientName)
- {
- if (injectionData.ConstructorArguments.Length < 2)
- {
- production.ReportDiagnostic(Diagnostic.Create(injectionShouldOmitDescriptor, context.Context.Node.GetLocation(), context.Context.Node));
- }
- }
- }
-
- lineBuilder.Clear().Append(CRLF);
- lineBuilder.Append(@" services.AddHttpClient<");
-
- AttributeData httpClientData = context.SingleAttribute(AttributeName);
- ImmutableArray arguments = httpClientData.ConstructorArguments;
-
- if (arguments.Length == 2)
- {
- lineBuilder.Append($"{arguments[1].Value}, ");
- }
-
- lineBuilder.Append($"{context.Symbol.ToDisplayString()}>(");
- lineBuilder.Append(arguments[0].ToCSharpString().Substring(HttpClientConfiguration.Length)).Append("Configuration)");
-
- if (context.SingleOrDefaultAttribute(PrimaryHttpMessageHandlerAttributeName) is AttributeData handlerData)
- {
- ImmutableArray> properties = handlerData.NamedArguments;
- lineBuilder.Append(@".ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() {");
-
- foreach (KeyValuePair property in properties)
- {
- lineBuilder.Append(' ');
- lineBuilder.Append(property.Key);
- lineBuilder.Append(" = ");
- lineBuilder.Append(property.Value.ToCSharpString());
- lineBuilder.Append(',');
- }
-
- lineBuilder.Append(" })");
- }
-
- lineBuilder.Append(';');
-
- lines.Add(lineBuilder.ToString());
- }
-
- foreach (string line in lines.OrderBy(x => x))
- {
- sourceBuilder.Append(line);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/InjectionGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/InjectionGenerator.cs
deleted file mode 100644
index 7aa07a88..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/InjectionGenerator.cs
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright (c) DGP Studio. All rights reserved.
-// Licensed under the MIT license.
-
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Snap.Hutao.SourceGeneration.Primitive;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Text;
-using System.Threading;
-
-namespace Snap.Hutao.SourceGeneration.DependencyInjection;
-
-[Generator(LanguageNames.CSharp)]
-internal sealed class InjectionGenerator : IIncrementalGenerator
-{
- public const string AttributeName = "Snap.Hutao.Core.DependencyInjection.Annotation.InjectionAttribute";
- public const string InjectAsSingletonName = "Snap.Hutao.Core.DependencyInjection.Annotation.InjectAs.Singleton";
- public const string InjectAsTransientName = "Snap.Hutao.Core.DependencyInjection.Annotation.InjectAs.Transient";
- public const string InjectAsScopedName = "Snap.Hutao.Core.DependencyInjection.Annotation.InjectAs.Scoped";
-
- private static readonly DiagnosticDescriptor invalidInjectionDescriptor = new("SH101", "无效的 InjectAs 枚举值", "尚未支持生成 {0} 配置", "Quality", DiagnosticSeverity.Error, true);
-
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- IncrementalValueProvider> injectionClasses = context.SyntaxProvider
- .CreateSyntaxProvider(FilterAttributedClasses, HttpClientClass)
- .Where(GeneratorSyntaxContext2.NotNull)
- .Collect();
-
- context.RegisterImplementationSourceOutput(injectionClasses, GenerateAddInjectionsImplementation);
- }
-
- private static bool FilterAttributedClasses(SyntaxNode node, CancellationToken token)
- {
- return node is ClassDeclarationSyntax classDeclarationSyntax
- && classDeclarationSyntax.HasAttributeLists();
- }
-
- private static GeneratorSyntaxContext2 HttpClientClass(GeneratorSyntaxContext context, CancellationToken token)
- {
- if (context.TryGetDeclaredSymbol(token, out INamedTypeSymbol? classSymbol))
- {
- ImmutableArray attributes = classSymbol.GetAttributes();
- if (attributes.Any(data => data.AttributeClass!.ToDisplayString() == AttributeName))
- {
- return new(context, classSymbol, attributes);
- }
- }
-
- return default;
- }
-
- private static void GenerateAddInjectionsImplementation(SourceProductionContext context, ImmutableArray context2s)
- {
- StringBuilder sourceBuilder = new StringBuilder().Append($$"""
- // Copyright (c) DGP Studio. All rights reserved.
- // Licensed under the MIT license.
-
- namespace Snap.Hutao.Core.DependencyInjection;
-
- internal static partial class ServiceCollectionExtension
- {
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{nameof(InjectionGenerator)}}", "1.0.0.0")]
- public static partial IServiceCollection AddInjections(this IServiceCollection services)
- {
- """);
-
- FillUpWithAddServices(sourceBuilder, context, context2s);
- sourceBuilder.Append("""
-
- return services;
- }
- }
- """);
-
- context.AddSource("ServiceCollectionExtension.g.cs", sourceBuilder.ToString());
- }
-
- private static void FillUpWithAddServices(StringBuilder sourceBuilder, SourceProductionContext production, ImmutableArray contexts)
- {
- List lines = [];
- StringBuilder lineBuilder = new();
-
- foreach (GeneratorSyntaxContext2 context in contexts.DistinctBy(c => c.Symbol.ToDisplayString()))
- {
- lineBuilder.Clear().AppendLine();
-
- AttributeData injectionInfo = context.SingleAttribute(AttributeName);
- ImmutableArray arguments = injectionInfo.ConstructorArguments;
-
- string injectAsName = arguments[0].ToCSharpString();
-
- bool hasKey = injectionInfo.TryGetNamedArgumentValue("Key", out TypedConstant key);
-
- switch (injectAsName, hasKey)
- {
- case (InjectAsSingletonName, false):
- lineBuilder.Append(" services.AddSingleton<");
- break;
- case (InjectAsSingletonName, true):
- lineBuilder.Append(" services.AddKeyedSingleton<");
- break;
- case (InjectAsTransientName, false):
- lineBuilder.Append(" services.AddTransient<");
- break;
- case (InjectAsTransientName, true):
- lineBuilder.Append(" services.AddKeyedTransient<");
- break;
- case (InjectAsScopedName, false):
- lineBuilder.Append(" services.AddScoped<");
- break;
- case (InjectAsScopedName, true):
- lineBuilder.Append(" services.AddKeyedScoped<");
- break;
- default:
- production.ReportDiagnostic(Diagnostic.Create(invalidInjectionDescriptor, context.Context.Node.GetLocation(), injectAsName));
- break;
- }
-
- if (arguments.Length == 2)
- {
- lineBuilder.Append($"{arguments[1].Value}, ");
- }
-
- if (hasKey)
- {
- lineBuilder.Append($"{context.Symbol.ToDisplayString()}>({key.ToCSharpString()});");
- }
- else
- {
- lineBuilder.Append($"{context.Symbol.ToDisplayString()}>();");
- }
-
- lines.Add(lineBuilder.ToString());
- }
-
- foreach (string line in lines.OrderBy(x => x))
- {
- sourceBuilder.Append(line);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/ServiceAnalyzer.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/ServiceAnalyzer.cs
deleted file mode 100644
index f655f151..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/DependencyInjection/ServiceAnalyzer.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Microsoft.CodeAnalysis.Diagnostics;
-using Snap.Hutao.SourceGeneration.Primitive;
-using System.Collections.Immutable;
-using System.Linq;
-
-namespace Snap.Hutao.SourceGeneration.DependencyInjection;
-
-[DiagnosticAnalyzer(LanguageNames.CSharp)]
-internal class ServiceAnalyzer : DiagnosticAnalyzer
-{
- private static readonly DiagnosticDescriptor NonSingletonUseServiceProviderDescriptor = new("SH301", "Non Singleton service should avoid direct use of IServiceProvider", "Non Singleton service should avoid direct use of IServiceProvider", "Quality", DiagnosticSeverity.Info, true);
- private static readonly DiagnosticDescriptor SingletonServiceCaptureNonSingletonServiceDescriptor = new("SH302", "Singleton service should avoid keep reference of non singleton service", "Singleton service should avoid keep reference of non singleton service", "Quality", DiagnosticSeverity.Info, true);
-
- public override ImmutableArray SupportedDiagnostics
- {
- get => new DiagnosticDescriptor[]
- {
- NonSingletonUseServiceProviderDescriptor,
- SingletonServiceCaptureNonSingletonServiceDescriptor,
- }.ToImmutableArray();
- }
-
- public override void Initialize(AnalysisContext context)
- {
- context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
- context.EnableConcurrentExecution();
-
- context.RegisterCompilationStartAction(CompilationStart);
- }
-
- private static void CompilationStart(CompilationStartAnalysisContext context)
- {
- context.RegisterSyntaxNodeAction(HandleNonSingletonUseServiceProvider, SyntaxKind.ClassDeclaration);
- context.RegisterSyntaxNodeAction(HandleSingletonServiceCaptureNonSingletonService, SyntaxKind.ClassDeclaration);
- }
-
- private static void HandleNonSingletonUseServiceProvider(SyntaxNodeAnalysisContext context)
- {
- ClassDeclarationSyntax classDeclarationSyntax = (ClassDeclarationSyntax)context.Node;
- if (classDeclarationSyntax.HasAttributeLists())
- {
- INamedTypeSymbol? classSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclarationSyntax);
- if (classSymbol is not null)
- {
- foreach (AttributeData attributeData in classSymbol.GetAttributes())
- {
- if (attributeData.AttributeClass!.ToDisplayString() is InjectionGenerator.AttributeName)
- {
- string serviceType = attributeData.ConstructorArguments[0].ToCSharpString();
- if (serviceType is InjectionGenerator.InjectAsTransientName or InjectionGenerator.InjectAsScopedName)
- {
- HandleNonSingletonUseServiceProviderActual(context, classSymbol);
- }
- }
- }
- }
- }
- }
-
- private static void HandleNonSingletonUseServiceProviderActual(SyntaxNodeAnalysisContext context, INamedTypeSymbol classSymbol)
- {
- ISymbol? symbol = classSymbol.GetMembers().Where(m => m is IFieldSymbol f && f.Type.ToDisplayString() == "System.IServiceProvider").SingleOrDefault();
-
- if (symbol is not null)
- {
- Diagnostic diagnostic = Diagnostic.Create(NonSingletonUseServiceProviderDescriptor, symbol.Locations.FirstOrDefault());
- context.ReportDiagnostic(diagnostic);
- }
- }
-
- private static void HandleSingletonServiceCaptureNonSingletonService(SyntaxNodeAnalysisContext context)
- {
- //classSymbol.GetMembers().Where(m => m is IFieldSymbol { IsReadOnly: true, DeclaredAccessibility: Accessibility.Private } f);
- }
-}
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Enum/LocalizedEnumGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Enum/LocalizedEnumGenerator.cs
deleted file mode 100644
index c8a4f07e..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Enum/LocalizedEnumGenerator.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-using Microsoft.CodeAnalysis;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
-using Snap.Hutao.SourceGeneration.Primitive;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.Linq;
-using System.Text;
-using System.Threading;
-
-namespace Snap.Hutao.SourceGeneration.Enum;
-
-[Generator(LanguageNames.CSharp)]
-internal class LocalizedEnumGenerator : IIncrementalGenerator
-{
- private const string AttributeName = "Snap.Hutao.Resource.Localization.LocalizationAttribute";
- private const string LocalizationKeyName = "Snap.Hutao.Resource.Localization.LocalizationKeyAttribute";
-
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- IncrementalValuesProvider localizationEnums = context.SyntaxProvider
- .CreateSyntaxProvider(FilterAttributedEnums, LocalizationEnum)
- .Where(GeneratorSyntaxContext2.NotNull);
-
- context.RegisterSourceOutput(localizationEnums, GenerateGetLocalizedDescriptionImplementation);
- }
-
- private static bool FilterAttributedEnums(SyntaxNode node, CancellationToken token)
- {
- return node is EnumDeclarationSyntax enumDeclarationSyntax
- && enumDeclarationSyntax.HasAttributeLists();
- }
-
- private static GeneratorSyntaxContext2 LocalizationEnum(GeneratorSyntaxContext context, CancellationToken token)
- {
- if (context.SemanticModel.GetDeclaredSymbol(context.Node, token) is INamedTypeSymbol enumSymbol)
- {
- ImmutableArray attributes = enumSymbol.GetAttributes();
- if (attributes.Any(data => data.AttributeClass!.ToDisplayString() == AttributeName))
- {
- return new(context, enumSymbol, attributes);
- }
- }
-
- return default;
- }
-
- private static void GenerateGetLocalizedDescriptionImplementation(SourceProductionContext context, GeneratorSyntaxContext2 context2)
- {
- StringBuilder sourceBuilder = new StringBuilder().Append($$"""
- // Copyright (c) DGP Studio. All rights reserved.
- // Licensed under the MIT license.
-
- using System.Globalization;
-
- namespace Snap.Hutao.Resource.Localization;
-
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{nameof(LocalizedEnumGenerator)}}", "1.0.0.0")]
- internal static class {{context2.Symbol.Name}}Extension
- {
- ///
- /// 获取本地化的描述
- ///
- /// 枚举值
- /// 本地化的描述
- public static string GetLocalizedDescription(this {{context2.Symbol}} value)
- {
- string key = value switch
- {
-
- """);
-
- FillUpWithSwitchBranches(sourceBuilder, context2);
-
- sourceBuilder.Append($$"""
- _ => string.Empty,
- };
-
- if (string.IsNullOrEmpty(key))
- {
- return Enum.GetName(value);
- }
- else
- {
- return SH.ResourceManager.GetString(key, CultureInfo.CurrentCulture);
- }
- }
-
- ///
- /// 获取本地化的描述
- ///
- /// 枚举值
- /// 本地化的描述
- [return:MaybeNull]
- public static string GetLocalizedDescriptionOrDefault(this {{context2.Symbol}} value)
- {
- string key = value switch
- {
-
- """);
-
- FillUpWithSwitchBranches(sourceBuilder, context2);
-
- sourceBuilder.Append($$"""
- _ => string.Empty,
- };
-
- return SH.ResourceManager.GetString(key, CultureInfo.CurrentCulture);
- }
- }
- """);
-
- context.AddSource($"{context2.Symbol.Name}Extension.g.cs", sourceBuilder.ToString());
- }
-
- private static void FillUpWithSwitchBranches(StringBuilder sourceBuilder, GeneratorSyntaxContext2 context)
- {
- IEnumerable fields = context.Symbol.GetMembers()
- .Where(m => m.Kind == SymbolKind.Field)
- .Cast();
-
- foreach (IFieldSymbol fieldSymbol in fields)
- {
- AttributeData? localizationKeyInfo = fieldSymbol.GetAttributes()
- .SingleOrDefault(data => data.AttributeClass!.ToDisplayString() == LocalizationKeyName);
- if (localizationKeyInfo != null)
- {
- sourceBuilder
- .Append(" ")
- .Append(fieldSymbol)
- .Append(" => \"")
- .Append(localizationKeyInfo.ConstructorArguments[0].Value)
- .AppendLine("\",");
- }
- }
- }
-}
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/GlobalSuppressions.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/GlobalSuppressions.cs
deleted file mode 100644
index 7d458146..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/GlobalSuppressions.cs
+++ /dev/null
@@ -1,8 +0,0 @@
-// This file is used by Code Analysis to maintain SuppressMessage
-// attributes that are applied to this project.
-// Project-level suppressions either have no target or are given
-// a specific target and scoped to a namespace, type, member, etc.
-
-using System.Diagnostics.CodeAnalysis;
-
-[assembly: SuppressMessage("", "RS2008")]
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Identity/IdentityGenerator.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Identity/IdentityGenerator.cs
deleted file mode 100644
index a3440e94..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/Identity/IdentityGenerator.cs
+++ /dev/null
@@ -1,202 +0,0 @@
-using Microsoft.CodeAnalysis;
-using System.Collections.Generic;
-using System.Collections.Immutable;
-using System.IO;
-using System.Linq;
-using System.Text;
-
-namespace Snap.Hutao.SourceGeneration.Identity;
-
-[Generator(LanguageNames.CSharp)]
-internal sealed class IdentityGenerator : IIncrementalGenerator
-{
- private const string FileName = "IdentityStructs.json";
-
- public void Initialize(IncrementalGeneratorInitializationContext context)
- {
- IncrementalValueProvider> provider = context.AdditionalTextsProvider.Where(MatchFileName).Collect();
-
- context.RegisterImplementationSourceOutput(provider, GenerateIdentityStructs);
- }
-
- private static bool MatchFileName(AdditionalText text)
- {
- return Path.GetFileName(text.Path) == FileName;
- }
-
- private static void GenerateIdentityStructs(SourceProductionContext context, ImmutableArray texts)
- {
- AdditionalText jsonFile = texts.Single();
-
- string identityJson = jsonFile.GetText(context.CancellationToken)!.ToString();
- List identities = identityJson.FromJson>()!;
-
- if (identities.Any())
- {
- foreach (IdentityStructMetadata identityStruct in identities)
- {
- GenerateIdentityStruct(context, identityStruct);
- }
- }
- }
-
- private static void GenerateIdentityStruct(SourceProductionContext context, IdentityStructMetadata metadata)
- {
- string name = metadata.Name;
-
- StringBuilder sourceBuilder = new StringBuilder().AppendLine($$"""
- // Copyright (c) DGP Studio. All rights reserved.
- // Licensed under the MIT license.
-
- using Snap.Hutao.Model.Primitive.Converter;
- using System.Numerics;
-
- namespace Snap.Hutao.Model.Primitive;
-
- ///
- /// {{metadata.Documentation}}
- ///
- [JsonConverter(typeof(IdentityConverter<{{name}}>))]
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{nameof(IdentityGenerator)}}","1.0.0.0")]
- internal readonly partial struct {{name}}
- {
- ///
- /// 值
- ///
- public readonly uint Value;
-
- ///
- /// Initializes a new instance of the struct.
- ///
- /// value
- public {{name}}(uint value)
- {
- Value = value;
- }
-
- public static implicit operator uint({{name}} value)
- {
- return value.Value;
- }
-
- public static implicit operator {{name}}(uint value)
- {
- return new(value);
- }
-
- ///
- public override int GetHashCode()
- {
- return Value.GetHashCode();
- }
-
- ///
- public override string ToString()
- {
- return Value.ToString();
- }
- }
- """);
-
- if (metadata.Equatable)
- {
- sourceBuilder.AppendLine($$"""
-
- internal readonly partial struct {{name}} : IEquatable<{{name}}>
- {
- ///
- public override bool Equals(object obj)
- {
- return obj is {{name}} other && Equals(other);
- }
-
- ///
- public bool Equals({{name}} other)
- {
- return Value == other.Value;
- }
- }
- """);
- }
-
- if (metadata.EqualityOperators)
- {
- sourceBuilder.AppendLine($$"""
-
- internal readonly partial struct {{name}} : IEqualityOperators<{{name}}, {{name}}, bool>, IEqualityOperators<{{name}}, uint, bool>
- {
- public static bool operator ==({{name}} left, {{name}} right)
- {
- return left.Value == right.Value;
- }
-
- public static bool operator ==({{name}} left, uint right)
- {
- return left.Value == right;
- }
-
- public static bool operator !=({{name}} left, {{name}} right)
- {
- return !(left == right);
- }
-
- public static bool operator !=({{name}} left, uint right)
- {
- return !(left == right);
- }
- }
- """);
- }
-
- if (metadata.AdditionOperators)
- {
- sourceBuilder.AppendLine($$"""
-
- internal readonly partial struct {{name}} : IAdditionOperators<{{name}}, {{name}}, {{name}}>, IAdditionOperators<{{name}}, uint, {{name}}>
- {
- public static {{name}} operator +({{name}} left, {{name}} right)
- {
- return left.Value + right.Value;
- }
-
- public static {{name}} operator +({{name}} left, uint right)
- {
- return left.Value + right;
- }
- }
- """);
- }
-
- if (metadata.IncrementOperators)
- {
- sourceBuilder.AppendLine($$"""
-
- internal readonly partial struct {{name}} : IIncrementOperators<{{name}}>
- {
- public static unsafe {{name}} operator ++({{name}} value)
- {
- ++*(uint*)&value;
- return value;
- }
- }
- """);
- }
-
- context.AddSource($"{name}.g.cs", sourceBuilder.ToString());
- }
-
- private sealed class IdentityStructMetadata
- {
- public string Name { get; set; } = default!;
-
- public string? Documentation { get; set; }
-
- public bool Equatable { get; set; }
-
- public bool EqualityOperators { get; set; }
-
- public bool AdditionOperators { get; set; }
-
- public bool IncrementOperators { get; set; }
- }
-}
\ No newline at end of file
diff --git a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/JsonParser.cs b/src/Snap.Hutao/Snap.Hutao.SourceGeneration/JsonParser.cs
deleted file mode 100644
index 24d06d4e..00000000
--- a/src/Snap.Hutao/Snap.Hutao.SourceGeneration/JsonParser.cs
+++ /dev/null
@@ -1,439 +0,0 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Runtime.Serialization;
-using System.Text;
-
-namespace Snap.Hutao.SourceGeneration;
-
-// Really simple JSON parser in ~300 lines
-// - Attempts to parse JSON files with minimal GC allocation
-// - Nice and simple "[1,2,3]".FromJson>() API
-// - Classes and structs can be parsed too!
-// class Foo { public int Value; }
-// "{\"Value\":10}".FromJson()
-// - Can parse JSON without type information into Dictionary and List