Files
UA-.NETStandard/tools/Opc.Ua.SourceGeneration/SourceGeneratorHelpers.cs
romanett 24399f1808 Fix source generator MODELGEN003 diagnostic dropping message placeholders (#4310)
## Problem

`LoggerAdapter.Log<TState>` in
`Tools/Opc.Ua.SourceGeneration/SourceGeneratorTelemetry.cs` reported an
**already fully-formatted** logger `message` against a looked-up
`DiagnosticDescriptor` whose `messageFormat` may declare more positional
placeholders than the single formatted string carries.

For `EventId == 3` the descriptor is `SourceGenerator.Exception`
(`MODELGEN003`) with:

```
messageFormat = "Exception during model generation '{0}': {1}"
```

That format has **two** placeholders but only **one** argument
(`message`) was supplied. Roslyn's `Diagnostic.GetMessage()` runs
`string.Format(format, args)`, which throws `FormatException` because
`{1}` has no argument; Roslyn's internal catch then returns the **raw,
unsubstituted template**. The user therefore saw the literal text
`Exception during model generation '{0}': {1}` with the placeholders
unreplaced, masking the real error.

## Fix

Route the pre-formatted message through a new
`CreateFormattedDiagnostic` helper that reports it via a **passthrough
descriptor whose `messageFormat` is exactly `"{0}"`**, while preserving
the original descriptor's `Id`, `Title`, `Category`, `DefaultSeverity`,
`IsEnabledByDefault`, `HelpLinkUri` and custom tags:

```csharp
public static Diagnostic CreateFormattedDiagnostic(
    DiagnosticDescriptor descriptor,
    string message)
{
    var passthrough = new DiagnosticDescriptor(
        descriptor.Id,
        descriptor.Title,
        "{0}",
        descriptor.Category,
        descriptor.DefaultSeverity,
        descriptor.IsEnabledByDefault,
        helpLinkUri: descriptor.HelpLinkUri,
        customTags: descriptor.CustomTags.ToArray());
    return Diagnostic.Create(passthrough, Location.None, message);
}
```

`LoggerAdapter.Log` now calls this helper instead of
`Diagnostic.Create(descriptor, Location.None, message)`. This renders
the message verbatim under the correct diagnostic id regardless of the
descriptor's placeholder arity, and is safe even when the message itself
contains `{`/`}` characters (the format string is only `"{0}"`).

> Note: the public `descriptor.CustomTags` (`IEnumerable<string>`) +
`.ToArray()` is used because Roslyn's `ImmutableCustomTags` property is
`internal`.

### Why the helper lives in `SourceGeneratorHelpers.cs` (not
`SourceGenerator.cs`)

`SourceGeneratorTelemetry.cs` and `SourceGeneratorHelpers.cs` are shared
(glob-linked) into **both** the model generator
(`Opc.Ua.SourceGeneration`) and the stack generator
(`Opc.Ua.SourceGeneration.Stack`). The stack generator has its **own**
`SourceGenerator` partial class and does **not** compile the model
generator's `SourceGenerator.cs`. Placing the helper in
`SourceGenerator.cs` broke the stack build with `CS0117:
'SourceGenerator' does not contain a definition for
'CreateFormattedDiagnostic'`. `SourceGeneratorHelpers.cs` is the shared
partial (where `Guard` also lives), so the helper is available to both
generators.

### Guard path untouched

The other emission path, `SourceGenerator.Guard(...)` in
`SourceGeneratorHelpers.cs`, uses the same `Exception` descriptor but
correctly passes **two** args (`ex.Message`, `ex.ToString()`), so that
path was already fine and is **not** changed.

## Tests

New
`tests/Opc.Ua.SourceGeneration.Tests/SourceGeneratorTelemetryTests.cs`
(4 tests):

1. **`DirectReportAgainstMultiPlaceholderDescriptorLosesMessage`** —
documents the pre-fix behaviour: the raw `Diagnostic.Create(Exception,
..., "boom")` render drops `"boom"` and leaks `{1}`.
2. **`CreateFormattedDiagnosticRendersMessageVerbatim`** — the fix
renders `"boom"` exactly, with no `{0}`/`{1}`.
3. **`CreateFormattedDiagnosticPreservesDescriptorMetadata`** — id
(`MODELGEN003`), severity, category, help link, IsEnabledByDefault and
custom tags are preserved.
4. **`CreateFormattedDiagnosticIsSafeForBracesInMessage`** — a message
containing `{`/`}` is emitted verbatim.

## Validation

- `tools/Opc.Ua.SourceGeneration` (and the stack variant) build with **0
warnings / 0 errors**.
- Full `Opc.Ua.SourceGeneration.Tests` suite on net10.0: **132/132
passing**, including the 4 new tests.

## Files changed

- `tools/Opc.Ua.SourceGeneration/SourceGeneratorHelpers.cs` — added
`using System.Linq;` + `CreateFormattedDiagnostic` helper.
- `tools/Opc.Ua.SourceGeneration/SourceGeneratorTelemetry.cs` —
`LoggerAdapter.Log` calls the helper.
- `tests/Opc.Ua.SourceGeneration.Tests/SourceGeneratorTelemetryTests.cs`
— new regression tests.

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-24 15:19:26 +00:00

121 lines
5.1 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace Opc.Ua.SourceGeneration
{
/// <summary>
/// Shared helpers for the source generator entry points. The file is
/// linked into every generator assembly, each of which supplies its own
/// diagnostic descriptors in the other half of the partial class.
/// </summary>
internal static partial class SourceGenerator
{
/// <summary>
/// Runs a source output callback and converts an unhandled exception
/// into a diagnostic. Roslyn fails the whole compilation with a bare
/// stack trace when a generator throws, so every callback funnels
/// through here to report a well-formed diagnostic instead.
/// </summary>
public static void Guard(SourceProductionContext context, Action action)
{
try
{
action();
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
// ex.ToString() rather than ex.StackTrace: it carries the exception
// type and the inner-exception chain, and is never null - a bare
// StackTrace is null for an exception that never left its throw site.
context.ReportDiagnostic(
Diagnostic.Create(
Exception,
Location.None,
ex.Message,
ex.ToString()));
}
}
/// <summary>
/// Creates a diagnostic that renders an already fully-formatted message
/// verbatim under the identity of <paramref name="descriptor"/>. The
/// looked-up descriptor's <c>messageFormat</c> may declare more
/// positional placeholders than the single formatted string carries
/// (for example the exception descriptor declares <c>{0}</c> and
/// <c>{1}</c>); reporting the message directly against it makes
/// <see cref="Diagnostic.GetMessage(System.IFormatProvider)"/> throw a
/// <see cref="System.FormatException"/> internally and fall back to the
/// raw, unsubstituted template. Reporting through a passthrough
/// descriptor whose format is exactly <c>"{0}"</c> avoids that, is
/// independent of the original placeholder arity, and is safe even when
/// the message itself contains <c>{</c> or <c>}</c> characters. All
/// other descriptor metadata is preserved.
/// </summary>
public static Diagnostic CreateFormattedDiagnostic(
DiagnosticDescriptor descriptor,
string message)
{
var passthrough = new DiagnosticDescriptor(
descriptor.Id,
descriptor.Title,
"{0}",
descriptor.Category,
descriptor.DefaultSeverity,
descriptor.IsEnabledByDefault,
description: descriptor.Description,
helpLinkUri: descriptor.HelpLinkUri,
customTags: descriptor.CustomTags.ToArray());
return Diagnostic.Create(passthrough, Location.None, message);
}
/// <summary>
/// Attaches a debugger to the compiler process hosting the generator.
/// Compiled away unless the generator is built with the DEBUGX
/// constant defined.
/// </summary>
[Conditional("DEBUGX")]
public static void AttachDebuggerIfRequested()
{
if (!Debugger.IsAttached)
{
Debugger.Launch();
}
}
}
}