rust-lang / rust-lang/rust-analyzer

Inline function assist changes logic by leading to `?` leaving the outer function

Open
#10,200 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-assists S-actionable
Dominant language
Rust
Stars
16.9k
Forks
2.2k
Avg merge
1d 12h
Merged PRs (30d)
72

Description

Example:

use std::{
    io::{self, Read},
    fs,
};

use anyhow::Context;

fn whatever() -> anyhow::Result<()> {
    do_stuff().context("do_stuff")
}

fn do_stuff() -> io::Result<()> {
    let mut f = File::open("foo.txt")?;
    let mut buffer = [0; 10];

    // read up to 10 bytes
    let n = f.read(&mut buffer)?;

    println!("The bytes: {:?}", &buffer[..n]);
    Ok(())
}

// after inlining do_stuff
fn whatever() -> anyhow::Result<()> {
    {
        let mut f = File::open("foo.txt")?;
        let mut buffer = [0; 10];

        // read up to 10 bytes
        let n = f.read(&mut buffer)?;

        println!("The bytes: {:?}", &buffer[..n]);
        Ok(())
    }.context("test")
}

After inlining, the ?s exit from whatever and bypass the .context call which is thus rendered pointless.

I think the only general solution to this is emitting an immediately-invoked function instead for regular functions, and an async (move?) block for async functions:

fn whatever() -> anyhow::Result<()> {
    (|| {
        let mut f = File::open("foo.txt")?;
        let mut buffer = [0; 10];

        // read up to 10 bytes
        let n = f.read(&mut buffer)?;

        println!("The bytes: {:?}", &buffer[..n]);
        Ok(())
    })().context("test")
}

But of course that's rather ugly..

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 with the inline function assist and reproduce the example showing that ? exits the outer function before .context runs. Compare regular and async function cases, then verify that inlining preserves the original error-handling scope so the surrounding context remains effective.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.