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

292 lines
12 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/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Logging;
using NUnit.Framework;
using Opc.Ua.SourceGeneration.Dependency;
using Opc.Ua.Tests;
namespace Opc.Ua.SourceGeneration.Generator.Tests
{
/// <summary>
/// A model normally belongs to exactly one assembly: whoever emits its
/// types. That leaves a node manager for it homeless whenever the
/// assembly that owns the model cannot reference
/// <c>Opc.Ua.Server</c> — a model-only package shared with clients, for
/// instance. Binding a <c>[NodeManager]</c> to a model a reference
/// already supplies is the way out: the manager and its fluent surface
/// are emitted in the server-side assembly while the model types keep
/// coming from the reference.
/// </summary>
[TestFixture]
[Category("Generator")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[Parallelizable(ParallelScope.All)]
public class NodeManagerBindingToReferencedModelTests
{
private const string ModelUri = "urn:opcfoundation.org:2024-01:TestModel";
private const string Prefix = "TestModel";
[Test]
public void ABoundManagerIsEmittedForAModelAReferenceSupplies()
{
Dictionary<string, string> files = Generate(WithBinding(), out _);
Assert.That(files.Keys, Has.Some.EndsWith(".NodeManager.g.cs"),
"The bound manager must be emitted even though the model is not");
string mgr = files.Single(
kv => kv.Key.EndsWith(".NodeManager.g.cs", StringComparison.Ordinal)).Value;
Assert.That(mgr, Does.Contain("namespace Consumer.Managers"));
Assert.That(mgr, Does.Contain("class BoundNodeManager"));
// The predefined nodes come from the referenced assembly's
// model composer — the whole point of the mode.
Assert.That(mgr, Does.Contain("LoadPredefinedNodesAsync"));
Assert.That(mgr, Does.Match(
@"global::TestModel\.TestModelExtensions\.AddTestModel\("));
}
[Test]
public void TheModelTypesAreNotReEmitted()
{
Dictionary<string, string> files = Generate(WithBinding(), out _);
// Everything that would collide with the referenced assembly.
Assert.That(files.Keys, Has.None.EndsWith(".NodeStates.g.cs"));
Assert.That(files.Keys, Has.None.EndsWith(".NodeStates.ex.g.cs"));
Assert.That(files.Keys, Has.None.EndsWith(".Constants.g.cs"));
Assert.That(files.Keys, Has.None.EndsWith(".DataTypes.g.cs"));
Assert.That(files.Keys, Has.None.EndsWith(".Identifiers.g.cs"));
Assert.That(files.Keys, Has.None.EndsWith(".EventRecords.g.cs"));
}
[Test]
public void TheFluentSurfaceIsEmittedAlongsideTheManager()
{
Dictionary<string, string> files = Generate(WithBinding(), out _);
Assert.That(files.Keys, Has.Some.EndsWith(".FluentBuilders.g.cs"),
"The typed builder the manager's Configure overload takes " +
"has to be emitted with it");
string builders = files.Single(
kv => kv.Key.EndsWith(".FluentBuilders.g.cs", StringComparison.Ordinal)).Value;
Assert.That(builders, Does.Contain("IBoundNodeManagerBuilder"),
"The typed builder must be named after the bound manager");
}
[Test]
public void TheBindingIsNotReportedAsUnmatched()
{
Generate(WithBinding(), out List<string> diagnostics);
Assert.That(diagnostics, Is.Empty,
"A binding that produced a manager must not be reported unmatched");
}
[Test]
public void WithoutABindingTheReferencedModelIsStillSkipped()
{
Dictionary<string, string> files = Generate(bindings: [], out _);
Assert.That(files, Is.Empty,
"A model a reference supplies and nothing binds to stays skipped");
}
/// <summary>
/// The skip is what stops duplicate type emission, so it must
/// survive: a binding for a <em>different</em> model may not drag
/// this one into generation.
/// </summary>
[Test]
public void ABindingForAnotherModelDoesNotUnlockThisOne()
{
var foreign = new NodeManagerAttributeBinding
{
TargetNamespace = "Consumer.Managers",
TargetClassName = "ForeignNodeManager",
NamespaceUri = "urn:example.org:SomeOtherModel"
};
Dictionary<string, string> files = Generate([foreign], out List<string> diagnostics);
Assert.That(files, Is.Empty);
Assert.That(diagnostics, Has.Count.EqualTo(1),
"The unmatched binding must still be reported");
}
/// <summary>
/// Regression: when the reference (or another referenced assembly) already
/// provides the fluent accessors, the whole binding used to be dropped -
/// no manager, only a fluent-accessors-only diagnostic that does not
/// mention the binding. Only the accessors must be left out; the manager
/// and its typed wrappers do not depend on them.
/// </summary>
[TestCase(true, false)]
[TestCase(false, true)]
public void ABoundManagerIsEmittedWhenAReferenceAlreadyProvidesTheAccessors(
bool producerEmittedAccessors,
bool separateAccessorProvider)
{
Dictionary<string, string> files = Generate(
WithBinding(),
out List<string> diagnostics,
producerEmittedAccessors,
(separateAccessorProvider
? [new ModelFluentAccessorProviderReference("Referenced.Server", ModelUri, Prefix)]
: null)!,
out List<string> accessorDiagnostics);
Assert.That(files.Keys, Has.Some.EndsWith(".NodeManager.g.cs"));
string builders = files.Single(
kv => kv.Key.EndsWith(".FluentBuilders.g.cs", StringComparison.Ordinal)).Value;
Assert.Multiple(() =>
{
Assert.That(builders, Does.Contain("IBoundNodeManagerBuilder"));
Assert.That(builders, Does.Not.Contain("StateComponents"),
"the accessors the reference provides must not be emitted a second time");
Assert.That(builders, Does.Not.Contain("ModelFluentAccessorProviderAttribute"),
"an assembly without accessors must not advertise them");
Assert.That(diagnostics, Is.Empty);
Assert.That(accessorDiagnostics, Is.Empty);
});
}
/// <summary>
/// Regression: the fluent accessor provider attribute recorded the manager
/// namespace of the binding instead of the model prefix, so a downstream
/// accessors-only build did not recognise the provider and emitted a second,
/// ambiguous set of accessors (CS0121).
/// </summary>
[Test]
public void TheAccessorProviderAttributeRecordsTheModelPrefix()
{
Dictionary<string, string> files = Generate(WithBinding(), out _);
string builders = files.Single(
kv => kv.Key.EndsWith(".FluentBuilders.g.cs", StringComparison.Ordinal)).Value;
Assert.That(builders, Does.Contain(
"ModelFluentAccessorProviderAttribute(\"" + ModelUri + "\", \"" + Prefix + "\")"));
Assert.That(builders, Does.Contain("namespace Consumer.Managers"),
"the accessors themselves stay in the manager namespace");
}
private static IReadOnlyList<NodeManagerAttributeBinding> WithBinding()
{
return
[
new NodeManagerAttributeBinding
{
TargetNamespace = "Consumer.Managers",
TargetClassName = "BoundNodeManager",
NamespaceUri = ModelUri,
GenerateFactory = false
}
];
}
private static Dictionary<string, string> Generate(
IReadOnlyList<NodeManagerAttributeBinding> bindings,
out List<string> diagnostics)
{
return Generate(bindings, out diagnostics, false, null!, out _);
}
private static Dictionary<string, string> Generate(
IReadOnlyList<NodeManagerAttributeBinding> bindings,
out List<string> diagnostics,
bool producerEmittedAccessors,
IReadOnlyList<ModelFluentAccessorProviderReference> accessorProviders,
out List<string> accessorDiagnostics)
{
const string designFile = "TestModel.xml";
ITelemetryContext telemetry = NUnitTelemetryContext.Create(logLevel: LogLevel.Error);
using var fileSystem = new VirtualFileSystem();
string resources = Path.Combine(Directory.GetCurrentDirectory(), "Resources");
var captured = new List<string>();
var capturedAccessors = new List<string>();
// A referenced assembly that supplies the model types but no
// fluent accessors — the shape of a model-only package.
var dependency = new ModelDependencyV1
{
ModelUri = ModelUri,
FluentAccessorsEmitted = producerEmittedAccessors
};
var referenced = new ModelDependencyReference(
"Referenced.Model",
ModelUri,
Prefix,
"1.0",
"2026-01-01",
payload: dependency.ToBase64Payload());
Generators.GenerateCode(
new DesignFileCollection
{
Targets = [Path.Combine(resources, designFile)],
IdentifierFilePath = Path.Combine(
resources,
Path.GetFileNameWithoutExtension(designFile) + ".csv")
},
fileSystem,
string.Empty,
telemetry,
options: null!,
useAllowSubtypes: false,
identifierFiles: null!,
referencedModels: new Dictionary<string, ModelDependencyReference>(StringComparer.Ordinal)
{
[ModelUri] = referenced
},
nodeManagerBindings: bindings,
reportBindingDiagnostic: (_, message) => captured.Add(message),
sharedUsedBindings: null!,
bindingModelCount: 0,
reportFluentAccessorsOnlyDiagnostic: (_, _, _, reason) => capturedAccessors.Add(reason),
referencedModelProviders: null!,
referencedAccessorProviders: accessorProviders);
diagnostics = captured;
accessorDiagnostics = capturedAccessors;
return fileSystem.CreatedFiles
.Where(c => Path.GetExtension(c) == ".cs")
.ToDictionary(c => c, c => Encoding.UTF8.GetString(fileSystem.Get(c)));
}
}
}