Skip to content

new lint: Recursive Display impl #2691

Closed
@oherrala

Description

@oherrala

It's possible to implement Display trait in such a way which recursively calls itself until stack is exhausted. There's probably more variations how to encounter this bug. I provide one example.

Consider the following code:

use std::fmt::{Display, Formatter, Result};

struct Foo;

impl Display for Foo {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "{}", self)
    }
}

fn main() {
    println!("{}", Foo);
}

Compiles perfectly fine, but there's stack trace at run time:

$ cargo run -q

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

The bug is in line write!(f, "{}", self) which recursively calls itself by trying to use Display trait implementation for self.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.L-correctnessLint: Belongs in the correctness lint group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions