]> git.lizzy.rs Git - rust.git/commitdiff
Merge #982
authorbors[bot] <bors[bot]@users.noreply.github.com>
Sun, 17 Mar 2019 21:41:37 +0000 (21:41 +0000)
committerbors[bot] <bors[bot]@users.noreply.github.com>
Sun, 17 Mar 2019 21:41:37 +0000 (21:41 +0000)
982: Implement BindingMode for pattern matching. r=flodiebold a=mjkillough

Implement `BindingMode` for pattern matching, so that types can be
correctly inferred using match ergonomics. The binding mode defaults to
`Move` (referred to as 'BindingMode::BindByValue` in rustc), and is
updated by automatic dereferencing of the value being matched.

Fixes #888.

 - [Binding modes in The Reference](https://doc.rust-lang.org/reference/patterns.html#binding-modes)
 - [`rustc` implementation](https://github.com/rust-lang/rust/blob/e17c48e2f21eefd59748e364234efc7037a3ec96/src/librustc_typeck/check/_match.rs#L77) (and [definition of `BindingMode`](https://github.com/rust-lang/rust/blob/e957ed9d10ec589bdd523b88b4b44c41b1ecf763/src/librustc/ty/binding.rs))
 - [Match Ergonomics RFC](https://github.com/rust-lang/rfcs/blob/master/text/2005-match-ergonomics.md#binding-mode-rules)

Co-authored-by: Michael Killough <michaeljkillough@gmail.com>
1  2 
crates/ra_hir/src/marks.rs
crates/ra_hir/src/ty/infer.rs
crates/ra_hir/src/ty/tests.rs

index bbf57004d5b57d5204399546325bf6d23ff47b32,6f3e5f09da112d5e4a09ca7cc366b45a47ac3782..5b640004288ff50fd7d5c60fb7d78a155aaf5203
@@@ -1,11 -1,11 +1,12 @@@
  test_utils::marks!(
 +    bogus_paths
      name_res_works_for_broken_modules
 -    item_map_enum_importing
 +    can_import_enum_variant
      type_var_cycles_resolve_completely
      type_var_cycles_resolve_as_possible
      type_var_resolves_to_int_var
      glob_enum
      glob_across_crates
      std_prelude
+     match_ergonomics_ref
  );
index c9a5bc7a100aa00ca8df8bb802bf2f152786ca5b,0a698988cb8b5cba0ab37351669bd3b0f5f95640..735cdecb910c11e4a8836d367916792343cac6d0
@@@ -63,6 -63,30 +63,30 @@@ enum ExprOrPatId 
  
  impl_froms!(ExprOrPatId: ExprId, PatId);
  
+ /// Binding modes inferred for patterns.
+ /// https://doc.rust-lang.org/reference/patterns.html#binding-modes
+ #[derive(Copy, Clone, Debug, Eq, PartialEq)]
+ enum BindingMode {
+     Move,
+     Ref(Mutability),
+ }
+ impl BindingMode {
+     pub fn convert(annotation: &BindingAnnotation) -> BindingMode {
+         match annotation {
+             BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move,
+             BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared),
+             BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut),
+         }
+     }
+ }
+ impl Default for BindingMode {
+     fn default() -> Self {
+         BindingMode::Move
+     }
+ }
  /// The result of type inference: A mapping from expressions and patterns to types.
  #[derive(Clone, PartialEq, Eq, Debug)]
  pub struct InferenceResult {
@@@ -530,6 -554,7 +554,7 @@@ impl<'a, D: HirDatabase> InferenceConte
          path: Option<&Path>,
          subpats: &[PatId],
          expected: &Ty,
+         default_bm: BindingMode,
      ) -> Ty {
          let (ty, def) = self.resolve_variant(path);
  
                  .and_then(|d| d.field(self.db, &Name::tuple_field_name(i)))
                  .map_or(Ty::Unknown, |field| field.ty(self.db))
                  .subst(&substs);
-             self.infer_pat(subpat, &expected_ty);
+             self.infer_pat(subpat, &expected_ty, default_bm);
          }
  
          ty
      }
  
-     fn infer_struct_pat(&mut self, path: Option<&Path>, subpats: &[FieldPat], expected: &Ty) -> Ty {
+     fn infer_struct_pat(
+         &mut self,
+         path: Option<&Path>,
+         subpats: &[FieldPat],
+         expected: &Ty,
+         default_bm: BindingMode,
+     ) -> Ty {
          let (ty, def) = self.resolve_variant(path);
  
          self.unify(&ty, expected);
              let matching_field = def.and_then(|it| it.field(self.db, &subpat.name));
              let expected_ty =
                  matching_field.map_or(Ty::Unknown, |field| field.ty(self.db)).subst(&substs);
-             self.infer_pat(subpat.pat, &expected_ty);
+             self.infer_pat(subpat.pat, &expected_ty, default_bm);
          }
  
          ty
      }
  
-     fn infer_pat(&mut self, pat: PatId, expected: &Ty) -> Ty {
+     fn infer_pat(&mut self, pat: PatId, mut expected: &Ty, mut default_bm: BindingMode) -> Ty {
          let body = Arc::clone(&self.body); // avoid borrow checker problem
  
+         let is_non_ref_pat = match &body[pat] {
+             Pat::Tuple(..)
+             | Pat::TupleStruct { .. }
+             | Pat::Struct { .. }
+             | Pat::Range { .. }
+             | Pat::Slice { .. } => true,
+             // TODO: Path/Lit might actually evaluate to ref, but inference is unimplemented.
+             Pat::Path(..) | Pat::Lit(..) => true,
+             Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false,
+         };
+         if is_non_ref_pat {
+             while let Ty::Ref(inner, mutability) = expected {
+                 expected = inner;
+                 default_bm = match default_bm {
+                     BindingMode::Move => BindingMode::Ref(*mutability),
+                     BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared),
+                     BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(*mutability),
+                 }
+             }
+         } else if let Pat::Ref { .. } = &body[pat] {
+             tested_by!(match_ergonomics_ref);
+             // When you encounter a `&pat` pattern, reset to Move.
+             // This is so that `w` is by value: `let (_, &w) = &(1, &2);`
+             default_bm = BindingMode::Move;
+         }
+         // Lose mutability.
+         let default_bm = default_bm;
+         let expected = expected;
          let ty = match &body[pat] {
              Pat::Tuple(ref args) => {
                  let expectations = match *expected {
                  let inner_tys = args
                      .iter()
                      .zip(expectations_iter)
-                     .map(|(&pat, ty)| self.infer_pat(pat, ty))
+                     .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm))
                      .collect::<Vec<_>>()
                      .into();
  
                      }
                      _ => &Ty::Unknown,
                  };
-                 let subty = self.infer_pat(*pat, expectation);
+                 let subty = self.infer_pat(*pat, expectation, default_bm);
                  Ty::Ref(subty.into(), *mutability)
              }
              Pat::TupleStruct { path: ref p, args: ref subpats } => {
-                 self.infer_tuple_struct_pat(p.as_ref(), subpats, expected)
+                 self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm)
              }
              Pat::Struct { path: ref p, args: ref fields } => {
-                 self.infer_struct_pat(p.as_ref(), fields, expected)
+                 self.infer_struct_pat(p.as_ref(), fields, expected, default_bm)
              }
              Pat::Path(path) => {
                  // TODO use correct resolver for the surrounding expression
                  self.infer_path_expr(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown)
              }
              Pat::Bind { mode, name: _name, subpat } => {
+                 let mode = if mode == &BindingAnnotation::Unannotated {
+                     default_bm
+                 } else {
+                     BindingMode::convert(mode)
+                 };
                  let inner_ty = if let Some(subpat) = subpat {
-                     self.infer_pat(*subpat, expected)
+                     self.infer_pat(*subpat, expected, default_bm)
                  } else {
                      expected.clone()
                  };
                  let inner_ty = self.insert_type_vars_shallow(inner_ty);
  
                  let bound_ty = match mode {
-                     BindingAnnotation::Ref => Ty::Ref(inner_ty.clone().into(), Mutability::Shared),
-                     BindingAnnotation::RefMut => Ty::Ref(inner_ty.clone().into(), Mutability::Mut),
-                     BindingAnnotation::Mutable | BindingAnnotation::Unannotated => inner_ty.clone(),
+                     BindingMode::Ref(mutability) => Ty::Ref(inner_ty.clone().into(), mutability),
+                     BindingMode::Move => inner_ty.clone(),
                  };
                  let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty);
                  self.write_pat_ty(pat, bound_ty);
              }
              Expr::For { iterable, body, pat } => {
                  let _iterable_ty = self.infer_expr(*iterable, &Expectation::none());
-                 self.infer_pat(*pat, &Ty::Unknown);
+                 self.infer_pat(*pat, &Ty::Unknown, BindingMode::default());
                  self.infer_expr(*body, &Expectation::has_type(Ty::unit()));
                  Ty::unit()
              }
                      } else {
                          Ty::Unknown
                      };
-                     self.infer_pat(*arg_pat, &expected);
+                     self.infer_pat(*arg_pat, &expected, BindingMode::default());
                  }
  
                  // TODO: infer lambda type etc.
              Expr::Call { callee, args } => {
                  let callee_ty = self.infer_expr(*callee, &Expectation::none());
                  let (param_tys, ret_ty) = match &callee_ty {
 -                    Ty::FnPtr(sig) => (sig.input.clone(), sig.output.clone()),
 -                    Ty::FnDef { substs, sig, .. } => {
 -                        let ret_ty = sig.output.clone().subst(&substs);
 +                    Ty::FnPtr(sig) => (sig.params().to_vec(), sig.ret().clone()),
 +                    Ty::FnDef { substs, def, .. } => {
 +                        let sig = self.db.callable_item_signature(*def);
 +                        let ret_ty = sig.ret().clone().subst(&substs);
                          let param_tys =
 -                            sig.input.iter().map(|ty| ty.clone().subst(&substs)).collect();
 +                            sig.params().iter().map(|ty| ty.clone().subst(&substs)).collect();
                          (param_tys, ret_ty)
                      }
                      _ => {
                  let method_ty = self.insert_type_vars(method_ty);
                  let (expected_receiver_ty, param_tys, ret_ty) = match &method_ty {
                      Ty::FnPtr(sig) => {
 -                        if !sig.input.is_empty() {
 -                            (sig.input[0].clone(), sig.input[1..].to_vec(), sig.output.clone())
 +                        if !sig.params().is_empty() {
 +                            (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone())
                          } else {
 -                            (Ty::Unknown, Vec::new(), sig.output.clone())
 +                            (Ty::Unknown, Vec::new(), sig.ret().clone())
                          }
                      }
 -                    Ty::FnDef { substs, sig, .. } => {
 -                        let ret_ty = sig.output.clone().subst(&substs);
 -
 -                        if !sig.input.is_empty() {
 -                            let mut arg_iter = sig.input.iter().map(|ty| ty.clone().subst(&substs));
 -                            let receiver_ty = arg_iter.next().unwrap();
 -                            (receiver_ty, arg_iter.collect(), ret_ty)
 +                    Ty::FnDef { substs, def, .. } => {
 +                        let sig = self.db.callable_item_signature(*def);
 +                        let ret_ty = sig.ret().clone().subst(&substs);
 +
 +                        if !sig.params().is_empty() {
 +                            let mut params_iter =
 +                                sig.params().iter().map(|ty| ty.clone().subst(&substs));
 +                            let receiver_ty = params_iter.next().unwrap();
 +                            (receiver_ty, params_iter.collect(), ret_ty)
                          } else {
                              (Ty::Unknown, Vec::new(), ret_ty)
                          }
  
                  for arm in arms {
                      for &pat in &arm.pats {
-                         let _pat_ty = self.infer_pat(pat, &input_ty);
+                         let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default());
                      }
                      if let Some(guard_expr) = arm.guard {
                          self.infer_expr(guard_expr, &Expectation::has_type(Ty::Bool));
                          decl_ty
                      };
  
-                     self.infer_pat(*pat, &ty);
+                     self.infer_pat(*pat, &ty, BindingMode::default());
                  }
                  Statement::Expr(expr) => {
                      self.infer_expr(*expr, &Expectation::none());
          for (type_ref, pat) in signature.params().iter().zip(body.params()) {
              let ty = self.make_ty(type_ref);
  
-             self.infer_pat(*pat, &ty);
+             self.infer_pat(*pat, &ty, BindingMode::default());
          }
          self.return_ty = self.make_ty(signature.ret_type());
      }
index acae71c266d2e5d9260b9547fff19912caa2cac1,0f8551a9d9681ed9e06e3d2e303aca0b2511d059..0f2172ddfc7898fe84ece9941673e92cc86fbb6b
@@@ -10,7 -10,6 +10,7 @@@ use test_utils::covers
  use crate::{
      source_binder,
      mock::MockDatabase,
 +    ty::display::HirDisplay,
  };
  
  // These tests compare the inference results for all expressions in a file
@@@ -830,6 -829,60 +830,60 @@@ fn test(x: &i32) 
      );
  }
  
+ #[test]
+ fn infer_pattern_match_ergonomics() {
+     assert_snapshot_matches!(
+         infer(r#"
+ struct A<T>(T);
+ fn test() {
+     let A(n) = &A(1);
+     let A(n) = &mut A(1);
+ }
+ "#),
+     @r###"
+ [28; 79) '{     ...(1); }': ()
+ [38; 42) 'A(n)': A<i32>
+ [40; 41) 'n': &i32
+ [45; 50) '&A(1)': &A<i32>
+ [46; 47) 'A': A<i32>(T) -> A<T>
+ [46; 50) 'A(1)': A<i32>
+ [48; 49) '1': i32
+ [60; 64) 'A(n)': A<i32>
+ [62; 63) 'n': &mut i32
+ [67; 76) '&mut A(1)': &mut A<i32>
+ [72; 73) 'A': A<i32>(T) -> A<T>
+ [72; 76) 'A(1)': A<i32>
+ [74; 75) '1': i32"###
+     );
+ }
+ #[test]
+ fn infer_pattern_match_ergonomics_ref() {
+     covers!(match_ergonomics_ref);
+     assert_snapshot_matches!(
+         infer(r#"
+ fn test() {
+     let v = &(1, &2);
+     let (_, &w) = v;
+ }
+ "#),
+     @r###"
+ [11; 57) '{     ...= v; }': ()
+ [21; 22) 'v': &(i32, &i32)
+ [25; 33) '&(1, &2)': &(i32, &i32)
+ [26; 33) '(1, &2)': (i32, &i32)
+ [27; 28) '1': i32
+ [30; 32) '&2': &i32
+ [31; 32) '2': i32
+ [43; 50) '(_, &w)': (i32, &i32)
+ [44; 45) '_': i32
+ [47; 49) '&w': &i32
+ [48; 49) 'w': i32
+ [53; 54) 'v': &(i32, &i32)"###
+     );
+ }
  #[test]
  fn infer_adt_pattern() {
      assert_snapshot_matches!(
@@@ -2143,7 -2196,7 +2197,7 @@@ fn type_at_pos(db: &MockDatabase, pos: 
      let node = algo::find_node_at_offset::<ast::Expr>(syntax.syntax(), pos.offset).unwrap();
      let expr = body_source_map.node_expr(node).unwrap();
      let ty = &inference_result[expr];
 -    ty.to_string()
 +    ty.display(db).to_string()
  }
  
  fn infer(content: &str) -> String {
                  "{} '{}': {}\n",
                  syntax_ptr.range(),
                  ellipsize(node.text().to_string().replace("\n", " "), 15),
 -                ty
 +                ty.display(&db)
              )
              .unwrap();
          }