From ee81f960ba07fd76246a681dd217a839560e15a4 Mon Sep 17 00:00:00 2001 From: Jesse Klaasse Date: Tue, 29 Sep 2026 13:22:17 +0200 Subject: [PATCH] fix(generator): keep inline markup when copying XML docs FormatXmlDocumentation copied XElement.Value, which concatenates text nodes only: , and vanished from the sentence, and lost their markup, and an escaped < was written back unescaped (CS1570 in the consuming project). The element content is now copied as XML. Crefs stay resolvable: Roslyn returns the comment with every cref already in documentation-ID form (P:Namespace.Type.Member), which the compiler takes verbatim, so a facet in another namespace than its source still gets no CS1574 (#45). A paramref or typeparamref to a parameter the facet does not have becomes name. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 4 + .../FacetGenerators/CodeGenerationHelpers.cs | 101 ++++++------- .../Core/Facet/CopyDocsInlineMarkupTests.cs | 140 ++++++++++++++++++ 3 files changed, 190 insertions(+), 55 deletions(-) create mode 100644 test/Facet.Tests/UnitTests/Core/Facet/CopyDocsInlineMarkupTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a9de030..c0e25032 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ All notable changes to Facet are documented in this file. - Added `SetAccessor` parameter to `[Facet]` with `PropertySetAccessor` enum (`Preserve` / `Set` / `Init`) to override the set accessor emitted on all generated properties (#381). Supports the immutable builder pattern: one mutable facet for building, one init-only facet as the frozen read model. - Each facet type now emits two generated files by default: `{Type}.Properties.g.cs` (property declarations) and `{Type}.Mappings.g.cs` (constructors, projections, and conversion methods). Opt out globally by setting `false` in your `.csproj` or `Directory.Build.props` to restore the previous single-file output. +### Fixed + +- `CopyDocs` no longer drops inline markup from the copied documentation. `` and `` used to vanish from the sentence (a summary read "see ." in Swagger/Scalar), `` and `` lost their markup, and an escaped `<` was written back unescaped (CS1570 in the consuming project). Crefs are copied in documentation-ID form (`P:Namespace.Type.Member`), which the compiler does not rebind, so a facet in another namespace than its source still gets no CS1574 (#45). A `paramref`/`typeparamref` to a parameter the facet does not have becomes `name`. + ## [6.6.3] - 2026-05-22 ### Fixed diff --git a/src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs b/src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs index 83e81cfa..827b9390 100644 --- a/src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs +++ b/src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs @@ -391,64 +391,13 @@ public static string FormatXmlDocumentation(string xmlDoc) if (root == null) return string.Empty; - var summary = root.Element("summary"); - if (summary != null) + foreach (var elementName in new[] { "summary", "value", "remarks", "example" }) { - lines.Add("/// "); - var summaryText = summary.Value.Trim(); - if (!string.IsNullOrEmpty(summaryText)) + var element = root.Element(elementName); + if (element != null) { - foreach (var line in summaryText.Split('\n')) - { - lines.Add($"/// {line.Trim()}"); - } - } - lines.Add("/// "); - } - - var value = root.Element("value"); - if (value != null) - { - lines.Add("/// "); - var valueText = value.Value.Trim(); - if (!string.IsNullOrEmpty(valueText)) - { - foreach (var line in valueText.Split('\n')) - { - lines.Add($"/// {line.Trim()}"); - } - } - lines.Add("/// "); - } - - var remarks = root.Element("remarks"); - if (remarks != null) - { - lines.Add("/// "); - var remarksText = remarks.Value.Trim(); - if (!string.IsNullOrEmpty(remarksText)) - { - foreach (var line in remarksText.Split('\n')) - { - lines.Add($"/// {line.Trim()}"); - } - } - lines.Add("/// "); - } - - var example = root.Element("example"); - if (example != null) - { - lines.Add("/// "); - var exampleText = example.Value.Trim(); - if (!string.IsNullOrEmpty(exampleText)) - { - foreach (var line in exampleText.Split('\n')) - { - lines.Add($"/// {line.Trim()}"); - } + AppendDocumentationElement(lines, element); } - lines.Add("/// "); } return lines.Count > 0 ? string.Join("\n", lines) : string.Empty; @@ -459,6 +408,48 @@ public static string FormatXmlDocumentation(string xmlDoc) } } + /// + /// Writes one documentation element as /// lines, keeping its inline markup. + /// + /// + /// The content is copied as XML, not as : that property + /// concatenates the text nodes only, so a <see cref="..."/> or + /// <see langword="null"/> vanished from the sentence, <c> and + /// <para> lost their markup, and an escaped &lt; was written back unescaped, + /// which is malformed XML in the generated comment. + /// + /// Crefs stay resolvable: Roslyn hands out the comment with every cref already turned into a + /// documentation ID (P:Namespace.Type.Member), and the compiler takes an ID-form cref verbatim + /// instead of binding it in the facet's namespace — so a facet in another namespace than its source + /// gets no CS1574 (the reason the text used to be flattened, #45). + /// + /// + /// A paramref or typeparamref points at a parameter of the source member that the + /// generated member does not have, so it becomes <c>name</c>. + /// + /// + private static void AppendDocumentationElement(List lines, System.Xml.Linq.XElement element) + { + foreach (var reference in element.Descendants() + .Where(descendant => descendant.Name == "paramref" || descendant.Name == "typeparamref") + .ToList()) + { + reference.ReplaceWith(new System.Xml.Linq.XElement("c", (string?)reference.Attribute("name") ?? string.Empty)); + } + + var content = string.Concat(element.Nodes().Select(node => node.ToString(System.Xml.Linq.SaveOptions.DisableFormatting))).Trim(); + + lines.Add($"/// <{element.Name}>"); + if (!string.IsNullOrEmpty(content)) + { + foreach (var line in content.Split('\n')) + { + lines.Add($"/// {line.Trim()}"); + } + } + lines.Add($"/// "); + } + /// /// Extracts and formats XML documentation from a symbol. /// When is true and the symbol has no usable diff --git a/test/Facet.Tests/UnitTests/Core/Facet/CopyDocsInlineMarkupTests.cs b/test/Facet.Tests/UnitTests/Core/Facet/CopyDocsInlineMarkupTests.cs new file mode 100644 index 00000000..94ba1125 --- /dev/null +++ b/test/Facet.Tests/UnitTests/Core/Facet/CopyDocsInlineMarkupTests.cs @@ -0,0 +1,140 @@ +using Facet.Generators; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Facet.Tests.UnitTests.Core.Facet; + +/// +/// Driver-based tests for CopyDocs on documentation with inline markup. The generated source is +/// compiled with documentation diagnostics on, so a cref the facet cannot resolve would surface as +/// CS1574 and malformed XML as CS1570 — the in-project models cannot show that, because this test +/// project's own build does not fail on warnings. +/// +public class CopyDocsInlineMarkupTests +{ + /// + /// The source type lives in another namespace than the facet, and the facet file has no using for + /// it: a cref copied as written (cref="Id") would not bind there. + /// + private const string Source = """ + namespace Domain.Orders + { + /// How an order is paid. + public enum PaymentKind { Card, Invoice } + + public class Order + { + /// The order id. + public int Id { get; set; } + + /// + /// How it is paid, see ; until checkout. + /// Matches in the ledger & uses INV-<n> numbers. + /// + public PaymentKind? Payment { get; set; } + } + + /// A customer called . + /// The customer's name. + public record Customer(string Name); + } + + namespace Api.Contracts + { + [global::Facet.Facet(typeof(global::Domain.Orders.Order), CopyDocs = true)] + public partial class OrderDto { } + + [global::Facet.Facet(typeof(global::Domain.Orders.Customer), CopyDocs = true)] + public partial class CustomerDto { } + } + """; + + private static readonly string[] DocumentationDiagnostics = + [ + "CS1570", // badly formed XML + "CS1574", // cref that could not be resolved + "CS1580", // invalid cref parameter type + "CS1581", // invalid cref return type + "CS1584", // syntactically incorrect cref + "CS1658", // warning inside a cref + "CS1734", // paramref to a parameter that does not exist + "CS1735", // typeparamref to a type parameter that does not exist + ]; + + [Fact] + public void CopyDocs_KeepsCrefsLangwordsAndCodeElements() + { + var (generated, _) = Run(); + + generated.Should().Contain("How it is paid, see ; until checkout."); + generated.Should().Contain("Matches in the ledger"); + } + + [Fact] + public void CopyDocs_KeepsEscapedCharactersEscaped() + { + var (generated, _) = Run(); + + generated.Should().Contain("& uses INV-<n> numbers."); + generated.Should().NotContain("INV-"); + } + + [Fact] + public void CopyDocs_KeepsParagraphs() + { + var (generated, _) = Run(); + + generated.Should().Contain("Matches"); + generated.Should().Contain("numbers."); + } + + [Fact] + public void CopyDocs_TurnsAParamrefTheFacetDoesNotHaveIntoCode() + { + var (generated, _) = Run(); + + generated.Should().Contain("A customer called Name."); + generated.Should().NotContain("paramref"); + } + + [Fact] + public void CopyDocs_ProducesNoDocumentationWarnings_WhenTheFacetLivesInAnotherNamespace() + { + var (_, diagnostics) = Run(); + + diagnostics.Where(diagnostic => DocumentationDiagnostics.Contains(diagnostic.Id)) + .Select(diagnostic => diagnostic.ToString()) + .Should().BeEmpty(); + } + + private static (string Generated, IReadOnlyList Diagnostics) Run() + { + var parseOptions = new CSharpParseOptions(LanguageVersion.Latest, DocumentationMode.Diagnose); + var references = AppDomain.CurrentDomain.GetAssemblies() + .Where(assembly => !assembly.IsDynamic && !string.IsNullOrEmpty(assembly.Location)) + .Select(assembly => assembly.Location) + .Append(typeof(FacetAttribute).Assembly.Location) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(location => (MetadataReference)MetadataReference.CreateFromFile(location)) + .ToList(); + + var compilation = CSharpCompilation.Create( + "CopyDocsInlineMarkup", + [CSharpSyntaxTree.ParseText(Source, parseOptions)], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); + + var driver = CSharpGeneratorDriver.Create( + [new FacetGenerator().AsSourceGenerator()], + parseOptions: parseOptions); + driver.RunGeneratorsAndUpdateCompilation(compilation, out var output, out _); + + var generated = string.Join( + "\n", + output.SyntaxTrees + .Where(tree => tree.FilePath.Contains("Dto", StringComparison.Ordinal)) + .Select(tree => tree.ToString())); + + return (generated, output.GetDiagnostics()); + } +}