rust-lang / rust-lang/rust

Type inference for the question mark operator

Open
#123,793 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-inference C-discussion T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I believe that in certain scenarios the question mark operator should infer the err variant of a result type

I tried this code:

pub fn inference<T, E, F>(mut f: F) -> Result<T, E> 
where F : FnMut () -> Result<T, E>,
      E : std::error::Error,
{
    f()
}

#[test]
fn inference_tester() {
    inference_user();
}

fn inference_user() {

    use std::env::VarError;

    // in this example x should always be inferred to be of type Result<String, VarError>

    // works fine, nothing ambiguous
    let x : Result<String, VarError> = inference(|| {
        Ok(std::env::var("key")?)
    });

    // works fine, it's ok to infer T to be String
    let x = inference::<_, VarError, _>(|| {
        Ok(std::env::var("key")?)
    });

    // works fine, apparently it's ok to infer the Ok variant
    let x : Result<_, VarError> = inference(|| {
        Ok(std::env::var("key")?)
    });

    // type annotations needed, apparently it's NOT ok to infer the Err variant
    let x : Result<String, _> = inference(|| {
        Ok(std::env::var("key")?)
    });

    // works fine
    let x = inference(|| {
        let result = std::env::var("key");
        // attempt to do what let result = result?; would do
        let result = match result {
            Ok(ok) => ok,
            Err(err) => {
                // the compiler "knows" that err : VarError
                return Err(err); // the ? operator uses From::from(err)
            },
        };
        Ok(result)
    });

    // works fine, apparently it's ok to infer the Err variant from dead code
    let x = inference(|| {
        let result = std::env::var("key");
        let result = match result {
            Ok(ok) => ok,
            Err(err) => {
                return Err(From::from(err));
                return Err(VarError::from(err)); // unreachable statement
            },
        };
        Ok(result)
    });

    // works fine, apparently it's ok to infer the Err variant from dead code
    let x = inference(|| {
        return Ok(std::env::var("key")?);
        Err(VarError::NotPresent)
    });

    // type annotations needed, but are they really ?
    let x = inference(|| {
        return Ok(std::env::var("key")?);
    });

}

I expected to see this happen: everything to compile, because all the types are actually known, I would've understood a type annotations needed compile error if I had multiple Err return points with different error types in which case inference would not have been possible.

Instead, this happened: compile error type annotations needed

Meta

rustc --version --verbose:

rustc 1.77.1 (7cf61ebde 2024-03-27)
binary: rustc
commit-hash: 7cf61ebde7b22796c69757901dd346d0fe70bd97
commit-date: 2024-03-27
host: x86_64-pc-windows-msvc
release: 1.77.1
LLVM version: 17.0.6

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 compiling the provided inference_tester reproduction with rustc 1.77.1 and compare the annotated and unannotated cases. Investigate Rust compiler type inference for the ? operator and whether the final error type can be inferred from the shown return paths. Done means the expected behavior is resolved, with the reproducer's inference cases covered or the current behavior clearly established as intentional.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.