Skip to content

Emit errors or warning to user about recursion of display #125292

Open
@gftea

Description

@gftea

Code

code cause recursion stack overflow

struct Hello;

impl std::fmt::Debug for Hello {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{}", self)
  }
}

impl std::fmt::Display for Hello {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "{:}", self)
  }
}

fn main() {
    let h = Hello;
    println!("{}", h);
}

Current output

Runtime error instead of compile time error at present

thread 'main' has overflowed its stack
fatal runtime error: stack overflow

Desired output

In a large code base, such small mistake is hard to locate because it does not point out which recursion call cause stack overflow.

Rationale and extra context

  1. It is calling Display in a implementation for Display, this seems to be abvious recursion can be detected by compiler. I guess there may be general effort to detect recursion call, but if such obvious recursion can be prevented by compiler earlier
  2. there is no use case for using : as standalone formatter, and it is better the compiler to emit error to use : as standalone formatter because it is likely user want to use :? but drop ? by mistake,

Other cases

No response

Rust Version

rustc v1.78.0

Anything else?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=15e6928ea61ea7e8ac7072fa82875e97

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.A-trait-systemArea: Trait systemL-unconditional_recursionLint: unconditional_recursionT-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