Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rust: Handle question mark operator in CFG #17749

Merged
merged 4 commits into from
Oct 14, 2024

Conversation

paldepind
Copy link
Contributor

@paldepind paldepind commented Oct 14, 2024

The primary goal of this PR is to handle the ? operator (TryExpr) in the CFG, as that is currently the cause of dead-ends.

The PR does a few other things as well:

  • Fixes a bug where abnormal control flow in the scrutinee of a match expression would incorrectly continue to match arms.
  • Simplifies the implementation of return to use a standard tree.

With this PR, the code

fn test_question_mark_operator_1(s: &str) -> Option<i32> {
    str.parse::<u32>()? + 4
}

results in the CFG below. The CFG is roughly as if the a? operator is sugar for (if a.is_ok() { a.unwrap() } else { return None }) which I think is a fine way to handle it. But, do note that match edges are not created in the CFG, so a successful ? will not look the same in the CFG as a succesfull match on Some(foo). If we end up needing/wanting that, we should probably do it through desugaring to HIR.

flowchart TD
1["enter test_question_mark_operator_1"]
10["... + ..."]
11["4"]
2["exit test_question_mark_operator_1"]
3["exit test_question_mark_operator_1 (normal)"]
4["s"]
5["Param"]
6["BlockExpr"]
7["PathExpr"]
8["MethodCallExpr"]
9["TryExpr"]

1 --> 4
3 --> 2
4 -- match --> 5
5 --> 7
6 --> 3
7 --> 8
8 --> 9
9 -- return --> 3
9 --> 11
10 --> 6
11 --> 10
Loading

@github-actions github-actions bot added the Rust Pull requests that update Rust code label Oct 14, 2024
@paldepind paldepind added the no-change-note-required This PR does not need a change note label Oct 14, 2024
Copy link
Contributor

@aibaars aibaars left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me!

@paldepind paldepind merged commit d0f978d into github:main Oct 14, 2024
14 checks passed
@paldepind paldepind deleted the rust-cfg-handle-question-mark branch October 14, 2024 14:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-change-note-required This PR does not need a change note Rust Pull requests that update Rust code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants