Skip to content

Better ref casting DX#15247

Merged
Ericson2314 merged 2 commits intoNixOS:masterfrom
roberth:clarify-ref-upcasting
Feb 16, 2026
Merged

Better ref casting DX#15247
Ericson2314 merged 2 commits intoNixOS:masterfrom
roberth:clarify-ref-upcasting

Conversation

@roberth
Copy link
Member

@roberth roberth commented Feb 16, 2026

Motivation

Wasn't sure whether implicit upcasts were supported, then found some room for improvement and clarification.

ref was already implicitly convertible to ref, but the
mechanism was unclear and error messages for rejected downcasts were
more cryptic than necessary.

When ref::cast() fails, the error message was also cryptic ("null pointer
cast to ref"). Now it throws bad_ref_cast (a std::bad_cast subclass)
with a clear message showing the actual types involved.

Context


Add 👍 to pull requests you find important.

The Nix maintainer team uses a GitHub project board to schedule and track reviews.

…ause

ref<Derived> was already implicitly convertible to ref<Base>, but the
mechanism was unclear and error messages for rejected downcasts were
more cryptic than necessary. This change:

- Adds RefImplicitlyUpcastableTo concept to constrain the conversion
  operator, making the intent explicit and improving error messages
- Documents .cast() and .dynamic_pointer_cast() as alternatives for
  explicit downcasting
- Adds unit tests for covariance behavior
When ref::cast() fails, the error message was cryptic ("null pointer
cast to ref"). Now it throws a proper bad_ref_cast (a std::bad_cast
subclass) with a clear message showing the actual types involved:

    ref<nix::Base> cannot be cast to ref<nix::Derived>

This also adds a demangle.hh utility.
@roberth roberth requested a review from edolstra as a code owner February 16, 2026 16:10
@Ericson2314 Ericson2314 added this pull request to the merge queue Feb 16, 2026
Merged via the queue into NixOS:master with commit a53391f Feb 16, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants