rust-lang/rust · #166013

make `ReturnsVisitor` more accurate

folkertdev · merged Nov 24, 20263 files · 217 + / 46 −
compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs56 + / 27 −
@@ -6915,51 +6915,80 @@ impl<'v> Visitor<'v> for SelfVisitor<'v> { #[derive(Default)] pub struct ReturnsVisitor<'v> {     pub returns: Vec<&'v hir::Expr<'v>>,-    in_block_tail: bool,+    /// The set of items in tail position that can be targeted with a break (loops and blocks).+    /// A break to such an item is a return.+    break_targets_in_tail_position: FxHashSet<HirId>, }  impl<'v> Visitor<'v> for ReturnsVisitor<'v> {     fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {-        // Visit every expression to detect `return` paths, either through the function's tail-        // expression or `return` statements. We walk all nodes to find `return` statements, but-        // we only care about tail expressions when `in_block_tail` is `true`, which means that-        // they're in the return path of the function body.         match ex.kind {-            hir::ExprKind::Ret(Some(ex)) => {-                self.returns.push(ex);+            hir::ExprKind::Ret(Some(val)) => self.returns.push(val),+            hir::ExprKind::Break(dest, Some(val)) if let Ok(id) = dest.target_id => {+                // If this is a break to a block/loop in tail position, this is a return.+                if self.break_targets_in_tail_position.contains(&id) {+                    self.returns.push(val)+                }+            }+            hir::ExprKind::Become(_) => {+                // A become is like a return, but for diagnostics it is not useful to treat it as+                // one. Often suggestions will break the tail call.             }-            hir::ExprKind::Block(block, _) if self.in_block_tail => {-                self.in_block_tail = false;+            _ => {}+        }++        // Continue the walk, there might be further nested return expressions.+        hir::intravisit::walk_expr(self, ex);+    }++    fn visit_body(&mut self, body: &hir::Body<'v>) {+        self.visit_tail(body.value);+    }+}++impl<'v> ReturnsVisitor<'v> {+    fn visit_tail(&mut self, ex: &'v hir::Expr<'v>) {+        match ex.kind {+            hir::ExprKind::Block(block, _) => {+                if block.targeted_by_break {+                    self.break_targets_in_tail_position.insert(block.hir_id);+                }                 for stmt in block.stmts {                     hir::intravisit::walk_stmt(self, stmt);                 }-                self.in_block_tail = true;-                if let Some(expr) = block.expr {-                    self.visit_expr(expr);+                if let Some(tail) = block.expr {+                    self.visit_tail(tail);                 }             }-            hir::ExprKind::If(_, then, else_opt) if self.in_block_tail => {-                self.visit_expr(then);-                if let Some(el) = else_opt {-                    self.visit_expr(el);+            hir::ExprKind::If(cond, then, els) => {+                self.visit_expr(cond);+                self.visit_tail(then);+                if let Some(els) = els {+                    self.visit_tail(els);                 }             }-            hir::ExprKind::Match(_, arms, _) if self.in_block_tail => {+            hir::ExprKind::Match(scrutinee, arms, _) => {+                self.visit_expr(scrutinee);                 for arm in arms {-                    self.visit_expr(arm.body);+                    if let Some(guard) = arm.guard {+                        self.visit_expr(guard);+                    }+                    self.visit_tail(arm.body);                 }             }-            // We need to walk to find `return`s in the entire body.-            _ if !self.in_block_tail => hir::intravisit::walk_expr(self, ex),-            _ => self.returns.push(ex),+            hir::ExprKind::Loop(block, ..) => {+                self.break_targets_in_tail_position.insert(ex.hir_id);+                self.visit_block(block);+            }+            hir::ExprKind::Ret(_) | hir::ExprKind::Become(_) | hir::ExprKind::Break(..) => {+                self.visit_expr(ex);+            }+            _ => {+                self.returns.push(ex);+                self.visit_expr(ex);+            }         }     }--    fn visit_body(&mut self, body: &hir::Body<'v>) {-        assert!(!self.in_block_tail);-        self.in_block_tail = true;-        hir::intravisit::walk_body(self, body);-    } }  /// Collect all the awaited expressions within the input expression.
tests/ui/error-codes/E0746.rs40 + / 4 −
@@ -1,18 +1,54 @@ #![allow(dead_code)] +fn main() {}+ struct Struct; trait Trait {} impl Trait for Struct {} impl Trait for u32 {}+impl Trait for () {} -fn foo() -> dyn Trait { Struct }-//~^ ERROR E0746+fn implicit_return() -> dyn Trait {+    //~^ ERROR E0746+    Struct+} -fn bar() -> dyn Trait { //~ ERROR E0746+fn return_in_branch() -> dyn Trait {+    //~^ ERROR E0746     if true {         return 0;     }     42 } -fn main() {}+// The examples below are mostly here to test the diagnostic output,+// in particular whether the suggestion is valid.++fn return_in_tail_loop(c: bool) -> dyn Trait {+    //~^ ERROR E0746+    loop {+        if c {+            return 1u32;+        }+    }+}++fn return_nested_in_leaf(c: bool) -> dyn Trait {+    //~^ ERROR E0746+    let identity = |x| x;+    identity(if c { return 1u32 } else { 2u32 })+}++fn labeled_block_break() -> dyn Trait {+    //~^ ERROR E0746+    'a: {+        break 'a 1u32; //~ ERROR mismatched types+    }+}++fn loop_break_value() -> dyn Trait {+    //~^ ERROR E0746+    loop {+        break 1u32; //~ ERROR mismatched types+    }+}
tests/ui/error-codes/E0746.stderr121 + / 15 −
@@ -1,39 +1,145 @@ error[E0746]: return type cannot be a trait object without pointer indirection-  --> $DIR/E0746.rs:8:13+  --> $DIR/E0746.rs:11:25    |-LL | fn foo() -> dyn Trait { Struct }-   |             ^^^^^^^^^ doesn't have a size known at compile-time+LL | fn implicit_return() -> dyn Trait {+   |                         ^^^^^^^^^ doesn't have a size known at compile-time    | help: consider returning an `impl Trait` instead of a `dyn Trait`    |-LL - fn foo() -> dyn Trait { Struct }-LL + fn foo() -> impl Trait { Struct }+LL - fn implicit_return() -> dyn Trait {+LL + fn implicit_return() -> impl Trait {    | help: alternatively, box the return type, and wrap all of the returned values in `Box::new`    |-LL | fn foo() -> Box<dyn Trait> { Box::new(Struct) }-   |             ++++         +   +++++++++      ++LL ~ fn implicit_return() -> Box<dyn Trait> {+LL |+LL ~     Box::new(Struct)+   |  error[E0746]: return type cannot be a trait object without pointer indirection-  --> $DIR/E0746.rs:11:13+  --> $DIR/E0746.rs:16:26    |-LL | fn bar() -> dyn Trait {-   |             ^^^^^^^^^ doesn't have a size known at compile-time+LL | fn return_in_branch() -> dyn Trait {+   |                          ^^^^^^^^^ doesn't have a size known at compile-time    | help: consider returning an `impl Trait` instead of a `dyn Trait`    |-LL - fn bar() -> dyn Trait {-LL + fn bar() -> impl Trait {+LL - fn return_in_branch() -> dyn Trait {+LL + fn return_in_branch() -> impl Trait {    | help: alternatively, box the return type, and wrap all of the returned values in `Box::new`    |-LL ~ fn bar() -> Box<dyn Trait> {+LL ~ fn return_in_branch() -> Box<dyn Trait> {+LL | LL |     if true { LL ~         return Box::new(0); LL |     } LL ~     Box::new(42)    | -error: aborting due to 2 previous errors+error[E0746]: return type cannot be a trait object without pointer indirection+  --> $DIR/E0746.rs:27:36+   |+LL | fn return_in_tail_loop(c: bool) -> dyn Trait {+   |                                    ^^^^^^^^^ doesn't have a size known at compile-time+   |+help: consider returning an `impl Trait` instead of a `dyn Trait`+   |+LL - fn return_in_tail_loop(c: bool) -> dyn Trait {+LL + fn return_in_tail_loop(c: bool) -> impl Trait {+   |+help: alternatively, box the return type, and wrap all of the returned values in `Box::new`+   |+LL ~ fn return_in_tail_loop(c: bool) -> Box<dyn Trait> {+LL |+LL |     loop {+LL |         if c {+LL ~             return Box::new(1u32);+   |++error[E0746]: return type cannot be a trait object without pointer indirection+  --> $DIR/E0746.rs:36:38+   |+LL | fn return_nested_in_leaf(c: bool) -> dyn Trait {+   |                                      ^^^^^^^^^ doesn't have a size known at compile-time+   |+help: consider returning an `impl Trait` instead of a `dyn Trait`+   |+LL - fn return_nested_in_leaf(c: bool) -> dyn Trait {+LL + fn return_nested_in_leaf(c: bool) -> impl Trait {+   |+help: alternatively, box the return type, and wrap all of the returned values in `Box::new`+   |+LL ~ fn return_nested_in_leaf(c: bool) -> Box<dyn Trait> {+LL |+LL |     let identity = |x| x;+LL ~     Box::new(identity(if c { return Box::new(1u32) } else { 2u32 }))+   |++error[E0746]: return type cannot be a trait object without pointer indirection+  --> $DIR/E0746.rs:42:29+   |+LL | fn labeled_block_break() -> dyn Trait {+   |                             ^^^^^^^^^ doesn't have a size known at compile-time+   |+help: consider returning an `impl Trait` instead of a `dyn Trait`+   |+LL - fn labeled_block_break() -> dyn Trait {+LL + fn labeled_block_break() -> impl Trait {+   |+help: alternatively, box the return type, and wrap all of the returned values in `Box::new`+   |+LL ~ fn labeled_block_break() -> Box<dyn Trait> {+LL |+LL |     'a: {+LL ~         break 'a Box::new(1u32);+   |++error[E0746]: return type cannot be a trait object without pointer indirection+  --> $DIR/E0746.rs:49:26+   |+LL | fn loop_break_value() -> dyn Trait {+   |                          ^^^^^^^^^ doesn't have a size known at compile-time+   |+help: consider returning an `impl Trait` instead of a `dyn Trait`+   |+LL - fn loop_break_value() -> dyn Trait {+LL + fn loop_break_value() -> impl Trait {+   |+help: alternatively, box the return type, and wrap all of the returned values in `Box::new`+   |+LL ~ fn loop_break_value() -> Box<dyn Trait> {+LL |+LL |     loop {+LL ~         break Box::new(1u32);+   |++error[E0308]: mismatched types+  --> $DIR/E0746.rs:45:18+   |+LL |         break 'a 1u32;+   |                  ^^^^ expected `dyn Trait`, found `u32`+   |+   = note: expected trait object `(dyn Trait + 'static)`+                      found type `u32`+   = help: `u32` implements `Trait` so you could box the found value and coerce it to the trait object `Box<dyn Trait>`, you will have to change the expected type as well++error[E0308]: mismatched types+  --> $DIR/E0746.rs:52:15+   |+LL | fn loop_break_value() -> dyn Trait {+   |                          --------- expected `dyn Trait` because of this return type+LL |+LL |     loop {+   |     ---- this loop is expected to be of type `(dyn Trait + 'static)`+LL |         break 1u32;+   |               ^^^^ expected `dyn Trait`, found `u32`+   |+   = note: expected trait object `(dyn Trait + 'static)`+                      found type `u32`+   = help: `u32` implements `Trait` so you could box the found value and coerce it to the trait object `Box<dyn Trait>`, you will have to change the expected type as well++error: aborting due to 8 previous errors -For more information about this error, try `rustc --explain E0746`.+Some errors have detailed explanations: E0308, E0746.+For more information about an error, try `rustc --explain E0308`.