Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add suggest mut method for loop #81466

Merged

Conversation

sasurau4
Copy link
Contributor

Part of #49839

This PR focus on the comment case

@rust-highfive
Copy link
Collaborator

r? @davidtwco

(rust-highfive has picked a reviewer for you, use r? to override)

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jan 28, 2021
@sasurau4 sasurau4 force-pushed the fix/enhance-sugget-mut-method-for-loop branch from 3024a14 to f66f94a Compare January 28, 2021 09:24
@rust-log-analyzer
Copy link
Collaborator

The job x86_64-gnu-llvm-9 failed! Check out the build log: (web) (plain)

Click to see the possible cause of the failure (guessed by this bot)
Successfully built 5b885f7944c6
Successfully tagged rust-ci:latest
Built container sha256:5b885f7944c6d0342cc43cdbd262399a7b326ebab62bcab4dad9f0c47d9884a9
Uploading finished image to https://ci-caches.rust-lang.org/docker/1c72b7d037d305d35e0735812f08df148b36d5d74ee11961d19c0c3224e3b4bbf04ff3ebce61c1c56645202b549f50aac19493c18cafdab069ba5b3de9c503bb
upload failed: - to s3://rust-lang-ci-sccache2/docker/1c72b7d037d305d35e0735812f08df148b36d5d74ee11961d19c0c3224e3b4bbf04ff3ebce61c1c56645202b549f50aac19493c18cafdab069ba5b3de9c503bb Unable to locate credentials
[CI_JOB_NAME=x86_64-gnu-llvm-9]
---
..................................................................................i.i............... 11200/11292
............................................................................................
failures:

---- [ui] ui/suggestions/suggest-mut-method-for-loop.rs stdout ----


1 error[E0594]: cannot assign to `t.v` which is behind a `&` reference
-   --> $DIR/suggest-mut-method-for-loop.rs:15:9
+   --> $DIR/suggest-mut-method-for-loop.rs:14:9
3    |
4 LL |     for mut t in buzz.values() {


The actual stderr differed from the expected stderr.
The actual stderr differed from the expected stderr.
Actual stderr saved to /checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/suggestions/suggest-mut-method-for-loop/suggest-mut-method-for-loop.stderr
To update references, rerun the tests and pass the `--bless` flag
To only update this specific test, also pass `--test-args suggestions/suggest-mut-method-for-loop.rs`
error: 1 errors occurred comparing output.
status: exit code: 1
status: exit code: 1
command: "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/bin/rustc" "/checkout/src/test/ui/suggestions/suggest-mut-method-for-loop.rs" "-Zthreads=1" "--target=x86_64-unknown-linux-gnu" "--error-format" "json" "-Zui-testing" "-Zdeduplicate-diagnostics=no" "-Zemit-future-incompat-report" "--emit" "metadata" "-C" "prefer-dynamic" "--out-dir" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/suggestions/suggest-mut-method-for-loop" "-A" "unused" "-Crpath" "-O" "-Cdebuginfo=0" "-Zunstable-options" "-Lnative=/checkout/obj/build/x86_64-unknown-linux-gnu/native/rust-test-helpers" "-L" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/suggestions/suggest-mut-method-for-loop/auxiliary"
------------------------------------------

------------------------------------------
stderr:
stderr:
------------------------------------------
error[E0594]: cannot assign to `t.v` which is behind a `&` reference
  --> /checkout/src/test/ui/suggestions/suggest-mut-method-for-loop.rs:14:9
Some tests failed in compiletest suite=ui mode=ui host=x86_64-unknown-linux-gnu target=x86_64-unknown-linux-gnu
Some tests failed in compiletest suite=ui mode=ui host=x86_64-unknown-linux-gnu target=x86_64-unknown-linux-gnu
LL |     for mut t in buzz.values() {
   |                  |    |
   |                  |    |
   |                  |    help: use mutable method: `values_mut()`
   |                  this iterator yields `&` references
...
LL |         t.v += 1;
   |         ^^^^^^^^ `t` is a `&` reference, so the data it refers to cannot be written
error: aborting due to previous error

For more information about this error, try `rustc --explain E0594`.

---
test result: FAILED. 11204 passed; 1 failed; 87 ignored; 0 measured; 0 filtered out; finished in 117.85s



command did not execute successfully: "/checkout/obj/build/x86_64-unknown-linux-gnu/stage0-tools-bin/compiletest" "--compile-lib-path" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib" "--run-lib-path" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/lib/rustlib/x86_64-unknown-linux-gnu/lib" "--rustc-path" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/bin/rustc" "--src-base" "/checkout/src/test/ui" "--build-base" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui" "--stage-id" "stage2-x86_64-unknown-linux-gnu" "--suite" "ui" "--mode" "ui" "--target" "x86_64-unknown-linux-gnu" "--host" "x86_64-unknown-linux-gnu" "--llvm-filecheck" "/usr/lib/llvm-9/bin/FileCheck" "--nodejs" "/usr/bin/node" "--host-rustcflags" "-Crpath -O -Cdebuginfo=0 -Zunstable-options  -Lnative=/checkout/obj/build/x86_64-unknown-linux-gnu/native/rust-test-helpers" "--target-rustcflags" "-Crpath -O -Cdebuginfo=0 -Zunstable-options  -Lnative=/checkout/obj/build/x86_64-unknown-linux-gnu/native/rust-test-helpers" "--docck-python" "/usr/bin/python3" "--lldb-python" "/usr/bin/python3" "--gdb" "/usr/bin/gdb" "--quiet" "--llvm-version" "9.0.0" "--llvm-components" "aarch64 aarch64asmparser aarch64codegen aarch64desc aarch64disassembler aarch64info aarch64utils aggressiveinstcombine all all-targets amdgpu amdgpuasmparser amdgpucodegen amdgpudesc amdgpudisassembler amdgpuinfo amdgpuutils analysis arm armasmparser armcodegen armdesc armdisassembler arminfo armutils asmparser asmprinter avr avrasmparser avrcodegen avrdesc avrdisassembler avrinfo binaryformat bitreader bitstreamreader bitwriter bpf bpfasmparser bpfcodegen bpfdesc bpfdisassembler bpfinfo codegen core coroutines coverage debuginfocodeview debuginfodwarf debuginfogsym debuginfomsf debuginfopdb demangle dlltooldriver engine executionengine fuzzmutate globalisel hexagon hexagonasmparser hexagoncodegen hexagondesc hexagondisassembler hexagoninfo instcombine instrumentation interpreter ipo irreader jitlink lanai lanaiasmparser lanaicodegen lanaidesc lanaidisassembler lanaiinfo libdriver lineeditor linker lto mc mca mcdisassembler mcjit mcparser mips mipsasmparser mipscodegen mipsdesc mipsdisassembler mipsinfo mirparser msp430 msp430asmparser msp430codegen msp430desc msp430disassembler msp430info native nativecodegen nvptx nvptxcodegen nvptxdesc nvptxinfo objcarcopts object objectyaml option orcjit passes perfjitevents powerpc powerpcasmparser powerpccodegen powerpcdesc powerpcdisassembler powerpcinfo profiledata remarks riscv riscvasmparser riscvcodegen riscvdesc riscvdisassembler riscvinfo riscvutils runtimedyld scalaropts selectiondag sparc sparcasmparser sparccodegen sparcdesc sparcdisassembler sparcinfo support symbolize systemz systemzasmparser systemzcodegen systemzdesc systemzdisassembler systemzinfo tablegen target textapi transformutils vectorize webassembly webassemblyasmparser webassemblycodegen webassemblydesc webassemblydisassembler webassemblyinfo windowsmanifest x86 x86asmparser x86codegen x86desc x86disassembler x86info x86utils xcore xcorecodegen xcoredesc xcoredisassembler xcoreinfo xray" "--system-llvm" "--cc" "" "--cxx" "" "--cflags" "" "--adb-path" "adb" "--adb-test-dir" "/data/tmp/work" "--android-cross-path" "" "--color" "always"


failed to run: /checkout/obj/build/bootstrap/debug/bootstrap --stage 2 test --exclude src/tools/tidy
Build completed unsuccessfully in 0:13:08

@sasurau4 sasurau4 force-pushed the fix/enhance-sugget-mut-method-for-loop branch from f66f94a to 9567192 Compare January 28, 2021 10:05
Comment on lines 473 to 481
if let hir::ItemKind::Fn(_, _, body_id) = node.kind {
let body = hir.body(body_id);
if let hir::ExprKind::Block(block, _) = body.value.kind {
if let Some(expr) = block.expr {
if let hir::ExprKind::DropTemps(expr) = expr.kind {
if let hir::ExprKind::Match(expr, ..) = expr.kind {
if let hir::ExprKind::Call(_, [expr, ..]) = expr.kind {
if let hir::ExprKind::MethodCall(path_segment, ..) = expr.kind {
if let Some(hir_id) = path_segment.hir_id {
Copy link
Contributor

Choose a reason for hiding this comment

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

I think it's time to use the if_chain crate in the compiler instead of just in clippy 😆

Copy link
Contributor

Choose a reason for hiding this comment

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

Heh, I did think about CCing you when I saw that xD

When playing around with it I came up with this. Still gnarly but at least it separates the actual code from taking the structure apart.

fn suggest_similar_mut_method_for_for_loop(&self, err: &mut DiagnosticBuilder<'_>) {
        let hir = self.infcx.tcx.hir();
        let node = hir.item(self.mir_hir_id());
        use hir::{
            Expr,
            ExprKind::{Block, Call, DropTemps, Match, MethodCall},
        };
        if let hir::ItemKind::Fn(_, _, body_id) = node.kind {
            if let Block(
                hir::Block {
                    expr:
                        Some(Expr {
                            kind:
                                DropTemps(Expr {
                                    kind:
                                        Match(
                                            Expr {
                                                kind:
                                                    Call(
                                                        _,
                                                        [Expr {
                                                            kind: MethodCall(path_segment, ..),
                                                            hir_id,
                                                            ..
                                                        }, ..],
                                                    ),
                                                ..
                                            },
                                            ..,
                                        ),
                                    ..
                                }),
                            ..
                        }),
                    ..
                },
                _,
            ) = hir.body(body_id).value.kind
            {
                let opt_suggestions = path_segment
                    .hir_id
                    .map(|path_hir_id| self.infcx.tcx.typeck(path_hir_id.owner))
                    .and_then(|typeck| typeck.type_dependent_def_id(*hir_id))
                    .and_then(|def_id| self.infcx.tcx.impl_of_method(def_id))
                    .map(|def_id| self.infcx.tcx.associated_items(def_id))
                    .map(|assoc_items| {
                        assoc_items
                            .in_definition_order()
                            .map(|assoc_item_def| assoc_item_def.ident)
                            .filter(|&ident| {
                                let original_method_ident = path_segment.ident;
                                original_method_ident != ident
                                    && ident
                                        .as_str()
                                        .starts_with(&original_method_ident.name.to_string())
                            })
                            .map(|ident| format!("{}()", ident))
                    });

                if let Some(suggestions) = opt_suggestions {
                    err.span_suggestions(
                        path_segment.ident.span,
                        &format!("use mutable method"),
                        suggestions,
                        Applicability::MaybeIncorrect,
                    );
                }
            }
        }
    }

Comment on lines 473 to 478
if let hir::ItemKind::Fn(_, _, body_id) = node.kind {
let body = hir.body(body_id);
if let hir::ExprKind::Block(block, _) = body.value.kind {
if let Some(expr) = block.expr {
if let hir::ExprKind::DropTemps(expr) = expr.kind {
if let hir::ExprKind::Match(expr, ..) = expr.kind {
Copy link
Contributor

Choose a reason for hiding this comment

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

I don't understand this part. Do we need to special case this suggestion to for loops? Or do other cases already work well?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No, we don't need to special case this suggestion in the future. But initially, this PR focuses on to suggest mutable method only for loop rhs method call.

Copy link
Contributor

Choose a reason for hiding this comment

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

ok, that makes sense. Please leave a comment explaining this in the source

@bors
Copy link
Contributor

bors commented Jan 29, 2021

☔ The latest upstream changes (presumably #81493) made this pull request unmergeable. Please resolve the merge conflicts.

buzz.insert("a", Y { v: 0 });

for mut t in buzz.values() {
//~^ HELP
Copy link
Contributor

Choose a reason for hiding this comment

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

How come this help is empty? This is also the first time I came across SUGGESTION.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I use this same as src/test/ui/suggestions/suggest-ref-mut.rs. In suggest-ref-mut, the help seems available to be empty.
The SUGGESTION is introduced by https://rustc-dev-guide.rust-lang.org/tests/adding.html#error-levels.

//~^ HELP
//~| SUGGESTION values_mut()
t.v += 1;
//~^ ERROR
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe we should have some key message here?

Copy link
Member

@davidtwco davidtwco left a comment

Choose a reason for hiding this comment

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

Implementation looks appropriate, I'd like to see the comments from other reviewers addressed, and, if feasible, an attempt to check that the method we're suggesting does produce mutable references. r=me after that.

});
err.span_suggestions(
path_segment.ident.span,
&format!("use mutable method"),
Copy link
Member

Choose a reason for hiding this comment

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

I'm surprised that we don't check that the methods we're suggesting are actually yielding mutable references. Is that something which is just too tricky to check here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This method called only here.
It seems we don't need to check.

Copy link
Member

Choose a reason for hiding this comment

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

Could you add a comment that documents this assumption?

@davidtwco davidtwco added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jan 30, 2021
@sasurau4 sasurau4 force-pushed the fix/enhance-sugget-mut-method-for-loop branch from 9567192 to 90c9b57 Compare February 5, 2021 13:12
@oli-obk
Copy link
Contributor

oli-obk commented Feb 9, 2021

@bors r+ rollup

@bors
Copy link
Contributor

bors commented Feb 9, 2021

📌 Commit 90c9b57 has been approved by oli-obk

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Feb 9, 2021
bors added a commit to rust-lang-ci/rust that referenced this pull request Feb 10, 2021
Rollup of 11 pull requests

Successful merges:

 - rust-lang#79849 (Clarify docs regarding sleep of zero duration)
 - rust-lang#80438 (Add `Box::into_inner`.)
 - rust-lang#81466 (Add suggest mut method for loop)
 - rust-lang#81687 (Make Vec::split_at_spare_mut public)
 - rust-lang#81904 (Bump stabilization version for const int methods)
 - rust-lang#81909 ([compiler/rustc_typeck/src/check/expr.rs] Remove unnecessary refs in pattern matching)
 - rust-lang#81910 (Use format string in bootstrap panic instead of a string directly)
 - rust-lang#81913 (Rename HIR UnOp variants)
 - rust-lang#81925 (Add long explanation for E0547)
 - rust-lang#81926 (add suggestion to use the `async_recursion` crate)
 - rust-lang#81951 (Update cargo)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors merged commit 3f09418 into rust-lang:master Feb 10, 2021
@rustbot rustbot added this to the 1.52.0 milestone Feb 10, 2021
@sasurau4 sasurau4 deleted the fix/enhance-sugget-mut-method-for-loop branch February 10, 2021 08:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

9 participants