rust-lang / rust-lang/rust

Emit errors or warning to user about recursion of display

Open
#125,292 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics A-lints A-trait-system L-unconditional_recursion T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the supplied Rust example with rustc or the linked Playground and confirm the stack overflow behavior. Investigate whether the compiler can identify this formatter recursion or the standalone : format syntax without changing valid formatting behavior. Done means an appropriate diagnostic or warning points to the problematic recursion, with coverage for the reported example.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.