Files
Copilot 02fb72e2d3 Support guid/opaque nodeids in NodeSet import (#4507)
# Description

`NodeSetToModelDesign.ImportNode` only stored Numeric and String NodeId
identifiers. Guid and Opaque identifiers (both valid per OPC 10000-3
5.2.2) fell through to an `Information` log line, so the node was
registered in `NodesByQName`/`NodesById` with no identifier at all and
code generation continued against a node whose identity had been
discarded.

The `ModelDesign` schema has no representation for Guid/Opaque
identifiers (`NodeDesign` exposes only `NumericId`/`StringId`), so the
import now fails loudly instead of emitting output that looks correct.

- **Importer**: the fall-through branches in `ImportNode` are replaced
with an `InvalidDataException` naming the NodeId, browse name and
identifier type. This matches the existing unsupported-input handling in
the file and surfaces through `ModelCompilation` as a generator
diagnostic.
- **Logger removal**: `m_logger` had no remaining use in
`NodeSetToModelDesign` and was removed along with its
`Microsoft.Extensions.Logging` import.
- **Tests**: `ImportUnsupportedNodeIdTypeThrowsInvalidDataException`
covers Guid, empty Guid and Opaque identifiers via an in-memory NodeSet.
- **Docs**: the source generator readme states the NodeSet2 identifier
restriction.

```csharp
else
{
    // The model design can only carry numeric and string identifiers.
    // Guid and Opaque identifiers (OPC 10000-3 5.2.2) would be dropped
    // and code would be generated for a node without any identity, so
    // the import fails instead of silently producing wrong output.
    throw new InvalidDataException(
        $"NodeId ({input.NodeId}) of node '{input.BrowseName}' uses the " +
        $"{nodeId.IdType} identifier type which is not supported by the model " +
        "design. Only Numeric and String identifiers can be imported.");
}
```

Note on behaviour: a null/unspecified NodeId parses as a Numeric
identifier (`i=0`) and is still handled by the numeric branch, so the
removed `IsNull` branch was only ever reachable for an empty Guid or
Opaque identifier, which is now reported as unsupported.

## Related Issues

## Checklist

_Put an `x` in the boxes that apply. You can complete these step by step
after opening the PR._

- [x] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

<!-- START COPILOT CODING AGENT SUFFIX -->

- Fixes #4504

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-09-21 14:52:55 +02:00

149 lines
6.0 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 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/
* ======================================================================*/
namespace Opc.Ua.SourceGeneration
{
/// <summary>
/// Templates for the <see cref="StateMachineIdsGenerator"/>.
/// Emits a strongly-typed identifier class per concrete
/// <c>FiniteStateMachineType</c> subtype, with nested
/// <c>StateIds</c> / <c>StateNumbers</c> / <c>TransitionIds</c> /
/// <c>TransitionNumbers</c> partial classes.
/// </summary>
internal static class StateMachineIdsTemplates
{
/// <summary>
/// Single output file template. Hosts every state-machine ids
/// class generated for the model in a single namespace block.
/// </summary>
public static readonly TemplateString File = TemplateString.Parse(
$$"""
{{Tokens.CodeHeader}}
namespace {{Tokens.Namespace}}
{
{{Tokens.ListOfTypes}}
}
""");
/// <summary>
/// One ids class per concrete FSM subtype. Wraps four nested
/// partial classes: <c>StateIds</c> (NodeId references),
/// <c>StateNumbers</c> (Part 16 StateNumber values),
/// <c>TransitionIds</c>, and <c>TransitionNumbers</c>.
/// </summary>
public static readonly TemplateString IdsClass = TemplateString.Parse(
$$"""
/// <summary>
/// Strongly-typed state and transition identifiers for the
/// <c>{{Tokens.TypeName}}</c> ObjectType.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("{{Tokens.Tool}}", "{{Tokens.Version}}")]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute()]
public static partial class {{Tokens.ClassName}}
{
/// <summary>
/// Numeric NodeId portion of each state in the model's namespace.
/// </summary>
public static partial class StateIds
{
{{Tokens.ListOfIdentifiers}}
}
/// <summary>
/// OPC UA <c>StateNumber</c> property value per state.
/// </summary>
public static partial class StateNumbers
{
{{Tokens.ListOfValues}}
}
/// <summary>
/// Numeric NodeId portion of each transition in the model's namespace.
/// </summary>
public static partial class TransitionIds
{
{{Tokens.ListOfChildren}}
}
/// <summary>
/// OPC UA <c>TransitionNumber</c> property value per transition.
/// </summary>
public static partial class TransitionNumbers
{
{{Tokens.ListOfFields}}
}
}
""");
/// <summary>
/// One <c>public const {uint|string} X = global::{ns}.Objects.{Y};</c>
/// line per state or transition NodeId entry. The constant type follows the
/// type of the aliased <c>Objects</c> constant, which is <c>string</c> for
/// models that use string NodeIds. Guid and Opaque identifiers cannot be
/// C# constants, so those entries are emitted as <c>static readonly</c>.
/// </summary>
public static readonly TemplateString IdEntry = TemplateString.Parse(
$$"""
public {{Tokens.IdModifier}} {{Tokens.IdType}} {{Tokens.Name}} = global::{{Tokens.NamespacePrefix}}.Objects.{{Tokens.Identifier}};
""");
/// <summary>
/// One <c>public const uint X = Nu;</c> line per state or
/// transition number entry that carries a value.
/// </summary>
public static readonly TemplateString NumberEntry = TemplateString.Parse(
$$"""
public const uint {{Tokens.Name}} = {{Tokens.NumericIdValue}}u;
""");
/// <summary>
/// Comment line for a state / transition whose number property
/// is not declared in the source model.
/// </summary>
public static readonly TemplateString NumberMissingComment = TemplateString.Parse(
$$"""
// {{Tokens.Name}}: StateNumber/TransitionNumber not declared in the model.
""");
/// <summary>
/// Comment emitted in place of any entries when the FSM does
/// not declare any states / transitions of the relevant kind.
/// </summary>
public static readonly TemplateString EmptySectionComment = TemplateString.Parse(
$$"""
// (none defined in the model)
""");
}
}