diff --git a/eng/submodules/silk.net-2.x b/eng/submodules/silk.net-2.x index 85acbf2772..c87fc664cc 160000 --- a/eng/submodules/silk.net-2.x +++ b/eng/submodules/silk.net-2.x @@ -1 +1 @@ -Subproject commit 85acbf2772e8a61ade6bd745073880138d61373a +Subproject commit c87fc664cc5d15abd754997b0a9ad138470554c4 diff --git a/sources/Core/Core/Annotations/NameAffixAttribute.cs b/sources/Core/Core/Annotations/NameAffixAttribute.cs index 3667f98fc4..d321570401 100644 --- a/sources/Core/Core/Annotations/NameAffixAttribute.cs +++ b/sources/Core/Core/Annotations/NameAffixAttribute.cs @@ -7,13 +7,13 @@ namespace Silk.NET.Core; /// [AttributeUsage( AttributeTargets.Class - | AttributeTargets.Delegate - | AttributeTargets.Enum - | AttributeTargets.Field - | AttributeTargets.Method - | AttributeTargets.Parameter - | AttributeTargets.Property - | AttributeTargets.Struct, + | AttributeTargets.Delegate + | AttributeTargets.Enum + | AttributeTargets.Field + | AttributeTargets.Method + | AttributeTargets.Parameter + | AttributeTargets.Property + | AttributeTargets.Struct, AllowMultiple = true, Inherited = true )] diff --git a/sources/Core/Core/Annotations/NativeNameAttribute.cs b/sources/Core/Core/Annotations/NativeNameAttribute.cs index 6cb2db2721..41cc1014c4 100644 --- a/sources/Core/Core/Annotations/NativeNameAttribute.cs +++ b/sources/Core/Core/Annotations/NativeNameAttribute.cs @@ -8,13 +8,13 @@ namespace Silk.NET.Core; /// [AttributeUsage( AttributeTargets.Class - | AttributeTargets.Delegate - | AttributeTargets.Enum - | AttributeTargets.Field - | AttributeTargets.Method - | AttributeTargets.Parameter - | AttributeTargets.Property - | AttributeTargets.Struct, + | AttributeTargets.Delegate + | AttributeTargets.Enum + | AttributeTargets.Field + | AttributeTargets.Method + | AttributeTargets.Parameter + | AttributeTargets.Property + | AttributeTargets.Struct, AllowMultiple = false, Inherited = true )] diff --git a/sources/SilkTouch/SilkTouch/Mods/AddIncludes.cs b/sources/SilkTouch/SilkTouch/Mods/AddIncludes.cs index 11de1ecadb..b20ff3b186 100644 --- a/sources/SilkTouch/SilkTouch/Mods/AddIncludes.cs +++ b/sources/SilkTouch/SilkTouch/Mods/AddIncludes.cs @@ -64,8 +64,13 @@ public async Task> BeforeScrapeAsync(string key, List $"--include-directory={x}") ?? []); - cmdLineArgs.AddRange(cfg.AdditionalIncludes?.Select(x => $"--include-directory={x}") ?? []); + cmdLineArgs.InsertRange( + 0, + cfg.PriorityIncludes?.Select(x => $"--include-directory={x}") ?? [] + ); + cmdLineArgs.AddRange( + cfg.AdditionalIncludes?.Select(x => $"--include-directory={x}") ?? [] + ); if (!cfg.SuppressStdIncludes) { diff --git a/sources/SilkTouch/SilkTouch/Mods/AddVTables.cs b/sources/SilkTouch/SilkTouch/Mods/AddVTables.cs index e1ad5d8d85..e3d3326dfd 100644 --- a/sources/SilkTouch/SilkTouch/Mods/AddVTables.cs +++ b/sources/SilkTouch/SilkTouch/Mods/AddVTables.cs @@ -777,9 +777,13 @@ out var callConv x.WithAttributes( SeparatedList( x.Attributes.Where(y => - !y.IsAttribute("System.Runtime.InteropServices.DllImport") + !y.IsAttribute( + "System.Runtime.InteropServices.DllImport" + ) && !y.IsAttribute("Silk.NET.Core.NativeFunction") - && !y.IsAttribute("System.Runtime.CompilerServices.MethodImpl") + && !y.IsAttribute( + "System.Runtime.CompilerServices.MethodImpl" + ) ) ) ) diff --git a/sources/SilkTouch/SilkTouch/Mods/Bakery/DefaultBakeStrategy.cs b/sources/SilkTouch/SilkTouch/Mods/Bakery/DefaultBakeStrategy.cs index 40d609aeda..63972d762d 100644 --- a/sources/SilkTouch/SilkTouch/Mods/Bakery/DefaultBakeStrategy.cs +++ b/sources/SilkTouch/SilkTouch/Mods/Bakery/DefaultBakeStrategy.cs @@ -197,7 +197,9 @@ node is BaseMethodDeclarationSyntax meth node.AttributeLists.Select(x => x.WithAttributes( SeparatedList( - x.Attributes.Where(y => y.IsAttribute("Silk.NET.Core.SupportedApiAttribute")) + x.Attributes.Where(y => + y.IsAttribute("Silk.NET.Core.SupportedApiAttribute") + ) ) ) ) diff --git a/sources/SilkTouch/SilkTouch/Mods/Common/AttributeUtils.cs b/sources/SilkTouch/SilkTouch/Mods/Common/AttributeUtils.cs index ee7e1a8789..ef3a5f71d7 100644 --- a/sources/SilkTouch/SilkTouch/Mods/Common/AttributeUtils.cs +++ b/sources/SilkTouch/SilkTouch/Mods/Common/AttributeUtils.cs @@ -29,9 +29,9 @@ public static bool IsAttribute(this AttributeSyntax node, string fullNameWithout var sep = node.Name.ToString().Split("::").Last(); var name = fullNameWithoutSuffix.Split('.').Last(); return sep == name - || sep == $"{name}Attribute" - || sep.EndsWith(fullNameWithoutSuffix) - || sep.EndsWith($"{fullNameWithoutSuffix}Attribute"); + || sep == $"{name}Attribute" + || sep.EndsWith(fullNameWithoutSuffix) + || sep.EndsWith($"{fullNameWithoutSuffix}Attribute"); } /// @@ -41,8 +41,13 @@ public static bool IsAttribute(this AttributeSyntax node, string fullNameWithout /// /// The fully-qualified attribute name including the namespace but without the Attribute suffix. /// - public static bool ContainsAttribute(this IEnumerable attributeLists, string fullNameWithoutSuffix) => - attributeLists.Any(list => list.Attributes.Any(attribute => attribute.IsAttribute(fullNameWithoutSuffix))); + public static bool ContainsAttribute( + this IEnumerable attributeLists, + string fullNameWithoutSuffix + ) => + attributeLists.Any(list => + list.Attributes.Any(attribute => attribute.IsAttribute(fullNameWithoutSuffix)) + ); /// /// Modifies the s the method may have to make them resistant to method identifier @@ -209,8 +214,12 @@ out _ /// Use false if not (outside or appended to end). /// True means that the attribute is added to the start of the attribute list, meaning that the affix is re-appended earlier. /// - public static SyntaxList AddNamePrefix(this IEnumerable attributeLists, string category, string prefix, bool addToInner = false) - => attributeLists.AddNamePrefixOrSuffix("Prefix", category, prefix, addToInner); + public static SyntaxList AddNamePrefix( + this IEnumerable attributeLists, + string category, + string prefix, + bool addToInner = false + ) => attributeLists.AddNamePrefixOrSuffix("Prefix", category, prefix, addToInner); /// /// Adds a name suffix attribute to the given attribute list. @@ -223,23 +232,38 @@ public static SyntaxList AddNamePrefix(this IEnumerable - public static SyntaxList AddNameSuffix(this IEnumerable attributeLists, string category, string suffix, bool addToInner = false) - => attributeLists.AddNamePrefixOrSuffix("Suffix", category, suffix, addToInner); - - private static SyntaxList AddNamePrefixOrSuffix(this IEnumerable attributeLists, string type, string category, string affix, bool addToInner = false) + public static SyntaxList AddNameSuffix( + this IEnumerable attributeLists, + string category, + string suffix, + bool addToInner = false + ) => attributeLists.AddNamePrefixOrSuffix("Suffix", category, suffix, addToInner); + + private static SyntaxList AddNamePrefixOrSuffix( + this IEnumerable attributeLists, + string type, + string category, + string affix, + bool addToInner = false + ) { - var typeArgument = AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal($"\"{type}\"", type))); - var categoryArgument = AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal($"\"{category}\"", category))); - var affixArgument = AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal($"\"{affix}\"", affix))); + var typeArgument = AttributeArgument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal($"\"{type}\"", type)) + ); + var categoryArgument = AttributeArgument( + LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal($"\"{category}\"", category) + ) + ); + var affixArgument = AttributeArgument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal($"\"{affix}\"", affix)) + ); var argumentList = AttributeArgumentList([typeArgument, categoryArgument, affixArgument]); - var attribute = AttributeList([ - Attribute(IdentifierName("NameAffix"), argumentList), - ]); + var attribute = AttributeList([Attribute(IdentifierName("NameAffix"), argumentList)]); - return addToInner - ? [attribute, ..attributeLists] - : [..attributeLists, attribute]; + return addToInner ? [attribute, .. attributeLists] : [.. attributeLists, attribute]; } /// @@ -248,7 +272,10 @@ private static SyntaxList AddNamePrefixOrSuffix(this IEnume /// /// The default usually should be the node's identifier. /// - public static string GetNativeNameOrDefault(this IEnumerable attributeLists, SyntaxToken identifier) + public static string GetNativeNameOrDefault( + this IEnumerable attributeLists, + SyntaxToken identifier + ) { if (TryGetNativeName(attributeLists, out var nativeName)) { @@ -264,7 +291,10 @@ public static string GetNativeNameOrDefault(this IEnumerable /// The default usually should be the node's identifier. /// - public static string GetNativeNameOrDefault(this IEnumerable attributeLists, string defaultName) + public static string GetNativeNameOrDefault( + this IEnumerable attributeLists, + string defaultName + ) { if (TryGetNativeName(attributeLists, out var nativeName)) { @@ -277,9 +307,14 @@ public static string GetNativeNameOrDefault(this IEnumerable /// Gets the value of the native name attribute from the given attribute list. /// - public static bool TryGetNativeName(this IEnumerable attributeLists, [NotNullWhen(true)] out string? nativeName) + public static bool TryGetNativeName( + this IEnumerable attributeLists, + [NotNullWhen(true)] out string? nativeName + ) { - var nativeNameAttribute = attributeLists.SelectMany(list => list.Attributes).FirstOrDefault(attribute => attribute.IsAttribute("Silk.NET.Core.NativeName")); + var nativeNameAttribute = attributeLists + .SelectMany(list => list.Attributes) + .FirstOrDefault(attribute => attribute.IsAttribute("Silk.NET.Core.NativeName")); if (nativeNameAttribute == null) { nativeName = null; @@ -295,25 +330,47 @@ public static bool TryGetNativeName(this IEnumerable attrib /// /// Sets or replaces the native name attribute in the given attribute list. /// - public static SyntaxList WithNativeName(this IEnumerable attributeLists, string nativeName) + public static SyntaxList WithNativeName( + this IEnumerable attributeLists, + string nativeName + ) { - var nativeNameAttribute = AttributeList([ - Attribute( - IdentifierName("NativeName"), - AttributeArgumentList([ - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal($"\"{nativeName}\"", nativeName))), - ])), - ]); - - return List(attributeLists.Select(list => { - var attributes = list.Attributes; - attributes = [..attributes.Where(attribute => !attribute.IsAttribute("Silk.NET.Core.NativeName"))]; - - return attributes.Count == 0 ? null : list.WithAttributes(attributes); - }) - .Where(list => list != null) - .Cast() - .Prepend(nativeNameAttribute)); + var nativeNameAttribute = AttributeList( + [ + Attribute( + IdentifierName("NativeName"), + AttributeArgumentList( + [ + AttributeArgument( + LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal($"\"{nativeName}\"", nativeName) + ) + ), + ] + ) + ), + ] + ); + + return List( + attributeLists + .Select(list => + { + var attributes = list.Attributes; + attributes = + [ + .. attributes.Where(attribute => + !attribute.IsAttribute("Silk.NET.Core.NativeName") + ), + ]; + + return attributes.Count == 0 ? null : list.WithAttributes(attributes); + }) + .Where(list => list != null) + .Cast() + .Prepend(nativeNameAttribute) + ); } /// @@ -368,7 +425,7 @@ out NativeTypeNameInfo info switch (nativeTypeName) { // Handle case: "#define NAME VALUE" - case {} when nativeTypeName.StartsWith("#define "): + case { } when nativeTypeName.StartsWith("#define "): { // Trim off the #define var nativeTypeSpan = nativeTypeName["#define ".Length..].Trim(); @@ -404,7 +461,7 @@ out NativeTypeNameInfo info } // Handle cases: "const NAME **", "NAME **" - case {}: + case { }: { // Trim off the const var isConst = false; diff --git a/sources/SilkTouch/SilkTouch/Mods/Common/ModCSharpSyntaxRewriter.cs b/sources/SilkTouch/SilkTouch/Mods/Common/ModCSharpSyntaxRewriter.cs index 1e6cf120f8..d7abbd6397 100644 --- a/sources/SilkTouch/SilkTouch/Mods/Common/ModCSharpSyntaxRewriter.cs +++ b/sources/SilkTouch/SilkTouch/Mods/Common/ModCSharpSyntaxRewriter.cs @@ -37,7 +37,9 @@ public Dictionary UsingsToAdd return ret; } - foreach (var use in comp.Usings.Where(use => !use.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword))) + foreach ( + var use in comp.Usings.Where(use => !use.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) + ) { AddUsing(use); } @@ -68,7 +70,9 @@ and not SyntaxKind.MultiLineCommentTrivia FileScopedNamespaceDeclarationSyntax node ) { - foreach (var use in node.Usings.Where(use => !use.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword))) + foreach ( + var use in node.Usings.Where(use => !use.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) + ) { AddUsing(use); } diff --git a/sources/SilkTouch/SilkTouch/Mods/Common/ModUtils.cs b/sources/SilkTouch/SilkTouch/Mods/Common/ModUtils.cs index cbdb8ee0c2..a0a8133a80 100644 --- a/sources/SilkTouch/SilkTouch/Mods/Common/ModUtils.cs +++ b/sources/SilkTouch/SilkTouch/Mods/Common/ModUtils.cs @@ -187,14 +187,20 @@ public static string FullPath(this Project proj, string relativePath) => /// /// Searches and replaces all occurrences of the with the in the document name and project *relative* file path. /// - public static Document ReplaceNameAndPath(this Document document, string oldValue, string newValue) + public static Document ReplaceNameAndPath( + this Document document, + string oldValue, + string newValue + ) { document = document.WithName(document.Name.Replace(oldValue, newValue)); var relativePath = document.RelativePath(); if (relativePath != null) { - document = document.WithFilePath(FullPath(document.Project, relativePath.Replace(oldValue, newValue))); + document = document.WithFilePath( + FullPath(document.Project, relativePath.Replace(oldValue, newValue)) + ); } return document; diff --git a/sources/SilkTouch/SilkTouch/Mods/ExtractNestedTyping.cs b/sources/SilkTouch/SilkTouch/Mods/ExtractNestedTyping.cs index 863a4863f6..b8f063e7ec 100644 --- a/sources/SilkTouch/SilkTouch/Mods/ExtractNestedTyping.cs +++ b/sources/SilkTouch/SilkTouch/Mods/ExtractNestedTyping.cs @@ -70,7 +70,8 @@ public override async Task ExecuteAsync(IModContext ctx, CancellationToken ct = foreach (var docId in project.DocumentIds) { var doc = - project.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); + project.GetDocument(docId) + ?? throw new InvalidOperationException("Document missing"); var (fname, node) = (doc.RelativePath(), await doc.GetSyntaxRootAsync(ct)); if (fname is null) { @@ -92,26 +93,30 @@ public override async Task ExecuteAsync(IModContext ctx, CancellationToken ct = foreach (var newStruct in rewriter.ExtractedNestedStructs) { // Add new documents for each nested struct - project = project.AddDocument( - $"{newStruct.Identifier}.gen.cs", - CompilationUnit() - .WithMembers( - rewriter.Namespace is not null - ? SingletonList( - FileScopedNamespaceDeclaration( - ModUtils.NamespaceIntoIdentifierName(rewriter.Namespace) - ) - .WithMembers( - SingletonList(newStruct) - ) - ) - : SingletonList(newStruct) + project = project + .AddDocument( + $"{newStruct.Identifier}.gen.cs", + CompilationUnit() + .WithMembers( + rewriter.Namespace is not null + ? SingletonList( + FileScopedNamespaceDeclaration( + ModUtils.NamespaceIntoIdentifierName( + rewriter.Namespace + ) + ) + .WithMembers( + SingletonList(newStruct) + ) + ) + : SingletonList(newStruct) + ) + .NormalizeWhitespace(), + filePath: project.FullPath( + $"{fname.AsSpan()[..fname.LastIndexOf('/')]}/{newStruct.Identifier}.gen.cs" ) - .NormalizeWhitespace(), - filePath: project.FullPath( - $"{fname.AsSpan()[..fname.LastIndexOf('/')]}/{newStruct.Identifier}.gen.cs" ) - ).Project; + .Project; } rewriter.File = null; @@ -124,25 +129,21 @@ rewriter.Namespace is not null var extractedFunctionPointers = rewriter .FunctionPointerTypes.Values //.Where(x => x.IsUnique) .SelectMany(x => - (IEnumerable<( - MemberDeclarationSyntax, - string, - HashSet, - HashSet - )>) [ - ( - x.Delegate, - x.Delegate.Identifier.ToString(), - x.ReferencingFileDirs, - x.ReferencingNamespaces - ), - ( - x.Pfn, - x.Pfn.Identifier.ToString(), - x.ReferencingFileDirs, - x.ReferencingNamespaces - ), - ] + (IEnumerable<(MemberDeclarationSyntax, string, HashSet, HashSet)>) + [ + ( + x.Delegate, + x.Delegate.Identifier.ToString(), + x.ReferencingFileDirs, + x.ReferencingNamespaces + ), + ( + x.Pfn, + x.Pfn.Identifier.ToString(), + x.ReferencingFileDirs, + x.ReferencingNamespaces + ), + ] ) .Concat( enums.Select(x => @@ -153,7 +154,8 @@ rewriter.Namespace is not null x.Value.Item3 ) ) - ).ToList(); + ) + .ToList(); foreach (var (typeDecl, identifier, fileDirs, namespaces) in extractedFunctionPointers) { @@ -508,13 +510,24 @@ _fallbackFromOuterFunctionPointer is not null var (pfn, @delegate) = CreateFunctionPointerTypes( currentNativeTypeName, $"{currentNativeTypeName}Delegate", - (currentNativeTypeName == fallback - ? SingletonList(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("Transformed"))))) - : default) - .WithNativeName(currentNativeTypeName), - (currentNativeTypeName == fallback - ? SingletonList(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("Transformed"))))) - : default) + ( + currentNativeTypeName == fallback + ? SingletonList( + AttributeList( + SingletonSeparatedList(Attribute(IdentifierName("Transformed"))) + ) + ) + : default + ).WithNativeName(currentNativeTypeName), + ( + currentNativeTypeName == fallback + ? SingletonList( + AttributeList( + SingletonSeparatedList(Attribute(IdentifierName("Transformed"))) + ) + ) + : default + ) .WithNativeName(currentNativeTypeName) .AddNameSuffix("FunctionPointerDelegateType", "Delegate"), node diff --git a/sources/SilkTouch/SilkTouch/Mods/InterceptNativeFunctions.cs b/sources/SilkTouch/SilkTouch/Mods/InterceptNativeFunctions.cs index 6a2b40b9ae..ada83e3b00 100644 --- a/sources/SilkTouch/SilkTouch/Mods/InterceptNativeFunctions.cs +++ b/sources/SilkTouch/SilkTouch/Mods/InterceptNativeFunctions.cs @@ -131,7 +131,8 @@ or SyntaxKind.ProtectedKeyword ); return node.WithAttributeLists( - node.AttributeLists.AddNameSuffix("InterceptedFunction", "Internal")); + node.AttributeLists.AddNameSuffix("InterceptedFunction", "Internal") + ); } } } diff --git a/sources/SilkTouch/SilkTouch/Mods/MarkNativeNames.cs b/sources/SilkTouch/SilkTouch/Mods/MarkNativeNames.cs index d3c6ccf53d..ebf68b4b0e 100644 --- a/sources/SilkTouch/SilkTouch/Mods/MarkNativeNames.cs +++ b/sources/SilkTouch/SilkTouch/Mods/MarkNativeNames.cs @@ -34,10 +34,11 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) var rewriter = new Rewriter(); foreach (var docId in proj.DocumentIds) { - var doc = proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); + var doc = + proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); proj = doc.WithSyntaxRoot( rewriter.Visit(await doc.GetSyntaxRootAsync(ct))?.NormalizeWhitespace() - ?? throw new InvalidOperationException("Visit returned null.") + ?? throw new InvalidOperationException("Visit returned null.") ).Project; } @@ -46,7 +47,10 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) private class Rewriter : ModCSharpSyntaxRewriter { - private SyntaxList TryAddNativeNameAttribute(SyntaxList attributeLists, SyntaxToken identifier) + private SyntaxList TryAddNativeNameAttribute( + SyntaxList attributeLists, + SyntaxToken identifier + ) { if (attributeLists.TryGetNativeName(out _)) { @@ -61,7 +65,9 @@ private SyntaxList TryAddNativeNameAttribute(SyntaxList public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node) { - node = node.WithAttributeLists(TryAddNativeNameAttribute(node.AttributeLists, node.Identifier)); + node = node.WithAttributeLists( + TryAddNativeNameAttribute(node.AttributeLists, node.Identifier) + ); node = (StructDeclarationSyntax)base.VisitStructDeclaration(node)!; return node; } @@ -69,7 +75,9 @@ public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node) /// public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) { - node = node.WithAttributeLists(TryAddNativeNameAttribute(node.AttributeLists, node.Identifier)); + node = node.WithAttributeLists( + TryAddNativeNameAttribute(node.AttributeLists, node.Identifier) + ); node = (EnumDeclarationSyntax)base.VisitEnumDeclaration(node)!; return node; } @@ -79,7 +87,9 @@ public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) /// public override SyntaxNode VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) { - node = node.WithAttributeLists(TryAddNativeNameAttribute(node.AttributeLists, node.Identifier)); + node = node.WithAttributeLists( + TryAddNativeNameAttribute(node.AttributeLists, node.Identifier) + ); node = (EnumMemberDeclarationSyntax)base.VisitEnumMemberDeclaration(node)!; return node; } @@ -87,7 +97,9 @@ public override SyntaxNode VisitEnumMemberDeclaration(EnumMemberDeclarationSynta /// public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) { - node = node.WithAttributeLists(TryAddNativeNameAttribute(node.AttributeLists, node.Identifier)); + node = node.WithAttributeLists( + TryAddNativeNameAttribute(node.AttributeLists, node.Identifier) + ); node = (PropertyDeclarationSyntax)base.VisitPropertyDeclaration(node)!; return node; } @@ -95,7 +107,9 @@ public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax no /// public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) { - node = node.WithAttributeLists(TryAddNativeNameAttribute(node.AttributeLists, node.Identifier)); + node = node.WithAttributeLists( + TryAddNativeNameAttribute(node.AttributeLists, node.Identifier) + ); node = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!; return node; } @@ -105,7 +119,12 @@ public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node) { // This just uses the first declared field's identifier in cases where a field declares multiple variables // Eg: int a, b; - node = node.WithAttributeLists(TryAddNativeNameAttribute(node.AttributeLists, node.Declaration.Variables.First().Identifier)); + node = node.WithAttributeLists( + TryAddNativeNameAttribute( + node.AttributeLists, + node.Declaration.Variables.First().Identifier + ) + ); node = (FieldDeclarationSyntax)base.VisitFieldDeclaration(node)!; return node; } diff --git a/sources/SilkTouch/SilkTouch/Mods/MixKhronosData.cs b/sources/SilkTouch/SilkTouch/Mods/MixKhronosData.cs index 8d79142baf..d6d9f4e20d 100644 --- a/sources/SilkTouch/SilkTouch/Mods/MixKhronosData.cs +++ b/sources/SilkTouch/SilkTouch/Mods/MixKhronosData.cs @@ -274,36 +274,45 @@ public async Task InitializeAsync(IModContext ctx, CancellationToken ct = defaul job.ApiSets = apiSets; job.SupportedApiProfiles = supportedApiProfiles; - var profiles = supportedApiProfiles.SelectMany(x => x.Value).Select(x => x.Profile).ToHashSet(); - - job.Vendors.UnionWith([ - .. xml.Element("registry") - ?.Element("tags") - ?.Elements("tag") - .Attributes("name") - .Select(x => x.Value) ?? [], - .. currentConfig.NonStandardExtensionNomenclature - ? [] - : xml.Element("registry") - ?.Element("extensions") - ?.Elements("extension") - // Only include vendors who have extensions that match a declared profile - // This is mainly to exclude extensions that are declared as supported="disabled" - .Where(ext => - { - var supportedProfiles = ext.Attribute("supported")?.Value.Split("|") ?? []; - return profiles.Intersect(supportedProfiles).Any(); - }) + var profiles = supportedApiProfiles + .SelectMany(x => x.Value) + .Select(x => x.Profile) + .ToHashSet(); + + job.Vendors.UnionWith( + [ + .. xml.Element("registry") + ?.Element("tags") + ?.Elements("tag") .Attributes("name") - // Extract the second part from the extension name - // Eg: GL_NV_command_list -> NV - .Select(name => name.Value.Split('_')[1].ToUpper()) ?? [], - .. currentConfig.Vendors ?? [], - ]); + .Select(x => x.Value) ?? [], + .. currentConfig.NonStandardExtensionNomenclature + ? [] + : xml.Element("registry") + ?.Element("extensions") + ?.Elements("extension") + // Only include vendors who have extensions that match a declared profile + // This is mainly to exclude extensions that are declared as supported="disabled" + .Where(ext => + { + var supportedProfiles = + ext.Attribute("supported")?.Value.Split("|") ?? []; + return profiles.Intersect(supportedProfiles).Any(); + }) + .Attributes("name") + // Extract the second part from the extension name + // Eg: GL_NV_command_list -> NV + .Select(name => name.Value.Split('_')[1].ToUpper()) ?? [], + .. currentConfig.Vendors ?? [], + ] + ); job.DeprecatedAliases = xml.Descendants() - .Where(x => x.Attribute("deprecated")?.Value == "aliased" && x.Attribute("name") != null) - .Select(x => x.Attribute("name")!.Value).ToHashSet(); + .Where(x => + x.Attribute("deprecated")?.Value == "aliased" && x.Attribute("name") != null + ) + .Select(x => x.Attribute("name")!.Value) + .ToHashSet(); ReadGroups(xml, job, job.Vendors); @@ -360,33 +369,33 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) var rewriter1 = new RewriterPhase1(jobData, logger); foreach (var docId in proj.DocumentIds) { - var doc = proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); + var doc = + proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); proj = doc.WithSyntaxRoot( rewriter1.Visit(await doc.GetSyntaxRootAsync(ct))?.NormalizeWhitespace() - ?? throw new InvalidOperationException("Visit returned null.") + ?? throw new InvalidOperationException("Visit returned null.") ).Project; } // Add missing enum types foreach (var (filePath, node) in rewriter1.GetMissingEnums()) { - proj = proj - .AddDocument( - Path.GetFileName(filePath), - node.NormalizeWhitespace(), - filePath: proj.FullPath(filePath) - ) - .Project; + proj = proj.AddDocument( + Path.GetFileName(filePath), + node.NormalizeWhitespace(), + filePath: proj.FullPath(filePath) + ).Project; } // Rewrite phase 2 var rewriter2 = new RewriterPhase2(jobData, rewriter1); foreach (var docId in proj.DocumentIds) { - var doc = proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); + var doc = + proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); proj = doc.WithSyntaxRoot( rewriter2.Visit(await doc.GetSyntaxRootAsync(ct))?.NormalizeWhitespace() - ?? throw new InvalidOperationException("Visit returned null.") + ?? throw new InvalidOperationException("Visit returned null.") ).Project; } @@ -394,17 +403,19 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) var rewriter3 = new RewriterPhase3(jobData, currentConfig); foreach (var docId in proj.DocumentIds) { - var doc = proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); + var doc = + proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); proj = doc.WithSyntaxRoot( rewriter3.Visit(await doc.GetSyntaxRootAsync(ct))?.NormalizeWhitespace() - ?? throw new InvalidOperationException("Visit returned null.") + ?? throw new InvalidOperationException("Visit returned null.") ).Project; } // Rename documents to account for FlagBits/Flags differences foreach (var docId in proj.DocumentIds) { - var doc = proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); + var doc = + proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); if (doc.FilePath == null) { continue; @@ -421,12 +432,20 @@ public Task> BeforeScrapeAsync(string key, List { var job = Jobs[key]; - rsps = rsps.Select(rsp => rsp with - { - GeneratorConfiguration = rsp.GeneratorConfiguration.ToWrapper() with { - RemappedNames = rsp.GeneratorConfiguration.RemappedNames.Concat(job.AdditionalTypeRemappings).ToDictionary(), - }, - }).ToList(); + rsps = rsps.Select(rsp => + rsp with + { + GeneratorConfiguration = rsp.GeneratorConfiguration.ToWrapper() with + { + RemappedNames = rsp + .GeneratorConfiguration.RemappedNames.Concat( + job.AdditionalTypeRemappings + ) + .ToDictionary(), + }, + } + ) + .ToList(); return Task.FromResult(rsps); } @@ -1222,8 +1241,10 @@ public void Trim(NameTrimmerContext context) { foreach (var name in (IEnumerable)[current, .. previous]) { - if (job.Groups.TryGetValue(name, out var group) - && name == $"{group.Namespace}Enum") + if ( + job.Groups.TryGetValue(name, out var group) + && name == $"{group.Namespace}Enum" + ) { context.Names[original] = new CandidateNames(name, []); break; @@ -1491,7 +1512,11 @@ public bool TryGetSymbolMetadata( [NotNullWhen(true)] out IEnumerable? metadata ) { - if (jobKey is null || !Jobs.TryGetValue(jobKey, out var job) || job.SupportedApiProfiles is null) + if ( + jobKey is null + || !Jobs.TryGetValue(jobKey, out var job) + || job.SupportedApiProfiles is null + ) { metadata = null; return false; @@ -1604,8 +1629,8 @@ private class RewriterPhase1(JobData job, ILogger logger) : CSharpSyntaxRewriter AllKnownEnums.Add(groupName); var attributes = SingletonList( - AttributeList( - [Attribute(IdentifierName("Transformed"))])); + AttributeList([Attribute(IdentifierName("Transformed"))]) + ); if (groupInfo.NativeName != null) { @@ -1614,44 +1639,60 @@ private class RewriterPhase1(JobData job, ILogger logger) : CSharpSyntaxRewriter var baseTypeSyntax = ParseTypeName(baseType); - results.Add(( - $"Enums/{groupName}.gen.cs", - CompilationUnit() - .WithMembers( - SingletonList( - FileScopedNamespaceDeclaration(ModUtils.NamespaceIntoIdentifierName(ns)) - .WithMembers( - SingletonList( - EnumDeclaration(groupName) - .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) - .WithAttributeLists(attributes) - .WithBaseList(BaseList([SimpleBaseType(baseTypeSyntax)])) - .WithMembers( - SeparatedList( - groupInfo.Enums.Select(x => - EnumMemberDeclaration(x.Identifier.ToString()) - .WithAttributeLists( - new SyntaxList() - .WithNativeName(x.Identifier.Text)) - .WithEqualsValue( - x.Initializer?.WithValue( - CheckedExpression( - SyntaxKind.UncheckedExpression, - CastExpression( - baseTypeSyntax, - x.Initializer.Value + results.Add( + ( + $"Enums/{groupName}.gen.cs", + CompilationUnit() + .WithMembers( + SingletonList( + FileScopedNamespaceDeclaration( + ModUtils.NamespaceIntoIdentifierName(ns) + ) + .WithMembers( + SingletonList( + EnumDeclaration(groupName) + .WithModifiers( + TokenList( + Token(SyntaxKind.PublicKeyword) + ) + ) + .WithAttributeLists(attributes) + .WithBaseList( + BaseList( + [SimpleBaseType(baseTypeSyntax)] + ) + ) + .WithMembers( + SeparatedList( + groupInfo.Enums.Select(x => + EnumMemberDeclaration( + x.Identifier.ToString() + ) + .WithAttributeLists( + new SyntaxList().WithNativeName( + x.Identifier.Text + ) + ) + .WithEqualsValue( + x.Initializer?.WithValue( + CheckedExpression( + SyntaxKind.UncheckedExpression, + CastExpression( + baseTypeSyntax, + x.Initializer.Value + ) ) ) ) - ) + ) ) ) - ) + ) ) - ) + ) ) - ) - )); + ) + ); } } @@ -1673,8 +1714,10 @@ private class RewriterPhase1(JobData job, ILogger logger) : CSharpSyntaxRewriter AllKnownEnums.Add(identifier); - if (job.Groups.TryGetValue(identifier, out _) - && !node.Ancestors().OfType().Any()) + if ( + job.Groups.TryGetValue(identifier, out _) + && !node.Ancestors().OfType().Any() + ) { AlreadyPresentGroups.Add(identifier); } @@ -1685,8 +1728,10 @@ private class RewriterPhase1(JobData job, ILogger logger) : CSharpSyntaxRewriter public override SyntaxNode? VisitFieldDeclaration(FieldDeclarationSyntax node) { // Only match constant fields - if (node.Declaration.Variables.Count != 1 - || !node.Modifiers.Any(SyntaxKind.ConstKeyword)) + if ( + node.Declaration.Variables.Count != 1 + || !node.Modifiers.Any(SyntaxKind.ConstKeyword) + ) { return base.VisitFieldDeclaration(node); } @@ -1740,7 +1785,8 @@ private class RewriterPhase1(JobData job, ILogger logger) : CSharpSyntaxRewriter /// private class RewriterPhase2(JobData job, RewriterPhase1 phase1) : CSharpSyntaxRewriter(true) { - public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) => IdentifierName(node.Identifier.ToString().Replace("FlagBits", "Flags")); + public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) => + IdentifierName(node.Identifier.ToString().Replace("FlagBits", "Flags")); public override SyntaxNode? VisitEnumDeclaration(EnumDeclarationSyntax node) { @@ -1749,17 +1795,21 @@ private class RewriterPhase2(JobData job, RewriterPhase1 phase1) : CSharpSyntaxR if (node.Members.Any(m => job.DeprecatedAliases.Contains(m.Identifier.ValueText))) { // Remove deprecated aliases - node = node.WithMembers([ - ..node.Members.Where(m => !job.DeprecatedAliases.Contains(m.Identifier.ValueText)), - ]); + node = node.WithMembers( + [ + .. node.Members.Where(m => + !job.DeprecatedAliases.Contains(m.Identifier.ValueText) + ), + ] + ); } if (job.Groups.TryGetValue(identifier, out var group) && group.KnownBitmask) { // Add [Flags] attribute var flagsAttribute = AttributeList( - SingletonSeparatedList( - Attribute(IdentifierName("Flags")))); + SingletonSeparatedList(Attribute(IdentifierName("Flags"))) + ); node = node.WithAttributeLists(node.AttributeLists.Add(flagsAttribute)); } @@ -1769,12 +1819,22 @@ private class RewriterPhase2(JobData job, RewriterPhase1 phase1) : CSharpSyntaxR public override SyntaxNode? VisitFieldDeclaration(FieldDeclarationSyntax node) { - if (node.Declaration.Variables.Any(v => job.DeprecatedAliases.Contains(v.Identifier.ValueText))) + if ( + node.Declaration.Variables.Any(v => + job.DeprecatedAliases.Contains(v.Identifier.ValueText) + ) + ) { // Remove deprecated aliases - node = node.WithDeclaration(node.Declaration.WithVariables([ - ..node.Declaration.Variables.Where(v => !job.DeprecatedAliases.Contains(v.Identifier.ValueText)), - ])); + node = node.WithDeclaration( + node.Declaration.WithVariables( + [ + .. node.Declaration.Variables.Where(v => + !job.DeprecatedAliases.Contains(v.Identifier.ValueText) + ), + ] + ) + ); if (node.Declaration.Variables.Count == 0) { @@ -1816,7 +1876,10 @@ private class RewriterPhase2(JobData job, RewriterPhase1 phase1) : CSharpSyntaxR /// /// This method is intentionally implemented in a naive manner to keep things simple. /// - private bool TryGetManagedEnumType(SyntaxList attributes, [NotNullWhen(true)] out string? managedName) + private bool TryGetManagedEnumType( + SyntaxList attributes, + [NotNullWhen(true)] out string? managedName + ) { managedName = null; @@ -1853,7 +1916,12 @@ private bool TryGetManagedEnumType(SyntaxList attributes, [ /// private class RewriterPhase3(JobData job, Configuration config) : CSharpSyntaxRewriter { - private SyntaxList ProcessAndGetNewAttributes(SyntaxList attributeLists, SyntaxToken identifier, bool trimHandleSuffix, MethodDeclarationSyntax? methodDeclaration = null) + private SyntaxList ProcessAndGetNewAttributes( + SyntaxList attributeLists, + SyntaxToken identifier, + bool trimHandleSuffix, + MethodDeclarationSyntax? methodDeclaration = null + ) { // Get the name of the identifier, preferring the native one if available // This name will be modified by the code below as different suffixes are identified @@ -1886,14 +1954,21 @@ private SyntaxList ProcessAndGetNewAttributes(SyntaxList ProcessAndGetNewAttributes(SyntaxList ProcessAndGetNewAttributes(SyntaxList - node.WithAttributeLists(ProcessAndGetNewAttributes(node.AttributeLists, node.Identifier, false)); + node.WithAttributeLists( + ProcessAndGetNewAttributes(node.AttributeLists, node.Identifier, false) + ); // Special case for enums since this code needs information about // the enum type name and its member names at the same time @@ -1951,7 +2038,10 @@ public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) // Figure out the enum's exclusive vendor var exclusiveVendor = groupInfo?.ExclusiveVendor ?? typeVendor; - if (exclusiveVendor == null || !node.Members.All(member => member.Identifier.Text.EndsWith(exclusiveVendor))) + if ( + exclusiveVendor == null + || !node.Members.All(member => member.Identifier.Text.EndsWith(exclusiveVendor)) + ) { // Not all enum members share the exclusive vendor // This means the vendor suffix isn't actually exclusive @@ -1966,7 +2056,8 @@ public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) // For example, SamplePatternEXT and SamplePatternSGIS are both enum types. // Trimming both would cause conflicts. // Trimming one but not the other would imply one is core and the other is not. - var hasMultipleVersions = job.Groups.Count(x => x.Key.StartsWith(typeName[..^typeVendor.Length])) > 1; + var hasMultipleVersions = + job.Groups.Count(x => x.Key.StartsWith(typeName[..^typeVendor.Length])) > 1; var isSafeToTrimType = !hasMultipleVersions; // Identify the affix for trimming if the type vendor suffix does not match the identified exclusive vendor suffix @@ -1984,7 +2075,9 @@ public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) if (typeVendor != null) { // Mark the type vendor suffix as identified - node = node.WithAttributeLists(node.AttributeLists.AddNameSuffix(vendorAffixType, typeVendor, true)); + node = node.WithAttributeLists( + node.AttributeLists.AddNameSuffix(vendorAffixType, typeVendor, true) + ); } // Check if the enum contains unsuffixed members @@ -2012,20 +2105,43 @@ public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) var canTrimImpliedVendors = hasTypeSuffix && !containsUnsuffixedMembers; // See config option for more info and examples on what this does - if (config.IdentifyEnumMemberImpliedVendors && typeVendor != null && canTrimImpliedVendors) + if ( + config.IdentifyEnumMemberImpliedVendors + && typeVendor != null + && canTrimImpliedVendors + ) { - node = node.WithMembers([ - ..node.Members.Select(member => { - if (member.AttributeLists.GetNativeNameOrDefault(member.Identifier).EndsWith(typeVendor)) + node = node.WithMembers( + [ + .. node.Members.Select(member => { - // Identify for trimming - return member.WithAttributeLists(member.AttributeLists.AddNameSuffix("KhronosImpliedVendor", typeVendor, true)); - } + if ( + member + .AttributeLists.GetNativeNameOrDefault(member.Identifier) + .EndsWith(typeVendor) + ) + { + // Identify for trimming + return member.WithAttributeLists( + member.AttributeLists.AddNameSuffix( + "KhronosImpliedVendor", + typeVendor, + true + ) + ); + } - // Default behavior - Identify, but not for trimming - return member.WithAttributeLists(ProcessAndGetNewAttributes(member.AttributeLists, member.Identifier, false)); - }), - ]); + // Default behavior - Identify, but not for trimming + return member.WithAttributeLists( + ProcessAndGetNewAttributes( + member.AttributeLists, + member.Identifier, + false + ) + ); + }), + ] + ); } else { @@ -2039,13 +2155,19 @@ public override SyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) // ----- Members ----- public override SyntaxNode VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) => - node.WithAttributeLists(ProcessAndGetNewAttributes(node.AttributeLists, node.Identifier, false)); + node.WithAttributeLists( + ProcessAndGetNewAttributes(node.AttributeLists, node.Identifier, false) + ); public override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) => - node.WithAttributeLists(ProcessAndGetNewAttributes(node.AttributeLists, node.Identifier, false)); + node.WithAttributeLists( + ProcessAndGetNewAttributes(node.AttributeLists, node.Identifier, false) + ); public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) => - node.WithAttributeLists(ProcessAndGetNewAttributes(node.AttributeLists, node.Identifier, false, node)); + node.WithAttributeLists( + ProcessAndGetNewAttributes(node.AttributeLists, node.Identifier, false, node) + ); } [SuppressMessage("ReSharper", "MoveLocalFunctionAfterJumpStatement")] @@ -2190,7 +2312,11 @@ var group in (groupName is null ? Enumerable.Empty() : [groupName]) } // Some enum groups don't have members, meaning that the code above won't catch them - if (groupName != null && !IsUngroupable(groupName) && !data.Groups.ContainsKey(groupName)) + if ( + groupName != null + && !IsUngroupable(groupName) + && !data.Groups.ContainsKey(groupName) + ) { data.Groups[groupName] = new EnumGroup( groupName, diff --git a/sources/SilkTouch/SilkTouch/Mods/PrettifyNames.cs b/sources/SilkTouch/SilkTouch/Mods/PrettifyNames.cs index f473c69ee2..0706fc13be 100644 --- a/sources/SilkTouch/SilkTouch/Mods/PrettifyNames.cs +++ b/sources/SilkTouch/SilkTouch/Mods/PrettifyNames.cs @@ -136,9 +136,35 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) foreach (var (name, (nonFunctions, functions)) in visitor.TrimmableTypes) { newNames[name] = new RenamedType( - ApplyPrettifyOnlyPipeline(null, name, cfg.NameOverrides, nameAffixer, nameTransformer), - nonFunctions.ToDictionary(x => x, x => ApplyPrettifyOnlyPipeline(name, x, cfg.NameOverrides, nameAffixer, nameTransformer)), - functions.ToDictionary(x => x.Name, x => ApplyPrettifyOnlyPipeline(name, x.Name, cfg.NameOverrides, nameAffixer, nameTransformer)) + ApplyPrettifyOnlyPipeline( + null, + name, + cfg.NameOverrides, + nameAffixer, + nameTransformer + ), + nonFunctions.ToDictionary( + x => x, + x => + ApplyPrettifyOnlyPipeline( + name, + x, + cfg.NameOverrides, + nameAffixer, + nameTransformer + ) + ), + functions.ToDictionary( + x => x.Name, + x => + ApplyPrettifyOnlyPipeline( + name, + x.Name, + cfg.NameOverrides, + nameAffixer, + nameTransformer + ) + ) ); } } @@ -188,10 +214,7 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) // Rename the "constants" i.e. all the consts/static readonlys in this type. These are treated // individually because everything that isn't a constant or a function is only prettified instead of prettified & trimmed. - var constNames = consts.ToDictionary( - x => x, - x => new CandidateNames(x, []) - ); + var constNames = consts.ToDictionary(x => x, x => new CandidateNames(x, [])); // Trim the constants. Trim( @@ -246,12 +269,28 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) { if (!newNames.TryGetValue(typeName, out var renamedType)) { - renamedType = new RenamedType(ApplyPrettifyOnlyPipeline(null, typeName, cfg.NameOverrides, nameAffixer, nameTransformer), [], []); + renamedType = new RenamedType( + ApplyPrettifyOnlyPipeline( + null, + typeName, + cfg.NameOverrides, + nameAffixer, + nameTransformer + ), + [], + [] + ); } foreach (var memberName in memberNames) { - renamedType.NonFunctions[memberName] = ApplyPrettifyOnlyPipeline(typeName, memberName, cfg.NameOverrides, nameAffixer, nameTransformer); + renamedType.NonFunctions[memberName] = ApplyPrettifyOnlyPipeline( + typeName, + memberName, + cfg.NameOverrides, + nameAffixer, + nameTransformer + ); } newNames[typeName] = renamedType; @@ -301,16 +340,16 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) var comp = await proj.GetCompilationAsync(ct) - ?? throw new InvalidOperationException("Failed to obtain compilation for source project!"); + ?? throw new InvalidOperationException( + "Failed to obtain compilation for source project!" + ); await NameUtils.RenameAllAsync( ctx, newNames.SelectMany(x => { var nonFunctionConflicts = x - .Value.NonFunctions.Values.Where(y => - x.Value.Functions.ContainsValue(y) - ) + .Value.NonFunctions.Values.Where(y => x.Value.Functions.ContainsValue(y)) .ToHashSet(); return comp.GetSymbolsWithName(x.Key, SymbolFilter.Type, ct) .OfType() @@ -398,7 +437,9 @@ z.MethodKind is MethodKind.Constructor or MethodKind.Destructor if (found) { - logger.LogError($"{originalName} -> {doc.Name} failed to rename file as a file already exists at {doc.FilePath}"); + logger.LogError( + $"{originalName} -> {doc.Name} failed to rename file as a file already exists at {doc.FilePath}" + ); } else { @@ -420,7 +461,8 @@ private string ApplyPrettifyOnlyPipeline( string name, Dictionary nameOverrides, NameAffixer nameAffixer, - ICulturedStringTransformer nameTransformer) + ICulturedStringTransformer nameTransformer + ) { // Check for overrides foreach (var (nativeName, overriddenName) in nameOverrides) @@ -436,7 +478,10 @@ private string ApplyPrettifyOnlyPipeline( // Check whether the override is for this type. var span = nativeName.AsSpan(); var containerSpan = span[..span.IndexOf('.')]; - if (!containerSpan.Equals("*", StringComparison.Ordinal) && !containerSpan.Equals(container, StringComparison.Ordinal)) + if ( + !containerSpan.Equals("*", StringComparison.Ordinal) + && !containerSpan.Equals(container, StringComparison.Ordinal) + ) { continue; } @@ -487,7 +532,10 @@ private void Trim( // Check whether the override is for this type. var span = nativeName.AsSpan(); var containerSpan = span[..span.IndexOf('.')]; - if (containerSpan.Equals("*", StringComparison.Ordinal) || containerSpan.Equals(context.Container, StringComparison.Ordinal)) + if ( + containerSpan.Equals("*", StringComparison.Ordinal) + || containerSpan.Equals(context.Container, StringComparison.Ordinal) + ) { nameToAdd = span[(span.IndexOf('.') + 1)..].ToString(); } @@ -559,7 +607,11 @@ private void Trim( // Keep track of the method discriminators to determine whether we have incompatible overloads that need to be // renamed. We keep track of the first trimming name so that we can add it to conflictingTrimmingNames when we // do discover a conflict (along with the trimming name of the actual conflict). - var methDiscrims = new Dictionary Methods)>(); + var methDiscrims = + new Dictionary< + string, + (string? FirstTrimmingName, List Methods) + >(); var conflictingTrimmingNames = new HashSet(); while (namesToEval.GetEnumerator() is var e && e.MoveNext() && e.Current is var primary) { @@ -699,7 +751,9 @@ var conflictingTrimmingName in ( // Update the output name. var firstSecondary = context.Names[first].Secondary - ?? throw new InvalidOperationException("More than one trimming name without secondary names."); + ?? throw new InvalidOperationException( + "More than one trimming name without secondary names." + ); var firstNextPrimary = firstSecondary[^1]; firstSecondary.RemoveAt(firstSecondary.Count - 1); context.Names[first] = new CandidateNames(firstNextPrimary, firstSecondary); @@ -739,7 +793,9 @@ out var tnff // Conflict resolution! Update the output name. var secondary = context.Names[conflictingTrimmingName].Secondary - ?? throw new InvalidOperationException("More than one trimming name without secondary names."); + ?? throw new InvalidOperationException( + "More than one trimming name without secondary names." + ); var nextPrimary = secondary[^1]; secondary.RemoveAt(secondary.Count - 1); context.Names[conflictingTrimmingName] = new CandidateNames(nextPrimary, secondary); @@ -780,7 +836,7 @@ public Task> BeforeScrapeAsync(string key, List { logger.LogWarning( "{} (for {}) should use exclude-using-statics-for-enums as PrettifyNames does not resolve " - + "conflicts with members of other types.", + + "conflicts with members of other types.", responseFile.FilePath, key ); @@ -789,7 +845,7 @@ public Task> BeforeScrapeAsync(string key, List { logger.LogWarning( "{} (for {}) should use exclude-using-statics-for-guid-members as PrettifyNames does not resolve " - + "conflicts with members of other types.", + + "conflicts with members of other types.", responseFile.FilePath, key ); @@ -805,13 +861,27 @@ public Task> BeforeScrapeAsync(string key, List /// The new name of the type. /// The mappings from original names to new names of the type's non-function members. /// The mappings from original names to new names of the type's function members. - private record struct RenamedType(string NewName, Dictionary NonFunctions, Dictionary Functions); - - private record struct NameAffix(bool IsPrefix, string Category, string Affix, int DeclarationOrder); + private record struct RenamedType( + string NewName, + Dictionary NonFunctions, + Dictionary Functions + ); + + private record struct NameAffix( + bool IsPrefix, + string Category, + string Affix, + int DeclarationOrder + ); private record struct TypeData(List NonFunctions, List Functions); + private record struct FunctionData(string Name, MethodDeclarationSyntax Syntax); - private record struct TypeAffixData(NameAffix[] TypeAffixes, Dictionary? MemberAffixes); + + private record struct TypeAffixData( + NameAffix[] TypeAffixes, + Dictionary? MemberAffixes + ); private class Visitor : CSharpSyntaxWalker { @@ -859,7 +929,11 @@ private class Visitor : CSharpSyntaxWalker /// The class or struct's declaration syntax node. /// The names of the non-function members directly contained by the type. /// The names of the function members directly contained by the type. - private record struct TypeInProgress(TypeDeclarationSyntax Type, List NonFunctions, List Functions); + private record struct TypeInProgress( + TypeDeclarationSyntax Type, + List NonFunctions, + List Functions + ); /// /// Represents an enum. @@ -881,7 +955,10 @@ _typeInProgress is not null || _enumInProgress is not null || node.Ancestors().OfType().Any(); - private bool TryGetAffixData(SyntaxList attributeLists, out NameAffix[] affixes) + private bool TryGetAffixData( + SyntaxList attributeLists, + out NameAffix[] affixes + ) { affixes = []; var declarationOrder = 0; @@ -894,12 +971,22 @@ private bool TryGetAffixData(SyntaxList attributeLists, out continue; } - if (attribute.ArgumentList != null - && (attribute.ArgumentList.Arguments[0].Expression as LiteralExpressionSyntax)?.Token.Value is string type - && (attribute.ArgumentList.Arguments[1].Expression as LiteralExpressionSyntax)?.Token.Value is string category - && (attribute.ArgumentList.Arguments[2].Expression as LiteralExpressionSyntax)?.Token.Value is string affix) + var argumentList = attribute.ArgumentList; + if ( + argumentList != null + && argumentList.Arguments[0].Expression + is LiteralExpressionSyntax { Token.Value: string type } + && argumentList.Arguments[1].Expression + is LiteralExpressionSyntax { Token.Value: string category } + && argumentList.Arguments[2].Expression + is LiteralExpressionSyntax { Token.Value: string affix } + ) { - affixes = [..affixes, new NameAffix(type == "Prefix", category, affix, declarationOrder)]; + affixes = + [ + .. affixes, + new NameAffix(type == "Prefix", category, affix, declarationOrder), + ]; declarationOrder++; } } @@ -908,7 +995,10 @@ private bool TryGetAffixData(SyntaxList attributeLists, out return affixes.Length != 0; } - private void ReportTypeAffixData(string typeIdentifier, SyntaxList attributeLists) + private void ReportTypeAffixData( + string typeIdentifier, + SyntaxList attributeLists + ) { if (!TryGetAffixData(attributeLists, out var affixes)) { @@ -922,11 +1012,15 @@ private void ReportTypeAffixData(string typeIdentifier, SyntaxList attributeLists) + private void ReportMemberAffixData( + string typeIdentifier, + string memberIdentifier, + SyntaxList attributeLists + ) { if (!TryGetAffixData(attributeLists, out var affixData)) { @@ -972,7 +1066,11 @@ public override void VisitClassDeclaration(ClassDeclarationSyntax node) TrimmableTypes.Add(identifier, typeData); } - typeData.NonFunctions.AddRange(_typeInProgress.Value.NonFunctions.Where(nonFunction => !typeData.NonFunctions.Contains(nonFunction))); + typeData.NonFunctions.AddRange( + _typeInProgress.Value.NonFunctions.Where(nonFunction => + !typeData.NonFunctions.Contains(nonFunction) + ) + ); typeData.Functions.AddRange(_typeInProgress.Value.Functions); _typeInProgress = null; @@ -1004,7 +1102,11 @@ public override void VisitStructDeclaration(StructDeclarationSyntax node) TrimmableTypes.Add(identifier, typeData); } - typeData.NonFunctions.AddRange(_typeInProgress.Value.NonFunctions.Where(nonFunction => !typeData.NonFunctions.Contains(nonFunction))); + typeData.NonFunctions.AddRange( + _typeInProgress.Value.NonFunctions.Where(nonFunction => + !typeData.NonFunctions.Contains(nonFunction) + ) + ); typeData.Functions.AddRange(_typeInProgress.Value.Functions); _typeInProgress = null; @@ -1080,7 +1182,9 @@ public override void VisitFieldDeclaration(FieldDeclarationSyntax node) { // If it's not a constant then we only prettify // C constants are globally scoped and typically prefixed, so we trim in addition to prettifying - var prettifyOnly = !node.Modifiers.Any(SyntaxKind.ConstKeyword) && !node.Modifiers.Any(SyntaxKind.StaticKeyword); + var prettifyOnly = + !node.Modifiers.Any(SyntaxKind.ConstKeyword) + && !node.Modifiers.Any(SyntaxKind.StaticKeyword); if (node.Parent == _typeInProgress?.Type) { @@ -1146,7 +1250,11 @@ public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) ReportMemberAffixData(typeIdentifier, memberIdentifier, node.AttributeLists); // If it's not a constant then we only prettify. - var hasSetter = node.AccessorList?.Accessors.Any(a => a.IsKind(SyntaxKind.SetAccessorDeclaration) || a.IsKind(SyntaxKind.InitAccessorDeclaration)) ?? false; + var hasSetter = + node.AccessorList?.Accessors.Any(a => + a.IsKind(SyntaxKind.SetAccessorDeclaration) + || a.IsKind(SyntaxKind.InitAccessorDeclaration) + ) ?? false; if (hasSetter) { if (!PrettifyOnlyTypes.TryGetValue(typeIdentifier, out var typeData)) @@ -1168,13 +1276,17 @@ public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) private class RenameSafeAttributeListsRewriter : CSharpSyntaxRewriter { public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) => - ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!) - .WithRenameSafeAttributeLists(); + ( + (MethodDeclarationSyntax)base.VisitMethodDeclaration(node)! + ).WithRenameSafeAttributeLists(); } /// The affix data retrieved by the . /// The configuration from . - private class NameAffixer(Dictionary affixTypes, Dictionary config) + private class NameAffixer( + Dictionary affixTypes, + Dictionary config + ) { private static readonly NameAffixConfiguration _defaultConfig = new(); @@ -1189,7 +1301,12 @@ private class NameAffixer(Dictionary affixTypes, Dictiona /// The original name of the identifier. Either the type name or the member name. /// The list of secondary names. This should be null if used by . /// The new primary name. - public string RemoveAffixes(string primary, string? container, string originalName, List? secondary) + public string RemoveAffixes( + string primary, + string? container, + string originalName, + List? secondary + ) { var affixes = GetAffixes(container, originalName); if (affixes.Length == 0) @@ -1200,12 +1317,14 @@ public string RemoveAffixes(string primary, string? container, string originalNa var originalPrimary = primary; // Sort affixes so that the outer affixes are first - affixes.Sort(static (a, b) => - { - // Sort by descending declaration order - // Lower declaration order means the affix is closer to the inside of the name - return -a.DeclarationOrder.CompareTo(b.DeclarationOrder); - }); + affixes.Sort( + static (a, b) => + { + // Sort by descending declaration order + // Lower declaration order means the affix is closer to the inside of the name + return -a.DeclarationOrder.CompareTo(b.DeclarationOrder); + } + ); var prefixes = affixes.Where(x => x.IsPrefix).ToList(); var suffixes = affixes.Where(x => !x.IsPrefix).ToList(); @@ -1228,9 +1347,15 @@ void RemoveSide(bool isPrefix, List nameAffixes) for (var i = 0; i < nameAffixes.Count; i++) { var affix = nameAffixes[i]; - if (isPrefix ? primary.StartsWith(affix.Affix) : primary.EndsWith(affix.Affix)) + if ( + isPrefix + ? primary.StartsWith(affix.Affix) + : primary.EndsWith(affix.Affix) + ) { - primary = isPrefix ? primary[affix.Affix.Length..] : primary[..^affix.Affix.Length]; + primary = isPrefix + ? primary[affix.Affix.Length..] + : primary[..^affix.Affix.Length]; nameAffixes.RemoveAt(i); removedAffix = true; @@ -1257,7 +1382,12 @@ void RemoveSide(bool isPrefix, List nameAffixes) /// The original name of the identifier. Either the type name or the member name. /// The list of secondary names. This should be null if used by . /// The new primary name. - public string ApplyAffixes(string primary, string? container, string originalName, List? secondary) + public string ApplyAffixes( + string primary, + string? container, + string originalName, + List? secondary + ) { var affixes = GetAffixes(container, originalName); if (affixes.Length == 0) @@ -1272,17 +1402,21 @@ public string ApplyAffixes(string primary, string? container, string originalNam // Processing [..A] will give us our primary name // Processing [..A, ..B] will give us the first secondary name // Processing [..A, ..B, ..C] will give us the second secondary name - affixes.Sort((a, b) => - { - // Sort so that non-discriminator affixes are first - if (GetConfiguration(a).IsDiscriminator != GetConfiguration(b).IsDiscriminator) + affixes.Sort( + (a, b) => { - return GetConfiguration(a).IsDiscriminator.CompareTo(GetConfiguration(b).IsDiscriminator); - } + // Sort so that non-discriminator affixes are first + if (GetConfiguration(a).IsDiscriminator != GetConfiguration(b).IsDiscriminator) + { + return GetConfiguration(a) + .IsDiscriminator.CompareTo(GetConfiguration(b).IsDiscriminator); + } - // Then sort the remaining by descending priority - return -GetConfiguration(a).DiscriminatorPriority.CompareTo(GetConfiguration(b).DiscriminatorPriority); - }); + // Then sort the remaining by descending priority + return -GetConfiguration(a) + .DiscriminatorPriority.CompareTo(GetConfiguration(b).DiscriminatorPriority); + } + ); // This is guaranteed to be non-null when this method returns if there is at least one affix string? newPrimary = null; @@ -1299,7 +1433,10 @@ public string ApplyAffixes(string primary, string? container, string originalNam } // Process group if we reached the end of the non-discriminator affixes or if the priority changes - if (!hasProcessedNonDiscriminator || GetConfiguration(affix).DiscriminatorPriority < currentPriority) + if ( + !hasProcessedNonDiscriminator + || GetConfiguration(affix).DiscriminatorPriority < currentPriority + ) { hasProcessedNonDiscriminator = true; currentPriority = GetConfiguration(affix).DiscriminatorPriority; @@ -1319,19 +1456,21 @@ public string ApplyAffixes(string primary, string? container, string originalNam void CreateName(string name, Span currentAffixes) { // Sort affixes so that the inner affixes are first - currentAffixes.Sort((a, b) => - { - // Sort by descending order - // Higher order means the affix is closer to the inside of the name - if (GetConfiguration(a).Order != GetConfiguration(b).Order) + currentAffixes.Sort( + (a, b) => { - return -GetConfiguration(a).Order.CompareTo(GetConfiguration(b).Order); - } + // Sort by descending order + // Higher order means the affix is closer to the inside of the name + if (GetConfiguration(a).Order != GetConfiguration(b).Order) + { + return -GetConfiguration(a).Order.CompareTo(GetConfiguration(b).Order); + } - // Then by ascending declaration order - // Lower declaration order means the affix is closer to the inside of the name - return a.DeclarationOrder.CompareTo(b.DeclarationOrder); - }); + // Then by ascending declaration order + // Lower declaration order means the affix is closer to the inside of the name + return a.DeclarationOrder.CompareTo(b.DeclarationOrder); + } + ); foreach (var affix in currentAffixes) { @@ -1380,7 +1519,9 @@ private NameAffix[] GetAffixes(string? container, string originalName) if (affixTypes.TryGetValue(container, out typeAffixData)) { - if (typeAffixData.MemberAffixes?.TryGetValue(originalName, out var affixes) ?? false) + if ( + typeAffixData.MemberAffixes?.TryGetValue(originalName, out var affixes) ?? false + ) { return affixes; } @@ -1389,9 +1530,11 @@ private NameAffix[] GetAffixes(string? container, string originalName) return []; } - private NameAffixConfiguration GetConfiguration(NameAffix affix) => GetConfiguration(affix.Category); + private NameAffixConfiguration GetConfiguration(NameAffix affix) => + GetConfiguration(affix.Category); - private NameAffixConfiguration GetConfiguration(string category) => config.GetValueOrDefault(category, _defaultConfig); + private NameAffixConfiguration GetConfiguration(string category) => + config.GetValueOrDefault(category, _defaultConfig); } /// @@ -1423,7 +1566,12 @@ public void Trim(NameTrimmerContext context) foreach (var (original, (primary, secondary)) in context.Names) { var secondaries = secondary; - var newPrimary = affixer.RemoveAffixes(primary, context.Container, original, secondaries); + var newPrimary = affixer.RemoveAffixes( + primary, + context.Container, + original, + secondaries + ); context.Names[original] = new CandidateNames(newPrimary, secondaries); } } @@ -1457,7 +1605,12 @@ public void Trim(NameTrimmerContext context) foreach (var (original, (primary, secondary)) in context.Names) { var secondaries = secondary; - var newPrimary = affixer.ApplyAffixes(primary, context.Container, original, secondaries); + var newPrimary = affixer.ApplyAffixes( + primary, + context.Container, + original, + secondaries + ); context.Names[original] = new CandidateNames(newPrimary, secondaries); } } @@ -1483,7 +1636,10 @@ public void Trim(NameTrimmerContext context) secondary[i] = secondary[i].Prettify(nameTransformer, allowAllCaps); } - context.Names[original] = new CandidateNames(primary.Prettify(nameTransformer, allowAllCaps), secondary); + context.Names[original] = new CandidateNames( + primary.Prettify(nameTransformer, allowAllCaps), + secondary + ); } } } diff --git a/sources/SilkTouch/SilkTouch/Mods/StripAttributes.cs b/sources/SilkTouch/SilkTouch/Mods/StripAttributes.cs index 09e2e10091..9bf511bf3b 100644 --- a/sources/SilkTouch/SilkTouch/Mods/StripAttributes.cs +++ b/sources/SilkTouch/SilkTouch/Mods/StripAttributes.cs @@ -45,10 +45,11 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) var rewriter = new Rewriter(config); foreach (var docId in proj.DocumentIds) { - var doc = proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); + var doc = + proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); proj = doc.WithSyntaxRoot( rewriter.Visit(await doc.GetSyntaxRootAsync(ct))?.NormalizeWhitespace() - ?? throw new InvalidOperationException("Visit returned null.") + ?? throw new InvalidOperationException("Visit returned null.") ).Project; } @@ -57,13 +58,20 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) private class Rewriter(Configuration config) : ModCSharpSyntaxRewriter { - private SyntaxList StripAttributes(SyntaxList attributeLists) + private SyntaxList StripAttributes( + SyntaxList attributeLists + ) { var results = attributeLists .Select(list => { var attributes = list.Attributes; - attributes = [..attributes.Where(attribute => !config.Remove.Contains(attribute.Name.ToString()))]; + attributes = + [ + .. attributes.Where(attribute => + !config.Remove.Contains(attribute.Name.ToString()) + ), + ]; return attributes.Count == 0 ? null : list.WithAttributes(attributes); }) diff --git a/sources/SilkTouch/SilkTouch/Mods/TransformEnums.cs b/sources/SilkTouch/SilkTouch/Mods/TransformEnums.cs index 81c6c91f37..e3fa94640f 100644 --- a/sources/SilkTouch/SilkTouch/Mods/TransformEnums.cs +++ b/sources/SilkTouch/SilkTouch/Mods/TransformEnums.cs @@ -65,7 +65,8 @@ public record Configuration /// The strategy to use when coercing backing types. /// Defaults to not modify the backing types at all. /// - public EnumBackingTypePreference CoerceBackingTypes { get; init; } = EnumBackingTypePreference.None; + public EnumBackingTypePreference CoerceBackingTypes { get; init; } = + EnumBackingTypePreference.None; /// /// Whether to rewrite enum member values or not. @@ -116,7 +117,10 @@ public EnumMemberFilter(EnumMemberFilterConfiguration configuration) { if (configuration.MemberValue.StartsWith("0x")) { - MemberValue = long.Parse(configuration.MemberValue["0x".Length..], NumberStyles.AllowHexSpecifier); + MemberValue = long.Parse( + configuration.MemberValue["0x".Length..], + NumberStyles.AllowHexSpecifier + ); } else { @@ -163,7 +167,9 @@ public bool IsMemberMatch(ISymbol? enumMember) public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) { var config = cfg.Get(ctx.JobKey); - var removeMemberFilters = config.RemoveMembers.Select(c => new EnumMemberFilter(c)).ToList(); + var removeMemberFilters = config + .RemoveMembers.Select(c => new EnumMemberFilter(c)) + .ToList(); var proj = ctx.SourceProject; if (proj == null) @@ -181,17 +187,23 @@ public async Task ExecuteAsync(IModContext ctx, CancellationToken ct = default) var rewriter = new Rewriter(config, removeMemberFilters, compilation, memberRewriteDecider); foreach (var docId in proj.DocumentIds) { - var doc = proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); + var doc = + proj.GetDocument(docId) ?? throw new InvalidOperationException("Document missing"); proj = doc.WithSyntaxRoot( rewriter.Visit(await doc.GetSyntaxRootAsync(ct))?.NormalizeWhitespace() - ?? throw new InvalidOperationException("Visit returned null.") + ?? throw new InvalidOperationException("Visit returned null.") ).Project; } ctx.SourceProject = proj; } - private class Rewriter(Configuration config, List removeMemberFilters, Compilation compilation, MemberRewriteDecider memberRewriteDecider) : CSharpSyntaxRewriter + private class Rewriter( + Configuration config, + List removeMemberFilters, + Compilation compilation, + MemberRewriteDecider memberRewriteDecider + ) : CSharpSyntaxRewriter { public override SyntaxNode? VisitEnumDeclaration(EnumDeclarationSyntax node) { @@ -223,31 +235,34 @@ private class Rewriter(Configuration config, List removeMember if (isFlagsEnum && config.AddNoneMemberToFlags) { // Add None member if it doesn't exist yet - var hasNoneMember = symbol.Members().Any(member => - { - if (member is not IFieldSymbol fieldSymbol) + var hasNoneMember = symbol + .Members() + .Any(member => { - return false; - } + if (member is not IFieldSymbol fieldSymbol) + { + return false; + } - if (member.Name == "None") - { - return true; - } + if (member.Name == "None") + { + return true; + } - if (fieldSymbol.ConstantValue == null) - { - // We don't know the constant value for sure - // Return false as a default - return false; - } + if (fieldSymbol.ConstantValue == null) + { + // We don't know the constant value for sure + // Return false as a default + return false; + } - return Convert.ToInt64(fieldSymbol.ConstantValue) == 0; - }); + return Convert.ToInt64(fieldSymbol.ConstantValue) == 0; + }); if (!hasNoneMember) { - var noneMember = EnumMemberDeclaration("None").WithEqualsValue(CreateEqualsValueClause(0, isFlagsEnum)); + var noneMember = EnumMemberDeclaration("None") + .WithEqualsValue(CreateEqualsValueClause(0, isFlagsEnum)); members.Insert(0, noneMember); } } @@ -263,14 +278,26 @@ private class Rewriter(Configuration config, List removeMember { var type = semanticModel.GetTypeInfo(t.Type).Type; - if (SymbolEqualityComparer.Default.Equals(type, compilation.GetSpecialType(SpecialType.System_UInt32))) + if ( + SymbolEqualityComparer.Default.Equals( + type, + compilation.GetSpecialType(SpecialType.System_UInt32) + ) + ) { return null; } - if (SymbolEqualityComparer.Default.Equals(type, compilation.GetSpecialType(SpecialType.System_UInt64))) + if ( + SymbolEqualityComparer.Default.Equals( + type, + compilation.GetSpecialType(SpecialType.System_UInt64) + ) + ) { - return SimpleBaseType(PredefinedType(Token(SyntaxKind.LongKeyword))); + return SimpleBaseType( + PredefinedType(Token(SyntaxKind.LongKeyword)) + ); } return t; @@ -285,7 +312,7 @@ private class Rewriter(Configuration config, List removeMember } else { - node = node.WithBaseList(BaseList([..baseTypes])); + node = node.WithBaseList(BaseList([.. baseTypes])); } break; @@ -293,7 +320,8 @@ private class Rewriter(Configuration config, List removeMember case EnumBackingTypePreference.PreferUnsigned: { - var hasNegativeValues = members.Any(m => { + var hasNegativeValues = members.Any(m => + { if (m.Parent == null) { return false; @@ -321,14 +349,28 @@ private class Rewriter(Configuration config, List removeMember { var type = semanticModel.GetTypeInfo(t.Type).Type; - if (SymbolEqualityComparer.Default.Equals(type, compilation.GetSpecialType(SpecialType.System_Int32))) + if ( + SymbolEqualityComparer.Default.Equals( + type, + compilation.GetSpecialType(SpecialType.System_Int32) + ) + ) { - return SimpleBaseType(PredefinedType(Token(SyntaxKind.UIntKeyword))); + return SimpleBaseType( + PredefinedType(Token(SyntaxKind.UIntKeyword)) + ); } - if (SymbolEqualityComparer.Default.Equals(type, compilation.GetSpecialType(SpecialType.System_Int64))) + if ( + SymbolEqualityComparer.Default.Equals( + type, + compilation.GetSpecialType(SpecialType.System_Int64) + ) + ) { - return SimpleBaseType(PredefinedType(Token(SyntaxKind.ULongKeyword))); + return SimpleBaseType( + PredefinedType(Token(SyntaxKind.ULongKeyword)) + ); } return t; @@ -339,11 +381,15 @@ private class Rewriter(Configuration config, List removeMember if (baseTypes.Count == 0) { - node = node.WithBaseList(BaseList([SimpleBaseType(PredefinedType(Token(SyntaxKind.UIntKeyword)))])); + node = node.WithBaseList( + BaseList( + [SimpleBaseType(PredefinedType(Token(SyntaxKind.UIntKeyword)))] + ) + ); } else { - node = node.WithBaseList(BaseList([..baseTypes])); + node = node.WithBaseList(BaseList([.. baseTypes])); } break; @@ -386,7 +432,7 @@ private class Rewriter(Configuration config, List removeMember .ToList(); } - node = node.WithMembers([..members]); + node = node.WithMembers([.. members]); return base.VisitEnumDeclaration(node); } @@ -395,8 +441,11 @@ private EqualsValueClauseSyntax CreateEqualsValueClause(long value, bool useHex) { var stringValue = useHex ? $"0x{value:X}" : $"{value}"; return EqualsValueClause( - LiteralExpression(SyntaxKind.NumericLiteralExpression, - Literal([], stringValue, value, []))); + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal([], stringValue, value, []) + ) + ); } } diff --git a/sources/SilkTouch/SilkTouch/Mods/TransformHandles.cs b/sources/SilkTouch/SilkTouch/Mods/TransformHandles.cs index b7362868f2..dd21eb2e6e 100644 --- a/sources/SilkTouch/SilkTouch/Mods/TransformHandles.cs +++ b/sources/SilkTouch/SilkTouch/Mods/TransformHandles.cs @@ -31,7 +31,10 @@ namespace Silk.NET.SilkTouch.Mods; /// Program, Program must be declared in Silk.NET.OpenGL, Silk.NET, or Silk. /// [ModConfiguration] -public class TransformHandles(IOptionsSnapshot config, ILogger logger) : Mod +public class TransformHandles( + IOptionsSnapshot config, + ILogger logger +) : Mod { /// /// The configuration for the mod. @@ -82,10 +85,13 @@ public override async Task ExecuteAsync(IModContext ctx, CancellationToken ct = foreach (var (fullyQualifiedName, node) in syntaxNodes) { var relativePath = $"Handles/{PathForFullyQualified(fullyQualifiedName)}"; - project = project.AddDocument( - Path.GetFileName(relativePath), - node.NormalizeWhitespace(), - filePath: project.FullPath(relativePath)).Project; + project = project + .AddDocument( + Path.GetFileName(relativePath), + node.NormalizeWhitespace(), + filePath: project.FullPath(relativePath) + ) + .Project; } // Update compilation @@ -109,7 +115,9 @@ public override async Task ExecuteAsync(IModContext ctx, CancellationToken ct = { // The struct is defined in multiple places (eg: partial keyword) // This means we don't know which of the parts to rewrite - throw new InvalidOperationException("Struct has more than 1 declaring syntax reference"); + throw new InvalidOperationException( + "Struct has more than 1 declaring syntax reference" + ); } var declaringSyntaxReference = handleTypeSymbol.DeclaringSyntaxReferences.Single(); @@ -123,16 +131,22 @@ public override async Task ExecuteAsync(IModContext ctx, CancellationToken ct = // Do the two following transformation to all references of the handle types: // 2. Reduce pointer dimensions ctx.SourceProject = project; - await LocationTransformationUtils.ModifyAllReferencesAsync(ctx, handleTypes, [ - new PointerDimensionReductionTransformer(), - ], logger, ct); + await LocationTransformationUtils.ModifyAllReferencesAsync( + ctx, + handleTypes, + [new PointerDimensionReductionTransformer()], + logger, + ct + ); project = ctx.SourceProject; // Use document IDs from earlier var handleTypeRewriter = new HandleTypeRewriter(cfg.UseDSL); foreach (var (originalName, documentId) in handleTypeDocumentIds) { - var document = project.GetDocument(documentId) ?? throw new InvalidOperationException("Failed to find document"); + var document = + project.GetDocument(documentId) + ?? throw new InvalidOperationException("Failed to find document"); var syntaxTree = await document.GetSyntaxTreeAsync(ct); if (syntaxTree == null) @@ -143,7 +157,9 @@ await LocationTransformationUtils.ModifyAllReferencesAsync(ctx, handleTypes, [ var syntaxRoot = await syntaxTree.GetRootAsync(ct); // Rewrite handle struct to include handle members - document = document.WithSyntaxRoot(handleTypeRewriter.Visit(syntaxRoot).NormalizeWhitespace()); + document = document.WithSyntaxRoot( + handleTypeRewriter.Visit(syntaxRoot).NormalizeWhitespace() + ); project = document.Project; } @@ -153,10 +169,16 @@ await LocationTransformationUtils.ModifyAllReferencesAsync(ctx, handleTypes, [ return; } - private class MissingHandleTypeDiscoverer(ILogger logger, Compilation compilation, CancellationToken ct) : SymbolVisitor + private class MissingHandleTypeDiscoverer( + ILogger logger, + Compilation compilation, + CancellationToken ct + ) : SymbolVisitor { - private readonly HashSet _nonHandleTypes = new(SymbolEqualityComparer.Default); - private readonly Dictionary _missingTypes = new(SymbolEqualityComparer.Default); + private readonly HashSet _nonHandleTypes = + new(SymbolEqualityComparer.Default); + private readonly Dictionary _missingTypes = + new(SymbolEqualityComparer.Default); private string? _currentNamespace = null; private int _pointerTypeDepth = 0; @@ -169,7 +191,8 @@ public Dictionary GetMissingHandleTypes() // We need to find and generate all missing handle types // Handle types are types that are only referenced through a pointer // We do this by parsing through the list of type errors - var typeErrors = compilation.GetDiagnostics(ct) + var typeErrors = compilation + .GetDiagnostics(ct) .Where(d => d.Id == "CS0246") // Type errors .ToList(); @@ -215,7 +238,10 @@ public Dictionary GetMissingHandleTypes() } case MemberDeclarationSyntax memberDeclarationSyntax: { - var symbol = semanticModel.GetDeclaredSymbol(memberDeclarationSyntax, ct); + var symbol = semanticModel.GetDeclaredSymbol( + memberDeclarationSyntax, + ct + ); if (symbol != null) { symbolsFound.Add(symbol); @@ -239,7 +265,9 @@ public Dictionary GetMissingHandleTypes() if (!isSuccess) { // This is to warn of unhandled cases - logger.LogWarning("Failed to find corresponding symbol for type error. There may be an unhandled case in the code"); + logger.LogWarning( + "Failed to find corresponding symbol for type error. There may be an unhandled case in the code" + ); } } @@ -249,7 +277,10 @@ public Dictionary GetMissingHandleTypes() Visit(symbol); } - return new Dictionary(_missingTypes.Where(kvp => !_nonHandleTypes.Contains(kvp.Key)), SymbolEqualityComparer.Default); + return new Dictionary( + _missingTypes.Where(kvp => !_nonHandleTypes.Contains(kvp.Key)), + SymbolEqualityComparer.Default + ); } public override void VisitMethod(IMethodSymbol symbol) @@ -317,7 +348,9 @@ public override void VisitNamedType(INamedTypeSymbol symbol) { if (_currentNamespace == null) { - throw new InvalidOperationException($"{nameof(_currentNamespace)} should not be null"); + throw new InvalidOperationException( + $"{nameof(_currentNamespace)} should not be null" + ); } if (_pointerTypeDepth == 0) @@ -327,7 +360,9 @@ public override void VisitNamedType(INamedTypeSymbol symbol) if (_missingTypes.TryGetValue(errorTypeSymbol, out var sharedNamespace)) { - _missingTypes[errorTypeSymbol] = NameUtils.FindCommonPrefix([sharedNamespace, _currentNamespace], true, false, true).Trim('.'); + _missingTypes[errorTypeSymbol] = NameUtils + .FindCommonPrefix([sharedNamespace, _currentNamespace], true, false, true) + .Trim('.'); } else { @@ -345,10 +380,13 @@ private class EmptyStructGenerator /// Map from error type symbol to the namespace the type should be created in. /// Map from the fully qualified name of the generated type to the syntax node containing code for that type. public Dictionary GenerateSyntaxNodes( - Dictionary typesToGenerate) => - GenerateSyntaxNodes(typesToGenerate - .Select(kvp => new KeyValuePair(kvp.Key.Name, kvp.Value)) - .ToDictionary()); + Dictionary typesToGenerate + ) => + GenerateSyntaxNodes( + typesToGenerate + .Select(kvp => new KeyValuePair(kvp.Key.Name, kvp.Value)) + .ToDictionary() + ); /// /// Generates a syntax node for each specified type. @@ -356,7 +394,8 @@ public Dictionary GenerateSyntaxNodes( /// Map from type name to the namespace the type should be created in. /// Map from the fully qualified name of the generated type to the syntax node containing code for that type. public Dictionary GenerateSyntaxNodes( - Dictionary missingHandleTypes) + Dictionary missingHandleTypes + ) { var results = new Dictionary(); foreach (var (name, ns) in missingHandleTypes) @@ -379,7 +418,11 @@ public Dictionary GenerateSyntaxNodes( : FileScopedNamespaceDeclaration( ModUtils.NamespaceIntoIdentifierName(ns) ) - .WithMembers(SingletonList(structDeclarationSyntax)) + .WithMembers( + SingletonList( + structDeclarationSyntax + ) + ) ) ); } @@ -388,7 +431,11 @@ public Dictionary GenerateSyntaxNodes( } } - private class HandleTypeDiscoverer(Project project, Compilation compilation, CancellationToken ct) : SymbolVisitor + private class HandleTypeDiscoverer( + Project project, + Compilation compilation, + CancellationToken ct + ) : SymbolVisitor { private readonly Solution _solution = project.Solution; @@ -412,7 +459,12 @@ public async Task> GetHandleTypesAsync() // For each struct, find its references // Verify that all references are through pointers // Also verify that there is at least one reference through a pointer - var references = await SymbolFinder.FindReferencesAsync(structSymbol, _solution, documents, ct); + var references = await SymbolFinder.FindReferencesAsync( + structSymbol, + _solution, + documents, + ct + ); var wasReferencedAsPointer = false; var wasReferencedAsNonPointer = false; @@ -468,7 +520,11 @@ public override void VisitNamedType(INamedTypeSymbol symbol) // Find empty structs // IsImplicitlyDeclared lets us ignore implicitly declared constructors // SpecialType lets us ignore Void and System.RuntimeArgumentHandle - if (symbol.TypeKind != TypeKind.Struct || symbol.Members().Any(member => !member.IsImplicitlyDeclared) || symbol.SpecialType != SpecialType.None) + if ( + symbol.TypeKind != TypeKind.Struct + || symbol.Members().Any(member => !member.IsImplicitlyDeclared) + || symbol.SpecialType != SpecialType.None + ) { return; } @@ -482,15 +538,16 @@ private class HandleTypeRewriter(bool useDSL) : CSharpSyntaxRewriter public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node) { var structName = node.Identifier.Text; - return node - .WithIdentifier(Identifier(structName)) + return node.WithIdentifier(Identifier(structName)) .WithAttributeLists( new SyntaxList() .WithNativeName(structName) - .AddNameSuffix("HandleType", "Handle")) + .AddNameSuffix("HandleType", "Handle") + ) .WithMembers( List( - GetDefaultHandleMembers(structName).Concat(useDSL ? GetDSLHandleMembers(structName) : []) + GetDefaultHandleMembers(structName) + .Concat(useDSL ? GetDSLHandleMembers(structName) : []) ) ) .WithModifiers( @@ -503,7 +560,9 @@ public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node) ); } - private static IEnumerable GetDefaultHandleMembers(string structName) + private static IEnumerable GetDefaultHandleMembers( + string structName + ) { var backingType = PointerType(PredefinedType(Token(SyntaxKind.VoidKeyword))); @@ -518,11 +577,13 @@ private static IEnumerable GetDefaultHandleMembers(stri ); yield return ConstructorDeclaration(Identifier(structName)) - .WithModifiers( - TokenList(Token(SyntaxKind.PublicKeyword)) - ) - .WithParameterList(ParameterList( - SingletonSeparatedList(Parameter(Identifier("handle")).WithType(backingType))) + .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))) + .WithParameterList( + ParameterList( + SingletonSeparatedList( + Parameter(Identifier("handle")).WithType(backingType) + ) + ) ) .WithBody( Block( @@ -648,7 +709,7 @@ private static IEnumerable GetDefaultHandleMembers(stri { Parameter(Identifier("left")).WithType(IdentifierName(structName)), Token(SyntaxKind.CommaToken), - Parameter(Identifier("right")).WithType(IdentifierName(structName)) + Parameter(Identifier("right")).WithType(IdentifierName(structName)), } ) ) @@ -683,7 +744,7 @@ private static IEnumerable GetDefaultHandleMembers(stri SeparatedList( [ Parameter(Identifier("left")).WithType(IdentifierName(structName)), - Parameter(Identifier("right")).WithType(IdentifierName(structName)) + Parameter(Identifier("right")).WithType(IdentifierName(structName)), ] ) ) @@ -748,7 +809,7 @@ private static IEnumerable GetDSLHandleMembers(string s { Parameter(Identifier("left")).WithType(IdentifierName(structName)), Token(SyntaxKind.CommaToken), - Parameter(Identifier("right")).WithType(IdentifierName("NullPtr")) + Parameter(Identifier("right")).WithType(IdentifierName("NullPtr")), } ) ) @@ -783,7 +844,7 @@ private static IEnumerable GetDSLHandleMembers(string s SeparatedList( [ Parameter(Identifier("left")).WithType(IdentifierName(structName)), - Parameter(Identifier("right")).WithType(IdentifierName("NullPtr")) + Parameter(Identifier("right")).WithType(IdentifierName("NullPtr")), ] ) ) diff --git a/sources/SilkTouch/SilkTouch/Mods/Transformation/ArrayParameterTransformer.cs b/sources/SilkTouch/SilkTouch/Mods/Transformation/ArrayParameterTransformer.cs index 38200c6165..290e0c5cfb 100644 --- a/sources/SilkTouch/SilkTouch/Mods/Transformation/ArrayParameterTransformer.cs +++ b/sources/SilkTouch/SilkTouch/Mods/Transformation/ArrayParameterTransformer.cs @@ -87,8 +87,8 @@ decl.ReturnType is not PredefinedTypeSyntax pt x.CountParamIdx, // 2. Select only the last parameter this count parameter is associated with ParamForCount: x.ParamsForCount.Select( - (y, j) => (PtrParamInfo: y, ParamForCountIdx: j) - ) + (y, j) => (PtrParamInfo: y, ParamForCountIdx: j) + ) .LastOrDefault() ) ) @@ -234,7 +234,12 @@ bool isHr public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) => node.WithIdentifier( // TODO: Temporarily hack to fix issue where OpenGL -OES vendor suffix gets replaced with -O - Identifier(node.Identifier.Text.EndsWith("OES") ? node.Identifier.Text : node.Identifier.Text.Singularize(false))) + Identifier( + node.Identifier.Text.EndsWith("OES") + ? node.Identifier.Text + : node.Identifier.Text.Singularize(false) + ) + ) .WithReturnType( isOutput ? ptrElementType : PredefinedType(Token(SyntaxKind.VoidKeyword)) ) @@ -255,7 +260,6 @@ is BlockSyntax blk // call. ? Block( (StatementSyntax[]) - [ LocalDeclarationStatement( VariableDeclaration( @@ -273,7 +277,7 @@ is BlockSyntax blk ) ), .. blk.Statements, - ReturnStatement(IdentifierName(ptrParam)) + ReturnStatement(IdentifierName(ptrParam)), ] ) : blk @@ -311,15 +315,15 @@ public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node) => ? syn.WithParameters( SeparatedList( syn.Parameters.Select(x => - x.Identifier.ToString() == countParam - || (isOutput && x.Identifier.ToString() == ptrParam) - ? null + x.Identifier.ToString() == countParam + || (isOutput && x.Identifier.ToString() == ptrParam) + ? null : base.VisitParameter(x) is ParameterSyntax p ? p.Identifier.ToString() == ptrParam - ? p.WithType(ptrElementType) + ? p.WithType(ptrElementType) : p - : null - ) + : null + ) .OfType() ) ) diff --git a/sources/SilkTouch/SilkTouch/Mods/Transformation/FunctionTransformer.cs b/sources/SilkTouch/SilkTouch/Mods/Transformation/FunctionTransformer.cs index a65454ef57..3ca2698ef7 100644 --- a/sources/SilkTouch/SilkTouch/Mods/Transformation/FunctionTransformer.cs +++ b/sources/SilkTouch/SilkTouch/Mods/Transformation/FunctionTransformer.cs @@ -182,7 +182,8 @@ meth.Body.Statements[0] as ExpressionStatementSyntax .WithIdentifier(Identifier(newIden)); newFun = newFun.WithAttributeLists( - newFun.AttributeLists.AddNameSuffix("RawFunction", "Raw")); + newFun.AttributeLists.AddNameSuffix("RawFunction", "Raw") + ); discrim = ModUtils.DiscrimStr( function.Modifiers, @@ -255,7 +256,9 @@ Action transform x.Attributes.Where(y => !y.IsAttribute("System.Runtime.InteropServices.DllImport") && !y.IsAttribute("Silk.NET.Core.NativeFunction") - && !y.IsAttribute("System.Runtime.CompilerServices.MethodImpl") + && !y.IsAttribute( + "System.Runtime.CompilerServices.MethodImpl" + ) ) ) ) diff --git a/sources/SilkTouch/SilkTouch/Naming/CandidateNamesWithOriginal.cs b/sources/SilkTouch/SilkTouch/Naming/CandidateNamesWithOriginal.cs index 98dcbfa1e4..2f2512704c 100644 --- a/sources/SilkTouch/SilkTouch/Naming/CandidateNamesWithOriginal.cs +++ b/sources/SilkTouch/SilkTouch/Naming/CandidateNamesWithOriginal.cs @@ -10,7 +10,11 @@ namespace Silk.NET.SilkTouch.Naming; /// The preferred version of the trimmed name. /// The fallback versions of the trimmed name in case the primary does not work. /// The original, unmodified name. -public record struct CandidateNamesWithOriginal(string Primary, List Secondary, string Original) +public record struct CandidateNamesWithOriginal( + string Primary, + List Secondary, + string Original +) { /// /// Formats this instance as a string. diff --git a/sources/SilkTouch/SilkTouch/Naming/NameTrimmer.cs b/sources/SilkTouch/SilkTouch/Naming/NameTrimmer.cs index c8a8ff7718..10579dbb15 100644 --- a/sources/SilkTouch/SilkTouch/Naming/NameTrimmer.cs +++ b/sources/SilkTouch/SilkTouch/Naming/NameTrimmer.cs @@ -168,7 +168,10 @@ hint is null // this was trimmingName originally. given that we're using trimming name to determine a prefix but then // using that prefix on the old primary, this could cause intended behaviour in some cases. there's probably // a better way to do this. (this is working around glDisablei -> glDisable -> Disablei). - context.Names![originalName] = new CandidateNames(oldPrimary[prefixLen..].Trim('_'), sec); + context.Names![originalName] = new CandidateNames( + oldPrimary[prefixLen..].Trim('_'), + sec + ); break; } } diff --git a/sources/SilkTouch/SilkTouch/Naming/NameUtils.cs b/sources/SilkTouch/SilkTouch/Naming/NameUtils.cs index a23297ce68..247b893ccc 100644 --- a/sources/SilkTouch/SilkTouch/Naming/NameUtils.cs +++ b/sources/SilkTouch/SilkTouch/Naming/NameUtils.cs @@ -46,7 +46,11 @@ public static partial class NameUtils /// /// Whether the output is allowed to be fully capitalised ("all caps"). /// The pretty string. - public static string Prettify(this string str, ICulturedStringTransformer nameTransformer, bool allowAllCaps = false) + public static string Prettify( + this string str, + ICulturedStringTransformer nameTransformer, + bool allowAllCaps = false + ) { if (str.Length == 0) { @@ -64,7 +68,9 @@ public static string Prettify(this string str, ICulturedStringTransformer nameTr if (ret.Length == 0) { - throw new InvalidOperationException($"Prettification for '{str}' led to an empty string"); + throw new InvalidOperationException( + $"Prettification for '{str}' led to an empty string" + ); } // Disallow all capitals @@ -328,8 +334,12 @@ public static async Task RenameAllAsync( ) { var newNames = toRename.ToList(); - await LocationTransformationUtils.ModifyAllReferencesAsync(ctx, newNames.Select(x => x.Symbol), [ - new IdentifierRenamingTransformer(newNames), - ], logger, ct); + await LocationTransformationUtils.ModifyAllReferencesAsync( + ctx, + newNames.Select(x => x.Symbol), + [new IdentifierRenamingTransformer(newNames)], + logger, + ct + ); } } diff --git a/sources/SilkTouch/SilkTouch/Sources/IInputResolver.cs b/sources/SilkTouch/SilkTouch/Sources/IInputResolver.cs index d78b13ec67..f5575a8890 100644 --- a/sources/SilkTouch/SilkTouch/Sources/IInputResolver.cs +++ b/sources/SilkTouch/SilkTouch/Sources/IInputResolver.cs @@ -89,10 +89,13 @@ async Task ResolveInPlace(IList rsps) (await TryResolvePath(rsp.FileDirectory))?.Replace('\\', '/') ?? rsp.FileDirectory, ClangCommandLineArgs = rsp.ClangCommandLineArgs, - GeneratorConfiguration = rsp.GeneratorConfiguration.ToWrapper() with { + GeneratorConfiguration = rsp.GeneratorConfiguration.ToWrapper() with + { OutputLocation = await ResolvePath(rsp.GeneratorConfiguration.OutputLocation), TraversalNames = traversals, - TestOutputLocation = await ResolvePath(rsp.GeneratorConfiguration.TestOutputLocation), + TestOutputLocation = await ResolvePath( + rsp.GeneratorConfiguration.TestOutputLocation + ), }, }; } @@ -130,7 +133,7 @@ async Task ResolveInPlace(IList files) : await ResolvePath(config.InputSourceRoot), InputTestRoot = config.InputTestRoot is null ? null - : await ResolvePath(config.InputTestRoot) + : await ResolvePath(config.InputTestRoot), }; } @@ -145,6 +148,6 @@ config with SourceProject = config.SourceProject is null ? null : await ResolvePath(config.SourceProject), - TestProject = config.TestProject is null ? null : await ResolvePath(config.TestProject) + TestProject = config.TestProject is null ? null : await ResolvePath(config.TestProject), }; } diff --git a/tests/SilkTouch/SilkTouch/Khronos/MixKhronosDataTests.cs b/tests/SilkTouch/SilkTouch/Khronos/MixKhronosDataTests.cs index 00c0df6d98..a64ee5a3db 100644 --- a/tests/SilkTouch/SilkTouch/Khronos/MixKhronosDataTests.cs +++ b/tests/SilkTouch/SilkTouch/Khronos/MixKhronosDataTests.cs @@ -339,7 +339,10 @@ public void OverzealousNameTrimming() var names = new Dictionary { { "GL_PIXEL_COUNT_NV", new CandidateNames("GL_PIXEL_COUNT_NV", []) }, - { "GL_PIXEL_COUNT_AVAILABLE_NV", new CandidateNames("GL_PIXEL_COUNT_AVAILABLE_NV", []) }, + { + "GL_PIXEL_COUNT_AVAILABLE_NV", + new CandidateNames("GL_PIXEL_COUNT_AVAILABLE_NV", []) + }, }; var ctx = new NameTrimmerContext { @@ -351,7 +354,10 @@ public void OverzealousNameTrimming() baseTrimmer.Trim(ctx); uut.Trim(ctx); Assert.That(names["GL_PIXEL_COUNT_NV"].Primary, Is.EqualTo("PixelCount")); - Assert.That(names["GL_PIXEL_COUNT_AVAILABLE_NV"].Primary, Is.EqualTo("PixelCountAvailable")); + Assert.That( + names["GL_PIXEL_COUNT_AVAILABLE_NV"].Primary, + Is.EqualTo("PixelCountAvailable") + ); } [Test] diff --git a/tests/SilkTouch/SilkTouch/Naming/NameTests.cs b/tests/SilkTouch/SilkTouch/Naming/NameTests.cs index 3ccc1398b6..23eb2c3376 100644 --- a/tests/SilkTouch/SilkTouch/Naming/NameTests.cs +++ b/tests/SilkTouch/SilkTouch/Naming/NameTests.cs @@ -52,7 +52,10 @@ public void SimpleGlfwTestDetermination(string? hint) }; foreach (var (key, (trimmed, _)) in test) { - Assert.That(trimmed.Prettify(new NameUtils.NameTransformer(4)), Is.EqualTo(expected[key])); + Assert.That( + trimmed.Prettify(new NameUtils.NameTransformer(4)), + Is.EqualTo(expected[key]) + ); } } @@ -84,7 +87,10 @@ public void RegressionFragmentShaderColorModMaskATI() }; foreach (var (key, (trimmed, _)) in test) { - Assert.That(trimmed.Prettify(new NameUtils.NameTransformer(4)), Is.EqualTo(expected[key])); + Assert.That( + trimmed.Prettify(new NameUtils.NameTransformer(4)), + Is.EqualTo(expected[key]) + ); } } @@ -112,7 +118,10 @@ public void RegressionEvalTargetNV() }; foreach (var (key, (trimmed, _)) in test) { - Assert.That(trimmed.Prettify(new NameUtils.NameTransformer(4)), Is.EqualTo(expected[key])); + Assert.That( + trimmed.Prettify(new NameUtils.NameTransformer(4)), + Is.EqualTo(expected[key]) + ); } } @@ -158,6 +167,9 @@ public void MultipleGlobalPrefixHints() }; var uut = new NameTrimmer(); uut.Trim(ctx); - Assert.That(names["ALC_CONTEXT_DEBUG_BIT_EXT"].Primary, Is.EqualTo("CONTEXT_DEBUG_BIT_EXT")); + Assert.That( + names["ALC_CONTEXT_DEBUG_BIT_EXT"].Primary, + Is.EqualTo("CONTEXT_DEBUG_BIT_EXT") + ); } }