`impl` blocks do not support conditional type parameters
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.2k
- PR merge metrics
- PR metrics pending
Description
I tried this code:
struct S<#[cfg(feature = "f")] T> {
#[cfg(feature = "f")]
t: T,
}
impl<#[cfg(feature = "f")] T> S<#[cfg(feature = "f")] T> {
fn m(&self) {
println!("m");
}
}
I expected to see this happen: code compiles successfully with both feature "f" enabled and disabled.
Instead, this happened:
❯ cargo test
Compiling rust-webapp v0.1.0 (/Users/dragnea/IdeaProjects/rust-webapp)
error: invalid const generic expression
--> src/cfg_type_parameter.rs:6:55
|
6 | impl<#[cfg(feature = "f")] T> S<#[cfg(feature = "f")] T> {
| ^
|
help: expressions must be enclosed in braces to be used as const generic arguments
|
6 | impl<#[cfg(feature = "f")] T> S<#[cfg(feature = "f")] { T }> {
| + +
error[E0747]: constant provided when a type was expected
--> src/cfg_type_parameter.rs:6:55
|
6 | impl<#[cfg(feature = "f")] T> S<#[cfg(feature = "f")] T> {
| ^
For more information about this error, try `rustc --explain E0747`.
error: could not compile `rust-webapp` (bin "rust-webapp" test) due to 2 previous errors
I managed to avoid this bug by using a macro hack, but this does not solve the original problem:
struct S<#[cfg(feature = "f")] T> {
#[cfg(feature = "f")]
t: T,
}
#[cfg(feature = "f")]
macro_rules! s_type {
[$t:ident] => {
S<$t>
}
}
#[cfg(not(feature = "f"))]
macro_rules! s_type {
[$t:ident] => {
S
}
}
impl<#[cfg(feature = "f")] T> s_type![T] {
fn m(&self) {
println!("m");
}
}
I reproduced this bug here. I also saw this bug discussed two times on Rust forum: here and here.
Meta
rustc --version --verbose:
rustc 1.77.0-nightly (2d7be7393 2023-12-23)
binary: rustc
commit-hash: 2d7be73931e0978c8758a672cc7258b417a7e999
commit-date: 2023-12-23
host: aarch64-apple-darwin
release: 1.77.0-nightly
LLVM version: 17.0.6
Backtrace
<backtrace>
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproducer in src/cfg_type_parameter.rs and run cargo test with feature "f" enabled and disabled. Compare the conditional type-parameter handling in the impl block with the expected successful compilation, and add coverage showing both configurations compile without treating T as a const generic.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100