Commit Graph

2 Commits

Author SHA1 Message Date
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
Marc Schier 66be6731f4 Source generator: support compiled companion models and safe NodeState writes (#4063)
## Summary

Combines the compiled companion-model support from #4062 with the
NodeState emission fixes already in this PR. The model source generator
can now consume compiled companion `NodeSet2` models more reliably,
while generated factories consistently target base `NodeState` members
even when a generated subclass shadows them.

## Changes

### Compiled companion NodeSets

- Add `OpcUaStateTypeIndex` and wire it through `ModelSourceGenerator` /
`ModelCompilation` so standard (`ns=0`) node-state and method-state
class names are resolved from referenced `Opc.Ua.Core(.Types)` metadata.
- Add the model-generation-scoped `StandardMethodStateFallback`, which
degrades an unresolved standard typed `*MethodState` reference to
`global::Opc.Ua.MethodState` only when the type is neither available in
the compilation nor declared by the current generation pass.
- Keep declaration names outside the reference-only fallback policy,
propagate fallback state through the logical execution context, reuse
the immutable availability index, and use named incremental-generator
inputs instead of deep `Left` / `Right` chains.
- Escape generated fluent-builder XML documentation where browse names
can contain XML-sensitive characters.

### Safe NodeState factory emission

- Declare one base-typed `global::Opc.Ua.NodeState nodeState = state;`
local per generated factory.
- Use `nodeState` for base-member reads and writes to `NodeId`,
`SymbolicName`, `BrowseName`, `DisplayName`, `Description`, `WriteMask`,
`UserWriteMask`, `AccessRestrictions`, `ReleaseStatus`, `Categories`,
`Specification` and `IsPartOfTypeHierarchy`.
- Base-qualify the optional-child `previousNodeId` read, NodeId
comparison, and existing-child NodeId update.
- `global::`-qualify emitted `NodeId` / `ExpandedNodeId` namespace
prefixes to avoid namespace collisions.

### Supporting updates

- Expose `Opc.Ua.Types` internals to `Opc.Ua.Core.Encoders.Tests`.
- Update generator assertions and add focused fallback regression
coverage.

## Why

Compiled companion models can instantiate standard types whose curated
Core implementation does not expose the conventionally named typed
method-state class. The scoped fallback lets those models generate
without weakening the Stack generator or masking classes emitted by the
current model.

Separately, generated subclasses can shadow base `NodeState` properties
with strongly typed `new` properties. Routing base attributes through a
`NodeState`-typed local guarantees initialization reaches the intended
base member while keeping generated code smaller and clearer than
repeated casts.

## Validation

- Full `Opc.Ua.SourceGeneration.Core.Tests` on net10.0: **3718 passed /
8 skipped / 0 failed**.
- Combined focused generator coverage on net48: **21 passed / 0
failed**.
- Full `Opc.Ua.SourceGeneration.Tests`: **68 passed / 0 failed**.
- Full `Opc.Ua.SourceGeneration.Stack.Tests`: **90 passed / 0 failed**.

## Context

This PR supersedes #4062 and contains both source-generator change sets.
The companion-model fallback remains the scoped interim workaround
tracked by #4060; a future upstream name-resolution step can remove it.
These changes also feed the experimental data-encodings work in #4007.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-07-21 20:48:44 +02:00