anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: intellij-rust/intellij-rust
Issue: Attach file to module fails with keyword-like names

<!--
Hello and thank you for the issue!
If you would like to report a bug, we have added some points below that you can fill out.
Consider using "Help | Create New Issue" action that fills out all necessary information automatically.
Feel free to remove all the irrelevant text to request a new feature.
-->

## Environment

* **IntelliJ Rust plugin version:** 0.4.161.4292-213
* **Rust toolchain version:** 1.57.0 (`cargo --version`)
* **IDE name and version:** Intellij Ultimate 2021.3
* **Operating system:** Linux FRONTIERDT 5.13.0-27-generic #29~20.04.1-Ubuntu SMP Fri Jan 14 00:32:30 UTC 2022 (`uname -snrv`)

## Problem description
It shouldn't be allowed that creating new directory in src folder that cannot be used as `mod` name because it may be cause of confusing.

## Steps to reproduce
1. Create new Project
2. Create directory in `src` with name `macro`
4. Create file as `src/macro.rs`
5. Open `src/macro.rs`
6. Choose `Attach file to main.rs` in `src/macro.rs`
7. Will see Could not create `mod macro`



Changed files:
src/main/kotlin/org/rust/lang/core/psi/RsPsiFactory.kt, src/test/kotlin/org/rust/ide/inspections/RsDetachedFileInspectionTest.kt

diff --git a/src/main/kotlin/org/rust/lang/core/psi/RsPsiFactory.kt b/src/main/kotlin/org/rust/lang/core/psi/RsPsiFactory.kt
index d93ca3ed3..23fd1ebff 100644
--- a/src/main/kotlin/org/rust/lang/core/psi/RsPsiFactory.kt
+++ b/src/main/kotlin/org/rust/lang/core/psi/RsPsiFactory.kt
@@ -225,7 +225,7 @@ class RsPsiFactory(
         tryCreateModDeclItem(modName) ?: error("Failed to create mod decl with name: `$modName`")
 
     fun tryCreateModDeclItem(modName: String): RsModDeclItem? =
-        createFromText("mod $modName;")
+        createFromText("mod ${modName.escapeIdentifierIfNeeded()};")
 
     fun createUseItem(text: String, visibility: String = "", alias: String? = null): RsUseItem {
         val aliasText = if (!alias.isNullOrEmpty()) " as $alias" else ""
diff --git a/src/test/kotlin/org/rust/ide/inspections/RsDetachedFileInspectionTest.kt b/src/test/kotlin/org/rust/ide/inspections/RsDetachedFileInspectionTest.kt
index 609831915..3b5b2cc40 100644
--- a/src/test/kotlin/org/rust/ide/inspections/RsDetachedFileInspectionTest.kt
+++ b/src/test/kotlin/org/rust/ide/inspections/RsDetachedFileInspectionTest.kt
@@ -284,6 +284,19 @@ class RsDetachedFileInspectionTest : RsInspectionsTestBase(RsDetachedFileInspect
         //- foo.rs
     """)
 
+    fun `test attach file with keywork-like name`() = checkFixByFileTree("Attach file to main.rs", """
+        //- main.rs
+            fn main() {}
+        //- macro.rs
+        <warning descr="File is not included in module tree, analysis is not available"></warning>/*caret*/
+    """, """
+        //- main.rs
+            mod r#macro;
+
+            fn main() {}
+        //- macro.rs
+    """)
+
     private fun checkFixWithMultipleModules(
         @Language("Rust") before: String,
         @Language("Rust") after: String,
Repository: intellij-rust/intellij-rust
Issue: False name resolution error with multiple `use Trait as _`

Sorry, don't have time for a proper bug report, please see

https://github.com/near/nearcore/commit/a9c07344b542173d353b5c4db43cf82e07db1a5f

Changed files:
src/main/kotlin/org/rust/lang/core/resolve/NameResolution.kt, src/test/kotlin/org/rust/ide/inspections/import/AutoImportFixTest.kt

diff --git a/src/main/kotlin/org/rust/lang/core/resolve/NameResolution.kt b/src/main/kotlin/org/rust/lang/core/resolve/NameResolution.kt
index e06e821ff..abfb1136e 100644
--- a/src/main/kotlin/org/rust/lang/core/resolve/NameResolution.kt
+++ b/src/main/kotlin/org/rust/lang/core/resolve/NameResolution.kt
@@ -1668,7 +1668,7 @@ inline fun processWithShadowingAndUpdateScope(
 ): Boolean {
     val currScope = mutableMapOf<String, Set<Namespace>>()
     val shadowingProcessor = createProcessor(processor.name) { e ->
-        val prevNs = prevScope[e.name]
+        val prevNs = if (e.name != "_") prevScope[e.name] else null
         if (prevNs != null) {
             val newNs = (e.element as? RsNamedElement)?.namespaces
             if (newNs != null && !ns.intersects(newNs.minus(prevNs))) {
@@ -1676,7 +1676,7 @@ inline fun processWithShadowingAndUpdateScope(
             }
         }
         val result = processor(e)
-        if (e.isInitialized) {
+        if (e.isInitialized && e.name != "_") {
             val newNs = (e.element as? RsNamedElement)?.namespaces
             if (newNs != null) {
                 currScope[e.name] = prevNs?.let { it + newNs } ?: newNs
@@ -1698,7 +1698,8 @@ inline fun processWithShadowing(
     f: (RsResolveProcessor) -> Boolean
 ): Boolean {
     val processor = createProcessor(originalProcessor.name) { e ->
-        val prevNs = prevScope[e.name] ?: return@createProcessor originalProcessor(e)
+        val prevNs = prevScope[e.name]
+        if (e.name == "_" || prevNs == null) return@createProcessor originalProcessor(e)
         val newNs = (e.element as? RsNamedElement)?.namespaces
         (newNs == null || ns.intersects(newNs.minus(prevNs))) && originalProcessor(e)
     }
diff --git a/src/test/kotlin/org/rust/ide/inspections/import/AutoImportFixTest.kt b/src/test/kotlin/org/rust/ide/inspections/import/AutoImportFixTest.kt
index 7ef612172..c9c3742bd 100644
--- a/src/test/kotlin/org/rust/ide/inspections/import/AutoImportFixTest.kt
+++ b/src/test/kotlin/org/rust/ide/inspections/import/AutoImportFixTest.kt
@@ -2938,4 +2938,21 @@ class AutoImportFixTest : AutoImportFixTestBase() {
             func();
         }
     """)
+
+    @MockEdition(CargoWorkspace.Edition.EDITION_2018)
+    fun `test UFCS with unnamed trait import inside another trait impl`() = checkAutoImportFixIsUnavailable("""
+        mod inner {
+            pub struct Foo {}
+            pub trait Trait { fn func() {} }
+            impl Trait for Foo {}
+        }
+        use inner::Trait as _;
+
+        trait OtherTrait { fn other_func(); }
+        impl OtherTrait for () {
+            fn other_func() {
+                inner::Foo::func/*caret*/();
+            }
+        }
+    """)
 }
Repository: intellij-rust/intellij-rust
Issue: Implement members generates invalid const generics

<!--
Hello and thank you for the issue!
If you would like to report a bug, we have added some points below that you can fill out.
Feel free to remove all the irrelevant text to request a new feature.
-->

## Environment

* **IntelliJ Rust plugin version:** 0.4.155.4092-212-nightly
* **Rust toolchain version:** 1.56.0-nightly (2f662b140 2021-08-29) x86_64-pc-windows-msvc
* **IDE name and version:** IntelliJ IDEA 2021.2 Community Edition (IC-212.4746.92)
* **Operating system:** Windows 10 10.0
* **Macro expansion engine:** new
* **Name resolution engine:** new

## Problem description
Implement members for `impl A for C` generates invalid code

## Steps to reproduce
```rust
trait A {
    fn b<const N: usize>();
}

struct C;

impl A for C {
    fn b<const Nusize>() {
        todo!()
    }
}
```

<!--
Please include as much of your codebase as needed to reproduce the error.
If the relevant files are large, please provide a link to a public repository or a [Gist](https://gist.github.com/).
-->

Changed files:
src/test/kotlin/org/rust/ide/refactoring/implementMembers/ImplementMembersHandlerTest.kt
src/main/kotlin/org/rust/ide/presentation/RsPsiRenderer.kt

diff --git a/src/main/kotlin/org/rust/ide/presentation/RsPsiRenderer.kt b/src/main/kotlin/org/rust/ide/presentation/RsPsiRenderer.kt
index 3b7db489c..29a7cbf0a 100644
--- a/src/main/kotlin/org/rust/ide/presentation/RsPsiRenderer.kt
+++ b/src/main/kotlin/org/rust/ide/presentation/RsPsiRenderer.kt
@@ -177,6 +177,7 @@ open class RsPsiRenderer(
                     sb.append(name ?: "_")
                     val type = typeReference
                     if (type != null) {
+                        sb.append(": ")
                         appendTypeReference(sb, type)
                     }
                 }
diff --git a/src/test/kotlin/org/rust/ide/refactoring/implementMembers/ImplementMembersHandlerTest.kt b/src/test/kotlin/org/rust/ide/refactoring/implementMembers/ImplementMembersHandlerTest.kt
index 7f0163b41..c4b5f6b91 100644
--- a/src/test/kotlin/org/rust/ide/refactoring/implementMembers/ImplementMembersHandlerTest.kt
+++ b/src/test/kotlin/org/rust/ide/refactoring/implementMembers/ImplementMembersHandlerTest.kt
@@ -1752,6 +1752,28 @@ class ImplementMembersHandlerTest : RsTestBase() {
         }
     """)
 
+    fun `test const type param`() = doTest("""
+        trait Foo {
+            fn foo<const N: usize>();
+        }
+        struct S;
+        impl Foo for S {
+            /*caret*/
+        }
+    """, listOf(
+        ImplementMemberSelection("foo<const N: usize>()", byDefault = true)
+    ), """
+        trait Foo {
+            fn foo<const N: usize>();
+        }
+        struct S;
+        impl Foo for S {
+            fn foo<const N: usize>() {
+                todo!()
+            }
+        }
+    """)
+
     private data class ImplementMemberSelection(val member: String, val byDefault: Boolean, val isSelected: Boolean = byDefault)
 
     private fun doTest(
Repository: intellij-rust/intellij-rust
Issue: E0404 On correct rust code

<!--
Hello and thank you for the issue!
If you would like to report a bug, we have added some points below that you can fill out.
Consider using "Help | Create New Issue" action that fills out all necessary information automatically.
Feel free to remove all the irrelevant text to request a new feature.
-->

## Environment

* **IntelliJ Rust plugin version:** 0.3.138.3572-202
* **Rust toolchain version:** 1.51.0-nightly (but also on stable)
* **IDE name and version:** CLion 2020.2.5
* **Operating system:** Ubuntu 20.04

## Problem description

A trait alias used in place of a trait triggers an IDE error (E0404, expected trait found trait alias)
but rustc compiles it correctly.

## Steps to reproduce

The minimal code that triggers the error is:
```rust
pub trait CloneAlias = Clone;
pub struct X<T: CloneAlias>();
```

<!--
Please include as much of your codebase as needed to reproduce the error.
If the relevant files are large, please provide a link to a public repository or a [Gist](https://gist.github.com/).
-->


Changed files:
src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt, src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt

diff --git a/src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt b/src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt
index f88d9da8d..c5d1c79b1 100644
--- a/src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt
+++ b/src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt
@@ -409,7 +409,7 @@ class RsErrorAnnotator : AnnotatorBase(), HighlightRangeExtension {
 
     private fun checkTraitRef(holder: RsAnnotationHolder, o: RsTraitRef) {
         val item = o.path.reference?.resolve() as? RsItemElement ?: return
-        if (item !is RsTraitItem) {
+        if (item !is RsTraitItem && item !is RsTraitAlias) {
             RsDiagnostic.NotTraitError(o, item).addToHolder(holder)
         }
     }
diff --git a/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt b/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
index a80f3044b..08deddb3c 100644
--- a/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
+++ b/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
@@ -1686,11 +1686,13 @@ class RsErrorAnnotatorTest : RsAnnotatorTestBase(RsErrorAnnotator::class) {
         type T = S;
         mod a {}
         trait Trait {}
+        trait TraitAlias = Trait;
         impl <error descr="Expected trait, found struct `S` [E0404]">S</error> for S {}
         impl <error descr="Expected trait, found enum `E` [E0404]">E</error> for S {}
         impl <error descr="Expected trait, found type alias `T` [E0404]">T</error> for S {}
         impl <error descr="Expected trait, found module `a` [E0404]">a</error> for S {}
         fn foo<A: <error descr="Expected trait, found struct `S` [E0404]">S</error>>() {}
+        fn foo2<A: TraitAlias>() {}
         impl Trait for S {}
     """)
Repository: intellij-rust/intellij-rust
Issue: can't set environments for a test run config

<!--
Hello and thank you for the issue!
If you would like to report a bug, we have added some points below that you can fill out.
Consider using "Help | Create New Issue" action that fills out all necessary information automatically.
Feel free to remove all the irrelevant text to request a new feature.
-->

## Environment

* **IntelliJ Rust plugin version:** 0.3.139.3589-203-nightly
* **Rust toolchain version:** rustc 1.51.0-nightly (26438b473 2021-01-08)
* **IDE name and version:** clion 2020.3.1
* **Operating system:** Archlinux

## Problem description
can't set environments for an existing test run config, if set environments, press ctrl+shift+f10 will create a new config named 'xxx(1)', xxx is the origin config name

## Steps to reproduce

1. press ctrl+shift+f10 for a test case, it will create a new run config
2. edit the config environments
3. press ctrl+shift+f10 again, it will create a new config named xxx(1), not reuse the existing config with the new environments


Changed files:
src/main/kotlin/org/rust/cargo/runconfig/command/CompositeCargoRunConfigurationProducer.kt

diff --git a/src/main/kotlin/org/rust/cargo/runconfig/command/CompositeCargoRunConfigurationProducer.kt b/src/main/kotlin/org/rust/cargo/runconfig/command/CompositeCargoRunConfigurationProducer.kt
index 73187310a..ef17ea05a 100644
--- a/src/main/kotlin/org/rust/cargo/runconfig/command/CompositeCargoRunConfigurationProducer.kt
+++ b/src/main/kotlin/org/rust/cargo/runconfig/command/CompositeCargoRunConfigurationProducer.kt
@@ -113,7 +113,6 @@ class CompositeCargoRunConfigurationProducer : CargoRunConfigurationProducer() {
             command != other.command -> false
             backtrace != other.backtrace -> false
             workingDirectory != other.workingDirectory -> false
-            env != other.env -> false
             else -> true
         }
 }
Repository: intellij-rust/intellij-rust
Issue: Native debug plugin is advertised for any run configuration

## Environment

* **IntelliJ Rust plugin version:** 0.2.124.SNAPSHOT-201-dev
* **Rust toolchain version:** 1.45.0-nightly (a74d1862d 2020-05-14) x86_64-apple-darwin
* **IDE name and version:** IntelliJ IDEA 2020.1.1 Ultimate Edition (IU-201.7223.91)
* **Operating system:** macOS 10.13.6

## Problem description
Our advertising debug runner (introduced in #5393) for IntelliJ IDEA affects any run configuration instead of cargo only. As a result, if you have rust plugin in IntelliJ IDEA Ultimate and don't have [Native Debug](https://plugins.jetbrains.com/plugin/12775-native-debugging-support), you will get an error message with a suggestion to install Native Debug plugin

## Steps to reproduce
* Ensure that [Native Debug](https://plugins.jetbrains.com/plugin/12775-native-debugging-support) plugin is not installed
* Create any kotlin jvm project
* Create kotlin run configuration. For example, try to execute `main`
* And try to debug this run configuration

<!--
Please include as much of your codebase as needed to reproduce the error.
If the relevant files are large, please provide a link to a public repository or a [Gist](https://gist.github.com/).
-->            

Changed files:
src/201/main/kotlin/org/rust/debugger/runconfig/RsDebugAdvertisingRunner.kt

diff --git a/src/201/main/kotlin/org/rust/debugger/runconfig/RsDebugAdvertisingRunner.kt b/src/201/main/kotlin/org/rust/debugger/runconfig/RsDebugAdvertisingRunner.kt
index 915509461..7cd0ecef8 100644
--- a/src/201/main/kotlin/org/rust/debugger/runconfig/RsDebugAdvertisingRunner.kt
+++ b/src/201/main/kotlin/org/rust/debugger/runconfig/RsDebugAdvertisingRunner.kt
@@ -22,11 +22,13 @@ import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.PluginsAdve
 import com.intellij.openapi.util.SystemInfo
 import com.intellij.util.PlatformUtils
 import org.rust.cargo.runconfig.RsDefaultProgramRunnerBase
+import org.rust.cargo.runconfig.command.CargoCommandConfiguration
 
 class RsDebugAdvertisingRunner : RsDefaultProgramRunnerBase() {
 
     override fun canRun(executorId: String, profile: RunProfile): Boolean {
         if (executorId != DefaultDebugExecutor.EXECUTOR_ID) return false
+        if (profile !is CargoCommandConfiguration) return false
         if (!(SystemInfo.isMac || SystemInfo.isLinux)) return false
         if (!(PlatformUtils.isIdeaUltimate() || PlatformUtils.isRubyMine())) return false
         val id = PluginId.getId(NATIVE_DEBUG_PLUGIN_ID)
Repository: intellij-rust/intellij-rust
Issue: False positive `Lift return` inspection on empty match

## Environment

* **IntelliJ Rust plugin version:** 0.2.124.3122-201-nightly
* **Rust toolchain version:** 1.43.1 (8d69840ab 2020-05-04) x86_64-apple-darwin
* **IDE name and version:** IntelliJ IDEA 2020.1.1 Ultimate Edition (IU-201.7223.91)
* **Operating system:** macOS 10.15.3

## Problem description
`Lift return out of 'match'` inspection suggests wrong quick-fix on an empty match.

It transforms the following code
```Rust
fn foo() {
    match/*caret*/ true { // `Lift return` is available
    }
    let x = 1;
}
```
into
```Rust
fn foo() {
    return match/*caret*/ true {} // `Lift return` is available again but does nothing
    let x = 1;
}
```

Changed files:
src/test/kotlin/org/rust/ide/inspections/RsLiftInspectionTest.kt, src/main/kotlin/org/rust/ide/inspections/RsLiftInspection.kt

diff --git a/src/main/kotlin/org/rust/ide/inspections/RsLiftInspection.kt b/src/main/kotlin/org/rust/ide/inspections/RsLiftInspection.kt
index 6291ed931..140e6a10b 100644
--- a/src/main/kotlin/org/rust/ide/inspections/RsLiftInspection.kt
+++ b/src/main/kotlin/org/rust/ide/inspections/RsLiftInspection.kt
@@ -101,6 +101,7 @@ private fun RsExpr.getFoldableReturns(): List<FoldableElement>? {
             }
             is RsMatchExpr -> {
                 val arms = matchBody?.matchArmList ?: return false
+                if (arms.isEmpty()) return false
                 for (arm in arms) {
                     if (arm.expr?.collectFoldableReturns() != true) return false
                 }
diff --git a/src/test/kotlin/org/rust/ide/inspections/RsLiftInspectionTest.kt b/src/test/kotlin/org/rust/ide/inspections/RsLiftInspectionTest.kt
index 44406a9f2..ff2cf4b8b 100644
--- a/src/test/kotlin/org/rust/ide/inspections/RsLiftInspectionTest.kt
+++ b/src/test/kotlin/org/rust/ide/inspections/RsLiftInspectionTest.kt
@@ -233,4 +233,12 @@ class RsLiftInspectionTest : RsInspectionsTestBase(RsLiftInspection::class) {
             }
         }
     """, checkWeakWarn = true)
+
+    fun `test lift return in empty match unavailable`() = checkFixIsUnavailable("Lift return out of 'match'", """
+        fn foo() {
+            match/*caret*/ true {
+            }
+            let x = 1;
+        }
+    """, checkWeakWarn = true)
 }
Repository: intellij-rust/intellij-rust
Issue: Irrefutable let pattern on const pattern 

<!--
Hello and thank you for the issue!
If you would like to report a bug, we have added some points below that you can fill out.
Feel free to remove all the irrelevant text to request a new feature.
-->

## Environment

* **Intellij-Rust plugin version:** v0.2.92.2116-183
* **Rust toolchain version:** rustc 1.32.0 (9fda7c223 2019-01-16)
* **IDE name and version:** CLion 2018.3.4
* **Operating system:** macOS 10.13.6

## Problem description

IntelliJ Rust incorrectly treats const pattern as irrefutable let pattern.

## Steps to reproduce

<!--
Please include as much of your codebase as needed to reproduce the error.
If the relevant files are large, please provide a link to a public repository or a [Gist](https://gist.github.com/).
-->

```rust
#[derive(PartialEq, Eq)]
struct S(usize);

const A: S = S(1);

fn main() {
    if let A = S(2) {
    }
}
```

Changed files:
src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt, src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt

diff --git a/src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt b/src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt
index 1bc3d067d..92501619e 100644
--- a/src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt
+++ b/src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt
@@ -39,7 +39,7 @@ private val RsPath.isIrrefutable: Boolean
 
 private val RsPatBinding.isIrrefutable: Boolean
     get() = when (reference.resolve()) {
-        is RsStructItem, is RsEnumVariant -> false
+        is RsStructItem, is RsEnumVariant, is RsConstant -> false
         else -> true
     }
 
diff --git a/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt b/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
index 898aabc23..10590b901 100644
--- a/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
+++ b/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
@@ -1476,4 +1476,16 @@ class RsErrorAnnotatorTest : RsAnnotatorTestBase(RsErrorAnnotator::class.java) {
             if let Unknown { x } = e {}
         }
     """)
+
+    /** Issue [#3410](https://github.com/intellij-rust/intellij-rust/issues/3410) */
+    @MockRustcVersion("1.32.0")
+    fun `test const pattern is not irrefutable`() = checkErrors("""
+        #[derive(PartialEq, Eq)]
+        struct S(usize);
+        const A: S = S(1);
+
+        fn main() {
+            if let A = S(2) {}
+        }
+        """)
 }
Repository: intellij-rust/intellij-rust
Issue: Irrefutable let pattern is experimental on valid code

## Environment

* **Intellij-Rust plugin version:** v0.2.92.2545-183-nightly
* **Rust toolchain version:** stable-2019-01-17
* **IDE name and version:** CLion 2018.3
* **Operating system:** Debian

## Problem description
Intellij-Rust complains about valid Rust code.

## Steps to reproduce
```rust
enum A {
    B { x: String, },
    C,
}

fn fun1(a: A) {
    if let A::B { x } = a {
        
    }
}
```
Error is highlighed at `A::B { x }`:
> irrefutable let pattern is experimental [E0658] 

Changed files:
src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt, src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt

diff --git a/src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt b/src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt
index db430c1fb..8c76b5567 100644
--- a/src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt
+++ b/src/main/kotlin/org/rust/lang/core/psi/ext/RsPat.kt
@@ -15,7 +15,14 @@ val RsPat.isIrrefutable: Boolean
         is RsPatTup -> patList.all { it.isIrrefutable }
         is RsPatBox -> pat.isIrrefutable
         is RsPatRef -> pat.isIrrefutable
-        is RsPatStruct -> patFieldList.all { it.pat?.isIrrefutable ?: (it.patBinding != null) }
+        is RsPatStruct -> {
+            val canBeIrrefutable = when (val item = path.reference.resolve()) {
+                is RsStructItem -> true
+                is RsEnumVariant -> item.parentEnum.enumBody?.enumVariantList?.size == 1
+                else -> false
+            }
+            canBeIrrefutable && patFieldList.all { it.pat?.isIrrefutable ?: (it.patBinding != null) }
+        }
         is RsPatConst, is RsPatRange -> false
         else -> true
     }
diff --git a/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt b/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
index f72ff3aee..493b15add 100644
--- a/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
+++ b/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
@@ -1440,4 +1440,22 @@ class RsErrorAnnotatorTest : RsAnnotatorTestBase(RsErrorAnnotator::class.java) {
             while let x = 42 {}
         }
     """)
+
+    @MockRustcVersion("1.31.0")
+    fun `test irrefutable let pattern E0658 for struct literals`() = checkErrors("""
+        struct S { x: i32 }
+        enum E1 {
+            V { x: i32 }
+        }
+        enum E2 {
+            A,
+            V { x: i32 }
+        }
+        fn foo(a: S, b: E1, c: E2, d: Unknown) {
+            if let <error descr="irrefutable let pattern is experimental [E0658]">S { x }</error> = a {}
+            if let <error descr="irrefutable let pattern is experimental [E0658]">E1::V { x }</error> = b {}
+            if let E2::V { x } = c {}
+            if let Unknown { x } = d {}
+        }
+    """)
 }
Repository: intellij-rust/intellij-rust
Issue: Issues with seeing variables in Debug

## Environment

* **Intellij-Rust plugin version:** v0.2.0.2113-183
* **Rust toolchain version:** 1.31.1
* **IDE name and version:** CLion 2018.3.2
* **Operating system:** Ubuntu 18.04, Linux 4.15.18-041518-generic

## Problem description
When I debug code a lot of time when it gets into a function I can't see any of the variables, I see only `Duplicate variable object name`

## Steps to reproduce
Just try to debug any big project.


Changed files:
debugger/src/main/kotlin/org/rust/debugger/lang/RsDebuggerTypesHelper.kt

diff --git a/debugger/src/main/kotlin/org/rust/debugger/lang/RsDebuggerTypesHelper.kt b/debugger/src/main/kotlin/org/rust/debugger/lang/RsDebuggerTypesHelper.kt
index 2963b1920..ec05ea078 100644
--- a/debugger/src/main/kotlin/org/rust/debugger/lang/RsDebuggerTypesHelper.kt
+++ b/debugger/src/main/kotlin/org/rust/debugger/lang/RsDebuggerTypesHelper.kt
@@ -12,10 +12,10 @@ import com.jetbrains.cidr.execution.debugger.CidrDebugProcess
 import com.jetbrains.cidr.execution.debugger.backend.LLValue
 import com.jetbrains.cidr.execution.debugger.evaluation.CidrDebuggerTypesHelper
 import com.jetbrains.cidr.execution.debugger.evaluation.CidrMemberValue
-import org.rust.lang.core.psi.RsCodeFragmentFactory
 import org.rust.lang.core.psi.ext.RsElement
 import org.rust.lang.core.psi.ext.ancestorOrSelf
-import org.rust.lang.core.psi.ext.getNextNonCommentSibling
+import org.rust.lang.core.resolve.VALUES
+import org.rust.lang.core.resolve.processNestedScopesUpwards
 
 class RsDebuggerTypesHelper(process: CidrDebugProcess) : CidrDebuggerTypesHelper(process) {
     override fun createReferenceFromText(`var`: LLValue, context: PsiElement): PsiReference? = null
@@ -33,10 +33,17 @@ class RsDebuggerTypesHelper(process: CidrDebugProcess) : CidrDebuggerTypesHelper
 }
 
 private fun resolveToDeclaration(ctx: PsiElement?, name: String): PsiElement? {
-    val composite = ctx?.getNextNonCommentSibling()?.ancestorOrSelf<RsElement>()
-        ?: return null
-    val path = RsCodeFragmentFactory(composite.project).createPath(name, composite)
-        ?: return null
-
-    return path.reference.resolve()
+    val composite = ctx?.ancestorOrSelf<RsElement>() ?: return null
+
+    var resolved: PsiElement? = null
+    processNestedScopesUpwards(composite, { entry ->
+        if (entry.name == name) {
+            resolved = entry.element
+            true
+        } else {
+            false
+        }
+    }, VALUES)
+
+    return resolved
 }
Repository: intellij-rust/intellij-rust
Issue: RsRenameProcessor shouldn't accept elements from other languages

* **Intellij-Rust plugin version:** v0.2.95.2120-191
* **IDE name and version**: Intellij IDEA Ultimate 2019.1

RsRenameProcessor shouldn't accept elements from other languages [here](https://github.com/intellij-rust/intellij-rust/blob/1409910b8f28133bc1d03c0ca2bfda7ea9a6e48a/src/main/kotlin/org/rust/ide/refactoring/RsRenameProcessor.kt#L18):
```
override fun canProcessElement(element: PsiElement): Boolean = element !is RsTupleFieldDecl
```

RenameProcessors should return true from `canProcessElement` only for elements that they can rename, otherwise chaos ensues. The platform picks the first available processor in `com.intellij.refactoring.rename.RenamePsiElementProcessor#forElement`.
Other processors can have language-specific logic like collecting implementors/inheriors for their language-specific elements.

Currently, having the rust plugin enabled causes invalid rename in JS because `com.intellij.lang.javascript.refactoring.JSDefaultRenameProcessor` has custom logic related to JS properties:

```js
//JS
const userId = 'john'; //rename 'userId here'
const response = { userId };
```
Expected:
```js
//JS
const johnId = 'john';
const response = { userId: johnId };
```

A user found that the problem is caused by the Rust plugin: https://jbs.zendesk.com/agent/tickets/2035133
A similar issue is not reproducible for me with Java-specific rename features, probably because processors from intellij-community are somehow ordered before plugins, but order between different plugins is not determined.

Changed files:
src/main/kotlin/org/rust/ide/refactoring/RsRenameProcessor.kt

diff --git a/src/main/kotlin/org/rust/ide/refactoring/RsRenameProcessor.kt b/src/main/kotlin/org/rust/ide/refactoring/RsRenameProcessor.kt
index ed00c66b8..fd3230ae7 100644
--- a/src/main/kotlin/org/rust/ide/refactoring/RsRenameProcessor.kt
+++ b/src/main/kotlin/org/rust/ide/refactoring/RsRenameProcessor.kt
@@ -10,12 +10,15 @@ import com.intellij.openapi.util.Pass
 import com.intellij.psi.PsiElement
 import com.intellij.psi.search.SearchScope
 import com.intellij.refactoring.rename.RenamePsiElementProcessor
-import org.rust.lang.core.psi.*
+import org.rust.lang.core.psi.RsLabel
+import org.rust.lang.core.psi.RsLabelDecl
+import org.rust.lang.core.psi.RsLifetime
+import org.rust.lang.core.psi.RsLifetimeParameter
 import org.rust.lang.core.psi.ext.*
 
 class RsRenameProcessor : RenamePsiElementProcessor() {
 
-    override fun canProcessElement(element: PsiElement): Boolean = element !is RsTupleFieldDecl
+    override fun canProcessElement(element: PsiElement): Boolean = element is RsNamedElement
 
     override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope) {
         if (element is RsLifetime || element is RsLifetimeParameter || element is RsLabel || element is RsLabelDecl) {
Repository: intellij-rust/intellij-rust
Issue: False-positive error when returning in async block

The following code is valid Rust, but in the IDE the `return` keyword shows an error:

```rust
#![feature(async_await)]

pub fn foo() -> i32 {
    let _ = async {
        return; // `return;` in a function whose return type is not `()`
    };

    0
}
```

## Environment

* **Intellij-Rust plugin version:** 0.2.97.4975-191
* **Rust toolchain version:** rustc 1.36.0-nightly (7d5aa4332 2019-05-16)
* **IDE name and version:** CLion 2019.1.2
* **Operating system:** Windows 10 x64

Changed files:
src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt, src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt

diff --git a/src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt b/src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt
index 2be75e532..409926278 100644
--- a/src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt
+++ b/src/main/kotlin/org/rust/ide/annotator/RsErrorAnnotator.kt
@@ -455,7 +455,9 @@ class RsErrorAnnotator : RsAnnotatorBase(), HighlightRangeExtension {
 
     private fun checkRetExpr(holder: AnnotationHolder, ret: RsRetExpr) {
         if (ret.expr != null) return
-        val fn = ret.ancestors.find { it is RsFunction || it is RsLambdaExpr } as? RsFunction ?: return
+        val fn = ret.ancestors.find {
+            it is RsFunction || it is RsLambdaExpr || it is RsBlockExpr && it.isAsync
+        } as? RsFunction ?: return
         val retType = fn.retType?.typeReference?.type ?: return
         if (retType is TyUnit) return
         RsDiagnostic.ReturnMustHaveValueError(ret).addToHolder(holder)
diff --git a/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt b/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
index d993b22bd..6663d08e5 100644
--- a/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
+++ b/src/test/kotlin/org/rust/ide/annotator/RsErrorAnnotatorTest.kt
@@ -285,6 +285,10 @@ class RsErrorAnnotatorTest : RsAnnotatorTestBase(RsErrorAnnotator::class.java) {
             let _ = || return;
             return 10
         }
+        fn ok4() -> u32 {
+            let _ = async { return; };
+            return 10
+        }
 
         fn err1() -> bool {
             <error descr="`return;` in a function whose return type is not `()` [E0069]">return</error>;
Repository: intellij-rust/intellij-rust
Issue: Non-public fields aren't shown in completion in nested modules

This should complete to `field` but completes to nothing
```rust
mod foo {
    pub struct S {
        field: i32
    }

    fn bar(s: S) {
        s./*caret*/
    }
}
```

Changed files:
src/main/kotlin/org/rust/lang/core/completion/RsCommonCompletionProvider.kt, src/test/kotlin/org/rust/lang/core/completion/RsCompletionFilteringTest.kt

diff --git a/src/main/kotlin/org/rust/lang/core/completion/RsCommonCompletionProvider.kt b/src/main/kotlin/org/rust/lang/core/completion/RsCommonCompletionProvider.kt
index 024af6dba..33136265f 100644
--- a/src/main/kotlin/org/rust/lang/core/completion/RsCommonCompletionProvider.kt
+++ b/src/main/kotlin/org/rust/lang/core/completion/RsCommonCompletionProvider.kt
@@ -98,8 +98,9 @@ object RsCommonCompletionProvider : CompletionProvider<CompletionParameters>() {
         result: CompletionResultSet,
         forSimplePath: Boolean
     ) {
-        val lookup = ImplLookup.relativeTo(element)
-        val receiver = CompletionUtil.getOriginalOrSelf(element.receiver).type
+        val receiver = CompletionUtil.getOriginalOrSelf(element.receiver)
+        val lookup = ImplLookup.relativeTo(receiver)
+        val receiverTy = receiver.type
         val processResolveVariants = if (element is RsMethodCall) {
             ::processMethodCallExprResolveVariants
         } else {
@@ -109,10 +110,10 @@ object RsCommonCompletionProvider : CompletionProvider<CompletionParameters>() {
 
         processResolveVariants(
             lookup,
-            receiver,
+            receiverTy,
             filterCompletionVariantsByVisibility(
-                filterMethodCompletionVariantsByTraitBounds(processor, lookup, receiver),
-                element.containingMod
+                filterMethodCompletionVariantsByTraitBounds(processor, lookup, receiverTy),
+                receiver.containingMod
             )
         )
     }
diff --git a/src/test/kotlin/org/rust/lang/core/completion/RsCompletionFilteringTest.kt b/src/test/kotlin/org/rust/lang/core/completion/RsCompletionFilteringTest.kt
index 37123d3a4..bf321ba74 100644
--- a/src/test/kotlin/org/rust/lang/core/completion/RsCompletionFilteringTest.kt
+++ b/src/test/kotlin/org/rust/lang/core/completion/RsCompletionFilteringTest.kt
@@ -162,6 +162,23 @@ class RsCompletionFilteringTest: RsCompletionTestBase() {
         }
     """)
 
+    // Issue https://github.com/intellij-rust/intellij-rust/issues/3694
+    fun `test issue 3694`() = doSingleCompletion("""
+        mod foo {
+            pub struct S { field: i32 }
+            fn bar(s: S) {
+                s./*caret*/
+            }
+        }
+    """, """
+        mod foo {
+            pub struct S { field: i32 }
+            fn bar(s: S) {
+                s.field/*caret*/
+            }
+        }
+    """)
+
     fun `test doc(hidden) item`() = checkNoCompletion("""
         mod foo {
             #[doc(hidden)]
Repository: intellij-rust/intellij-rust
Issue: Invalid "mismatched types error" when matching references

<!--
Hello and thank you for the issue!
If you would like to report a bug, we have added some points below that you can fill out.
Feel free to remove all the irrelevant text to request a new feature.
-->

## Environment

* **Intellij-Rust plugin version:** 0.2.0.2100-181 (Changelog 78)
* **IDE name and version:** 2018.1.6 
* **Operating system:** Windows 10 64bit

## Problem description
When matching any references, there is a mismatched type error stating that it is expecting the referenced version of the type. This sort of makes sense in most cases, however, when trying to match &str, this shows some ridiculous errors

## Steps to reproduce

Simplest case

    match "abcd" {
        "abcd" => {}, // This line would be underlined in red "expected `str`, found `&str`"
        _ => {}
    }

A more practical example would be:
```
let args: Vec<&str> = args_string.split(' ').collect();
match args[0] {
    "connect" => {}  // This line would be underlined in red "expected `str`, found `&str`"
    _ => {}
}
```


Changed files:
src/main/kotlin/org/rust/lang/core/types/infer/PatternMatching.kt, src/test/kotlin/org/rust/ide/inspections/RsTypeCheckInspectionTest.kt

diff --git a/src/main/kotlin/org/rust/lang/core/types/infer/PatternMatching.kt b/src/main/kotlin/org/rust/lang/core/types/infer/PatternMatching.kt
index 409f01cf6..976ab6c0c 100644
--- a/src/main/kotlin/org/rust/lang/core/types/infer/PatternMatching.kt
+++ b/src/main/kotlin/org/rust/lang/core/types/infer/PatternMatching.kt
@@ -15,8 +15,12 @@ fun RsPat.extractBindings(fcx: RsFnInferenceContext, type: Ty, ignoreRef: Boolea
     when (this) {
         is RsPatWild -> {}
         is RsPatConst -> {
-            val (derefTy, _) = type.stripReferences()
-            fcx.inferTypeCoercableTo(expr, derefTy)
+            val expr = expr
+            val expectedTy = when {
+                expr is RsLitExpr && expr.kind is RsLiteralKind.String -> type
+                else -> type.stripReferences().first
+            }
+            fcx.inferTypeCoercableTo(expr, expectedTy)
         }
         is RsPatRef -> {
             pat.extractBindings(fcx, (type as? TyReference)?.referenced ?: TyUnknown)
diff --git a/src/test/kotlin/org/rust/ide/inspections/RsTypeCheckInspectionTest.kt b/src/test/kotlin/org/rust/ide/inspections/RsTypeCheckInspectionTest.kt
index 5720908e6..a2b0989fa 100644
--- a/src/test/kotlin/org/rust/ide/inspections/RsTypeCheckInspectionTest.kt
+++ b/src/test/kotlin/org/rust/ide/inspections/RsTypeCheckInspectionTest.kt
@@ -140,4 +140,14 @@ class RsTypeCheckInspectionTest : RsInspectionsTestBase(RsTypeCheckInspection())
             let _: RefWrapper<u32> = RefWrapper(w);
         }
     """)
+
+    // issue 2670
+    fun `test no type mismatch E0308 when matching with string literal`() = checkByText("""
+        fn main() {
+            match "" {
+                "" => {}
+                _ => {}
+            }
+        }
+    """)
 }
Repository: intellij-rust/intellij-rust
Issue: Types of variables from a tuple are not recognized after unwrap()

Create an Optional or Result with a tuple. After unwrapping it into variables with unwrap(), their types will be displayed as `<unknown>`.

Example:
```rust
let a: Option<(i32, i32)> = Some((0, 0));
let (b, c) = a.unwrap();
```
`b` and `c` will be displayed as `<unknown>` instead of `i32`.


IDE and plugin:
intellij-rust 0.2.0.2234-nightly
IntelliJ IDEA 2017.3.1 (Community Edition)
Build #IC-173.3942.27, built on December 11, 2017

Changed files:
src/test/kotlin/org/rust/lang/core/type/RsGenericExpressionTypeInferenceTest.kt, src/main/kotlin/org/rust/lang/core/types/infer/TypeInference.kt

diff --git a/src/main/kotlin/org/rust/lang/core/types/infer/TypeInference.kt b/src/main/kotlin/org/rust/lang/core/types/infer/TypeInference.kt
index 0bb0101c1..2028b12e7 100644
--- a/src/main/kotlin/org/rust/lang/core/types/infer/TypeInference.kt
+++ b/src/main/kotlin/org/rust/lang/core/types/infer/TypeInference.kt
@@ -460,7 +460,7 @@ private class RsFnInferenceContext(
                 ?.let { psi.expr?.inferTypeCoercableTo(it) }
                 ?: psi.expr?.inferType()
                 ?: TyUnknown
-            psi.pat?.extractBindings(explicitTy ?: inferredTy)
+            psi.pat?.extractBindings(explicitTy ?: resolveTypeVarsWithObligations(inferredTy))
             inferredTy == TyNever
         }
         is RsExprStmt -> psi.expr.inferType() == TyNever
@@ -1043,7 +1043,7 @@ private class RsFnInferenceContext(
     }
 
     private fun inferMatchExprType(expr: RsMatchExpr, expected: Ty?): Ty {
-        val matchingExprTy = expr.expr?.inferType() ?: TyUnknown
+        val matchingExprTy = resolveTypeVarsWithObligations(expr.expr?.inferType() ?: TyUnknown)
         val arms = expr.matchBody?.matchArmList.orEmpty()
         for (arm in arms) {
             for (pat in arm.patList) {
diff --git a/src/test/kotlin/org/rust/lang/core/type/RsGenericExpressionTypeInferenceTest.kt b/src/test/kotlin/org/rust/lang/core/type/RsGenericExpressionTypeInferenceTest.kt
index b025a1d13..4a92c8a32 100644
--- a/src/test/kotlin/org/rust/lang/core/type/RsGenericExpressionTypeInferenceTest.kt
+++ b/src/test/kotlin/org/rust/lang/core/type/RsGenericExpressionTypeInferenceTest.kt
@@ -1304,4 +1304,24 @@ class RsGenericExpressionTypeInferenceTest : RsTypificationTestBase() {
             let _: RefWrapper<u8> = A.ref_wrapper(&Wrapper(0));
         }                                                //^ u8
     """)
+
+    fun `test type variable resolved for let pattern matching`() = testExpr("""
+        struct X;
+        fn foo<T>(_: T) -> T { unimplemented!() }
+        fn main () {
+            let (a,) = foo((X,));
+            a;
+        } //^ X
+    """)
+
+    fun `test type variable resolved for pattern matching`() = testExpr("""
+        struct X;
+        fn foo<T>(_: T) -> T { unimplemented!() }
+        fn main () {
+            match foo((X,)) {
+                (a,) => { a; }
+                _ => {} //^ X
+            }
+        }
+    """)
 }
Repository: intellij-rust/intellij-rust
Issue: Glob imports after self don't work

Here's a test case that should work, but currently fails.

```rust
mod m {
    pub enum A { X }
}              //X

use m::A::{self, *};

fn main() {
    let a: A = X;
}            //^
```

Changed files:
src/main/kotlin/org/rust/lang/core/resolve/ItemResolution.kt, src/test/kotlin/org/rust/lang/core/resolve/RsUseResolveTest.kt

diff --git a/src/main/kotlin/org/rust/lang/core/resolve/ItemResolution.kt b/src/main/kotlin/org/rust/lang/core/resolve/ItemResolution.kt
index bfd4729fa..db88bd899 100644
--- a/src/main/kotlin/org/rust/lang/core/resolve/ItemResolution.kt
+++ b/src/main/kotlin/org/rust/lang/core/resolve/ItemResolution.kt
@@ -116,7 +116,16 @@ fun processItemDeclarations(
         return false
     }
     for (speck in starImports) {
-        val basePath = speck.path
+        val path = speck.path
+        val basePath = if (path == null && speck.context is RsUseGroup) {
+            // `use foo::bar::{self, *}`
+            //           ~~~
+            speck.qualifier
+        } else {
+            // `use foo::bar::*` or `use foo::{self, bar::*}`
+            //           ~~~                         ~~~
+            path
+        }
         val mod = (if (basePath != null) basePath.reference.resolve() else speck.crateRoot)
             ?: continue
 
diff --git a/src/test/kotlin/org/rust/lang/core/resolve/RsUseResolveTest.kt b/src/test/kotlin/org/rust/lang/core/resolve/RsUseResolveTest.kt
index be3b44765..ddd9d6e29 100644
--- a/src/test/kotlin/org/rust/lang/core/resolve/RsUseResolveTest.kt
+++ b/src/test/kotlin/org/rust/lang/core/resolve/RsUseResolveTest.kt
@@ -559,4 +559,16 @@ class RsUseResolveTest : RsResolveTestBase() {
         use self::m::E::foo;
                         //^ unresolved
     """)
+
+    fun `test wildcard in braces`() = checkByCode("""
+        mod m {
+            pub enum A { X }
+        }              //X
+
+        use m::A::{self, *};
+
+        fn main() {
+            let a: A = X;
+        }            //^
+    """)
 }
Repository: intellij-rust/intellij-rust
Issue: Inactive "Refresh Cargo project" button

<!--
Hello and thank you for the issue!
If you would like to report a bug, we have added some points below that you can fill out.
Feel free to remove all the irrelevant text to request a new feature.
-->

## Environment

* **Intellij-Rust plugin version:** 0.2.0.2111-183
* **Rust toolchain version:** stable-x86_64-pc-windows-gnu v1.31.0
* **IDE name and version:** CLion 2018.3.1
* **Operating system:** Windows 10 x64 Update 1809

## Problem description
Inactive "Refresh Cargo project" button

## Steps to reproduce

<!--
Please include as much of your codebase as needed to reproduce the error.
If the relevant files are large, please provide a link to a public repository or a [Gist](https://gist.github.com/).
-->
* Create Rust project
* Open "Cargo" tab
* Now you can see this button


Changed files:
src/main/kotlin/org/rust/ide/actions/RefreshCargoProjectAction.kt

diff --git a/src/main/kotlin/org/rust/ide/actions/RefreshCargoProjectAction.kt b/src/main/kotlin/org/rust/ide/actions/RefreshCargoProjectAction.kt
index 325b57ce2..3b714340b 100644
--- a/src/main/kotlin/org/rust/ide/actions/RefreshCargoProjectAction.kt
+++ b/src/main/kotlin/org/rust/ide/actions/RefreshCargoProjectAction.kt
@@ -21,9 +21,7 @@ class RefreshCargoProjectAction : CargoProjectActionBase() {
 
     override fun update(e: AnActionEvent) {
         val project = e.project
-        if (project == null || project.toolchain == null || !project.hasCargoProject) {
-            e.presentation.isEnabled = false
-        }
+        e.presentation.isEnabled = project != null && project.toolchain != null && project.hasCargoProject
     }
 
     override fun actionPerformed(e: AnActionEvent) {
Repository: intellij-rust/intellij-rust
Issue: False positive "Cannot move"

<!--
Hello and thank you for the issue!
If you would like to report a bug, we have added some points below that you can fill out.
Feel free to remove all the irrelevant text to request a new feature.
-->

## Environment

* **Intellij-Rust plugin version: 0.2.0.2110-182**
* **Rust toolchain version: stable-x86_64-apple-darwin - rustc 1.30.1 (1433507eb 2018-11-07)**
* **IDE name and version: IntelliJ IDEA 2018.2.6 (Ultimate Edition)**
* **Operating system: macOS Mojave 10.14.1**

## Problem description
There is a false positive if you want to dereference a `Copy` type in a generic trait implementation that takes `self` by reference. However since `Self` implements `Copy` this is perfectly valid and compiles fine.

## Steps to reproduce
```rust
trait Dummy where Self: Copy {
    fn dummy(&self) -> Self {
        *self // ← This shows the error "Cannot move" ("Inspection info: Implements simple cases of borrow checking.")
    }
}
```

Changed files:
src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt, src/test/kotlin/org/rust/ide/inspections/borrowck/RsBorrowCheckerMovesTest.kt

diff --git a/src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt b/src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt
index 79fb2fc4c..1c4fc80a2 100644
--- a/src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt
+++ b/src/main/kotlin/org/rust/lang/core/types/ty/Ty.kt
@@ -151,11 +151,16 @@ fun Ty.builtinDeref(explicit: Boolean = true): Pair<Ty, Mutability>? =
         else -> null
     }
 
-// TODO
+/**
+ * TODO:
+ * There are some problems with `Self` inference (e.g. https://github.com/intellij-rust/intellij-rust/issues/2530)
+ * so for now just assume `Self` is always copyable
+ */
 fun Ty.isMovesByDefault(lookup: ImplLookup): Boolean =
     when (this) {
         is TyUnknown, is TyReference, is TyPointer, is TyFunction -> false
         is TyTuple -> types.any { it.isMovesByDefault(lookup) }
+        is TyTypeParameter -> parameter != TyTypeParameter.Self
         else -> lookup.isCopy(this).not()
     }
 
diff --git a/src/test/kotlin/org/rust/ide/inspections/borrowck/RsBorrowCheckerMovesTest.kt b/src/test/kotlin/org/rust/ide/inspections/borrowck/RsBorrowCheckerMovesTest.kt
index 90e4dd379..2fdc09f65 100644
--- a/src/test/kotlin/org/rust/ide/inspections/borrowck/RsBorrowCheckerMovesTest.kt
+++ b/src/test/kotlin/org/rust/ide/inspections/borrowck/RsBorrowCheckerMovesTest.kt
@@ -259,4 +259,14 @@ class RsBorrowCheckerMovesTest : RsInspectionsTestBase(RsBorrowCheckerInspection
             let (b, c) = *Box::new((S, S));
         }
     """, checkWarn = false)
+
+    /** Issue [#3062](https://github.com/intellij-rust/intellij-rust/issues/3062) */
+    @ProjectDescriptor(WithStdlibRustProjectDescriptor::class)
+    fun `test no move error E0507 when deref copyable self`() = checkByText("""
+        trait Dummy where Self: Copy {
+            fn dummy(&self) -> Self {
+                *self
+            }
+        }
+    """, checkWarn = false)
 }