Files
romanett 9b034f8291 Enable nullable reference types centrally; migrate all unset and annotations-only projects (#4700)
# 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>
2026-10-08 08:48:13 +02:00

337 lines
14 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 System.Xml;
using Opc.Ua.Schema.Model;
using Opc.Ua.Types;
namespace Opc.Ua.SourceGeneration
{
/// <summary>
/// Generates namespace and browse name constants.
/// TODO: Use resource generator infrastructure.
/// </summary>
internal sealed class ConstantsGenerator : IGenerator
{
/// <summary>
/// Create constants generator
/// </summary>
public ConstantsGenerator(IGeneratorContext context)
{
m_context = context ?? throw new ArgumentNullException(nameof(context));
m_logger = context.Telemetry.CreateLogger<ConstantsGenerator>();
}
/// <inheritdoc/>
public IEnumerable<Resource> Emit()
{
SortedDictionary<string, string> browseNames = [];
m_defaultInstanceBrowseNameKeys.Clear();
foreach (NodeDesign node in m_context.ModelDesign.GetNodeDesigns())
{
CollectBrowseNames(node, browseNames);
}
if (browseNames.Count == 0)
{
// Nothing to do
return [];
}
string fileName = Path.Combine(m_context.OutputFolder, CoreUtils.Format(
"{0}.Constants.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, ConstantsTemplates.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.ModelVersion,
SourceGenerationUtils.Escape(
m_context.ModelDesign.TargetVersion ??
m_context.ModelDesign.TargetNamespace.Version ??
string.Empty));
template.AddReplacement(
Tokens.ListOfNamespaceUris,
ConstantsTemplates.NamespaceUri,
GetNamespaceUris(),
WriteTemplate_NamespaceUriStrings);
template.AddReplacement(
Tokens.ListOfBrowseNames,
ConstantsTemplates.BrowseName,
browseNames.ToArray(),
LoadTemplate_BrowseNames,
WriteTemplate_BrowseNames);
template.Render();
return [fileName.AsTextFileResource()];
}
private TemplateString? LoadTemplate_BrowseNames(ILoadContext context)
{
if (context.Target is not KeyValuePair<string, string> browseName ||
browseName.Value == null)
{
return null;
}
return context.TemplateString;
}
private bool WriteTemplate_BrowseNames(IWriteContext context)
{
if (context.Target is not KeyValuePair<string, string> browseName ||
browseName.Value == null)
{
return false;
}
context.Template.AddReplacement(Tokens.SymbolicName, browseName.Key);
context.Template.AddBrowseNameReplacement(
Tokens.BrowseName,
Tokens.BrowseNameLiteral,
browseName.Value,
m_logger);
return context.Template.Render();
}
private static bool WriteTemplate_NamespaceUriStrings(IWriteContext context)
{
if (context.Target is not NamespaceUriConstant constant)
{
return false;
}
context.Template.AddReplacement(Tokens.NamespaceUri, SourceGenerationUtils.Escape(constant.Uri));
context.Template.AddReplacement(Tokens.CodeName, constant.Prefix);
context.Template.AddReplacement(Tokens.Name, constant.Name);
return context.Template.Render();
}
private void CollectBrowseNames(
NodeDesign node,
SortedDictionary<string, string> browseNames)
{
if (m_context.ModelDesign.IsExcluded(node))
{
return;
}
if (node.SymbolicName.Namespace == m_context.ModelDesign.TargetNamespace.Value)
{
browseNames[node.SymbolicName.Name] = node.BrowseName;
m_defaultInstanceBrowseNameKeys.Remove(node.SymbolicName.Name);
}
if (node.Children?.Items == null)
{
return;
}
foreach (NodeDesign child in node.Children.Items)
{
if (m_context.ModelDesign.IsExcluded(child))
{
continue;
}
if (child.SymbolicName == new XmlQualifiedName(BrowseNames.DefaultInstanceBrowseName, Namespaces.OpcUa))
{
var variable = (VariableDesign)child;
if (variable.DecodedValue is QualifiedName qname &&
!string.IsNullOrEmpty(qname.Name))
{
// The default instance browse name is authored data, not a
// symbolic name, so it can contain spaces and punctuation.
// The constant name has to be a legal C# identifier while the
// constant value stays the browse name verbatim.
// Sanitizing can land on a constant name another node
// already claimed ("Device Set" and "DeviceSet" both
// yield "DeviceSet"), and this dictionary is keyed by
// symbolic name everywhere else, so a hit here is not
// necessarily a design error. Keep the entry that is
// already there rather than overwriting it with a
// different value or failing the whole model.
string constantName = qname.Name.ToCSharpIdentifierPreserveCase();
if (!browseNames.ContainsKey(constantName))
{
browseNames[constantName] = qname.Name;
// Remember that this entry is not a symbolic name, so a
// node visited later that really has this symbolic name
// replaces it instead of being reported as a clash.
m_defaultInstanceBrowseNameKeys.Add(constantName);
}
}
continue;
}
if (child.SymbolicName.Namespace == m_context.ModelDesign.TargetNamespace.Value)
{
if (browseNames.TryGetValue(child.SymbolicName.Name, out string? browseName) &&
!m_defaultInstanceBrowseNameKeys.Remove(child.SymbolicName.Name))
{
if (browseName != child.BrowseName)
{
throw ServiceResultException.Create(
StatusCodes.BadTypeMismatch,
"Two nodes with the same symbolic name have different browse names: {0} != {1}.",
browseName,
child.BrowseName);
}
continue;
}
browseNames[child.SymbolicName.Name] = child.BrowseName;
}
if (child is InstanceDesign)
{
CollectBrowseNames(child, browseNames);
}
}
}
private List<NamespaceUriConstant> GetNamespaceUris()
{
List<NamespaceUriConstant> namespaceUris = [];
// Keyed by constant name: the Namespaces class has one member per
// name. A repeat of the same (name, URI) pair is simply dropped -
// that is the XmlNamespace == Value case this used to emit twice.
// Two different URIs claiming one name is not something this can
// resolve, because GetConstantSymbolForNamespace formats the same
// name for both: emitting both gives CS0102 and dropping one makes
// every reference to it resolve to the other one's URI, so report it.
var emitted = new Dictionary<string, string>(StringComparer.Ordinal);
for (int ii = 0; ii < m_context.ModelDesign.Namespaces.Length; ii++)
{
Namespace ns = m_context.ModelDesign.Namespaces[ii];
if (!string.IsNullOrEmpty(ns.Value) &&
ClaimConstantName(emitted, ns.Name, ns.Value))
{
namespaceUris.Add(new NamespaceUriConstant(ns.Name, ns.Prefix, ns.Value));
}
// Only emit the "...Xsd" companion constant when the XML namespace
// actually differs from the namespace URI. When they are equal the
// plain constant above already covers it - emitting both here used
// to produce two "...Xsd" constants and no plain one.
// GetConstantForXmlNamespace applies the same condition, so the
// name it references is always one that was emitted.
if (!string.IsNullOrEmpty(ns.XmlNamespace) &&
!string.Equals(ns.XmlNamespace, ns.Value, StringComparison.Ordinal) &&
ClaimConstantName(emitted, ns.Name + "Xsd", ns.XmlNamespace))
{
namespaceUris.Add(
new NamespaceUriConstant(ns.Name + "Xsd", ns.Prefix, ns.XmlNamespace));
}
}
return namespaceUris;
}
/// <summary>
/// Claims a namespace constant name for a URI. Returns false when the
/// same name and URI were already emitted, and throws when a different
/// URI already owns the name - the Namespaces class can only hold one
/// member of that name, and both callers of it would resolve to it.
/// </summary>
private static bool ClaimConstantName(
Dictionary<string, string> emitted,
string name,
string uri)
{
if (!emitted.TryGetValue(name, out string? claimed))
{
emitted.Add(name, uri);
return true;
}
if (!string.Equals(claimed, uri, StringComparison.Ordinal))
{
throw ServiceResultException.Create(
StatusCodes.BadTypeMismatch,
"Two namespaces map to the constant name '{0}': {1} and {2}. " +
"Give one of them a distinct Name in the model design.",
name,
claimed,
uri);
}
return false;
}
/// <summary>
/// A single namespace URI constant to emit: the C# constant name, the
/// namespace prefix it belongs to and the URI value.
/// </summary>
private sealed class NamespaceUriConstant
{
public NamespaceUriConstant(string name, string prefix, string uri)
{
Name = name;
Prefix = prefix;
Uri = uri;
}
public string Name { get; }
public string Prefix { get; }
public string Uri { get; }
}
private readonly IGeneratorContext m_context;
private readonly Microsoft.Extensions.Logging.ILogger m_logger;
/// <summary>
/// Browse-name dictionary keys that were derived from a
/// DefaultInstanceBrowseName value rather than a symbolic name.
/// </summary>
private readonly HashSet<string> m_defaultInstanceBrowseNameKeys = new(StringComparer.Ordinal);
}
}