rust-analyzer: Try blocks give false errors (`type-mismatch` false positive)

Rust Analyzer sometimes gives errors on try blocks where there shouldn’t be any, e.g.

let _: Option<()> = try {
    let first_rhs = self.values.get(graph.input_source(sub.rhs()))?;

    let lhs_sub = *graph.cast_input_source::<Sub>(sub.lhs())?;
    let second_rhs = self.values.get(graph.input_source(lhs_sub.rhs()))?;

    let sum = first_rhs + second_rhs;
    let new_rhs = graph.constant(sum);
    self.values.add(new_rhs.value(), sum);

    graph.remove_inputs(sub.node());

    let value = graph.input_source(lhs_sub.lhs());
    graph.add_value_edge(value, sub.lhs());
    graph.add_value_edge(new_rhs.value(), sub.rhs());

    self.changes.inc::<"sub-sub">();
};

This code is correct (and rustc doesn’t complain), but RA emits this error: image

Changing it as suggested (adding a Some(()) or None to the end of the block) is incorrect and (correctly) causes both rustc and RA to emit errors

rust-analyzer version: bc08b8eff 2022-03-28 stable

rustc version: (eg. output of rustc -V)

rustc 1.60.0-nightly (777bb86bc 2022-01-20)
binary: rustc
commit-hash: 777bb86bcdbc568be7cff6eeeaaf81a89b4aa50b
commit-date: 2022-01-20
host: x86_64-pc-windows-msvc
release: 1.60.0-nightly
LLVM version: 13.0.0

relevant settings: N/A

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 11
  • Comments: 19 (12 by maintainers)

Commits related to this issue

Most upvoted comments

Supporting try blocks is a different problem. Try blocks won’t be the last feature which r-a supports with a delay.

This approach would not be what we want long-term: Long-term I would expect that we can either support most features fast enough since we’re not still catching up anymore, or at least detect new features and suppress errors for them specifically. For example, we could just infer the error type for try blocks and rely on follow-up error suppression. That would require the same effort as reducing the confidence level in your approach.

It’s also not what we want short-term, because we want to see bugs and not paper over them. The type-mismatch diagnostic is already experimental anyway (except it shows up here because we heuristically show it when we have a quickfix, but that’s something we could address in the heuristic), so I don’t see the need to hide it in even more cases.

I would rather just implement support for try blocks.

In other cases, e.g. unresolved names and unknown types, the error type is supposed to act as an error suppressor. So we e.g. shouldn’t actually emit type mismatches involving an error type, because we know there already was an error before.

Yeah, I see this on 0.2.993, but not on 0.2.985.