Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<Facet_SplitGeneratedFiles>false</Facet_SplitGeneratedFiles>` 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. `<see cref="..."/>` and `<see langword="..."/>` used to vanish from the sentence (a summary read "see ." in Swagger/Scalar), `<c>` and `<para>` lost their markup, and an escaped `&lt;` 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 `<c>name</c>`.

## [6.6.3] - 2026-05-22

### Fixed
Expand Down
101 changes: 46 additions & 55 deletions src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@

var memberNamespace = ExtractNamespaceFromFullyQualifiedType(memberTypeName);
string typeNameWithoutNamespace = !string.IsNullOrWhiteSpace(memberNamespace)
? memberTypeName.Substring(memberNamespace.Length + 1)

Check warning on line 100 in src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 100 in src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs

View workflow job for this annotation

GitHub Actions / test

Dereference of a possibly null reference.
: memberTypeName;

if (typeNameWithoutNamespace.Contains('.'))
Expand Down Expand Up @@ -275,7 +275,7 @@
string typeNameWithoutNamespace;
if (!string.IsNullOrWhiteSpace(memberNamespace))
{
typeNameWithoutNamespace = memberTypeName.Substring(memberNamespace.Length + 1);

Check warning on line 278 in src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 278 in src/Facet/Generators/FacetGenerators/CodeGenerationHelpers.cs

View workflow job for this annotation

GitHub Actions / test

Dereference of a possibly null reference.
}
else
{
Expand Down Expand Up @@ -391,64 +391,13 @@
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("/// <summary>");
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("/// </summary>");
}

var value = root.Element("value");
if (value != null)
{
lines.Add("/// <value>");
var valueText = value.Value.Trim();
if (!string.IsNullOrEmpty(valueText))
{
foreach (var line in valueText.Split('\n'))
{
lines.Add($"/// {line.Trim()}");
}
}
lines.Add("/// </value>");
}

var remarks = root.Element("remarks");
if (remarks != null)
{
lines.Add("/// <remarks>");
var remarksText = remarks.Value.Trim();
if (!string.IsNullOrEmpty(remarksText))
{
foreach (var line in remarksText.Split('\n'))
{
lines.Add($"/// {line.Trim()}");
}
}
lines.Add("/// </remarks>");
}

var example = root.Element("example");
if (example != null)
{
lines.Add("/// <example>");
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("/// </example>");
}

return lines.Count > 0 ? string.Join("\n", lines) : string.Empty;
Expand All @@ -459,6 +408,48 @@
}
}

/// <summary>
/// Writes one documentation element as <c>///</c> lines, keeping its inline markup.
/// </summary>
/// <remarks>
/// The content is copied as XML, not as <see cref="System.Xml.Linq.XElement.Value"/>: that property
/// concatenates the text nodes only, so a <c>&lt;see cref="..."/&gt;</c> or
/// <c>&lt;see langword="null"/&gt;</c> vanished from the sentence, <c>&lt;c&gt;</c> and
/// <c>&lt;para&gt;</c> lost their markup, and an escaped <c>&amp;lt;</c> was written back unescaped,
/// which is malformed XML in the generated comment.
/// <para>
/// Crefs stay resolvable: Roslyn hands out the comment with every <c>cref</c> already turned into a
/// documentation ID (<c>P:Namespace.Type.Member</c>), 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).
/// </para>
/// <para>
/// A <c>paramref</c> or <c>typeparamref</c> points at a parameter of the source member that the
/// generated member does not have, so it becomes <c>&lt;c&gt;name&lt;/c&gt;</c>.
/// </para>
/// </remarks>
private static void AppendDocumentationElement(List<string> 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($"/// </{element.Name}>");
}

/// <summary>
/// Extracts and formats XML documentation from a symbol.
/// When <paramref name="inheritDocs"/> is true and the symbol has no usable
Expand Down
140 changes: 140 additions & 0 deletions test/Facet.Tests/UnitTests/Core/Facet/CopyDocsInlineMarkupTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
using Facet.Generators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace Facet.Tests.UnitTests.Core.Facet;

/// <summary>
/// Driver-based tests for <c>CopyDocs</c> 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.
/// </summary>
public class CopyDocsInlineMarkupTests
{
/// <summary>
/// The source type lives in another namespace than the facet, and the facet file has no using for
/// it: a cref copied as written (<c>cref="Id"</c>) would not bind there.
/// </summary>
private const string Source = """
namespace Domain.Orders
{
/// <summary>How an order is paid.</summary>
public enum PaymentKind { Card, Invoice }

public class Order
{
/// <summary>The order id.</summary>
public int Id { get; set; }

/// <summary>
/// How it is paid, see <see cref="PaymentKind"/>; <see langword="null"/> until checkout.
/// <para>Matches <see cref="Id"/> in the ledger &amp; uses <c>INV-&lt;n&gt;</c> numbers.</para>
/// </summary>
public PaymentKind? Payment { get; set; }
}

/// <summary>A customer called <paramref name="Name"/>.</summary>
/// <param name="Name">The customer's name.</param>
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 <see cref=\"T:Domain.Orders.PaymentKind\" />; <see langword=\"null\" /> until checkout.");
generated.Should().Contain("Matches <see cref=\"P:Domain.Orders.Order.Id\" /> in the ledger");
}

[Fact]
public void CopyDocs_KeepsEscapedCharactersEscaped()
{
var (generated, _) = Run();

generated.Should().Contain("&amp; uses <c>INV-&lt;n&gt;</c> numbers.");
generated.Should().NotContain("INV-<n>");
}

[Fact]
public void CopyDocs_KeepsParagraphs()
{
var (generated, _) = Run();

generated.Should().Contain("<para>Matches");
generated.Should().Contain("numbers.</para>");
}

[Fact]
public void CopyDocs_TurnsAParamrefTheFacetDoesNotHaveIntoCode()
{
var (generated, _) = Run();

generated.Should().Contain("A customer called <c>Name</c>.");
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<Diagnostic> 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());
}
}
Loading