Skip to content

Invalid code suggested when encountering unsatisfied trait bounds in derive macro code #104884

Closed
@jonasbb

Description

@jonasbb

Given the following code: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=0345475f1b234a0cf26f97bfb712cceb

use std::collections::BinaryHeap;

#[derive(PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
struct PriorityQueueEntry<T> {
    value: T,
}

#[derive(serde::Serialize)]
struct PriorityQueue<T>(BinaryHeap<PriorityQueueEntry<T>>);

The current output is:

Compiling playground v0.0.1 (/playground)
error[[E0277]](https://doc.rust-lang.org/nightly/error-index.html#E0277): the trait bound `T: Ord` is not satisfied
   --> src/lib.rs:8:10
    |
8   | #[derive(serde::Serialize)]
    |          ^^^^^^^^^^^^^^^^ the trait `Ord` is not implemented for `T`
9   | struct PriorityQueue<T>(BinaryHeap<PriorityQueueEntry<T>>);
    |                         --------------------------------- required by a bound introduced by this call
    |
note: required for `PriorityQueueEntry<T>` to implement `Ord`
   --> src/lib.rs:3:37
    |
3   | #[derive(PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
    |                                     ^^^
    = note: required for `BinaryHeap<PriorityQueueEntry<T>>` to implement `Serialize`
note: required by a bound in `serialize_newtype_struct`
   --> /playground/.cargo/registry/src/github.com-1ecc6299db9ec823/serde-1.0.147/src/ser/mod.rs:904:12
    |
904 |         T: Serialize;
    |            ^^^^^^^^^ required by this bound in `serialize_newtype_struct`
    = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider further restricting type parameter `T`
    |
8   | #[derive(serde::Serialize, T: std::cmp::Ord)]
    |                          ++++++++++++++++++

The last part of the suggestion #[derive(serde::Serialize, T: std::cmp::Ord)] is not valid Rust code and therefore should not be suggested like this.

This problem occurs on the Playground on both stable and nightly with basically identical error messages. serde v1.0.147 requires T: Ord such that BinaryHeap will be Serialize. Otherwise the problem does not seem serde specific.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions