ernie-research/MEnvData-SWE huggingface dataset:
Repository: dtolnay/serde-yaml (Rust)

Issue:
Deserialization failure results in panic
I expect de-serialization failure will result in returning error, but it seems not the case for program below:
```rust
#[macro_use]
extern crate serde;
extern crate serde_yaml;

#[derive(Deserialize)]
#[derive(Debug)]
pub struct Foo {
    pub foo: [(); 1],
}

fn main() {
    let result: serde_yaml::Result<Foo> = serde_yaml::from_str("foo:\n");
    println!("{:?}", result);
}
```
Running this using stable 1.28.0 will result in
```
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Message("invalid type: unit value, expected an array of length 1", None)', libcore/result.rs:945:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.
```
It appears [this](https://github.com/dtolnay/serde-yaml/blob/0.8.2/src/de.rs#L576) is the offending line.


Discussion:
Thanks! Fixed in 0.8.3.



Patch:
diff --git a/src/de.rs b/src/de.rs
index c4d65518..24249324 100644
--- a/src/de.rs
+++ b/src/de.rs
@@ -557,12 +557,14 @@ where
 }
 
 fn invalid_type(event: &Event, exp: &Expected) -> Error {
+    enum Void {}
+
     struct InvalidType<'a> {
         exp: &'a Expected,
     }
 
     impl<'de, 'a> Visitor<'de> for InvalidType<'a> {
-        type Value = Error;
+        type Value = Void;
 
         fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
             self.exp.fmt(formatter)
@@ -573,7 +575,10 @@ fn invalid_type(event: &Event, exp: &Expected) -> Error {
         Event::Alias(_) => unreachable!(),
         Event::Scalar(ref v, style, ref tag) => {
             let get_type = InvalidType { exp: exp };
-            visit_scalar(v, style, tag, get_type).unwrap()
+            match visit_scalar(v, style, tag, get_type) {
+                Ok(void) => match void {},
+                Err(invalid_type) => invalid_type,
+            }
         }
         Event::SequenceStart => de::Error::invalid_type(Unexpected::Seq, exp),
         Event::MappingStart => de::Error::invalid_type(Unexpected::Map, exp),


Test patch:
diff --git a/tests/test_error.rs b/tests/test_error.rs
index 17405f34..796d9ba1 100644
--- a/tests/test_error.rs
+++ b/tests/test_error.rs
@@ -245,3 +245,15 @@ fn test_no_location() {
 
     assert_eq!(utf8_location.is_none(), true);
 }
+
+#[test]
+fn test_invalid_scalar_type() {
+    #[derive(Deserialize, Debug)]
+    struct S {
+        x: [(); 1],
+    }
+
+    let yaml = "x:\n";
+    let expected = "x: invalid type: unit value, expected an array of length 1 at line 2 column 1";
+    test_error::<S>(yaml, expected);
+}
Repository: gfx-rs/naga (Rust)

Issue:
Discard is allowed in compute shader stage
<!-- Thank you for filing this! Please read the [debugging tips](https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications).
That may let you investigate on your own, or provide additional information that helps us to assist.-->

**Description**
A compute shader may include `discard` statements. This is not allowed by the WGSL spec.

**Repro steps**
Invoke a compute shader like
```wgsl
@compute @workgroup_size(1)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
    if global_id.x == 3u {
        discard;
    }
}
```

**Expected vs observed behavior**
* Expected: Shader is rejected
* Vulkan: Pipeline creation succeeds but validation layers catch the invalid use of `OpKill`. Device is lost upon dispatch.
* Dx12: Pipeline creation fails with an FXC error X4532

**Extra materials**
This can easily be reproduced by modifying the hello compute example

**Platform**
Windows 10, RTX 2070. Reproduced for wgpu 0.15.1 and #df54bc4


Discussion:

Patch:
diff --git a/src/valid/function.rs b/src/valid/function.rs
index b615895ae3..386937d705 100644
--- a/src/valid/function.rs
+++ b/src/valid/function.rs
@@ -595,6 +595,7 @@ impl super::Validator {
                     finished = true;
                 }
                 S::Kill => {
+                    stages &= super::ShaderStages::FRAGMENT;
                     finished = true;
                 }
                 S::Barrier(_) => {


Test patch:
diff --git a/tests/wgsl-errors.rs b/tests/wgsl-errors.rs
index d76252ced5..d44dd97f37 100644
--- a/tests/wgsl-errors.rs
+++ b/tests/wgsl-errors.rs
@@ -943,6 +943,35 @@ fn invalid_arrays() {
     }
 }
 
+#[test]
+fn discard_in_wrong_stage() {
+    check_validation! {
+        "@compute @workgroup_size(1)
+fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
+    if global_id.x == 3u {
+        discard;
+    }
+}":
+        Err(naga::valid::ValidationError::EntryPoint {
+            stage: naga::ShaderStage::Compute,
+            source: naga::valid::EntryPointError::ForbiddenStageOperations,
+            ..
+        })
+    }
+
+    check_validation! {
+        "@vertex
+fn main() {
+    discard;
+}":
+        Err(naga::valid::ValidationError::EntryPoint {
+            stage: naga::ShaderStage::Vertex,
+            source: naga::valid::EntryPointError::ForbiddenStageOperations,
+            ..
+        })
+    }
+}
+
 #[test]
 fn invalid_structs() {
     check_validation! {
Repository: time-rs/time (Rust)

Issue:
implement `std::iter::Sum` for `Duration`?
Summing a sequence of durations is a useful operation. In fact, `std::time::Duration` implements `std::iter::Sum`. Any reason why this implementation was omitted in `time`?


Discussion:
Not really. I can do this at some point :+1:
That would be great, thanks!



Patch:
diff --git a/src/duration.rs b/src/duration.rs
index 55b0b0b54..f9b686058 100644
--- a/src/duration.rs
+++ b/src/duration.rs
@@ -1,6 +1,7 @@
 use core::cmp::Ordering;
 use core::convert::{TryFrom, TryInto};
 use core::fmt;
+use core::iter::Sum;
 use core::ops::{Add, Div, Mul, Neg, Sub, SubAssign};
 use core::time::Duration as StdDuration;
 
@@ -953,4 +954,16 @@ impl PartialOrd<Duration> for StdDuration {
         rhs.partial_cmp(self).map(Ordering::reverse)
     }
 }
+
+impl Sum<Duration> for Duration {
+    fn sum<I: Iterator<Item = Duration>>(iter: I) -> Duration {
+        iter.reduce(|a, b| a + b).unwrap_or_default()
+    }
+}
+
+impl<'a> Sum<&'a Duration> for Duration {
+    fn sum<I: Iterator<Item = &'a Duration>>(iter: I) -> Duration {
+        iter.copied().sum()
+    }
+}
 // endregion trait impls


Test patch:
diff --git a/tests/integration/duration.rs b/tests/integration/duration.rs
index 71c561410..75127f0b2 100644
--- a/tests/integration/duration.rs
+++ b/tests/integration/duration.rs
@@ -732,3 +732,17 @@ fn arithmetic_regression() {
     assert_eq!(subtracted.whole_seconds(), 3);
     assert_eq!(subtracted.subsec_milliseconds(), 200);
 }
+
+#[test]
+fn sum_iter_ref() {
+    let i = vec![1.6.seconds(), 1.6.seconds()];
+    let sum = i.iter().sum::<Duration>();
+    assert_eq!(sum, 3.2.seconds());
+}
+
+#[test]
+fn sum_iter() {
+    let i = vec![1.6.seconds(), 1.6.seconds()];
+    let sum = i.into_iter().sum::<Duration>();
+    assert_eq!(sum, 3.2.seconds());
+}
Repository: drager/wasm-pack (Rust)

Issue:
TypeScript definition file not published
The TypeScript definition file is missing from the `files` whitelist and so isn't published to npm. e.g. https://unpkg.com/hello-wasm-jsconfeu@0.1.0/


Discussion:
zomg! thank you for catching this!!



Patch:
diff --git a/src/manifest.rs b/src/manifest.rs
index b8d98aad..8662eeaa 100644
--- a/src/manifest.rs
+++ b/src/manifest.rs
@@ -66,6 +66,15 @@ impl CargoManifest {
         if let Some(s) = scope {
             self.package.name = format!("@{}/{}", s, self.package.name);
         }
+        let mut files = vec![wasm_file];
+
+        match dts_file {
+            Some(ref dts_file) => {
+                files.push(dts_file.to_string());
+            }
+            None => {}
+        }
+
         NpmPackage {
             name: self.package.name,
             collaborators: self.package.authors,
@@ -76,7 +85,7 @@ impl CargoManifest {
                 ty: "git".to_string(),
                 url: repo_url,
             }),
-            files: vec![wasm_file],
+            files: files,
             main: js_file,
             types: dts_file,
         }


Test patch:
diff --git a/tests/manifest/main.rs b/tests/manifest/main.rs
index 65103742..995273a7 100644
--- a/tests/manifest/main.rs
+++ b/tests/manifest/main.rs
@@ -40,7 +40,7 @@ fn it_creates_a_package_json_default_path() {
         pkg.repository.url,
         "https://github.com/ashleygwilliams/wasm-pack.git"
     );
-    assert_eq!(pkg.files, ["wasm_pack_bg.wasm"]);
+    assert_eq!(pkg.files, ["wasm_pack_bg.wasm", "wasm_pack.d.ts"]);
     assert_eq!(pkg.main, "wasm_pack.js");
     let types = pkg.types.unwrap_or_default();
     assert_eq!(types, "wasm_pack.d.ts");
Repository: tokio-rs/bytes (Rust)

Issue:
reserve_inner over allocates which can lead to a OOM conidition
# Summary

`reseve_inner` will double the size of the underlying shared vector instead of just extending the BytesMut buffer in place if a call to `BytesMut::reserve` would fit inside the current allocated shared buffer. If this happens repeatedly you will eventually attempt to allocate a buffer that is too large.

# Repro

```rust
fn reserve_in_arc_unique_does_not_overallocate_after_split() {
    let mut bytes = BytesMut::from(LONG);
    let orig_capacity = bytes.capacity();
    drop(bytes.split_off(LONG.len() / 2));
    let new_capacity = bytes.capacity();
    bytes.reserve(orig_capacity - new_capacity);
    assert_eq!(bytes.capacity(), orig_capacity);
}
```


Discussion:

Patch:
diff --git a/src/bytes_mut.rs b/src/bytes_mut.rs
index 99e849716..2282bdc48 100644
--- a/src/bytes_mut.rs
+++ b/src/bytes_mut.rs
@@ -670,7 +670,10 @@ impl BytesMut {
 
                 // Compare the condition in the `kind == KIND_VEC` case above
                 // for more details.
-                if v_capacity >= new_cap && offset >= len {
+                if v_capacity >= new_cap + offset {
+                    self.cap = new_cap;
+                    // no copy is necessary
+                } else if v_capacity >= new_cap && offset >= len {
                     // The capacity is sufficient, and copying is not too much
                     // overhead: reclaim the buffer!
 


Test patch:
diff --git a/tests/test_bytes.rs b/tests/test_bytes.rs
index 6bf01d67d..4ddb24de5 100644
--- a/tests/test_bytes.rs
+++ b/tests/test_bytes.rs
@@ -515,6 +515,34 @@ fn reserve_in_arc_unique_doubles() {
     assert_eq!(2000, bytes.capacity());
 }
 
+#[test]
+fn reserve_in_arc_unique_does_not_overallocate_after_split() {
+    let mut bytes = BytesMut::from(LONG);
+    let orig_capacity = bytes.capacity();
+    drop(bytes.split_off(LONG.len() / 2));
+
+    // now bytes is Arc and refcount == 1
+
+    let new_capacity = bytes.capacity();
+    bytes.reserve(orig_capacity - new_capacity);
+    assert_eq!(bytes.capacity(), orig_capacity);
+}
+
+#[test]
+fn reserve_in_arc_unique_does_not_overallocate_after_multiple_splits() {
+    let mut bytes = BytesMut::from(LONG);
+    let orig_capacity = bytes.capacity();
+    for _ in 0..10 {
+        drop(bytes.split_off(LONG.len() / 2));
+
+        // now bytes is Arc and refcount == 1
+
+        let new_capacity = bytes.capacity();
+        bytes.reserve(orig_capacity - new_capacity);
+    }
+    assert_eq!(bytes.capacity(), orig_capacity);
+}
+
 #[test]
 fn reserve_in_arc_nonunique_does_not_overallocate() {
     let mut bytes = BytesMut::with_capacity(1000);
Repository: paupino/rust-decimal (Rust)

Issue:
Possible loss of precision/wrong result on conversion from f64
For `0.00006927f64`, `Decimal::from_str(&f.to_string())` works fine, but `Decimal::from_f64(f)` will return `0.00006927000000000001`.

I committed a test case with the failing value here: https://github.com/tomhoule/rust-decimal/commit/df6196c7c9cf802c0c4e6fcb680c4275fd3b7acb

Please tell me if I can help any further :)


Discussion:
Thanks for raising this - fortunately, I can reproduce this quite easily. I'll see if I can trace down the root cause.



Patch:
diff --git a/src/decimal.rs b/src/decimal.rs
index e88dda43..944ddbc9 100644
--- a/src/decimal.rs
+++ b/src/decimal.rs
@@ -914,7 +914,7 @@ impl Decimal {
         // floating point number
         if is64 {
             // Guaranteed to about 16 dp
-            while exponent10 < 0 && (bits[2] != 0 || (bits[1] & 0xFFE0_0000) != 0) {
+            while exponent10 < 0 && (bits[2] != 0 || (bits[1] & 0xFFF0_0000) != 0) {
                 let rem10 = div_by_u32(bits, 10);
                 exponent10 += 1;
                 if rem10 >= 5 {


Test patch:
diff --git a/tests/decimal_tests.rs b/tests/decimal_tests.rs
index 87b24fed..8e16e670 100644
--- a/tests/decimal_tests.rs
+++ b/tests/decimal_tests.rs
@@ -1142,6 +1142,9 @@ fn it_converts_from_f64() {
         from_f64(0.12345678901234567890123456789f64).unwrap().to_string()
     );
     assert_eq!("0", from_f64(0.00000000000000000000000000001f64).unwrap().to_string());
+    assert_eq!("0.6927", from_f64(0.6927f64).unwrap().to_string());
+    assert_eq!("0.00006927", from_f64(0.00006927f64).unwrap().to_string());
+    assert_eq!("0.000000006927", from_f64(0.000000006927f64).unwrap().to_string());
 
     assert!(from_f64(std::f64::NAN).is_none());
     assert!(from_f64(std::f64::INFINITY).is_none());
Repository: paupino/rust-decimal (Rust)

Issue:
Serialize/obtain the unscaled representation
In financial settings, it's fairly common for the serialized (possibly JSON) form of a message to be scaled by 100. So when I deserialize, I call `rust_decimal::Decimal::new(raw, 2)`. Now I want to round-trip that data for various reasons (test data generation, etc.) so I'd like the inverse of that operation. If I want to extract the `2` I can call `scale()`, but there doesn't seem to be an obvious way to get the unscaled representation back out of the decimal.

Is there a good way to do this today, and if not could one be added?


Discussion:
The best roundabout way I've been able to find to do this right now has been as follows:

```
let copy = orig;
copy.set_scale(0).expect("scaling");
let raw = copy.to_i128().expect("this can't fail but rust doesn't know that")
```

Which feels a bit messy.
This is an interesting case, and certainly something I can extend to support. Fortunately, the method you have above doesn't perform any rescaling so is fairly lightweight, however it shouldn't be too much effort to create an explicit function that doesn't require this workaround at all. 



Patch:
diff --git a/src/decimal.rs b/src/decimal.rs
index 6955bfe6..0d818b40 100644
--- a/src/decimal.rs
+++ b/src/decimal.rs
@@ -353,6 +353,26 @@ impl Decimal {
         ((self.flags & SCALE_MASK) >> SCALE_SHIFT) as u32
     }
 
+    /// Returns the mantissa of the decimal number.
+    ///
+    /// # Example
+    ///
+    /// ```
+    /// use rust_decimal::prelude::*;
+    ///
+    /// let num = Decimal::from_str("-1.2345678").unwrap();
+    /// assert_eq!(num.mantissa(), -12345678i128);
+    /// assert_eq!(num.scale(), 7);
+    /// ```
+    pub const fn mantissa(&self) -> i128 {
+        let raw = (self.lo as i128) | ((self.mid as i128) << 32) | ((self.hi as i128) << 64);
+        if self.is_sign_negative() {
+            -raw
+        } else {
+            raw
+        }
+    }
+
     /// An optimized method for changing the sign of a decimal number.
     ///
     /// # Arguments


Test patch:
diff --git a/tests/decimal_tests.rs b/tests/decimal_tests.rs
index 24133d84..f65c6566 100644
--- a/tests/decimal_tests.rs
+++ b/tests/decimal_tests.rs
@@ -16,6 +16,20 @@ macro_rules! either {
     };
 }
 
+#[test]
+fn it_can_extract_the_mantissa() {
+    let tests = [
+        ("1", 1i128, 0),
+        ("1.123456", 1123456i128, 6),
+        ("-0.123456", -123456i128, 6),
+    ];
+    for &(input, mantissa, scale) in &tests {
+        let num = Decimal::from_str(input).unwrap();
+        assert_eq!(num.mantissa(), mantissa, "Mantissa for {}", input);
+        assert_eq!(num.scale(), scale, "Scale for {}", input);
+    }
+}
+
 // Parsing
 
 #[test]
Repository: rust-bakery/nom (Rust)

Issue:
Implement FindToken<char> for &[char]?
Would you accept a PR to implement `FindToken<char> for &[char]`? It's not a super common use case but it would be convenient.

```rust
use nom::character::complete::one_of;

const SUBSCRIPTS: [char; 10] =
    ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉'];

fn main() {
  assert_eq!(one_of(&SUBSCRIPTS[..])("₈rest"), Ok(("rest", "₈")));
}
```
```
error[E0277]: the trait bound `&[char]: FindToken<_>` is not satisfied
   --> src/main.rs:7:21
    |
7   |   assert_eq!(one_of(&SUBSCRIPTS[..])("₈rest"), Ok(("rest", '₈')));
    |                     ^^^^^^^^^^^^^^^ the trait `FindToken<_>` is not implemented for `&[char]`
    |
   ::: ~/.cargo/registry/src/github.com-1ecc6299db9ec823/nom-6.1.0/src/character/complete.rs:89:6
    |
89  |   T: FindToken<<I as InputIter>::Item>,
    |      --------------------------------- required by this bound in `nom::character::complete::one_of`
    |
    = help: the following implementations were found:
              <&'a [u8] as FindToken<char>>
              <&'a [u8] as FindToken<u8>>
              <&'b [u8] as FindToken<&'a u8>>
              <[u8; 0] as FindToken<&'a u8>>
            and 65 others
```


Discussion:
Solved in #1463.



Patch:
diff --git a/src/traits.rs b/src/traits.rs
index 3c3053e89..f6a683cb0 100644
--- a/src/traits.rs
+++ b/src/traits.rs
@@ -914,6 +914,18 @@ impl<'a> FindToken<char> for &'a str {
   }
 }
 
+impl<'a> FindToken<char> for &'a [char] {
+  fn find_token(&self, token: char) -> bool {
+    self.iter().any(|i| *i == token)
+  }
+}
+
+impl<'a, 'b> FindToken<&'a char> for &'b [char] {
+  fn find_token(&self, token: &char) -> bool {
+    self.find_token(*token)
+  }
+}
+
 /// Look for a substring in self
 pub trait FindSubstring<T> {
   /// Returns the byte position of the substring if it is found


Test patch:
diff --git a/tests/issues.rs b/tests/issues.rs
index 6df183bd4..24f705008 100644
--- a/tests/issues.rs
+++ b/tests/issues.rs
@@ -206,3 +206,11 @@ fn issue_1231_bits_expect_fn_closure() {
   }
   assert_eq!(example(&[0xff]), Ok((&b""[..], (1, 1))));
 }
+
+#[test]
+fn issue_1282_findtoken_char() {
+  use nom::character::complete::one_of;
+  use nom::error::Error;
+  let parser = one_of::<_, _, Error<_>>(['a', 'b', 'c'].as_slice());
+  assert_eq!(parser("aaa"), Ok(("aa", 'a')));
+}
Repository: apache/datafusion (Rust)

Issue:
Support type-coercion from `Decimal` to `Float64`
**Is your feature request related to a problem or challenge? Please describe what you are trying to do.**

``` rust
#[tokio::test]
async fn sql_abs_decimal() -> Result<()> {
    let ctx = SessionContext::new();
    register_decimal_csv_table_by_sql(&ctx).await;
    let sql = "SELECT abs(c1) from decimal_simple";
    let actual = execute_to_batches(&ctx, sql).await;
```

Fails with

```
Coercion from [Decimal(10, 6)] to the signature Uniform(1, [Float64, Float32]) failed.
```

**Describe the solution you'd like**
I would like the decimal to be coerced into a floating-point value.

**Describe alternatives you've considered**
None

**Additional context**
None



Discussion:
@andygrove Please check the PR 
Opening new PR to resolve commit history



Patch:
diff --git a/datafusion/expr/src/type_coercion.rs b/datafusion/expr/src/type_coercion.rs
index 5b8b303611de..8cea256f1829 100644
--- a/datafusion/expr/src/type_coercion.rs
+++ b/datafusion/expr/src/type_coercion.rs
@@ -169,6 +169,7 @@ pub fn can_coerce_from(type_into: &DataType, type_from: &DataType) -> bool {
                 | UInt64
                 | Float32
                 | Float64
+                | Decimal(_, _)
         ),
         Timestamp(TimeUnit::Nanosecond, None) => matches!(type_from, Timestamp(_, None)),
         Utf8 | LargeUtf8 => true,


Test patch:
diff --git a/datafusion/core/tests/sql/decimal.rs b/datafusion/core/tests/sql/decimal.rs
index 2153495a62fe..c8c242155257 100644
--- a/datafusion/core/tests/sql/decimal.rs
+++ b/datafusion/core/tests/sql/decimal.rs
@@ -780,3 +780,34 @@ async fn decimal_group_function() -> Result<()> {
     assert_batches_eq!(expected, &actual);
     Ok(())
 }
+
+#[tokio::test]
+async fn sql_abs_decimal() -> Result<()> {
+    let ctx = SessionContext::new();
+    register_decimal_csv_table_by_sql(&ctx).await;
+    let sql = "SELECT abs(c1) from decimal_simple";
+    let actual = execute_to_batches(&ctx, sql).await;
+    let expected = vec![
+        "+------------------------+",
+        "| abs(decimal_simple.c1) |",
+        "+------------------------+",
+        "| 0.00001                |",
+        "| 0.00002                |",
+        "| 0.00002                |",
+        "| 0.00003                |",
+        "| 0.00003                |",
+        "| 0.00003                |",
+        "| 0.00004                |",
+        "| 0.00004                |",
+        "| 0.00004                |",
+        "| 0.00004                |",
+        "| 0.00005                |",
+        "| 0.00005                |",
+        "| 0.00005                |",
+        "| 0.00005                |",
+        "| 0.00005                |",
+        "+------------------------+",
+    ];
+    assert_batches_eq!(expected, &actual);
+    Ok(())
+}
Repository: rust-lang/rust-bindgen (Rust)

Issue:
Infinite loop resolving items when combining partial template specialization with qualified dependent types
Another fun one. This is minimized from GCC 8's version of `<unordered_map>` in the STL.

### Input C/C++ Header

```C++
template<typename T>
struct Foo;

template<typename T, typename U>
struct Bar {};

template<typename T>
struct Bar<T, void> {
    using BarDependent = typename Foo<T>::Dependent;
    void method(const BarDependent &);
};

template<typename T>
void Bar<T, void>::method(const BarDependent &) {}
```

### Bindgen Invocation

```
$ bindgen input.hpp -- -x c++
```

### Actual Results

I haven't fully investigated yet, but I think the failing loop is here:

```
    frame #4: 0x00000001001dd8b2 bindgen`bindgen::ir::context::ItemResolver::resolve::h03bf533c52fa58fd(self=ItemResolver @ 0x00007ffeefbe71f0, ctx=0x00007ffeefbe9d28) at context.rs:2721:24
```

### Expected Results

We don't need bindings for these methods, but we need to not hang or panic.



Discussion:

Patch:
diff --git a/src/ir/context.rs b/src/ir/context.rs
index bd21058c4b..44df063a9b 100644
--- a/src/ir/context.rs
+++ b/src/ir/context.rs
@@ -2723,8 +2723,16 @@ impl ItemResolver {
         assert!(ctx.collected_typerefs());
 
         let mut id = self.id;
+        let mut seen_ids = HashSet::default();
         loop {
             let item = ctx.resolve_item(id);
+
+            // Detect cycles and bail out. These can happen in certain cases
+            // involving incomplete qualified dependent types (#2085).
+            if !seen_ids.insert(id) {
+                return item;
+            }
+
             let ty_kind = item.as_type().map(|t| t.kind());
             match ty_kind {
                 Some(&TypeKind::ResolvedTypeRef(next_id))


Test patch:
diff --git a/tests/expectations/tests/qualified-dependent-types.rs b/tests/expectations/tests/qualified-dependent-types.rs
new file mode 100644
index 0000000000..f1b2c8459c
--- /dev/null
+++ b/tests/expectations/tests/qualified-dependent-types.rs
@@ -0,0 +1,17 @@
+#![allow(
+    dead_code,
+    non_snake_case,
+    non_camel_case_types,
+    non_upper_case_globals
+)]
+
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone)]
+pub struct Foo {
+    pub _address: u8,
+}
+#[repr(C)]
+#[derive(Debug, Default, Copy, Clone)]
+pub struct Bar {
+    pub _address: u8,
+}
diff --git a/tests/headers/qualified-dependent-types.hpp b/tests/headers/qualified-dependent-types.hpp
new file mode 100644
index 0000000000..fcdfc87c81
--- /dev/null
+++ b/tests/headers/qualified-dependent-types.hpp
@@ -0,0 +1,16 @@
+// Issue #2085.
+
+template<typename T>
+struct Foo;
+
+template<typename T, typename U>
+struct Bar {};
+
+template<typename T>
+struct Bar<T, void> {
+    using BarDependent = typename Foo<T>::Dependent;
+    void method(const BarDependent &);
+};
+
+template<typename T>
+void Bar<T, void>::method(const BarDependent &) {}
Repository: paupino/rust-decimal (Rust)

Issue:
A sequence of operations results in widly incorrect result
The following code prints a wildly incorrect value.

```
use rust_decimal_macros::dec;

fn main() {
    let x = dec!(5000) / dec!(1000.26957490549);
    let y = x * dec!(1228.87000756);
    println!("{}", y / dec!(2) / dec!(1228.87000756));
}
```

**Expected Result:** 2.499326244
**Actual Result:** 0.0000000028395229317693263811
**Rust Version:** 1.49.0
**rust_decimal Version:** 1.10.1
**OS:** Debian Unstable


Discussion:
Thank you for this write up. I've managed to reproduce it based on the final division in the sequence. I'll look at getting a fix out for this once I track down the issue, however if you need a faster fix you can enable the feature `legacy-ops` which gives a more accurate result.
Ok, good news is I have uncovered the issue. I'll run a couple more tests and then publish a fix.
Published 1.10.2 which should fix this issue for you. At the moment I have a few [generated tests](https://github.com/paupino/rust-decimal/tree/master/tests/generated) however I may change this from 10000 each sequence to 100000 in 1.11.0 to hopefully capture more coverage.



Patch:
diff --git a/src/decimal.rs b/src/decimal.rs
index 88295880..e1ef17ee 100644
--- a/src/decimal.rs
+++ b/src/decimal.rs
@@ -2665,7 +2665,7 @@ mod ops {
                 let rem_lo = remainder.lo;
                 remainder.lo = remainder.mid;
                 remainder.mid = remainder.hi;
-                remainder.hi = 0;
+                remainder.hi = remainder.overflow;
                 quotient.mid = remainder.partial_divide_64(divisor64);
 
                 remainder.hi = remainder.mid;


Test patch:
diff --git a/tests/decimal_tests.rs b/tests/decimal_tests.rs
index c5b335b8..68d9604e 100644
--- a/tests/decimal_tests.rs
+++ b/tests/decimal_tests.rs
@@ -557,6 +557,13 @@ fn it_divides_decimals() {
             "3.27629537",
             either!("10.046792359274942644546996384", "10.046792359274942644546996383"),
         ),
+        ("5000", "1000.26957490549", "4.9986524887277738570721416846"),
+        ("6142.6941216127122745222131114", "2", "3071.3470608063561372611065557"),
+        (
+            "3071.3470608063561372611065557",
+            "1228.87000756",
+            either!("2.4993262443638869285360708423", "2.4993262443638869285360708422"),
+        ),
     ];
     for &(a, b, c) in tests {
         div(a, b, c);
Repository: uutils/coreutils (Rust)

Issue:
cp: Copying directory into itself causes unbounded recursion
`cp -R dir dir` fails on GNU with the error `cp: cannot copy a directory, 'dir', into itself, 'dir/dir'`.However,  uutils continues copying `dir` into itself until the full path `dir/dir/dir/.../` becomes too long to parse. 


Discussion:
I can work on fixing this.



Patch:
diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs
index 2ffa1e3ca1f..2082fecbd2e 100644
--- a/src/uu/cp/src/cp.rs
+++ b/src/uu/cp/src/cp.rs
@@ -969,6 +969,16 @@ fn copy_directory(
         return copy_file(root, target, options, symlinked_files);
     }
 
+    // check if root is a prefix of target
+    if path_has_prefix(target, root)? {
+        return Err(format!(
+            "cannot copy a directory, {}, into itself, {}",
+            root.quote(),
+            target.quote()
+        )
+        .into());
+    }
+
     let current_dir =
         env::current_dir().unwrap_or_else(|e| crash!(1, "failed to get current directory {}", e));
 
@@ -1573,6 +1583,13 @@ pub fn paths_refer_to_same_file(p1: &Path, p2: &Path) -> io::Result<bool> {
     Ok(pathbuf1 == pathbuf2)
 }
 
+pub fn path_has_prefix(p1: &Path, p2: &Path) -> io::Result<bool> {
+    let pathbuf1 = canonicalize(p1, MissingHandling::Normal, ResolveMode::Logical)?;
+    let pathbuf2 = canonicalize(p2, MissingHandling::Normal, ResolveMode::Logical)?;
+
+    Ok(pathbuf1.starts_with(pathbuf2))
+}
+
 #[test]
 fn test_cp_localize_to_target() {
     assert!(


Test patch:
diff --git a/tests/by-util/test_cp.rs b/tests/by-util/test_cp.rs
index 7c8ccce5295..cfa946d471b 100644
--- a/tests/by-util/test_cp.rs
+++ b/tests/by-util/test_cp.rs
@@ -1462,6 +1462,52 @@ fn test_cp_archive_on_nonexistent_file() {
             "cp: cannot stat 'nonexistent_file.txt': No such file or directory (os error 2)",
         );
 }
+
+#[test]
+fn test_dir_recursive_copy() {
+    let scene = TestScenario::new(util_name!());
+    let at = &scene.fixtures;
+
+    at.mkdir("parent1");
+    at.mkdir("parent2");
+    at.mkdir("parent1/child");
+    at.mkdir("parent2/child1");
+    at.mkdir("parent2/child1/child2");
+    at.mkdir("parent2/child1/child2/child3");
+
+    // case-1: copy parent1 -> parent1: should fail
+    scene
+        .ucmd()
+        .arg("-R")
+        .arg("parent1")
+        .arg("parent1")
+        .fails()
+        .stderr_contains("cannot copy a directory");
+    // case-2: copy parent1 -> parent1/child should fail
+    scene
+        .ucmd()
+        .arg("-R")
+        .arg("parent1")
+        .arg("parent1/child")
+        .fails()
+        .stderr_contains("cannot copy a directory");
+    // case-3: copy parent1/child -> parent2 should pass
+    scene
+        .ucmd()
+        .arg("-R")
+        .arg("parent1/child")
+        .arg("parent2")
+        .succeeds();
+    // case-4: copy parent2/child1/ -> parent2/child1/child2/child3
+    scene
+        .ucmd()
+        .arg("-R")
+        .arg("parent2/child1/")
+        .arg("parent2/child1/child2/child3")
+        .fails()
+        .stderr_contains("cannot copy a directory");
+}
+
 #[test]
 fn test_cp_dir_vs_file() {
     new_ucmd!()
Repository: rust-bakery/nom (Rust)

Issue:
parse_to! doesn't consume its input
The documentation for the `parse_to!` macro claims that "this will completely consume the input", which is what one would expect. By contrast, the input is actually not consumed, but returned unaltered.

## Setup
- Rust version : 1.24.1
- nom version : 4.0.0-beta2
- nom compilation features used: N/A

## Test case

```
#[macro_use]
extern crate nom;

fn main() {
    let res: nom::IResult<&str, u16> = parse_to!("1234", u16);
    assert_eq!(res, Ok(("", 1234)));
}
```


Discussion:
I have a working fix for this, but I can't seem to create a branch and hence a pull request.

Edit: Nevermind, I figured it out.



Patch:
diff --git a/src/macros.rs b/src/macros.rs
index 2f8c51bd3..9af7ab8c3 100644
--- a/src/macros.rs
+++ b/src/macros.rs
@@ -670,7 +670,7 @@ macro_rules! parse_to (
 
       let res: Option<$t> = ($i).parse_to();
       match res {
-        Some(output) => Ok(($i.slice(..$i.input_len()), output)),
+        Some(output) => Ok(($i.slice($i.input_len()..), output)),
         None         => Err(Err::Error(Context::Code($i, ErrorKind::MapOpt::<u32>)))
       }
     }


Test patch:
diff --git a/tests/issues.rs b/tests/issues.rs
index 9abdb8a2e..288087f42 100644
--- a/tests/issues.rs
+++ b/tests/issues.rs
@@ -224,3 +224,9 @@ fn issue_667() {
     Ok((CompleteByteSlice(b"!@#$"), vec![]))
   );
 }
+
+#[test]
+fn issue_721() {
+  assert_eq!(parse_to!("1234", u16), Ok(("", 1234)));
+  assert_eq!(parse_to!("foo", String), Ok(("", "foo".to_string())));
+}
\ No newline at end of file
Repository: rust-lang/rust-bindgen (Rust)

Issue:
Rust method wrapper is still emitted for blacklisted functions
Is it intended behavior that a Rust method is still emitted even though the function it wraps is blacklisted? Is there a different way to blacklist a method so the method wrapper is not emitted? Looking through the code I don't see one.

I've got a simple three line change to not emit methods for blacklisted functions, if this was not intended behavior. Because that's a behavior change, I thought I should file this issue to discuss first.



Discussion:
You mean that we emit an `impl Foo { fn bar() { ... } }` calling a blacklisted function? Yeah I don't think that's expected.
Feel free to submit the PR for discussion directly next time, fwiw :)

Thanks!



Patch:
diff --git a/src/codegen/mod.rs b/src/codegen/mod.rs
index 408d88bfe7..8344c4d1b5 100644
--- a/src/codegen/mod.rs
+++ b/src/codegen/mod.rs
@@ -2146,6 +2146,10 @@ impl MethodCodegen for Method {
 
         // First of all, output the actual function.
         let function_item = ctx.resolve_item(self.signature());
+        if function_item.is_blacklisted(ctx) {
+            // We shouldn't emit a method declaration if the function is blacklisted
+            return;
+        }
         function_item.codegen(ctx, result, &());
 
         let function = function_item.expect_function();


Test patch:
diff --git a/tests/expectations/tests/blacklist-function.rs b/tests/expectations/tests/blacklist-function.rs
index b1d5564339..5c4e849719 100644
--- a/tests/expectations/tests/blacklist-function.rs
+++ b/tests/expectations/tests/blacklist-function.rs
@@ -23,4 +23,22 @@ pub mod root {
             pub fn NamespacedFunction();
         }
     }
+    #[repr(C)]
+    #[derive(Debug, Default, Copy, Clone)]
+    pub struct C {
+        pub _address: u8,
+    }
+    #[test]
+    fn bindgen_test_layout_C() {
+        assert_eq!(
+            ::std::mem::size_of::<C>(),
+            1usize,
+            concat!("Size of: ", stringify!(C))
+        );
+        assert_eq!(
+            ::std::mem::align_of::<C>(),
+            1usize,
+            concat!("Alignment of ", stringify!(C))
+        );
+    }
 }
diff --git a/tests/headers/blacklist-function.hpp b/tests/headers/blacklist-function.hpp
index c4a923fcea..8087295cc1 100644
--- a/tests/headers/blacklist-function.hpp
+++ b/tests/headers/blacklist-function.hpp
@@ -1,4 +1,4 @@
-// bindgen-flags: --blacklist-function "ExternFunction" --blacklist-function "foo::NamespacedFunction" --enable-cxx-namespaces
+// bindgen-flags: --blacklist-function "ExternFunction" --blacklist-function "foo::NamespacedFunction" --blacklist-function "C_ClassMethod" --enable-cxx-namespaces
 
 extern "C" void ExternFunction();
 
@@ -9,3 +9,8 @@ namespace foo {
 namespace bar {
   void NamespacedFunction();
 }
+
+class C {
+public:
+  void ClassMethod();
+};
Repository: uutils/coreutils (Rust)

Issue:
`sha1sum -c testf.sha1` is failing with an weird error
with
```
#export C=./target/debug/coreutils 
echo "foobar" > testf
sha1sum testf > testf.sha1  
$C sha1sum --check testf.sha1
```

With GNU:
`testf: OK`

With Rust:
```
thread 'main' panicked at 'Mismatch between definition and access of `no-names`. Unknown argument or group id.  Make sure you are using the argument id and not the short or long flags
', /home/sylvestre/.cargo/registry/src/github.com-1ecc6299db9ec823/clap-3.2.15/src/parser/matches/arg_matches.rs:318:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```

Tested in GNU by `tests/misc/sha1sum.pl `


Discussion:

Patch:
diff --git a/src/uu/hashsum/src/hashsum.rs b/src/uu/hashsum/src/hashsum.rs
index fecdc1d0554..3d8ba8d41b4 100644
--- a/src/uu/hashsum/src/hashsum.rs
+++ b/src/uu/hashsum/src/hashsum.rs
@@ -296,7 +296,11 @@ pub fn uumain(mut args: impl uucore::Args) -> UResult<()> {
     };
     let check = matches.contains_id("check");
     let tag = matches.contains_id("tag");
-    let nonames = matches.contains_id("no-names");
+    let nonames = if binary_name == "b3sum" {
+        matches.contains_id("no-names")
+    } else {
+        false
+    };
     let status = matches.contains_id("status");
     let quiet = matches.contains_id("quiet") || status;
     let strict = matches.contains_id("strict");


Test patch:
diff --git a/tests/by-util/test_hashsum.rs b/tests/by-util/test_hashsum.rs
index 160798f36d9..06d039d5900 100644
--- a/tests/by-util/test_hashsum.rs
+++ b/tests/by-util/test_hashsum.rs
@@ -1,4 +1,5 @@
-// spell-checker:ignore checkfile, nonames
+use crate::common::util::*;
+// spell-checker:ignore checkfile, nonames, testf
 macro_rules! get_hash(
     ($str:expr) => (
         $str.split(' ').collect::<Vec<&str>>()[0]
@@ -33,10 +34,13 @@ macro_rules! test_digest {
         fn test_nonames() {
             let ts = TestScenario::new("hashsum");
             // EXPECTED_FILE has no newline character at the end
-            assert_eq!(format!("{0}\n{0}\n", ts.fixtures.read(EXPECTED_FILE)),
+            if DIGEST_ARG == "b3sum" {
+                // Option only available on b3sum
+                assert_eq!(format!("{0}\n{0}\n", ts.fixtures.read(EXPECTED_FILE)),
                        ts.ucmd().arg(DIGEST_ARG).arg(BITS_ARG).arg("--no-names").arg("input.txt").arg("-").pipe_in_fixture("input.txt")
                        .succeeds().no_stderr().stdout_str()
                        );
+                }
         }
 
         #[test]
@@ -92,3 +96,23 @@ test_digest! {
     b2sum b2sum 512
     b3sum b3sum 256
 }
+
+#[test]
+fn test_check_sha1() {
+    // To make sure that #3815 doesn't happen again
+    let scene = TestScenario::new(util_name!());
+    let at = &scene.fixtures;
+
+    at.write("testf", "foobar\n");
+    at.write(
+        "testf.sha1",
+        "988881adc9fc3655077dc2d4d757d480b5ea0e11  testf\n",
+    );
+    scene
+        .ccmd("sha1sum")
+        .arg("-c")
+        .arg(at.subdir.join("testf.sha1"))
+        .succeeds()
+        .stdout_is("testf: OK\n")
+        .stderr_is("");
+}
Repository: pulldown-cmark/pulldown-cmark (Rust)

Issue:
Bad markdown intepretation
The following markdown:

```
[`
i8
`](
../../../std/primitive.i8.html
)
```

is currently badly interpreted. It should ignore backlines and trim content. Currently it generates a result pretty strange:

```html
<a href="https://doc.rust-lang.org/nightly/std/primitive.i8.html" title="` i8 `"><code>i8</code></a>(
../../../std/primitive.i8.html
)
```


Discussion:
That does look pretty funky :thinking: 

Thanks for the report. I'll look into it!



Patch:
diff --git a/specs/regression.txt b/specs/regression.txt
index f185e769..d5e701b3 100644
--- a/specs/regression.txt
+++ b/specs/regression.txt
@@ -123,3 +123,15 @@ ISSUE #43 (2)
 
 ````````````````````````````````
 
+ISSUE #239
+
+```````````````````````````````` example
+[`
+i8
+`](
+../../../std/primitive.i8.html
+)
+.
+<p><a href="../../../std/primitive.i8.html"><code>i8</code></a></p>
+````````````````````````````````
+
diff --git a/src/parse.rs b/src/parse.rs
index efd85985..663db749 100644
--- a/src/parse.rs
+++ b/src/parse.rs
@@ -2193,8 +2193,8 @@ fn scan_inline_link<'t, 'a>(scanner: &mut InlineScanner<'t, 'a>) -> Option<(CowS
     scanner.scan_while(is_ascii_whitespace);
     let url = scan_link_destination(scanner)?;
     let mut title = "".into();
-    let save = scanner.clone();
     if scanner.scan_while(is_ascii_whitespace) > 0 {
+        let save = scanner.clone();
         if let Some(t) = scan_link_title(scanner) {
             title = t;
             scanner.scan_while(is_ascii_whitespace);


Test patch:
diff --git a/tests/regression.rs b/tests/regression.rs
index ca88ea59..d44aaf24 100644
--- a/tests/regression.rs
+++ b/tests/regression.rs
@@ -229,6 +229,33 @@ This is a test of the details element.
 </li>
 </ul>
 
+"##;
+
+        use pulldown_cmark::{Parser, html, Options};
+
+        let mut s = String::new();
+
+        let mut opts = Options::empty();
+        opts.insert(Options::ENABLE_TABLES);
+        opts.insert(Options::ENABLE_FOOTNOTES);
+        opts.insert(Options::ENABLE_STRIKETHROUGH);
+        opts.insert(Options::ENABLE_TASKLISTS);
+
+        let p = Parser::new_ext(&original, opts);
+        html::push_html(&mut s, p);
+
+        assert_eq!(normalize_html(&expected), normalize_html(&s));
+    }
+
+    #[test]
+    fn regression_test_9() {
+        let original = r##"[`
+i8
+`](
+../../../std/primitive.i8.html
+)
+"##;
+        let expected = r##"<p><a href="../../../std/primitive.i8.html"><code>i8</code></a></p>
 "##;
 
         use pulldown_cmark::{Parser, html, Options};
Repository: uutils/coreutils (Rust)

Issue:
`du -h` on an empty file
When I do `du -h empty.txt` using WSL (+Ubuntu) I get

```
0       empty.txt
```

When I do `coreutils du -h empty.txt` though I get

```
0B      empty.txt
```


Discussion:
Any objections to me adjusting this?
Please go ahead :)




Patch:
diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs
index 2eb7bd658fe..5ce19384296 100644
--- a/src/uu/du/src/du.rs
+++ b/src/uu/du/src/du.rs
@@ -305,6 +305,9 @@ fn convert_size_human(size: u64, multiplier: u64, _block_size: u64) -> String {
             return format!("{:.1}{}", (size as f64) / (limit as f64), unit);
         }
     }
+    if size == 0 {
+        return format!("0");
+    }
     format!("{}B", size)
 }
 


Test patch:
diff --git a/tests/by-util/test_du.rs b/tests/by-util/test_du.rs
index c810bd395d0..b3b1b34659d 100644
--- a/tests/by-util/test_du.rs
+++ b/tests/by-util/test_du.rs
@@ -162,3 +162,13 @@ fn _du_d_flag(s: String) {
         assert_eq!(s, "8\t./subdir\n8\t./\n");
     }
 }
+
+#[test]
+fn test_du_h_flag_empty_file() {
+    let ts = TestScenario::new("du");
+
+    let result = ts.ucmd().arg("-h").arg("empty.txt").run();
+    assert!(result.success);
+    assert_eq!(result.stderr, "");
+    assert_eq!(result.stdout, "0\tempty.txt\n");
+}
diff --git a/tests/fixtures/du/empty.txt b/tests/fixtures/du/empty.txt
new file mode 100644
index 00000000000..e69de29bb2d
Repository: seanmonstar/reqwest (Rust)

Issue:
[Question] How to tell if timeout is caused by Connect?
Is it possible to tell a TimedOut err is caused by connect? 
The reason is, if it is caused by connect timeout, then I can retry the request.

hyper's error has two methods for this, is_connect and is_timeout. Seems I have to downcast the boxed err to hyper err and call those two methods?


Discussion:
Yes, you could check the `source()`. We could also add a `is_connect` method to `reqwest::Error`. Would you want to try adding that?
@seanmonstar The pr failed on wasm, I have zero experience on wasm, any idea how to fix it?
@seanmonstar pr is done, added a compile condition to skip wasm.



Patch:
diff --git a/src/error.rs b/src/error.rs
index b8e84b521..cb05eb774 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -102,6 +102,24 @@ impl Error {
         }
     }
 
+    #[cfg(not(target_arch = "wasm32"))]
+    /// Returns true if the error is related to connect
+    pub fn is_connect(&self) -> bool {
+        let mut source = self.source();
+
+        while let Some(err) = source {
+            if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() {
+                if hyper_err.is_connect() {
+                    return true;
+                }
+            }
+
+            source = err.source();
+        }
+
+        false
+    }
+
     /// Returns true if the error is related to the request or response body
     pub fn is_body(&self) -> bool {
         match self.inner.kind {


Test patch:
diff --git a/tests/timeouts.rs b/tests/timeouts.rs
index 4a8880e9f..8c3a269bb 100644
--- a/tests/timeouts.rs
+++ b/tests/timeouts.rs
@@ -54,10 +54,37 @@ async fn request_timeout() {
 
     let err = res.unwrap_err();
 
-    assert!(err.is_timeout());
+    if cfg!(not(target_arch = "wasm32")) {
+        assert!(err.is_timeout() && !err.is_connect());
+    } else {
+        assert!(err.is_timeout());
+    }
     assert_eq!(err.url().map(|u| u.as_str()), Some(url.as_str()));
 }
 
+#[cfg(not(target_arch = "wasm32"))]
+#[tokio::test]
+async fn connect_timeout() {
+    let _ = env_logger::try_init();
+
+    let client = reqwest::Client::builder()
+        .connect_timeout(Duration::from_millis(100))
+        .build()
+        .unwrap();
+
+    let url = format!("http://10.255.255.1:81/slow");
+
+    let res = client
+        .get(&url)
+        .timeout(Duration::from_millis(1000))
+        .send()
+        .await;
+
+    let err = res.unwrap_err();
+
+    assert!(err.is_connect() && err.is_timeout());
+}
+
 #[tokio::test]
 async fn response_timeout() {
     let _ = env_logger::try_init();
Repository: rust-lang/rust-analyzer (Rust)

Issue:
{unknown} type deduced for a function pointer with omitted return type stored in a struct
rust-analyzer version: nightly (e300e1e)

Reporduction:
```rust
struct Vtable {
    method: fn()
}

fn main() {
    let vtable = Vtable {
        method: || {}
    };
    let m = vtable.method;
}

```
<details>
<summary>Screen</summary>

![image](https://user-images.githubusercontent.com/36276403/78473459-95eee200-7749-11ea-9f7f-b12d83de2256.png)

</details>



Discussion:
The relevant code is here:
https://github.com/rust-analyzer/rust-analyzer/blob/e300e1e8d8f4de273d52fa62762ed14e8a7f96bb/crates/ra_hir_def/src/type_ref.rs#L96
Instead of using `from_ast_opt`, we should use `from_ast` and `TypeRef::Tuple(Vec::new())` in the `None` case. We can add a test for this [here](https://github.com/rust-analyzer/rust-analyzer/blob/master/crates/ra_hir_ty/src/tests/simple.rs).



Patch:
diff --git a/crates/ra_hir_def/src/type_ref.rs b/crates/ra_hir_def/src/type_ref.rs
index 102fdb13d72f..01cc392db027 100644
--- a/crates/ra_hir_def/src/type_ref.rs
+++ b/crates/ra_hir_def/src/type_ref.rs
@@ -93,7 +93,11 @@ impl TypeRef {
             }
             ast::TypeRef::PlaceholderType(_inner) => TypeRef::Placeholder,
             ast::TypeRef::FnPointerType(inner) => {
-                let ret_ty = TypeRef::from_ast_opt(inner.ret_type().and_then(|rt| rt.type_ref()));
+                let ret_ty = inner
+                    .ret_type()
+                    .and_then(|rt| rt.type_ref())
+                    .map(TypeRef::from_ast)
+                    .unwrap_or_else(|| TypeRef::Tuple(Vec::new()));
                 let mut params = if let Some(pl) = inner.param_list() {
                     pl.params().map(|p| p.ascribed_type()).map(TypeRef::from_ast_opt).collect()
                 } else {


Test patch:
diff --git a/crates/ra_hir_ty/src/tests/simple.rs b/crates/ra_hir_ty/src/tests/simple.rs
index a600b947d0af..141f0245aa08 100644
--- a/crates/ra_hir_ty/src/tests/simple.rs
+++ b/crates/ra_hir_ty/src/tests/simple.rs
@@ -1729,3 +1729,29 @@ fn foo() -> u32 {
     "###
     );
 }
+
+#[test]
+fn fn_pointer_return() {
+    assert_snapshot!(
+        infer(r#"
+struct Vtable {
+    method: fn(),
+}
+
+fn main() {
+    let vtable = Vtable { method: || {} };
+    let m = vtable.method;
+}
+"#),
+        @r###"
+    [48; 121) '{     ...hod; }': ()
+    [58; 64) 'vtable': Vtable
+    [67; 91) 'Vtable...| {} }': Vtable
+    [84; 89) '|| {}': || -> ()
+    [87; 89) '{}': ()
+    [101; 102) 'm': fn() -> ()
+    [105; 111) 'vtable': Vtable
+    [105; 118) 'vtable.method': fn() -> ()
+    "###
+    );
+}