Skip to content

Compile-time stack overflow when trait impl contains extern crate #55779

Closed
@dtolnay

Description

@dtolnay

I have two crates:

helper/src/lib.rs

pub trait Trait {
    fn method();
}

repro/src/main.rs

struct Local;

impl helper::Trait for Local {
    fn method() {
        extern crate helper;
        unimplemented!()
    }
}

fn main() {
    <Local as helper::Trait>::method();
}

Notice that the implementation of helper::Trait contains an extern crate helper. Something is not happy about that.

$ ./repro.sh 
     Created library `helper` package
     Created binary (application) `repro` package
   Compiling helper v0.1.0
   Compiling repro v0.1.0

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
error: Could not compile `repro`.

To learn more, run the command again with --verbose.

This currently affects Serde trait impls that use a private helper type with a Serde derive, which is a common pattern.

use serde::{Serialize, Serializer};
use serde_derive::Serialize;

struct _Local {
    range: std::ops::Range<usize>,
}

impl Serialize for _Local {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Helper {
            min: usize,
            max: usize,
        }

        let helper = Helper {
            min: self.range.start,
            max: self.range.end,
        };
        helper.serialize(serializer)
    }
}

fn main() {}

The following script reproduces the issue as of rustc 1.31.0-beta.4 (04da282 2018-11-01) as well as rustc 1.32.0-nightly (25a42b2 2018-11-07).

#!/bin/bash

cargo new --lib helper
cargo new --bin repro

echo >helper/src/lib.rs '
pub trait Trait {
    fn method();
}
'

echo >>repro/Cargo.toml '
helper = { path = "../helper" }
'

echo >repro/src/main.rs '
struct Local;

impl helper::Trait for Local {
    fn method() {
        extern crate helper;
        unimplemented!()
    }
}

fn main() {
    <Local as helper::Trait>::method();
}
'

cargo build --manifest-path repro/Cargo.toml

Metadata

Metadata

Assignees

Labels

C-bugCategory: This is a bug.I-crashIssue: The compiler crashes (SIGSEGV, SIGABRT, etc). Use I-ICE instead when the compiler panics.P-highHigh priorityT-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