Commit graph

17794 commits

Author SHA1 Message Date
bors
4932d05733 Auto merge of #11373 - Red-Rapious:master, r=blyxyas,y21
Added new lint: `reserve_after_initialization`

Closes https://github.com/rust-lang/rust-clippy/issues/11330.

A new lint that informs the user about a more concise way to create a vector with a known capacity.
Example:
```rust
let mut v: Vec<usize> = vec![];
v.reserve(10);
```

Produces the following help:
```rust
  |
2 | /     let mut v: Vec<usize> = vec![];
3 | |     v.reserve(10);
  | |__________________^ help: consider using `Vec::with_capacity(space_hint)`: `let v: Vec<usize> = Vec::with_capacity(10);`
  |
```

And can be rewritten as:
```rust
let v: Vec<usize> = Vec::with_capacity(10);
```

changelog: new lint [`reserve_after_initialization`]
2023-08-23 12:06:41 +00:00
Red Rapious
f3c5877302 Put is_from_proc_macro last 2023-08-23 13:46:12 +02:00
bors
edfee16ade Auto merge of #11379 - popzxc:fix-tuple-array-conversions, r=xFrednet
Fix tuple_array_conversions lint on nightly

```
changelog: ICE: [`tuple_array_conversions`]: Don't expect array length to always be usize
```

tl;dr: changed [`Const::eval_target_usize`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_middle/src/ty/consts.rs#L359) to [`Consts::try_eval_target_usize`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_middle/src/ty/consts.rs#L327) to get rid of ICE.

I have encountered a problem with clippy: it caught ICE when working with a codebase that uses a lot of nightly features.
Here's a (stripped) ICE info:

```
error: internal compiler error: /rustc/5c6a7e71cd66705c31c9af94077901a220f0870c/compiler/rustc_middle/src/ty/consts.rs:361:32: expected usize, got Const { ty: usize, kind: N/#1 }

thread 'rustc' panicked at /rustc/5c6a7e71cd66705c31c9af94077901a220f0870c/compiler/rustc_errors/src/lib.rs:1635:9:
Box<dyn Any>
stack backtrace:
...
  16:        0x110b9c590 - rustc_middle[449edf845976488d]::util:🐛:bug_fmt
  17:        0x102f76ae0 - clippy_lints[71754038dd04c2d2]::tuple_array_conversions::all_bindings_are_for_conv
...
```

I don't really know what's going on low-level-wise, but seems like this lin assumed that the length of the array can always be treated as `usize`, and *I assume* this doesn't play well with `feat(generic_const_exprs)`.

I wasn't able to build a minimal reproducible example, but locally this fix does resolve the issue.
2023-08-23 07:20:41 +00:00
Igor Aleksanov
f0eaa66263 Add a test for tuple_array_conversion 2023-08-23 09:54:50 +04:00
Red Rapious
e9a222beb5 Minor changes 2023-08-22 23:41:06 +02:00
Red Rapious
7977d209b2 Do not lint inside macros 2023-08-22 19:36:58 +02:00
Red Rapious
df8bb47f17 Improved snippets and added tests 2023-08-22 18:46:16 +02:00
bors
4be90d0305 Auto merge of #11249 - GuillaumeGomez:ui-tests-annotations, r=Centri3,llogiq
Add error annotations in UI tests

As discussed on [zulip](https://rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/Improve.20UI.20error.20checks), this PR adds missing error annotations in UI tests.

I used this script to generate them:

<details>

```python
import os

def handle_err(line, stderr, elems, kind, i):
    msg = line.split("{}: ".format(kind), 1)[1]
    i += 1
    try:
        line_nb = int(stderr[i].split(":")[1])
    except Exception:
        return i
    in_macro = False
    note_found = False
    help_found = False
    elem = {"kind": kind, "msg": msg, "line": line_nb, "notes": [], "helps": []}
    while i < len(stderr):
        if len(stderr[i]) == 0:
            break
        elif stderr[i].startswith("note:"):
            note_found = True # error checker doesn't like multi-note apparently.
        elif stderr[i].startswith("   = note:"):
            if not note_found and not help_found and "this error originates in the macro" not in stderr[i]:
                elem["notes"].append(stderr[i].split("   = note:", 1)[1].strip())
            note_found = True # error checker doesn't like multi-note apparently.
        elif stderr[i].startswith("   = help:") or stderr[i].startswith("help:"):
            help_found = True
        # elif stderr[i].startswith("help:"):
        #     if not help_found:
        #         elem["helps"].append(stderr[i].split("help:", 1)[1].strip())
        #         help_found = True # error checker doesn't like multi-help apparently.
        elif "in this macro invocation" in stderr[i]:
            in_macro = True
        i += 1
    if not in_macro:
        elems.append(elem)
    return i

def show_kind(kind):
    if kind == "error":
        return "ERROR"
    elif kind == "warning":
        return "WARNING"
    elif kind == "note":
        return "NOTE"
    return "HELP"

def generate_code_err(indent, elem, up):
    content = "{}//~{} {}: {}".format(indent, up, show_kind(elem["kind"]), elem["msg"])
    if up == "^":
        up = "|"
    for note in elem["notes"]:
        content += "\n{}//~{} {}: {}".format(indent, up, show_kind("note"), note)
    for help_msg in elem["helps"]:
        content += "\n{}//~{} {}: {}".format(indent, up, show_kind("help"), help_msg)
    return content, up

def update_content(p, content):
    TO_IGNORE = [
        "needless_bool/simple.rs", # https://github.com/rust-lang/rust-clippy/issues/11248
        "crashes/ice-7868.rs", # Has errors but in another file.
        "trivially_copy_pass_by_ref.rs", # the `N` in the stderr needs to be replaced by the number
        "tests/ui/large_types_passed_by_value.rs", # the `N` in the stderr needs to be replaced by the number
    ]
    for to_ignore in TO_IGNORE:
        if p.endswith(to_ignore):
            return
    try:
        with open(p.replace(".rs", ".stderr"), "r", encoding="utf8") as f:
            stderr = f.read().split('\n')
    except Exception:
        return
    print("Updating `{}`".format(p))
    i = 0
    elems = []
    while i < len(stderr):
        line = stderr[i]
        if line.startswith("error: ") and not line.startswith("error: aborting due to"):
            i = handle_err(line, stderr, elems, "error", i)
        elif line.startswith("warning: ") and not line.endswith("warning emitted") and line.endswith("warnings emitted"):
            i = handle_err(line, stderr, elems, "warning", i)
        i += 1
    elems.sort(key=lambda e: e["line"], reverse=True)
    i = 0
    while i < len(elems):
        elem = elems[i]
        indent = ""
        c = 0
        line = content[elem["line"] - 1]
        while c < len(line) and line[c] == ' ':
            indent += " "
            c += 1
        new_content, up = generate_code_err(indent, elem, "^")
        i += 1
        while i < len(elems) and elems[i]["line"] == elem["line"]:
            elem = elems[i]
            ret = generate_code_err(indent, elem, up)
            new_content += "\n" + ret[0]
            up = ret[1]
            i += 1
        content.insert(elem["line"], new_content)
    with open(p, "w", encoding="utf8") as f:
        f.write("\n".join(content))

def check_if_contains_ui_test(p):
    if not p.endswith(".rs"):
        return
    with open(p, "r", encoding="utf8") as f:
        x = f.read()
    if "//~" not in x and "`@run-rustfix"` not in x and "`@aux-build"` not in x:
        update_content(p, x.split("\n"))

for path, subdirs, files in os.walk("tests/ui"):
    for name in files:
        check_if_contains_ui_test(os.path.join(path, name))
```

</details>

Then ran `cargo uibless`.

changelog: none
2023-08-22 15:52:08 +00:00
Guillaume Gomez
f4670121d5 Move code comments to prevent having weird clippy fmt issues 2023-08-22 17:18:12 +02:00
Guillaume Gomez
a05d3a4137 Automatic generation of error annotations for ui tests 2023-08-22 17:18:11 +02:00
Guillaume Gomez
3a31c05578 Remove/move comments to prevent weird rustfmt wrapping 2023-08-22 17:17:48 +02:00
Guillaume Gomez
9c96605b20 Manually add annotations for ui tests 2023-08-22 17:14:08 +02:00
Igor Aleksanov
e35eb91a33 Fix tuple_array_conversions lint on nightly 2023-08-22 13:15:05 +04:00
Red Rapious
b0bd6219c8 Simplified code and added tests 2023-08-21 23:36:15 +02:00
Red Rapious
a1bf23f0a3 Added more use cases 2023-08-21 22:22:48 +02:00
Red Rapious
073149a7ef Changed documentation example and removed comments 2023-08-21 19:21:02 +02:00
Red Rapious
e33a17e33c Changed Box 2023-08-21 19:05:59 +02:00
Red Rapious
7fbf808a50 Added new lint: reserve_after_initialization 2023-08-21 18:50:53 +02:00
bors
fc1152abf6 Auto merge of #11359 - Alexendoo:unwrap-or-default-check-suggestion, r=dswij
Check that the suggested method exists in unwrap_or_default

Fixes #11355

changelog: none
2023-08-20 15:26:33 +00:00
Alex Macleod
8f2d47ea72 Check that the suggested method exists in unwrap_or_default 2023-08-19 20:22:45 +00:00
bors
7408f1d231 Auto merge of #11319 - lengyijun:map_foreach, r=blyxyas
[iter_overeager_cloned]: detect .cloned().map() and .cloned().for_each()

changelog: [`iter_overeager_cloned`]

key idea:
for `f` in `.map(f)` and `.for_each(f)`:
1. `f` must be closure
2. don't lint if mutable paramter in clsure `f`: `|mut x| ...`
3. don't lint if parameter is moved
4. maybe incorrect
2023-08-19 13:42:11 +00:00
lengyijun
e440065a0f [iter_overeager_cloned]: detect .cloned().map() and .cloned().for_each()
key idea:
for `f` in `.map(f)` and `.for_each(f)`:
1. `f` must be a closure with one parameter
2. don't lint if mutable paramter in clsure `f`: `|mut x| ...`
3. don't lint if parameter is moved
2023-08-19 21:18:14 +08:00
bors
b7cad50eca Auto merge of #11204 - y21:issue10956, r=Alexendoo
new lint: [`should_panic_without_expect`]

Closes #10956

changelog: new lint: [`should_panic_without_expect`]
2023-08-19 12:28:44 +00:00
y21
b4ab67fd4a remove useless path 2023-08-19 14:20:15 +02:00
y21
e52bd6f850 new lint: should_panic_without_expect 2023-08-18 18:57:14 +02:00
bors
d9e6aac8bb Auto merge of #11351 - xFrednet:changelog-1-72, r=Centri3
Update version attribute for 1.72 lints

Roses are red,
Violets are blue,
Marker is alive,
and so are you!

---

![cat gif](https://cataas.com/cat/SbbeZwoC81vSTzBX)

cc: https://github.com/rust-lang/rust-clippy/issues/10847#issuecomment-1683927955

---

I've also checked the `beta-nominated` label, the changelog should include everything :)

changelog: none
2023-08-18 16:27:53 +00:00
xFrednet
8f06b19b45
Changelog for Rust 1.72 🏖️ 2023-08-18 18:27:11 +02:00
xFrednet
41570c1ee7
Update version attribute for 1.72 lints 2023-08-18 18:27:10 +02:00
bors
1698ce0ba1 Auto merge of #11280 - samueltardieu:issue-11267, r=Centri3
[new_without_default]: include `where` clause in suggestions, make applicable

changelog: [`new_without_default`]: include `where` clause in suggestions
2023-08-18 15:55:40 +00:00
bors
40872cb30f Auto merge of #11348 - eopb:eopb-patch-1, r=flip1995
Remove use of `box_syntax` in `CONTRIBUTING.md` example

`box_syntax` no longer exists.
[`clippy_lints/src/lib.rs` now uses `Box::new`](d5298bea7f/clippy_lints/src/lib.rs (L809C70-L809C70))

changelog: none
2023-08-18 12:56:48 +00:00
Ethan Brierley
ede43069cc
Remove use of box_syntax CONTRIBUTING.md` example
`box_syntax` no longer exists.
[`clippy_lints/src/lib.rs` now uses `Box::new`](d5298bea7f/clippy_lints/src/lib.rs (L809C70-L809C70))
2023-08-17 21:47:03 +01:00
bors
d5298bea7f Auto merge of #11314 - GuillaumeGomez:needless_ref_mut_async_block, r=Centri3
Correctly handle async blocks for NEEDLESS_PASS_BY_REF_MUT

Fixes https://github.com/rust-lang/rust-clippy/issues/11299.

The problem was that the `async block`s are popping a closure which we didn't go into, making it miss the mutable access to the variables.

cc `@Centri3`

changelog: none
2023-08-17 15:55:23 +00:00
Guillaume Gomez
5875bd2b5f Use HirId from PlaceWithHirId rather than using the one provided to the function 2023-08-17 17:45:17 +02:00
bors
701e77c87f Auto merge of #11070 - y21:issue11065, r=flip1995
[`useless_conversion`]: only lint on paths to fn items and fix FP in macro

Fixes #11065 (which is actually two issues: an ICE and a false positive)

It now makes sure that the function call path points to a function-like item (and not e.g. a `const` like in the linked issue), so that calling `TyCtxt::fn_sig` later in the lint does not ICE (fixes https://github.com/rust-lang/rust-clippy/issues/11065#issuecomment-1616836099).
It *also* makes sure that the expression is not part of a macro call (fixes https://github.com/rust-lang/rust-clippy/issues/11065#issuecomment-1616919639). ~~I'm not sure if there's a better way to check this other than to walk the parent expr chain and see if any of them are expansions.~~ (edit: it doesn't do this anymore)

changelog: [`useless_conversion`]: fix ICE when call receiver is a non-fn item
changelog: [`useless_conversion`]: don't lint if argument is a macro argument (fixes a FP)

r? `@llogiq` (reviewed #10814, which introduced these issues)
2023-08-17 14:41:46 +00:00
Guillaume Gomez
7e46217362 Add new regression test for needless_pass_by_ref_mut 2023-08-17 14:24:04 +02:00
bors
d43486dc8c Auto merge of #10644 - blyxyas:book-method_checking, r=flip1995
Clippy Book Chapter Updates Reborn: Method Checking

This PR adds a new chapter to the book: "Method Checking". Some major re-phrasing was done and some changes in the code comments (apart from grammar and minor changes).

## Notes

- Requires #10595 **and** #10622 to be merged before this, or else several links will be broken
- To talk about the whole project, please use the tracking issue for the project #10597 (It also contains a timeline, discussions and more information)

changelog: Add a new "Method Checking" chapter to the book.

r? `@flip1995`
2023-08-16 12:57:18 +00:00
Philipp Krones
1dbc8dd0cf
Fix define_lints->defining_lints typo in link 2023-08-16 14:54:47 +02:00
Philipp Krones
e8d79b8645
Formatting 2023-08-16 14:50:40 +02:00
blyxyas
9e4a2d7fca
Fixes based on reviews 2023-08-16 14:50:40 +02:00
blyxyas
111f0229da
Add "Method Checking"
Co-authored-by: Nahua <kangnahua@gmail.com>
2023-08-16 14:50:40 +02:00
bors
87d148759a Auto merge of #10595 - blyxyas:book-define_lints, r=flip1995
Clippy Book Chapter Updates Reborn: Defining Lints

Revival of #9659, I've made a few changes (mainly ones from reviews from #9426, like removing mid-section storytelling) and some re-writes. The goal of the project would be to slowly re-write the Clippy book (only chapters that need it) to more up-to-date style.

## Notes

- Things like `git status` commands have changed, we need to make sure that they're correct.
- As this is a team-wide effort, I would please ask anyone and everyone to read it and give your opinion.
- To talk about the whole project, please use the tracking issue for the project #10597  (It also contains a timeline, discussions and more information)

---

changelog: Add a new "Defining lints" chapter to the book

r? `@flip1995`
2023-08-16 12:37:22 +00:00
Philipp Krones
783c119768
Address review comments and formatting 2023-08-16 14:36:09 +02:00
blyxyas
6076cda3c5
Fix CI 2023-08-16 14:30:39 +02:00
blyxyas
b91d676b60
Move "Lint types to the top" 2023-08-16 14:30:39 +02:00
blyxyas
7465436270
Improve briefness 2023-08-16 14:30:39 +02:00
blyxyas
735380b2cc
Try to clear up confusion between type and category. 2023-08-16 14:30:39 +02:00
blyxyas
c22906b37f
Fix CI formatting issues 2023-08-16 14:30:38 +02:00
blyxyas
97d31c8ae0
New chapter: Defining Lints
Co-authored-by: Nahua <kangnahua@gmail.com>
2023-08-16 14:30:38 +02:00
bors
710db18ccd Auto merge of #11336 - Alexendoo:uitest-backslash, r=flip1995
Use ui_test's Windows path backslash heuristic

changelog: none

Instead of unconditionally replacing `\` with `/` we now use [`Match::PathBackslash`](https://docs.rs/ui_test/latest/ui_test/enum.Match.html#variant.PathBackslash) to only replace backslashes in paths that look like windows paths

`ui-toml` and `ui-cargo` tests still use the old way because they produce verbatim paths on windows in some tests (`\\?\C:\foo\...`) which was finnicky to get the replacement order correct with

Also removes the `ui_test` -> `compiletest` alias and `VarGuard`
2023-08-15 15:22:29 +00:00
bors
11efa0133f Auto merge of #11321 - J-ZhengLi:issue11281, r=giraffate
allow calling `to_owned` on borrowed value for [`implicit_clone`]

fixes: #11281

a small and simple fix that give up checking for `referenced_value.to_owned()` usage.

changelog: allow calling `to_owned` with borrowed value for [`implicit_clone`]
2023-08-15 11:42:05 +00:00