Skip to content

Avoid method-call shadowing of the hidden AsDynError helper - #463

Open
draarivpatel-ui wants to merge 2 commits into
dtolnay:masterfrom
draarivpatel-ui:fix/as-dyn-error-shadowing
Open

draarivpatel-ui wants to merge 2 commits into
dtolnay:masterfrom
draarivpatel-ui:fix/as-dyn-error-shadowing

Conversation

@draarivpatel-ui

Copy link
Copy Markdown

Summary

thiserror expands #[error(transparent)] and #[source] fields to a call of the hidden AsDynError::as_dyn_error method through method-call resolution. An inherent method with the same name on the field type therefore shadows the trait method, and the generated source() forwards to whatever the inherent method returns. Rootcause hit this after adding an inherent as_dyn_error (#452).

Change

Fully qualifying the call as suggested in the issue is not possible without breaking Box<dyn Error> fields: UFCS does not deref through the box, and Box<dyn Error> does not implement Error because of its Sized bound. Instead this renames the hidden method to __thiserror_as_dyn_error, which keeps method-call auto-deref while making accidental shadowing essentially impossible.

Tests

cargo test (full suite) and cargo fmt --check pass. The new regression test defines a source type with an inherent as_dyn_error and checks transparent struct/enum and source struct/enum variants still forward to the real error. It fails on the previous code.

Fixes #452

The derive generates calls to `AsDynError::as_dyn_error` through method-call
resolution, so an inherent method with the same name on the source field type
silently shadows it. That makes `#[error(transparent)]` and `#[source]` fields
forward to the wrong error, which rootcause hit when it added an inherent
`as_dyn_error`.

Fully qualifying the call would break auto-deref for fields such as
`Box<dyn Error>`, because UFCS does not deref through the box. Instead, rename
the hidden method to `__thiserror_as_dyn_error`. Method-call resolution keeps
the auto-deref behavior, and the generated code no longer collides with a name
that downstream crates use.

Adds a regression test covering transparent structs and enums as well as
source struct and enum variants with an inherent `as_dyn_error`.

Fixes dtolnay#452
Copilot AI balanced review requested due to automatic review settings November 26, 2026 00:39

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

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.

Semver question: Is the non-qualified call to .as_dyn_error() intentional?

2 participants