mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 14:43:08 +08:00
9b034f8291
# Description Nullable reference types are now enabled once, in `common.props`, and every project in the repository builds warning-clean with them. **Configuration** - `<Nullable>enable</Nullable>` lives in `common.props`. All per-project `<Nullable>` settings are removed: 178 project files (enable, annotations, and the `disable` in the three Aot test projects). - 419 per-file `#nullable enable`/`restore` directives and the 4 `#nullable disable` directives are removed. - Kept on purpose: - The 5 `<auto-generated>` schema files (`UANodeSet.cs`, `UA Type Dictionary.cs`, `OPCBinarySchema.cs`, `SecuredApplication.cs`, `PInvokeHelper.cs`) keep `#nullable enable`. The compiler ignores the project setting in generated code, so the directive is required there. - `tests/Opc.Ua.Interop.LegacyPeer` keeps `disable`. It builds against the 1.5.378 packages and does not import the repository props. - `docs/DeveloperGuide.md` and `.github/copilot-instructions.md` now describe the central setting. **Migration** (the 43 unset and 13 annotations-only projects, roughly 10k diagnostics) - **Production code: annotated at the declarations.** Covers `tools/Opc.Ua.SourceGeneration.Core`, `src/Opc.Ua.Lds.Server` and the LDS sample. - Members, parameters and returns are nullable where null actually flows. - Null-check helpers carry `[NotNullWhen]` (`IsNull`, `IsValidXmlName`, `IsMethodTypeDesign`). - `CoreUtils.Format`, `Utils.Format`, `ITemplateWriter.WriteLine` take `params object?[]`. `Template.AddReplacement` takes `string?` (rendering already skips null replacements). - `IRegisteredServerStore.RegisterAsync` returns `Task<RegistrationEntry?>`: it returns null when a registration is removed. - Dereferences backed by an invariant (for example, the validated model) use `!`, so runtime behaviour is unchanged. - **Behavioural changes in production code** (small, deliberate): - `NodeSetToModelDesign` throws `InvalidOperationException` when the file is not a NodeSet. Before, it threw a NullReferenceException on the next line. - `ModelDesignValidator` starts its lookup tables empty instead of null. A redundant `if (m_nodes == null) return;` guard is gone. - **Test code: minimal annotations.** - `?` on values that can be null, `!` where the test asserts non-null. - `= null!` for fixture members assigned in SetUp. - `TryGetStructure<T>(out T? x)` where the inferred `T?` broke the `IEncodeable` constraint. - A few redundant `== null` checks on structs (`NodeId`, `ArrayOf<T>`) folded into the adjacent `IsNull`/`Count` checks. **Notes for reviewers** - The diff is large (~1,500 files) but almost entirely mechanical: `?`, `!` and directive removal. The non-annotation changes are listed above. - Known follow-up, not done here: `IModelDesign.Namespaces/TargetNamespace/NamespaceUris` stay non-nullable even though the validator returns null before it loads a dictionary. Making them nullable would ripple through every generator call site. ## Related Issues - Fixes #4439 ## Checklist - [ ] 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. - [ ] 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. The "no new warnings" box covers net10.0 and net48: full non-incremental builds of `UA.slnx`, `tools/SourceGeneration.slnx`, `tools/MigrationAnalyzer.slnx` and the Aot test projects finished with 0 warnings and 0 errors under the repository's warnings-as-errors settings. net9.0 and net8.0 also had no nullable diagnostics, but they were not rebuilt after the final fixes. Tests have not been run locally yet. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
493 lines
18 KiB
C#
493 lines
18 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.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using Opc.Ua.Schema.Model;
|
|
using Opc.Ua.Types;
|
|
|
|
namespace Opc.Ua.SourceGeneration
|
|
{
|
|
/// <summary>
|
|
/// Generates node identifier and corresponding NodeId/ExpandedNodeId constants.
|
|
/// </summary>
|
|
internal sealed class NodeIdGenerator : IGenerator
|
|
{
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="NodeIdGenerator"/> class.
|
|
/// </summary>
|
|
public NodeIdGenerator(IGeneratorContext context)
|
|
{
|
|
m_context = context ?? throw new ArgumentNullException(nameof(context));
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public IEnumerable<Resource> Emit()
|
|
{
|
|
SortedDictionary<string, List<NodeDesign>> identifiers = GetIdentifiers();
|
|
if (identifiers.Count == 0)
|
|
{
|
|
// Nothing to do
|
|
return [];
|
|
}
|
|
string fileName = Path.Combine(m_context.OutputFolder, CoreUtils.Format(
|
|
"{0}.Identifiers.g.cs",
|
|
m_context.ModelDesign.TargetNamespace.Prefix));
|
|
|
|
using TextWriter writer = m_context.FileSystem.CreateTextWriter(fileName);
|
|
using var templateWriter = new TemplateWriter(writer);
|
|
var template = new Template(templateWriter, NodeIdTemplates.File);
|
|
template.AddReplacement(
|
|
Tokens.Namespace,
|
|
m_context.ModelDesign.TargetNamespace.Prefix);
|
|
template.AddReplacement(
|
|
Tokens.NamespaceUri,
|
|
m_context.ModelDesign.Namespaces.GetConstantSymbolForNamespace(
|
|
m_context.ModelDesign.TargetNamespace.Value));
|
|
|
|
template.AddReplacement(
|
|
Tokens.ListOfIdentifiers,
|
|
NodeIdTemplates.IdsPerNodeClass,
|
|
identifiers,
|
|
LoadTemplate_IdsPerNodeClass,
|
|
WriteTemplate_IdsPerNodeClass);
|
|
|
|
template.AddReplacement(
|
|
Tokens.ListOfNodeIds,
|
|
NodeIdTemplates.NodeIdPerNodeClass,
|
|
identifiers,
|
|
LoadTemplate_IdsPerNodeClass,
|
|
WriteTemplate_NodeIdPerNodeClass);
|
|
|
|
template.Render();
|
|
return [fileName.AsTextFileResource()];
|
|
}
|
|
|
|
private TemplateString? LoadTemplate_IdsPerNodeClass(ILoadContext context)
|
|
{
|
|
if (context.Target is not KeyValuePair<string, List<NodeDesign>> nodes)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (nodes.Value == null || nodes.Value.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return context.TemplateString;
|
|
}
|
|
|
|
private bool WriteTemplate_IdsPerNodeClass(IWriteContext context)
|
|
{
|
|
if (context.Target is not KeyValuePair<string, List<NodeDesign>> nodes ||
|
|
nodes.Value == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
context.Template.AddReplacement(Tokens.NodeClass, nodes.Key);
|
|
context.Template.AddReplacement(
|
|
Tokens.NamespacePrefix,
|
|
m_context.ModelDesign.TargetNamespace.Prefix);
|
|
context.Template.AddReplacement(
|
|
Tokens.Namespace,
|
|
m_context.ModelDesign.TargetNamespace.Value);
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.ListOfIdentifiers,
|
|
NodeIdTemplates.IdDeclaration,
|
|
nodes.Value,
|
|
WriteTemplate_IdDeclaration);
|
|
|
|
// Collection reflection lookups. Note if the identifiers are not assigned
|
|
// or duplicate, the reflection will be pointing to the last node design.
|
|
var numericIds = new Dictionary<uint, NodeDesign>();
|
|
foreach (NodeDesign item in nodes.Value.Where(n => n.NumericIdSpecified))
|
|
{
|
|
numericIds[item.NumericId] = item;
|
|
}
|
|
var stringIds = new Dictionary<string, NodeDesign>();
|
|
// Save time by not looping again if all numeric
|
|
if (numericIds.Count != nodes.Value.Count)
|
|
{
|
|
foreach (NodeDesign item in nodes.Value.Where(n => !n.NumericIdSpecified))
|
|
{
|
|
if (!string.IsNullOrEmpty(item.StringId))
|
|
{
|
|
stringIds[item.StringId] = item;
|
|
}
|
|
else if (item.HasNonConstantIdentifier())
|
|
{
|
|
// Guid and Opaque identifiers are not part of the
|
|
// string keyed reflection tables.
|
|
continue;
|
|
}
|
|
else if (!string.IsNullOrEmpty(item.SymbolicId.Name))
|
|
{
|
|
stringIds[item.SymbolicId.Name] = item;
|
|
}
|
|
}
|
|
}
|
|
|
|
// For simplicity do not emit reflection for mixed identifiers (yet)
|
|
// Prefer numeric if both are present and more numeric ids than strings
|
|
if (numericIds.Count > stringIds.Count)
|
|
{
|
|
context.Template.AddReplacement(
|
|
Tokens.IdentifierReflection,
|
|
NodeIdTemplates.Reflection,
|
|
[new KeyValuePair<string, List<NodeDesign>>(nodes.Key, [.. numericIds.Values])],
|
|
WriteTemplate_IdClassReflection);
|
|
}
|
|
else if (stringIds.Count > 0)
|
|
{
|
|
context.Template.AddReplacement(
|
|
Tokens.IdentifierReflection,
|
|
NodeIdTemplates.Reflection,
|
|
[new KeyValuePair<string, List<NodeDesign>>(nodes.Key, [.. stringIds.Values])],
|
|
WriteTemplate_IdClassReflection);
|
|
}
|
|
|
|
return context.Template.Render();
|
|
}
|
|
|
|
private bool WriteTemplate_NodeIdPerNodeClass(IWriteContext context)
|
|
{
|
|
if (context.Target is not KeyValuePair<string, List<NodeDesign>> nodes ||
|
|
nodes.Value == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
context.Template.AddReplacement(Tokens.NodeClass, nodes.Key);
|
|
context.Template.AddReplacement(
|
|
Tokens.NamespacePrefix,
|
|
m_context.ModelDesign.TargetNamespace.Prefix);
|
|
context.Template.AddReplacement(
|
|
Tokens.Namespace,
|
|
m_context.ModelDesign.TargetNamespace.Value);
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.ListOfIdentifiers,
|
|
m_context.ModelDesign.TargetNamespace.Value != Namespaces.OpcUa ?
|
|
NodeIdTemplates.NodeIdDeclarationAbsolute :
|
|
NodeIdTemplates.NodeIdDeclaration,
|
|
nodes.Value,
|
|
WriteTemplate_IdDeclaration);
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.IdentifierReflection,
|
|
NodeIdTemplates.Reflection,
|
|
[nodes],
|
|
WriteTemplate_NodeIdReflection);
|
|
|
|
return context.Template.Render();
|
|
}
|
|
|
|
private bool WriteTemplate_IdDeclaration(IWriteContext context)
|
|
{
|
|
if (context.Target is not NodeDesign node)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
object? id;
|
|
string idType;
|
|
// Guid and Opaque identifiers have no C# constant form and are
|
|
// emitted as static readonly fields instead.
|
|
string idModifier = "const";
|
|
if (node.NumericIdSpecified)
|
|
{
|
|
id = node.NumericId;
|
|
idType = "uint";
|
|
}
|
|
else if (!string.IsNullOrEmpty(node.StringId))
|
|
{
|
|
id = node.StringId.AsStringLiteral(); // TODO: Make string resource
|
|
idType = "string";
|
|
}
|
|
else if (node.HasNonConstantIdentifier())
|
|
{
|
|
id = ModelDesignExtensions.GetIdentifierAsCode(node.GetIdentifier()!, out idType!);
|
|
idModifier = "static readonly";
|
|
}
|
|
else
|
|
{
|
|
id = node.SymbolicId.Name.AsStringLiteral(); // TODO: Make string resource
|
|
idType = "string";
|
|
}
|
|
|
|
context.Template.AddReplacement(Tokens.NodeClass, node.GetNodeClassAsString());
|
|
context.Template.AddReplacement(Tokens.SymbolicName, node.SymbolicId.Name);
|
|
context.Template.AddReplacement(Tokens.Identifier, id);
|
|
context.Template.AddReplacement(
|
|
Tokens.NamespaceUri,
|
|
m_context.ModelDesign.Namespaces.GetConstantSymbolForNamespace(
|
|
node.SymbolicId.Namespace));
|
|
context.Template.AddReplacement(
|
|
Tokens.NamespacePrefix,
|
|
m_context.ModelDesign.Namespaces.GetNamespacePrefix(
|
|
node.SymbolicId.Namespace));
|
|
context.Template.AddReplacement(Tokens.IdType, idType);
|
|
context.Template.AddReplacement(Tokens.IdModifier, idModifier);
|
|
|
|
return context.Template.Render();
|
|
}
|
|
|
|
private TemplateString? LoadTemplate_IdentifierLookup(ILoadContext context)
|
|
{
|
|
if (context.Target is not NodeDesign node)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
string symbolicId = node.SymbolicId.Name; // See above - should be SymbolicName.Name?
|
|
|
|
if (context.Token == Tokens.ListOfIdentifersToNames)
|
|
{
|
|
context.Out.WriteLine("lookup[{0}] = \"{0}\";", symbolicId);
|
|
}
|
|
else if (context.Token == Tokens.ListOfNamesToIdentifiers)
|
|
{
|
|
context.Out.WriteLine("lookup[\"{0}\"] = {0};", symbolicId);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private bool WriteTemplate_IdClassReflection(IWriteContext context)
|
|
{
|
|
if (context.Target is not KeyValuePair<string, List<NodeDesign>> nodes)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
context.Template.AddReplacement(Tokens.ClassName, nodes.Key);
|
|
context.Template.AddReplacement(Tokens.IdType,
|
|
nodes.Value[0].NumericIdSpecified ?
|
|
"uint" :
|
|
"string");
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.ListOfIdentifersToNames,
|
|
nodes.Value,
|
|
LoadTemplate_IdentifierLookup);
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.ListOfNamesToIdentifiers,
|
|
nodes.Value,
|
|
LoadTemplate_IdentifierLookup);
|
|
|
|
return context.Template.Render();
|
|
}
|
|
|
|
private bool WriteTemplate_NodeIdReflection(IWriteContext context)
|
|
{
|
|
if (context.Target is not KeyValuePair<string, List<NodeDesign>> nodes)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.ClassName,
|
|
CoreUtils.Format("{0}Ids", nodes.Key));
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.IdType,
|
|
m_context.ModelDesign.TargetNamespace.Value == Namespaces.OpcUa ?
|
|
"global::Opc.Ua.NodeId" :
|
|
"global::Opc.Ua.ExpandedNodeId");
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.ListOfIdentifersToNames,
|
|
nodes.Value,
|
|
LoadTemplate_IdentifierLookup);
|
|
|
|
context.Template.AddReplacement(
|
|
Tokens.ListOfNamesToIdentifiers,
|
|
nodes.Value,
|
|
LoadTemplate_IdentifierLookup);
|
|
|
|
return context.Template.Render();
|
|
}
|
|
|
|
private bool IsParentExcluded(NodeDesign root, KeyValuePair<string, HierarchyNode> child)
|
|
{
|
|
string parentId = child.Key;
|
|
|
|
while (parentId != null)
|
|
{
|
|
int index = parentId.LastIndexOf('_');
|
|
|
|
if (index > 0)
|
|
{
|
|
parentId = parentId[..index];
|
|
}
|
|
|
|
if (!root.Hierarchy.Nodes.TryGetValue(parentId, out HierarchyNode? parent))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (m_context.ModelDesign.IsExcluded(parent.Instance!))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (index <= 0)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private SortedDictionary<string, List<NodeDesign>> GetIdentifiers()
|
|
{
|
|
SortedDictionary<string, List<NodeDesign>> identifiers = [];
|
|
|
|
for (int ii = 0; ii < m_context.ModelDesign.Nodes.Length; ii++)
|
|
{
|
|
NodeDesign node = m_context.ModelDesign.Nodes[ii];
|
|
|
|
if (m_context.ModelDesign.IsExcluded(node))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (node is InstanceDesign instance &&
|
|
instance.TypeDefinitionNode != null &&
|
|
m_context.ModelDesign.IsExcluded(instance.TypeDefinitionNode))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
string nodeClass = node.GetNodeClassAsString();
|
|
|
|
if (!identifiers.TryGetValue(nodeClass, out List<NodeDesign>? nodesWithinClass))
|
|
{
|
|
identifiers[nodeClass] = nodesWithinClass = [];
|
|
}
|
|
|
|
if (!nodesWithinClass.Contains(node))
|
|
{
|
|
nodesWithinClass.Add(node);
|
|
}
|
|
|
|
if (node.Hierarchy == null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
foreach (KeyValuePair<string, HierarchyNode> current in node.Hierarchy.Nodes)
|
|
{
|
|
if (string.IsNullOrEmpty(current.Key))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (m_context.ModelDesign.IsExcluded(current.Value.Instance!))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (IsParentExcluded(node, current))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var method = current.Value.Instance as MethodDesign;
|
|
|
|
if (method?.MethodDeclarationNode != null &&
|
|
m_context.ModelDesign.IsExcluded((method?.MethodDeclarationNode)!))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (node is TypeDesign)
|
|
{
|
|
if (!current.Value.ExplicitlyDefined)
|
|
{
|
|
if (current.Value.Inherited &&
|
|
(current.Value.Instance == null ||
|
|
current.Value.Instance.BrowseName == current.Value.RelativePath))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (current.Value.Instance is InstanceDesign child &&
|
|
child.ModellingRule != ModellingRule.Mandatory)
|
|
{
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (node is InstanceDesign)
|
|
{
|
|
if (current.Value.Instance is not InstanceDesign child)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (child.ModellingRule != ModellingRule.Mandatory)
|
|
{
|
|
continue;
|
|
}
|
|
}
|
|
|
|
if (current.Value.Instance!.NumericIdSpecified
|
|
? current.Value.Instance.NumericId == 0
|
|
: current.Value.Instance.StringId == null &&
|
|
!current.Value.Instance.HasNonConstantIdentifier())
|
|
{
|
|
continue;
|
|
}
|
|
|
|
nodeClass = current.Value.Instance.GetNodeClassAsString();
|
|
|
|
if (!identifiers.TryGetValue(nodeClass, out nodesWithinClass))
|
|
{
|
|
identifiers[nodeClass] = nodesWithinClass = [];
|
|
}
|
|
|
|
nodesWithinClass.Add(current.Value.Instance);
|
|
}
|
|
}
|
|
|
|
return identifiers;
|
|
}
|
|
|
|
private readonly IGeneratorContext m_context;
|
|
}
|
|
}
|