mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-25 20:00:31 +08:00
# 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>
237 lines
12 KiB
C#
237 lines
12 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.Buffers;
|
|
|
|
namespace Opc.Ua.Aot.Tests
|
|
{
|
|
/// <summary>
|
|
/// Direct native instantiations of scalar, builder, nesting and codec paths.
|
|
/// </summary>
|
|
[ClassDataSource<AotTestFixture>(Shared = SharedType.PerTestSession)]
|
|
public sealed class VariantStorageAotTests(AotTestFixture fixture)
|
|
{
|
|
[Test]
|
|
[Arguments(0)]
|
|
[Arguments(65535)]
|
|
public async Task QualifiedNamesPreserveRawNamesAndNamespacesAsync(int ns)
|
|
{
|
|
foreach (string? name in new string?[] { null, string.Empty, "native" })
|
|
{
|
|
var input = new QualifiedName(name, (ushort)ns);
|
|
var value = Variant.From(input);
|
|
await Assert.That(value.TryGetValue(out QualifiedName actual)).IsTrue();
|
|
await Assert.That(actual.Name).IsEqualTo(name);
|
|
await Assert.That(actual.NamespaceIndex).IsEqualTo((ushort)ns);
|
|
// A null qualified name equals Variant.Null and hashes like it.
|
|
await Assert.That(value.GetHashCode()).IsEqualTo(input.IsNull ? 0 : input.GetHashCode());
|
|
await Assert.That(value.AsBoxedObject() is QualifiedName).IsTrue();
|
|
await CheckAsync(input, value, default(VariantBuilder)).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
[Arguments(0)]
|
|
[Arguments(65535)]
|
|
public async Task NodeIdsPreserveKindsCachedHashesAndBorrowedPayloadsAsync(int ns)
|
|
{
|
|
byte[] buffer = [9, 1, 2, 8];
|
|
NodeId[] inputs =
|
|
[
|
|
new NodeId(0u, (ushort)ns), new NodeId(uint.MaxValue, (ushort)ns),
|
|
new NodeId(null!, (ushort)ns), new NodeId(default(ByteString), (ushort)ns),
|
|
new NodeId(string.Empty, (ushort)ns), new NodeId("native", (ushort)ns),
|
|
new NodeId(Guid.Empty, (ushort)ns),
|
|
new NodeId(new ByteString(buffer.AsMemory(1, 2)), (ushort)ns)
|
|
];
|
|
foreach (NodeId input in inputs)
|
|
{
|
|
int hash = input.GetHashCode();
|
|
var value = Variant.From(input);
|
|
buffer[1] = 7;
|
|
await Assert.That(value.TryGetValue(out NodeId actual)).IsTrue();
|
|
await Assert.That(actual.IdType).IsEqualTo(input.IdType);
|
|
await Assert.That(actual.NamespaceIndex).IsEqualTo(input.NamespaceIndex);
|
|
await Assert.That(actual.GetHashCode()).IsEqualTo(hash);
|
|
await Assert.That(actual.Equals(input)).IsTrue();
|
|
await Assert.That(input.Equals(actual)).IsTrue();
|
|
await Assert.That(value.AsBoxedObject() is NodeId).IsTrue();
|
|
await CheckAsync(input, value, default(VariantBuilder)).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public async Task ByteStringsPreserveSlicesNullsAndByteArrayConversionAsync()
|
|
{
|
|
byte[] buffer = [9, 1, 2, 8];
|
|
foreach (ByteString input in new[]
|
|
{
|
|
default, ByteString.Empty, new ByteString(buffer.AsMemory(1, 2))
|
|
})
|
|
{
|
|
var value = Variant.From(input);
|
|
await Assert.That(value.TryGetValue(out ByteString actual)).IsTrue();
|
|
await Assert.That(actual.IsNull).IsEqualTo(input.IsNull);
|
|
await Assert.That(actual.Memory.Equals(input.Memory)).IsTrue();
|
|
await Assert.That(value.GetByteArray().Span.SequenceEqual(input.Span)).IsTrue();
|
|
buffer[1] = 42;
|
|
// A null or empty byte string hashes like Variant.Null.
|
|
await Assert.That(value.GetHashCode()).IsEqualTo(input.IsEmpty ? 0 : input.GetHashCode());
|
|
await Assert.That(value.AsBoxedObject() is ByteString).IsTrue();
|
|
await CheckAsync(input, value, default(VariantBuilder)).ConfigureAwait(false);
|
|
}
|
|
byte[] source = [1, 2];
|
|
ArrayOf<byte> copiedArray = Variant.From(new ByteString(source)).GetByteArray();
|
|
ByteString copiedBytes = Variant.From(new ArrayOf<byte>(source)).GetByteString();
|
|
source[0] = 42;
|
|
await Assert.That(copiedArray[0]).IsEqualTo((byte)1);
|
|
await Assert.That(copiedBytes[0]).IsEqualTo((byte)1);
|
|
}
|
|
|
|
[Test]
|
|
public async Task ByteStringMemoryManagerRetainsSliceFlagsAndDisposalAsync()
|
|
{
|
|
using var manager = new NativeMemoryManager();
|
|
var input = new ByteString(manager.Memory.Slice(1, 3).Slice(1, 2));
|
|
var value = Variant.From(input);
|
|
await Assert.That(value.TryGetValue(out ByteString actual)).IsTrue();
|
|
await Assert.That(actual.Memory.Equals(input.Memory)).IsTrue();
|
|
await Assert.That(actual[0]).IsEqualTo((byte)2);
|
|
manager.GetSpan()[2] = 42;
|
|
await Assert.That(actual[0]).IsEqualTo((byte)42);
|
|
await Assert.That(value.GetHashCode()).IsEqualTo(input.GetHashCode());
|
|
((IDisposable)manager).Dispose();
|
|
await Assert.That(() => _ = actual.Span.Length).Throws<ObjectDisposedException>();
|
|
}
|
|
|
|
[Test]
|
|
public async Task TextOnlyAndRichLocalizedTextKeepTheirRawStateAsync()
|
|
{
|
|
LocalizedText[] inputs =
|
|
[
|
|
default, new LocalizedText(string.Empty), new LocalizedText("native"),
|
|
new LocalizedText(string.Empty, "native"), new LocalizedText("en", "native"),
|
|
new LocalizedText("key", "en", "Value {0}", 7),
|
|
new LocalizedText("key", null!, "Value {0}", 7),
|
|
new LocalizedText(new Dictionary<string, string> { ["en"] = "native", ["de"] = "nativ" })
|
|
];
|
|
foreach (LocalizedText input in inputs)
|
|
{
|
|
var value = Variant.From(input);
|
|
await Assert.That(value.TryGetValue(out LocalizedText actual)).IsTrue();
|
|
await Assert.That(actual.Locale).IsEqualTo(input.Locale);
|
|
await Assert.That(actual.Text).IsEqualTo(input.Text);
|
|
await Assert.That(ReferenceEquals(actual.Translations, input.Translations)).IsTrue();
|
|
await Assert.That(actual.TranslationInfo.Equals(input.TranslationInfo)).IsTrue();
|
|
// LocalizedText has no order, except that an absent value
|
|
// (equal to Variant.Null) compares as 0 like Variant.Null.
|
|
int expectedOrder = value.Equals(Variant.Null) ? 0 : int.MinValue;
|
|
await Assert.That(value.CompareTo(value)).IsEqualTo(expectedOrder);
|
|
await Assert.That(value.GetHashCode()).IsEqualTo(input.GetHashCode());
|
|
await CheckAsync(input, value, default(VariantBuilder)).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public async Task PackedMetadataDoesNotParticipateInBitwiseOperatorsAsync()
|
|
{
|
|
byte[] buffer = [9, 1, 2, 8];
|
|
Variant[] inputs =
|
|
[
|
|
Variant.From(new QualifiedName("native", ushort.MaxValue)),
|
|
Variant.From(new NodeId(uint.MaxValue, ushort.MaxValue)),
|
|
Variant.From(new ByteString(buffer.AsMemory(1, 2))),
|
|
Variant.From(new LocalizedText("native"))
|
|
];
|
|
foreach (Variant input in inputs)
|
|
{
|
|
Variant andResult = Variant.From(-1L) & input;
|
|
Variant orResult = Variant.From(0L) | input;
|
|
|
|
// An operand that does not resolve to an integer makes the
|
|
// result null (OPC 10000-4 7.7.3), rather than a zero that is
|
|
// indistinguishable from a real result. Either way the packed
|
|
// payload's raw bits never reach the operator.
|
|
await Assert.That(andResult.IsNull).IsTrue();
|
|
await Assert.That(orResult.IsNull).IsTrue();
|
|
await Assert.That(andResult.TryGetValue(out long _)).IsFalse();
|
|
await Assert.That(orResult.TryGetValue(out long _)).IsFalse();
|
|
await Assert.That((Variant.From(true) & input).GetBoolean()).IsFalse();
|
|
await Assert.That((Variant.From(false) | input).GetBoolean()).IsFalse();
|
|
}
|
|
await Assert.That((Variant.From(-1L) & Variant.From(7L)).GetInt64()).IsEqualTo(7L);
|
|
await Assert.That((Variant.From(0L) | Variant.From(7L)).GetInt64()).IsEqualTo(7L);
|
|
}
|
|
|
|
private async Task CheckAsync<T>(T input, Variant value, IVariantBuilder<T> builder)
|
|
{
|
|
await Assert.That(EqualityComparer<T>.Default.Equals(builder.GetValue(value), input)).IsTrue();
|
|
await Assert.That(builder.WithValue(input).Equals(value)).IsTrue();
|
|
await Assert.That(VariantHelper.CastFrom(input).Equals(value)).IsTrue();
|
|
await Assert.That(value.Copy().Equals(value)).IsTrue();
|
|
var data = new DataValue(value);
|
|
await Assert.That(Variant.From(data).GetDataValue().WrappedValue.Equals(value)).IsTrue();
|
|
var context = ServiceMessageContext.CreateEmpty(fixture.Telemetry);
|
|
using var encoder = new BinaryEncoder(context);
|
|
encoder.WriteVariant(null, value);
|
|
using var decoder = new BinaryDecoder(
|
|
encoder.CloseAndReturnBuffer() ?? throw new InvalidOperationException("No encoded value."), context);
|
|
Variant decoded = decoder.ReadVariant(null);
|
|
await Assert.That(decoded.TypeInfo).IsEqualTo(value.TypeInfo);
|
|
await Assert.That(decoded.Equals(value)).IsTrue();
|
|
}
|
|
|
|
private sealed class NativeMemoryManager : MemoryManager<byte>
|
|
{
|
|
public override Span<byte> GetSpan()
|
|
{
|
|
ObjectDisposedException.ThrowIf(m_disposed, this);
|
|
return m_buffer;
|
|
}
|
|
|
|
public override MemoryHandle Pin(int elementIndex = 0)
|
|
{
|
|
throw new NotSupportedException();
|
|
}
|
|
|
|
public override void Unpin()
|
|
{
|
|
}
|
|
|
|
protected override void Dispose(bool disposing)
|
|
{
|
|
m_disposed = true;
|
|
}
|
|
|
|
private readonly byte[] m_buffer = [0, 1, 2, 3, 4];
|
|
private bool m_disposed;
|
|
}
|
|
}
|
|
}
|