profile
viewpoint
Esteban Kuber estebank San Francisco, CA http://esteban.kuber.com.ar/resume/ Off-by-one error fixer/introducer. I 💖@rust-lang⚙️ PST tz

estebank/galvanize 9

Galvanize: Pure Rust CDB reader/writer

commure/hazy 5

OpaqueDebug implementation

estebank/jsmk 4

Javascript Canvas based fighting game engine

estebank/panorama 2

HTML5+JS diff display

estebank/resume 2

My HTML resume. It's self-contained with no external dependencies. Emphasis on readability across User Agents.

estebank/difference.rs 1

Rust text diffing and assertion library

estebank/galvanize_cli 1

CLI Tool to interact with CDBs.

estebank/pysmell 1

PySmell is an attempt to create an IDE completion helper for python.

estebank/atom 0

trying things out

push eventestebank/rust

Esteban Küber

commit sha 9e16213610f606de0e44ac2b26ab9666bf0e83bf

Suggest calling associated `fn` inside `trait`s When calling a function that doesn't exist inside of a trait's associated `fn`, and another associated `fn` in that trait has that name, suggest calling it with the appropriate fully-qualified path. Expand the label to be more descriptive. Prompted by the following user experience: https://users.rust-lang.org/t/cannot-find-function/50663

view details

push time in 25 minutes

PR opened rust-lang/rust

Suggest calling associated `fn` inside `trait`s

When calling a function that doesn't exist inside of a trait's associated fn, and another associated fn in that trait has that name, suggest calling it with the appropriate fully-qualified path.

Expand the label to be more descriptive.

Prompted by the following user experience: https://users.rust-lang.org/t/cannot-find-function/50663

+129 -49

0 comment

9 changed files

pr created time in 27 minutes

create barnchestebank/rust

branch : suggest-assoc-fn

created branch time in 27 minutes

Pull request review commentrust-lang/rust

Avoid complex diagnostics in snippets which contain newlines

+error: future cannot be sent between threads safely+  --> $DIR/issue-70935-complex-spans.rs:10:45+   |+LL | fn foo(tx: std::sync::mpsc::Sender<i32>) -> impl Future + Send {+   |                                             ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send`+   |+   = help: the trait `Sync` is not implemented for `Sender<i32>`+note: future is not `Send` as this value is used across an await+  --> $DIR/issue-70935-complex-spans.rs:13:9+   |+LL | /         baz(|| async{+LL | |             foo(tx.clone());+LL | |         }).await;+   | |________________^ first, await occurs here, with the value maybe used later...+note: the value is later dropped here+  --> $DIR/issue-70935-complex-spans.rs:15:17+   |+LL |         }).await;+   |                 ^+note: this has type `[closure@$DIR/issue-70935-complex-spans.rs:13:13: 15:10]` which is not `Send`+  --> $DIR/issue-70935-complex-spans.rs:13:13+   |+LL |           baz(|| async{+   |  _____________^+LL | |             foo(tx.clone());+LL | |         }).await;+   | |_________^

r=me with or without the proposed changes.

JohnTitor

comment created time in 6 hours

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Avoid complex diagnostics in snippets which contain newlines

+error: future cannot be sent between threads safely+  --> $DIR/issue-70935-complex-spans.rs:10:45+   |+LL | fn foo(tx: std::sync::mpsc::Sender<i32>) -> impl Future + Send {+   |                                             ^^^^^^^^^^^^^^^^^^ future created by async block is not `Send`+   |+   = help: the trait `Sync` is not implemented for `Sender<i32>`+note: future is not `Send` as this value is used across an await+  --> $DIR/issue-70935-complex-spans.rs:13:9+   |+LL | /         baz(|| async{+LL | |             foo(tx.clone());+LL | |         }).await;+   | |________________^ first, await occurs here, with the value maybe used later...+note: the value is later dropped here+  --> $DIR/issue-70935-complex-spans.rs:15:17+   |+LL |         }).await;+   |                 ^+note: this has type `[closure@$DIR/issue-70935-complex-spans.rs:13:13: 15:10]` which is not `Send`+  --> $DIR/issue-70935-complex-spans.rs:13:13+   |+LL |           baz(|| async{+   |  _____________^+LL | |             foo(tx.clone());+LL | |         }).await;+   | |_________^

@JohnTitor something I've done in other errors i check whether Spans are exactly the same, if one encloses the other, or if one of them is multiline to provide different output depending on what looks best. In this case just checking whether the "inner" span is multiline to decide between span_labels and span_notes should be easy to do and reasonable as a solution. What do you two think?

JohnTitor

comment created time in 6 hours

PullRequestReviewEvent

pull request commentrust-lang/rust

Prefer to use `print_def_path`

r? @estebank @bors r+

JohnTitor

comment created time in 6 hours

issue commentrust-lang/rust

Better diagnostics for `:` instead of `->` in return type

In my mind, we could introduce a check in expect and expect_one_of to check for confusable tokens. We'd have a mapping of similar looking or close enough in the keyboard and compare them against what was expected. If there's a match, emit a specific error and return a non-error back up.

In expected_one_of_not_found we already perform something similar for closing delimiters, so the machinery to signal recovery is already in place. That can be used higher in the call stack to avoid producing further errors caused by misparses. Ideally we could pass in a list of expected tokens after the next one to do some sanity checks for the recovery not to kick in if it is too far from what we'd expect. (Basically, just bail if the code is too far gone from normal code.)

LeSeulArtichaut

comment created time in 6 hours

issue commentrust-lang/rust

Come up with regression test for #66286

@camelid https://github.com/rust-lang/rust/blob/5c6f7b32aab683276d4feb1810244ccf72bda736/src/test/ui/proc_macro.rs is an example of a test that relies on a proc_macro, and we can use @hellow554's snippet for the necessary proc_macro being tested.

estebank

comment created time in 7 hours

pull request commentrust-lang/rust

resolve: private fields in tuple struct ctor diag

@bors r+

davidtwco

comment created time in 7 hours

Pull request review commentrust-lang/rust

resolve: private fields in tuple struct ctor diag

 impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {                 self.suggest_using_enum_variant(err, source, def_id, span);             }             (Res::Def(DefKind::Struct, def_id), _) if ns == ValueNS => {-                if let Some((ctor_def, ctor_vis, fields)) =-                    self.r.struct_constructors.get(&def_id).cloned()+                let (ctor_def, ctor_vis, fields) =+                    if let Some(struct_ctor) = self.r.struct_constructors.get(&def_id).cloned() {+                        struct_ctor+                    } else {+                        bad_struct_syntax_suggestion(def_id);+                        return true;+                    };++                let is_accessible = self.r.is_accessible_from(ctor_vis, self.parent_scope.module);+                if !is_expected(ctor_def) || is_accessible {+                    return true;+                }++                let field_spans = match source {+                    // e.g. `if let Enum::TupleVariant(field1, field2) = _`+                    PathSource::TupleStruct(_, pattern_spans) => {+                        err.set_primary_message(+                            "cannot match against a tuple struct which contains private fields",+                        );++                        // Use spans of the tuple struct pattern.+                        Some(Vec::from(pattern_spans))+                    }+                    // e.g. `let _ = Enum::TupleVariant(field1, field2);`+                    _ if source.is_call() => {+                        err.set_primary_message(+                            "cannot initialize a tuple struct which contains private fields",+                        );++                        // Use spans of the tuple struct definition.+                        self.r+                            .field_names+                            .get(&def_id)+                            .map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())+                    }+                    _ => None,+                };++                if let Some(spans) =+                    field_spans.filter(|spans| spans.len() > 0 && fields.len() == spans.len())                 {-                    let accessible_ctor =-                        self.r.is_accessible_from(ctor_vis, self.parent_scope.module);-                    if is_expected(ctor_def) && !accessible_ctor {-                        let mut better_diag = false;-                        if let PathSource::TupleStruct(_, pattern_spans) = source {-                            if pattern_spans.len() > 0 && fields.len() == pattern_spans.len() {-                                let non_visible_spans: Vec<Span> = fields-                                    .iter()-                                    .zip(pattern_spans.iter())-                                    .filter_map(|(vis, span)| {-                                        match self-                                            .r-                                            .is_accessible_from(*vis, self.parent_scope.module)-                                        {-                                            true => None,-                                            false => Some(*span),-                                        }-                                    })-                                    .collect();-                                // Extra check to be sure-                                if non_visible_spans.len() > 0 {-                                    let mut m: rustc_span::MultiSpan =-                                        non_visible_spans.clone().into();-                                    non_visible_spans.into_iter().for_each(|s| {-                                        m.push_span_label(s, "private field".to_string())-                                    });-                                    err.span_note(-                                        m,-                                        "constructor is not visible here due to private fields",-                                    );-                                    better_diag = true;-                                }-                            }-                        }+                    let non_visible_spans: Vec<Span> = fields+                        .iter()+                        .zip(spans.iter())+                        .filter(|(vis, _)| {+                            !self.r.is_accessible_from(**vis, self.parent_scope.module)+                        })+                        .map(|(_, span)| *span)+                        .collect(); -                        if !better_diag {-                            err.span_label(-                                span,-                                "constructor is not visible here due to private fields".to_string(),-                            );-                        }+                    if non_visible_spans.len() > 0 {+                        let mut m: rustc_span::MultiSpan = non_visible_spans.clone().into();+                        non_visible_spans+                            .into_iter()+                            .for_each(|s| m.push_span_label(s, "private field".to_string()));

oh! I hadn't thought about doing this this way! neat.

davidtwco

comment created time in 7 hours

PullRequestReviewEvent

issue commentrust-lang/rust

Better diagnostics for `:` instead of `->` in return type

@bugaevc for a while now I've been thinking that we should have a general typo checker for arbitrary positions. Such a check would allow us to give suggestions for for example match foo { _ -> {} } without us explicitly coding it. Is this something you would also be interesting to work on?

LeSeulArtichaut

comment created time in 7 hours

pull request commentrust-lang/rust

Suggest calling await on method call and field access

@bors r=oli-obk

estebank

comment created time in 9 hours

push eventestebank/rust

Simonas Kazlauskas

commit sha 4bfacffb903d382333a39c1646ee2b3956bd59bf

Optimise align_offset for stride=1 further `stride == 1` case can be computed more efficiently through `-p (mod a)`. That, then translates to a nice and short sequence of LLVM instructions: %address = ptrtoint i8* %p to i64 %negptr = sub i64 0, %address %offset = and i64 %negptr, %a_minus_one And produces pretty much ideal code-gen when this function is used in isolation. Typical use of this function will, however, involve use of the result to offset a pointer, i.e. %aligned = getelementptr inbounds i8, i8* %p, i64 %offset This still looks very good, but LLVM does not really translate that to what would be considered ideal machine code (on any target). For example that's the codegen we obtain for an unknown alignment: ; x86_64 dec rsi mov rax, rdi neg rax and rax, rsi add rax, rdi In particular negating a pointer is not something that’s going to be optimised for in the design of CISC architectures like x86_64. They are much better at offsetting pointers. And so we’d love to utilize this ability and produce code that's more like this: ; x86_64 lea rax, [rsi + rdi - 1] neg rsi and rax, rsi To achieve this we need to give LLVM an opportunity to apply its various peep-hole optimisations that it does during DAG selection. In particular, the `and` instruction appears to be a major inhibitor here. We cannot, sadly, get rid of this load-bearing operation, but we can reorder operations such that LLVM has more to work with around this instruction. One such ordering is proposed in #75579 and results in LLVM IR that looks broadly like this: ; using add enables `lea` and similar CISCisms %offset_ptr = add i64 %address, %a_minus_one %mask = sub i64 0, %a %masked = and i64 %offset_ptr, %mask ; can be folded with `gepi` that may follow %offset = sub i64 %masked, %address …and generates the intended x86_64 machine code. One might also wonder how the increased amount of code would impact a RISC target. Turns out not much: ; aarch64 previous ; aarch64 new sub x8, x1, #1 add x8, x1, x0 neg x9, x0 sub x8, x8, #1 and x8, x9, x8 neg x9, x1 add x0, x0, x8 and x0, x8, x9 (and similarly for ppc, sparc, mips, riscv, etc) The only target that seems to do worse is… wasm32. Onto actual measurements – the best way to evaluate snippets like these is to use llvm-mca. Much like Aarch64 assembly would allow to suspect, there isn’t any performance difference to be found. Both snippets execute in same number of cycles for the CPUs I tried. On x86_64, we get throughput improvement of >50%, however!

view details

rail

commit sha dc89bb1135afc31fc9ee2272e627192c04354d22

Use if_chain in Increment/InitializeVisitor

view details

rail

commit sha 116f30dc33d9e3744f257f2f7f5467acfbff178b

Use else blocks instead of return statements in Increment/InitializeVisitor

view details

rail

commit sha b2d5b89a1de15df9052fdf44d01b174add82837f

Check if it's after the loop earlier

view details

rail

commit sha 31cb1109648bf4242cab47571343578244e7fb9d

add concinient methods to Increment/InitializeVisitor

view details

rail

commit sha c599e2fcfaaedb12b560f4136bab3d0b450acf8f

Split VarState

view details

rail

commit sha 13c207d3756754c54a6b20d852087616d5abfbf4

Generalise `InitializeVisitor`

view details

rail

commit sha 9573a0d378033a81e55ca834a5d305d3cf2be24d

Rename variables

view details

rail

commit sha 1026b42f0694eb9239b5cebe80be743d5ded0da5

Rename a struct and variables

view details

rail

commit sha b4b4da162f19e9a4c63854a2b5a6167b83f9d8b9

Introduce Start and StartKind

view details

rail

commit sha 720f19f2ec4282f636889b35beabf31272e3b1b2

Implement detecting `manual_memcpy` with loop counters

view details

rail

commit sha de56279cd9047832216e1d1c06dc45375bf01b31

Implement building the `manual_memcpy` sugggestion with loop counters

view details

rail

commit sha 8da6cfd17b7707d678d01a6688572169015ea83e

fmt

view details

rail

commit sha d9a88be0b05c2cfec0679caf428d129c9d46256d

Rename `get_offset` and its private items

view details

rail

commit sha 774e82a566c6c3349700a8bece44d6a8c6755039

Add the tests for `manual_memcpy` with loop counters

view details

rail

commit sha 9aad38bf614c3fb6d306f5dec4a0af606bb3c9c8

Update `manual_memcpy.stderr` to reflect additional parentheses

view details

rail

commit sha 4ea4a972500a8ddecfc737d51eec960324dcb02f

Add tests for bitwise operations

view details

rail

commit sha eb3ffe6ed2999e9d3385be0ff981e30082ea0d2c

make use of macros in operator overloading

view details

rail

commit sha 10d7a18f72155f03dbd27b872a52b5dd45def8db

fmt

view details

rail

commit sha 174065fc98ef9335ea45a234aa18286cdf6c3934

fix the multiple counters test

view details

push time in 9 hours

pull request commentrust-lang/rust

Tweak invalid `fn` header and body parsing

@bors r=varkor

estebank

comment created time in a day

push eventestebank/rust

Esteban Küber

commit sha ff61949860813247b26d96eb374b41b46becba81

Tweak invalid `fn` header and body parsing * Recover empty `fn` bodies when encountering `}` * Recover trailing `>` in return types * Recover from non-type in array type `[<BAD TOKEN>; LEN]`

view details

push time in a day

issue closedrust-lang/rust

Improve compiler diagnostics on missing let

This code:

struct Foo;

impl Foo {
    fn get() -> Option<Self> { Some(Foo) }
}

fn do_it() {
    if Some(foo) = Foo::get() {
        println!("Got a foo!");
    }
}

(Playground)

Give confusing diagnostics:

error[E0425]: cannot find value `foo` in this scope
 --> src/lib.rs:8:13
  |
1 | struct Foo;
  | ----------- similarly named unit struct `Foo` defined here
...
8 |     if Some(foo) = Foo::get() {
  |             ^^^ help: a unit struct with a similar name exists (notice the capitalization): `Foo`

error[E0308]: mismatched types
 --> src/lib.rs:8:8
  |
8 |     if Some(foo) = Foo::get() {
  |        ^^^^^^^^^^^^^^^^^^^^^^
  |        |
  |        expected `bool`, found `()`
  |        help: try comparing for equality: `Some(foo) == Foo::get()`

If instead of foo the identifier is different, the diagnostics are less confusing (because they don't mention Foo again), but they still don't suggest adding the missing let. The same is true for while [let].

closed time in a day

amosonn

issue commentrust-lang/rust

Improve compiler diagnostics on missing let

Current output:

error[E0425]: cannot find value `foo` in this scope
 --> src/lib.rs:8:13
  |
1 | struct Foo;
  | ----------- similarly named unit struct `Foo` defined here
...
8 |     if Some(foo) = Foo::get() {
  |             ^^^
  |
help: you might have meant to use pattern matching
  |
8 |     if let Some(foo) = Foo::get() {
  |        ^^^
help: a unit struct with a similar name exists
  |
8 |     if Some(Foo) = Foo::get() {
  |             ^^^
amosonn

comment created time in a day

issue commentrust-lang/rust

Mismatched delimiters recovered incorrectly

This happens because the token tree is built before the actual parsing happens. If we were able to start parsing, we would instead emit

error: expected `|`, found `)`
 --> file.rs:2:20
  |
2 |     let x = a.map(|)| s}
  |                    ^ expected `|`
SOF3

comment created time in a day

issue commentrust-lang/rust

Confusing error messages when using wrong trait in fully qualified syntax (`<T as Trait>::Assoc`)

Current output:

error[E0277]: the trait bound `T: Op2` is not satisfied
  --> src/lib.rs:24:5
   |
24 |     type Output = <T as Op2>::Output;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Op2` is not implemented for `T`
   |
help: consider further restricting this bound
   |
23 | impl<T: Op + Op2> Op for Wrap<T> {
   |            ^^^^^

error[E0277]: the trait bound `T: Op2` is not satisfied
  --> src/lib.rs:27:5
   |
27 | /     fn op(self) -> Self::Output {
28 | |         self.0.op()
29 | |     }
   | |_____^ the trait `Op2` is not implemented for `T`
   |
help: consider further restricting this bound
   |
23 | impl<T: Op + Op2> Op for Wrap<T> {
   |            ^^^^^
WaffleLapkin

comment created time in a day

issue commentrust-lang/rust

Better diagnostics for `:` instead of `->` in return type

Pushed #78379 to use the regular "expected"/"found" error machinery, which will correctly say ->, ;, where or { can go there. That should be enough to direct people in the right direction (we would have to add a lot of checks to see if they meant ; or ->, which might be worth it 🤷‍♀️).

LeSeulArtichaut

comment created time in a day

pull request commentrust-lang/rust

Tweak `if let` suggestion to be more liberal with suggestion and to not ICE

@Mark-Simulacrum done.

estebank

comment created time in a day

push eventestebank/rust

Esteban Küber

commit sha cabf6d052329c8ba5f23c7fc4873e9db64874997

Tweak `if let` suggestion to be more liberal with suggestion and to not ICE Fix #77218. Fix #77238.

view details

push time in a day

PR opened rust-lang/rust

Tweak invalid `fn` header and body parsing
  • Rely on regular "expected"/"found" parser error for fn, fix #77115
  • Recover empty fn bodies when encountering }
  • Recover trailing > in return types
  • Recover from non-type in array type [<BAD TOKEN>; LEN]
+79 -48

0 comment

16 changed files

pr created time in a day

create barnchestebank/rust

branch : fn-signature-parse

created branch time in a day

issue commentrust-lang/rust

"Reach into" to Result/Option to look for expected methods in error messages

We already special case errors for Option and Result, and provide similar suggestions to await Futures.

qrnch-jan

comment created time in a day

pull request commentrust-lang/rust

Suggest that expressions that look like const generic arguments should be enclosed in brackets

The error messages in these cases are not ideal, but they're particularly difficult to handle well.

Handling >> will be hard but we could potentially keep track of how many < we've seen to decide whether to detect it as bitshift or closing type param (we already have recovery for too many closing > in type params so it would have to interact nicely with it), but I don't think it is necessary just yet as the suggestion does give you enough of a clue as to what to do.

varkor

comment created time in a day

Pull request review commentrust-lang/rust

Suggest calling await on method call and field access

 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {         self.note_error_origin(diag, cause, exp_found);     } +    pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {

That sounds good.

estebank

comment created time in 3 days

PullRequestReviewEvent

pull request commentrust-lang/rust

Fix #78192

r? @oli-obk who's more familiar with the nuance here.

simonvandel

comment created time in 3 days

pull request commentrust-lang/rust

impl<A, B> IntoIterator for (A, B) as Zip

I really like this change, but am slightly concerned about the insta-stabilization. r=me on the code, but defer to @rust-lang/libs

@rfcbot fcp merge

cuviper

comment created time in 3 days

Pull request review commentrust-lang/rust

Suggest calling await on method call and field access

 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {         self.note_error_origin(diag, cause, exp_found);     } +    pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {

Whenever you have a ty::Ty<'tcx> it is easier to do it this way, when you have access to the hir::Ty that comes from the return type of the hir fn return type it easier to use that directly.

We might be able to unify these two methods, but I've found in the past that I've had to have the same logic twice, one for the hir and another for ty, so I wouldn't be too torn about the "duplication".

estebank

comment created time in 3 days

PullRequestReviewEvent

push eventestebank/rust

Esteban Küber

commit sha 15c74d57f01f30412b50cf50d72766f7b9724fa3

Do not skip "type annotation needed"/`Sized` error

view details

Esteban Küber

commit sha 0d3f077ac723e2c679cadb97661d66f928ae0cc0

Skip lifetimes in turbofish suggestions

view details

Esteban Küber

commit sha 1ae1a1347280351dc31ce0628558b5d5bce2db97

Fix new ICE caused by derred arg `Sized` check

view details

Esteban Küber

commit sha f26b748303f1795c86f4ee331551af8b8d0457ac

Suggest `&[_]` instead of `&[_; N]` on inference error

view details

Esteban Küber

commit sha 654a4129159eaac624c84f2db3aaba2712e1b990

Fix rebase

view details

push time in 3 days

push eventestebank/rust

Mark Rousskov

commit sha 05c9c0ee5dcd935f518db151bee2dc88380fb92f

Modify executable checking to be more universal This uses a dummy file to check if the filesystem being used supports the executable bit in general.

view details

dylni

commit sha 1ff7da6551a7cdf6ace2a9d00e92bbab550334ee

Move `slice::check_range` to `RangeBounds`

view details

dylni

commit sha 1095dcab96d524e700b11edf366d45a0fd173fa0

Fix links

view details

dylni

commit sha eb63168e007058dad4af758faf1dca449c049777

Fix doctests

view details

dylni

commit sha f055b0bb0847ecf08fe452a270faae8324b55b05

Rename method to `assert_len`

view details

Bastian Kauschke

commit sha fd22e87afc9082522bc7b52e32d25d43c64594e6

fix flag computation for `ExistentialPredicate::Projection`

view details

Bastian Kauschke

commit sha 7652b4b1d9cec0ad22f529a4335d05f7d7792521

guard against `skip_binder` errors during FlagComputation

view details

follower

commit sha a7bd6c449aef07dc8daa889f4ddbdda326593e32

Link to "Contributing to Rust" rather than "Getting Started". Change to link to "Contributing to Rust" chapter of `rustc` Dev Guide, primarily on the basis that the GitHub "first contribution" Issue "pop-up" says "Be sure to review the [contributing guidelines] and [code of conduct]" and links to this file. When/if the guide/"Getting Started" section gets revised to not be `rustc`-specific the linked section can be changed. In the meantime this prevents leading first time contributors into a confusing cul de sac.

view details

Camelid

commit sha 549f861f7d53811521cf929cf58fb6828a2a88d9

Use correct article in help message for conversion or cast Before it always used `an`; now it uses the correct article for the type.

view details

Mara Bos

commit sha 81edbbc2bfacd29558a5020990d49fc07ed80ac7

Implement TryFrom between NonZero types.

view details

Camelid

commit sha 094f14c554c3a1f103a5d6778d4b4e131c297f11

Add article after "to" Also added missing backtick in "you can cast" message.

view details

Camelid

commit sha 8a6831a7fd3fc624643b50f494212e0ceaad3c28

Say "doesn't" instead of "wouldn't" in convert message

view details

Dylan MacKenzie

commit sha 77e6c56ab6f108fdbb8acbd176497be9f074af9a

Unify `&mut` and `&raw mut` const-checking errors

view details

Dylan MacKenzie

commit sha c1494d60dbad39c218e7b0825bfe590cc22bf2fa

Bless tests

view details

Bastian Kauschke

commit sha 9c302f55bd07a04305dfa2bd815d2559deb8468f

normalize in codegen_fulfill_obligations

view details

Bastian Kauschke

commit sha f0487cee7439f3a4b4c7daec0e7f2a0ccc21053c

normalize substs during inlining

view details

Bastian Kauschke

commit sha 32739a2ff1b7b6e5c1b475341b01f4a499830a84

add regression test

view details

Bastian Kauschke

commit sha ac893b8a02788eec6f6fad0cc89de0177b0c0a50

add test for should_inline incorrect param_env

view details

Mara Bos

commit sha 64839ee00ab4076d797901ddea55f2613c5b75b5

Add Pin::new_static.

view details

Mara Bos

commit sha 390883e888c580d054ab4a2584c851aba50865e9

Make Pin::new_static const.

view details

push time in 3 days

pull request commentrust-lang/rust

Do not ICE with TraitPredicates containing [type error]

@bors r=eddyb

estebank

comment created time in 3 days

push eventestebank/rust

Mark Rousskov

commit sha e023158145ece18176a2e93420600ccda0d0bc58

Permit uninhabited enums to cast into ints This essentially reverts part of #6204.

view details

Mark Rousskov

commit sha 990a39596cf3b33e550f2045f78a62970f8d78f8

Prevent ICE on uninhabited MIR interpretation

view details

Nathan West

commit sha a02014280586b53997622c501db00398376967a8

Refactor io/buffered.rs into submodules

view details

Nathan West

commit sha 96229f02402e82914ec6100b28ad2cbdd273a0d4

move buffered.rs to mod.rs

view details

Nathan West

commit sha 6d75cdfc9ed9e6987bd23add6cf3954d2499dce2

Added updated compiler diagnostic

view details

Amjad Alsharafi

commit sha da700cba08a2b194d19e63d3c51ebadce96fe46b

Stabilize move_ref_pattern

view details

Amjad Alsharafi

commit sha afb9eeb1b9ea16ca65e38673a0ef3e7be81d7252

Disabled error `E0007` from rustc_error_codes

view details

Mark Rousskov

commit sha 05c9c0ee5dcd935f518db151bee2dc88380fb92f

Modify executable checking to be more universal This uses a dummy file to check if the filesystem being used supports the executable bit in general.

view details

Nathan West

commit sha c4280af8285c61b367a87c8f6eef9876011a8150

Retry fix error reporting suggestions

view details

dylni

commit sha 1ff7da6551a7cdf6ace2a9d00e92bbab550334ee

Move `slice::check_range` to `RangeBounds`

view details

dylni

commit sha 1095dcab96d524e700b11edf366d45a0fd173fa0

Fix links

view details

dylni

commit sha eb63168e007058dad4af758faf1dca449c049777

Fix doctests

view details

dylni

commit sha f055b0bb0847ecf08fe452a270faae8324b55b05

Rename method to `assert_len`

view details

Bastian Kauschke

commit sha fd22e87afc9082522bc7b52e32d25d43c64594e6

fix flag computation for `ExistentialPredicate::Projection`

view details

Bastian Kauschke

commit sha 7652b4b1d9cec0ad22f529a4335d05f7d7792521

guard against `skip_binder` errors during FlagComputation

view details

follower

commit sha a7bd6c449aef07dc8daa889f4ddbdda326593e32

Link to "Contributing to Rust" rather than "Getting Started". Change to link to "Contributing to Rust" chapter of `rustc` Dev Guide, primarily on the basis that the GitHub "first contribution" Issue "pop-up" says "Be sure to review the [contributing guidelines] and [code of conduct]" and links to this file. When/if the guide/"Getting Started" section gets revised to not be `rustc`-specific the linked section can be changed. In the meantime this prevents leading first time contributors into a confusing cul de sac.

view details

Camelid

commit sha 549f861f7d53811521cf929cf58fb6828a2a88d9

Use correct article in help message for conversion or cast Before it always used `an`; now it uses the correct article for the type.

view details

Mara Bos

commit sha 81edbbc2bfacd29558a5020990d49fc07ed80ac7

Implement TryFrom between NonZero types.

view details

Camelid

commit sha 094f14c554c3a1f103a5d6778d4b4e131c297f11

Add article after "to" Also added missing backtick in "you can cast" message.

view details

Camelid

commit sha 8a6831a7fd3fc624643b50f494212e0ceaad3c28

Say "doesn't" instead of "wouldn't" in convert message

view details

push time in 3 days

Pull request review commentrust-lang/rust

Tweak `if let` suggestion to be more liberal with suggestion and to not ICE

+error[E0308]: mismatched types+  --> $DIR/issue-77218.rs:3:11+   |+LL |     while Some(0) = value.get(0) {+   |           ^^^^^^^^^^^^^^^^^^^^^^ expected `bool`, found `()`

Fixed.

estebank

comment created time in 3 days

PullRequestReviewEvent

push eventestebank/rust

Bastian Kauschke

commit sha fd22e87afc9082522bc7b52e32d25d43c64594e6

fix flag computation for `ExistentialPredicate::Projection`

view details

Bastian Kauschke

commit sha 7652b4b1d9cec0ad22f529a4335d05f7d7792521

guard against `skip_binder` errors during FlagComputation

view details

follower

commit sha a7bd6c449aef07dc8daa889f4ddbdda326593e32

Link to "Contributing to Rust" rather than "Getting Started". Change to link to "Contributing to Rust" chapter of `rustc` Dev Guide, primarily on the basis that the GitHub "first contribution" Issue "pop-up" says "Be sure to review the [contributing guidelines] and [code of conduct]" and links to this file. When/if the guide/"Getting Started" section gets revised to not be `rustc`-specific the linked section can be changed. In the meantime this prevents leading first time contributors into a confusing cul de sac.

view details

Mara Bos

commit sha 81edbbc2bfacd29558a5020990d49fc07ed80ac7

Implement TryFrom between NonZero types.

view details

Dylan MacKenzie

commit sha 77e6c56ab6f108fdbb8acbd176497be9f074af9a

Unify `&mut` and `&raw mut` const-checking errors

view details

Dylan MacKenzie

commit sha c1494d60dbad39c218e7b0825bfe590cc22bf2fa

Bless tests

view details

Mara Bos

commit sha 64839ee00ab4076d797901ddea55f2613c5b75b5

Add Pin::new_static.

view details

Mara Bos

commit sha 390883e888c580d054ab4a2584c851aba50865e9

Make Pin::new_static const.

view details

Joshua Nelson

commit sha bd135674814d74ca6fca3ab79d778ecaaeb02cf5

Allow setting up git hooks from other worktrees

view details

Ralf Jung

commit sha 0ec3ea9e697ea9c2ce225ba0b9f3715434fc773e

const keyword: brief paragraph on 'const fn'

view details

Ralf Jung

commit sha c8405d2251ce78651f591ed8a2189c41593f5110

fix markdown reference Co-authored-by: Dariusz Niedoba <darksv@users.noreply.github.com>

view details

Julian Wollersberger

commit sha 39b0e7928579c4ce3a42e849695f9380b7869d62

Remove generic argument from `QueryConfig`.

view details

Mara Bos

commit sha 104c0f0194177442ff16cf14907a96d2f8d200dd

Rename Pin::new_static to Pin::static_ref.

view details

Mara Bos

commit sha 2c71f682d74d13ae6673dc701a9bb3a0562f57c0

Add Pin::static_mut.

view details

Giles Cope

commit sha 0c32e811577fbf2ff46a607897f9ea7b6b95b364

Fixing escaping to ensure generation of welformed json.

view details

Mara Bos

commit sha f83446b836900ce9afbaa0816a5b4feda654b51e

Reword safety guarantee of Pin::static_{ref,mut}. Co-authored-by: Peter Todd <pete@petertodd.org>

view details

wcampbell

commit sha a93f58f5e6c9e4e1fbc076d966a9e1e853ea06fd

Join map operators Signed-off-by: wcampbell <wcampbell1995@gmail.com>

view details

wcampbell

commit sha 964a5ac962d32c280d036df42b2e747809939cc4

Use is_ok() instead of empty Ok(_) Signed-off-by: wcampbell <wcampbell1995@gmail.com>

view details

ayazhafiz

commit sha abfbd1bd719bd1440132ead24ec64c0acd293f41

Avoid extraneous space between visibility kw and ident for statics Today, given a static like `static mut FOO: usize = 1`, rustdoc would emit `static mut FOO: usize = 1`, as it emits both the mutability kw with a space and reserves a space after the mutability kw. This patch fixes that misformatting. This patch also adds some tests for emit of other statics, as I could not find an existing test devoted to statics.

view details

ayazhafiz

commit sha e60072f5c65c619263d137daf9afab9c6cb94c8e

fixup! Avoid extraneous space between visibility kw and ident for statics

view details

push time in 3 days

pull request commentrust-lang/rust

Do not try to report on closures to avoid ICE

@bors r+

JohnTitor

comment created time in 3 days

PR opened rust-lang/rust

Suggest calling await on method call and field access

When encountering a failing method or field resolution on a Future, look at the Output and try the same operation on it. If successful, suggest calling .await on the Future.

This had already been introduced in #72784, but at some point they stopped working.

Built on top of #78214, only last commit is relevant.

r? @oli-obk

+656 -412

0 comment

27 changed files

pr created time in 3 days

create barnchestebank/rust

branch : match-semicolon-2

created branch time in 3 days

pull request commentrust-lang/rust

Await on mismatched future types

These suggestions became dead code at some point (😩), but will be emitted again after https://github.com/rust-lang/rust/pull/78214.

csmoe

comment created time in 3 days

Pull request review commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {                 if self.predicate_may_hold(&try_obligation) && impls_future {                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {                         if snippet.ends_with('?') {-                            err.span_suggestion(-                                span,-                                "consider using `.await` here",-                                format!("{}.await?", snippet.trim_end_matches('?')),+                            err.span_suggestion_verbose(+                                span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),

We have a few in rustc, but I try to avoid them like the plague* whenever feasible.

  • Really need to stop using that phrase, some people embrace the plague.
estebank

comment created time in 3 days

PullRequestReviewEvent

push eventestebank/rust

follower

commit sha a7bd6c449aef07dc8daa889f4ddbdda326593e32

Link to "Contributing to Rust" rather than "Getting Started". Change to link to "Contributing to Rust" chapter of `rustc` Dev Guide, primarily on the basis that the GitHub "first contribution" Issue "pop-up" says "Be sure to review the [contributing guidelines] and [code of conduct]" and links to this file. When/if the guide/"Getting Started" section gets revised to not be `rustc`-specific the linked section can be changed. In the meantime this prevents leading first time contributors into a confusing cul de sac.

view details

Mara Bos

commit sha 81edbbc2bfacd29558a5020990d49fc07ed80ac7

Implement TryFrom between NonZero types.

view details

Giles Cope

commit sha 0c32e811577fbf2ff46a607897f9ea7b6b95b364

Fixing escaping to ensure generation of welformed json.

view details

wcampbell

commit sha a93f58f5e6c9e4e1fbc076d966a9e1e853ea06fd

Join map operators Signed-off-by: wcampbell <wcampbell1995@gmail.com>

view details

wcampbell

commit sha 964a5ac962d32c280d036df42b2e747809939cc4

Use is_ok() instead of empty Ok(_) Signed-off-by: wcampbell <wcampbell1995@gmail.com>

view details

ayazhafiz

commit sha abfbd1bd719bd1440132ead24ec64c0acd293f41

Avoid extraneous space between visibility kw and ident for statics Today, given a static like `static mut FOO: usize = 1`, rustdoc would emit `static mut FOO: usize = 1`, as it emits both the mutability kw with a space and reserves a space after the mutability kw. This patch fixes that misformatting. This patch also adds some tests for emit of other statics, as I could not find an existing test devoted to statics.

view details

ayazhafiz

commit sha e60072f5c65c619263d137daf9afab9c6cb94c8e

fixup! Avoid extraneous space between visibility kw and ident for statics

view details

Ryan Scott

commit sha 000ec5e2f8e7bf3f5da59f6f219fe02dff42d116

Made slice sort documentation consistent between stable and unstable versions

view details

Ryan Scott

commit sha 8446d949f1d53b2c7ee4155f8fbf3d1390e3f203

Following #74010 by converting some newer cases of backticked O notations to be italicized

view details

Mara Bos

commit sha b9db54b3a238124b19856a03eccef7ae3ae86d91

Bump nzint_try_from_nzint_conv stabilization version to 1.49. Missed the 1.48 cycle.

view details

est31

commit sha 5948e62f3443df626cc803fd3a08bc24e42209e8

Sync LLVM submodule if it has been initialized Since having enabled the download-ci-llvm option, and having rebased on top of f05b47ccdfa63f8b4b9fb47a9aa92381801d3ff1, I've noticed that I had to update the llvm-project submodule manually if it was checked out. Orignally, the submodule update logic was introduced to reduce the friction for contributors to manage the submodules, or in other words, to prevent getting PRs that have unwanted submodule rollbacks because the contributors didn't run git submodule update. This commit adds logic to ensure there is no inadvertent LLVM submodule rollback in a PR if download-ci-llvm (or llvm-config) is enabled. It will detect whether the llvm-project submodule is initialized, and if so, update it in any case. If it is not initialized, behaviour is kept to not do any update/initialization. An alternative to the chosen implementation would be to not pass the --init command line arg to `git submodule update` for the src/llvm-project submodule. This would show a confusing error message however on all builds with an uninitialized repo. We could pass the --silent param, but we still want it to print something if it is initialized and has to update something. So we just do a manual check for whether the submodule is initialized.

view details

Eric Huss

commit sha e852a4abf01f605aa71cd529887c17c4c64f33ed

Update cargo

view details

varkor

commit sha e0b61111f83d4465fcc439d4186710f860b05a4b

Mark `repr128` as `incomplete_features`

view details

Camelid

commit sha d725da129e76963ec4309edc49a34471a2b21038

Clean up and improve some docs * compiler docs * Don't format list as part of a code block * Clean up some other formatting * rustdoc book * Update CommonMark spec version to latest (0.28 -> 0.29) * Clean up some various wording and formatting

view details

LeSeulArtichaut

commit sha 769b4108e288c4074b502336a38a5c39bfff555a

Make closures inherit the parent function's target features

view details

varkor

commit sha 683db310c4a2e205bd954ea030cff3ce2fa9ef68

Fix clippy tests

view details

LeSeulArtichaut

commit sha b4a9854afe0ab75f1b0e0c46a9342c835d5bf7b9

Fixup: add missing trailing newline

view details

Aaron Hill

commit sha 36a5244da311b9cd9a4ee04a75f15e23cf9fe891

Explain where the closure return type was inferred Fixes #78193

view details

Santiago Pastorino

commit sha 954b5a81b46f60df640f36cfc83f04cd2a965051

Rename parse_const_expr to parse_const_block

view details

Santiago Pastorino

commit sha f8842b9bacaf277430fa5c6cdf430b046dc7f323

Make inline const work in range patterns

view details

push time in 3 days

Pull request review commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

 impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {                 if self.predicate_may_hold(&try_obligation) && impls_future {                     if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {                         if snippet.ends_with('?') {-                            err.span_suggestion(-                                span,-                                "consider using `.await` here",-                                format!("{}.await?", snippet.trim_end_matches('?')),+                            err.span_suggestion_verbose(+                                span.with_hi(span.hi() - BytePos(1)).shrink_to_hi(),

We could add a method Span::shrink_by_one(Self) to avoid the BytePos play, but two calls would still be needed.

estebank

comment created time in 3 days

PullRequestReviewEvent

push eventestebank/rust

Esteban Küber

commit sha 226ac27e973274c03a4f613c28fe84140a9eb080

Suggest semicolon removal and boxing when appropriate

view details

push time in 4 days

push eventestebank/rust

Esteban Küber

commit sha 981eab09742bd23e4f911a4a8f429d8feb0b1380

Add test case for different `impl Future`s

view details

Esteban Küber

commit sha e9f9942cbfdf081879107e7409a0b674c1763759

Add more `.await` suggestions on E0308

view details

push time in 4 days

Pull request review commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

 error[E0277]: the `?` operator can only be applied to values that implement `Try   --> $DIR/incorrect-syntax-suggestions.rs:16:19    | LL |     let _ = await bar()?;

Done. We also silence the await in non-async fn error for this case in particular, but that should be fine.

estebank

comment created time in 4 days

PullRequestReviewEvent

push eventestebank/rust

Dylan MacKenzie

commit sha 77e6c56ab6f108fdbb8acbd176497be9f074af9a

Unify `&mut` and `&raw mut` const-checking errors

view details

Dylan MacKenzie

commit sha c1494d60dbad39c218e7b0825bfe590cc22bf2fa

Bless tests

view details

Mara Bos

commit sha 64839ee00ab4076d797901ddea55f2613c5b75b5

Add Pin::new_static.

view details

Mara Bos

commit sha 390883e888c580d054ab4a2584c851aba50865e9

Make Pin::new_static const.

view details

Julian Wollersberger

commit sha 39b0e7928579c4ce3a42e849695f9380b7869d62

Remove generic argument from `QueryConfig`.

view details

Mara Bos

commit sha 104c0f0194177442ff16cf14907a96d2f8d200dd

Rename Pin::new_static to Pin::static_ref.

view details

Mara Bos

commit sha 2c71f682d74d13ae6673dc701a9bb3a0562f57c0

Add Pin::static_mut.

view details

Mara Bos

commit sha f83446b836900ce9afbaa0816a5b4feda654b51e

Reword safety guarantee of Pin::static_{ref,mut}. Co-authored-by: Peter Todd <pete@petertodd.org>

view details

Mara Bos

commit sha df95dcebf5f98cefdc60c9b9d818fb285ac07d5b

Add missing `mut`. Co-authored-by: David Tolnay <dtolnay@gmail.com>

view details

Niels Sascha Reedijk

commit sha 7b652d341e9a476658af8a9186972ce73ec38c3c

Haiku: explicitly set CMAKE_SYSTEM_NAME when cross-compiling This resolves issues where the cross-build of LLVM fails because it tries to link to the host's system libraries instead of the target's system libraries.

view details

Dániel Buga

commit sha 64c239cbd6d694dbe2a5a13198c265669d7a8f8e

Add codegen test for issue #73827

view details

Wesley Wiser

commit sha 1d07d696d22a6d5a1ea1a41e0408ea5e990b25ae

Optimize const value interning for ZST types Interning can skip any inhabited ZST type in general.

view details

Olivia Crain

commit sha cc0b718aaa35bfb2a9ca5dd59078ae7e54dbc4bb

Mark inout asm! operands as used in liveness pass

view details

Olivia Crain

commit sha fd193f2d7f7ebed086de9977951cac76211533b0

Treat InOut variables like other input variables

view details

Camelid

commit sha 7b33ae642e29635f8446fed7641b5665d0c149e6

Improve wording of "cannot multiply" type error For example, if you had this code: fn foo(x: i32, y: f32) -> f32 { x * y } You would get this error: error[E0277]: cannot multiply `f32` to `i32` --> src/lib.rs:2:7 | 2 | x * y | ^ no implementation for `i32 * f32` | = help: the trait `Mul<f32>` is not implemented for `i32` However, that's not usually how people describe multiplication. People usually describe multiplication like how the division error words it: error[E0277]: cannot divide `i32` by `f32` --> src/lib.rs:2:7 | 2 | x / y | ^ no implementation for `i32 / f32` | = help: the trait `Div<f32>` is not implemented for `i32` So that's what this change does. It changes this: error[E0277]: cannot multiply `f32` to `i32` --> src/lib.rs:2:7 | 2 | x * y | ^ no implementation for `i32 * f32` | = help: the trait `Mul<f32>` is not implemented for `i32` To this: error[E0277]: cannot multiply `i32` by `f32` --> src/lib.rs:2:7 | 2 | x * y | ^ no implementation for `i32 * f32` | = help: the trait `Mul<f32>` is not implemented for `i32`

view details

Stein Somers

commit sha 003516f91a80dd8d440c932352b2fd6c6dc900b7

BTreeMap: split off most code of remove and split_off

view details

Ralf Jung

commit sha 762ded17f83a9309c5d8a626e2bc30a544048007

we can test std and core panic macros together

view details

est31

commit sha 66c1fc4c87215d6555941909996afb18eb1402ea

Move orphan module-name/mod.rs files into module-name.rs files

view details

Guillaume Gomez

commit sha 4e2c59a970695b2809a0f68f2ffe415ebdb04913

Greatly improve display for small mobile devices screens

view details

Camelid

commit sha 48060f1a63aa8b1ae04b34c3597f691d4b5e13db

rustdoc: Show the correct source filename, without `.html` Previously the title would be lib.rs.html -- source if `lib.rs` was the actual source filename. Now the title is lib.rs – source (note the en dash).

view details

push time in 4 days

Pull request review commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

 error[E0277]: the `?` operator can only be applied to values that implement `Try   --> $DIR/incorrect-syntax-suggestions.rs:16:19    | LL |     let _ = await bar()?;

I'll fix it in this PR after all.

estebank

comment created time in 4 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

 error[E0277]: the `?` operator can only be applied to values that implement `Try   --> $DIR/incorrect-syntax-suggestions.rs:16:19    | LL |     let _ = await bar()?;

I just took a look: this is because await bar()? gets recovered as bar()?.await instead of bar().await?. Either one will be a pure guess. We could avoid the subsequent errors by not recovering and just leaving an error node in the AST...

estebank

comment created time in 4 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

 static_assert_size!(ObligationCauseCode<'_>, 32); #[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)] pub struct MatchExpressionArmCause<'tcx> {     pub arm_span: Span,-    pub semi_span: Option<Span>,+    pub semi_span: Option<(Span, bool)>,

Done.

estebank

comment created time in 4 days

PullRequestReviewEvent

push eventestebank/rust

Esteban Küber

commit sha 7302584eb64997666dfa91dda45442f369f93c7d

Review comments: use newtype instead of `bool`

view details

push time in 4 days

Pull request review commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {             _ => return None,         };         let last_expr_ty = self.node_ty(last_expr.hir_id);-        if matches!(last_expr_ty.kind(), ty::Error(_))-            || self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err()+        let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) {+            (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => {+                debug!(

I tried that, but by boxing both types. I'll try only with one.

estebank

comment created time in 4 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

 error[E0277]: the `?` operator can only be applied to values that implement `Try   --> $DIR/incorrect-syntax-suggestions.rs:16:19    | LL |     let _ = await bar()?;

It's indeed not. This is a pre-existing suggestion artifact that I would rather tackle in a separate PR.

estebank

comment created time in 5 days

PullRequestReviewEvent

issue commentrust-lang/rust

Nonsensical error when trying to use associated const in array

I'm pretty sure there was an existing ticket for this 😅 but yeah, unless anyone has spare cycles it will become moot once min_const_generics is stabilized. Do not close the ticket though.

Aaron1011

comment created time in 5 days

issue closedrust-lang/rust

rust missing features like powerful text formatting

rust doesn't have printf or scanf function so we can specify the %4d or %5.4f (to format the text) and do like:

int main(void){
char c='d';
printf("%d",c);
}

which would print the char as the ASCII value and allow all sorts of text manipulation

closed time in 5 days

anshul-birajdar

issue commentrust-lang/rust

rust missing features like powerful text formatting

You can also try out C/Python style format strings and rustc will show you the Rust way to represent the same formatting string.

You have to use println!("format str", args); in Rust.

I would advice you read the freely available Rust Book and visit https://users.rust-lang.org/ for support. This issue tracker is for bug reporting and feature requests.

anshul-birajdar

comment created time in 5 days

pull request commentrust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures

r? @oli-obk

estebank

comment created time in 5 days

PR opened rust-lang/rust

Tweak match arm semicolon removal suggestion to account for futures
  • Suggest removal of semicolon on prior match arm
  • Account for impl Future when suggesting semicolon removal

Thanks to https://twitter.com/a_hoverbear/status/1318960787105353728 for pointing this out!

+296 -82

0 comment

18 changed files

pr created time in 5 days

create barnchestebank/rust

branch : match-semicolon

created branch time in 5 days

pull request commentrust-lang/rust

Tweak "object unsafe" errors

@bors r=oli-obk

estebank

comment created time in 6 days

push eventestebank/rust

Bastian Kauschke

commit sha fd22e87afc9082522bc7b52e32d25d43c64594e6

fix flag computation for `ExistentialPredicate::Projection`

view details

Bastian Kauschke

commit sha 7652b4b1d9cec0ad22f529a4335d05f7d7792521

guard against `skip_binder` errors during FlagComputation

view details

Joshua Nelson

commit sha bd135674814d74ca6fca3ab79d778ecaaeb02cf5

Allow setting up git hooks from other worktrees

view details

Ralf Jung

commit sha 0ec3ea9e697ea9c2ce225ba0b9f3715434fc773e

const keyword: brief paragraph on 'const fn'

view details

Ralf Jung

commit sha c8405d2251ce78651f591ed8a2189c41593f5110

fix markdown reference Co-authored-by: Dariusz Niedoba <darksv@users.noreply.github.com>

view details

wcampbell

commit sha 058699d0a2fca02127761f014d0ecfce1c5541ec

[net] clippy: needless_update warning: struct update has no effect, all the fields in the struct have already been specified --> library/std/src/net/addr.rs:367:19 | 367 | ..unsafe { mem::zeroed() } | ^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(clippy::needless_update)]` on by default = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_update

view details

wcampbell

commit sha e6dc604e8b184b1224ae7acf58f06fa021ece82c

[net] clippy: match_like_matches_macro warning: match expression looks like `matches!` macro --> library/std/src/net/ip.rs:459:9 | 459 | / match self.octets() { 460 | | [169, 254, ..] => true, 461 | | _ => false, 462 | | } | |_________^ help: try this: `matches!(self.octets(), [169, 254, ..])` | = note: `#[warn(clippy::match_like_matches_macro)]` on by default = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#match_like_matches_macro Signed-off-by: wcampbell <wcampbell1995@gmail.com>

view details

wcampbell

commit sha 7a75f4418313da0173192ed4d2f198e505e11428

[net] clippy: identity_op warning: the operation is ineffective. Consider reducing it to `self.segments()[0]` --> library/std/src/net/ip.rs:1265:9 | 1265 | (self.segments()[0] & 0xffff) == 0xfe80 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(clippy::identity_op)]` on by default = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_op warning: the operation is ineffective. Consider reducing it to `self.segments()[1]` --> library/std/src/net/ip.rs:1266:16 | 1266 | && (self.segments()[1] & 0xffff) == 0 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_op warning: the operation is ineffective. Consider reducing it to `self.segments()[2]` --> library/std/src/net/ip.rs:1267:16 | 1267 | && (self.segments()[2] & 0xffff) == 0 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_op warning: the operation is ineffective. Consider reducing it to `self.segments()[3]` --> library/std/src/net/ip.rs:1268:16 | 1268 | && (self.segments()[3] & 0xffff) == 0 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_op Signed-off-by: wcampbell <wcampbell1995@gmail.com>

view details

aticu

commit sha 39867f3c9fea0e01b5b199d8c2b6b0889284cc85

Fixed false positive for `unused_parens` lint

view details

wcampbell

commit sha 7da0e58da4f1a4a7f102eb5478dbd4e7fa7edbaf

use matches! in library/std/src/net/ip.rs Apply suggestion from review Co-authored-by: LingMan <LingMan@users.noreply.github.com>

view details

wcampbell

commit sha ce04836327e6aebab6a834d89e7305d1b1be958b

fmt Signed-off-by: wcampbell <wcampbell1995@gmail.com>

view details

Yuki Okushi

commit sha 608f2600de26a37000e5ba0c76891d7cef13a3c5

Rename some RFC dirs to be sorted alphabetically

view details

Yuki Okushi

commit sha d87c17d22f6e5dce477dbd5d26e35847682f3a9c

Migrate from `associated-const` to `associated-consts`

view details

Yuki Okushi

commit sha 3113c077c042cdcbc0a071c11452118e7711a1c4

Migrate from `associated-type` to `associated-types`

view details

Yuki Okushi

commit sha 72b3807a09fd46a8650915dd4118eee4369ae6b8

Clarify the `mod` dir name not to make confusion with the `modules`

view details

Yuki Okushi

commit sha 3156310eb342bfe441d49bad5249b18ead651cdc

Migrate from `generic` to `generics`

view details

Stein Somers

commit sha 488b999fc20896318192f8e22709095cccd0a6bf

BTreeMap: test invariants more thoroughly and more readably

view details

wcampbell

commit sha 736c27ec0b2cd8c79fedd66e5487b47b8746b7c0

Revert "[net] clippy: needless_update" This reverts commit 058699d0a2fca02127761f014d0ecfce1c5541ec.

view details

Bastian Kauschke

commit sha 34c80aaffd6fb7104460489952c58238eaea92ab

change name in mailmap

view details

Aaron Hill

commit sha f6aec82d4d7c9a75698808c28454d601aceac06f

Avoid cloning the contents of a `TokenStream` in a few places

view details

push time in 6 days

push eventestebank/rust

Esteban Küber

commit sha b017f312f27ad745940e3923382d03304b3398a2

Add regression test for ICE

view details

push time in 7 days

pull request commentrust-lang/rust

Tweak `if let` suggestion to be more liberal with suggestion and to not ICE

The ICE is in the beta now.

estebank

comment created time in 7 days

Pull request review commentrust-lang/rust

Tweak `if let` suggestion to be more liberal with suggestion and to not ICE

 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {             let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();             let lhs_ty = self.check_expr(&lhs);             let rhs_ty = self.check_expr(&rhs);-            if self.can_coerce(lhs_ty, rhs_ty) {-                if !lhs.is_syntactic_place_expr() {-                    // Do not suggest `if let x = y` as `==` is way more likely to be the intention.-                    if let hir::Node::Expr(hir::Expr {-                        kind: ExprKind::Match(_, _, hir::MatchSource::IfDesugar { .. }),-                        ..-                    }) = self.tcx.hir().get(-                        self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(expr.hir_id)),-                    ) {-                        // Likely `if let` intended.-                        err.span_suggestion_verbose(-                            expr.span.shrink_to_lo(),-                            "you might have meant to use pattern matching",-                            "let ".to_string(),-                            Applicability::MaybeIncorrect,-                        );-                    }+            let (mut msg, applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) {+                ("likely", Applicability::MachineApplicable, true)+            } else {+                ("might have", Applicability::MaybeIncorrect, false)

Addressed, now we only use "might have" regardless of applicability.

estebank

comment created time in 7 days

PullRequestReviewEvent

push eventestebank/rust

Yuki Okushi

commit sha 5a7218009ec093f03bc0d2eb3ea2444ed4276f23

Rollup merge of #77429 - WaffleLapkin:doc_link_default_hasher_new, r=jyn514 Link `new` method in `DefautHasher`s doc FIXME referenced #56922 which was resolved r? @jyn514

view details

Wesley Wiser

commit sha f9d7720be7805d24f5f9c14e33b22f7ca3c7b964

Disable the SimplifyArmIdentity mir-opt The optimization still has some bugs that need to be worked out such as #77359. We can try re-enabling this again after the known issues are resolved.

view details

varkor

commit sha 0801263279bbd44b7dbe88d5039a6b810a037f3b

Fix missing diagnostic span for `impl Trait` with const generics

view details

bors

commit sha f283d3f02cf3ed261a519afe05cde9e23d1d9278

Auto merge of #77436 - JohnTitor:rollup-65dh7rp, r=JohnTitor Rollup of 11 pull requests Successful merges: - #76851 (Fix 'FIXME' about using NonZeroU32 instead of u32.) - #76979 (Improve std::sys::windows::compat) - #77111 (Stabilize slice_ptr_range.) - #77147 (Split sys_common::Mutex in StaticMutex and MovableMutex.) - #77312 (Remove outdated line from `publish_toolstate` hook) - #77362 (Fix is_absolute on WASI) - #77375 (rustc_metadata: Do not forget to encode inherent impls for foreign types) - #77385 (Improve the example for ptr::copy) - #77389 (Fix some clippy lints) - #77399 (BTreeMap: use Unique::from to avoid a cast where type information exists) - #77429 (Link `new` method in `DefautHasher`s doc) Failed merges: r? `@ghost`

view details

varkor

commit sha 1db05e032db798b3162926ee4b72072d3c4de56f

Add various `min_const_generics` regression tests

view details

Andrew Dona-Couch

commit sha cd506eaea3064c396e851cc9e92b3405e8bc77c6

Fix AVR stack corruption bug Updates the Rust LLVM fork to pull in a fix for a stack corruption bug in AVR platform interrupt code lowering. Fixes #75504

view details

Michael Wright

commit sha e91202cf683b7265eec484ad311b5a9d3b56fc3e

Allow exponent separator Fixes #6096

view details

Ivan Tham

commit sha ddd19866a739deb7cf798218d3b5b52a77b04a7a

Clean up on example doc fixes for ptr::copy Follow up of #77385

view details

Harald Hoyer

commit sha cadd12b5f020b9b2c7bb0c5e7078b81fbdcfb6d8

Implement Make `handle_alloc_error` default to panic (for no_std + liballoc) Related: https://github.com/rust-lang/rust/issues/66741 Guarded with `#![feature(default_alloc_error_handler)]` a default `alloc_error_handler` is called, if a custom allocator is used and no other custom `#[alloc_error_handler]` is defined. The panic message does not contain the size anymore, because it would pull in the fmt machinery, which would blow up the code size significantly.

view details

Esteban Küber

commit sha 7d5a6203ec08ef6f5cf2349ba478f54ca1513989

Fix span for incorrect pattern field and add label

view details

Mara Bos

commit sha a8c2d4fc3d29496aa0a3563ec9d44f6222597fe3

Move boxing and mutex checking logic of condvar into sys_common.

view details

Mara Bos

commit sha 58deb7001deceb74cec38590a161d781d5d953b4

Make it possible to have unboxed mutexes on specific platforms. This commit keeps all mutexes boxed on all platforms, but makes it trivial to remove the box on some platforms later.

view details

Mara Bos

commit sha def5188ca887e36efdccd2cfda159eb1f3b89f9b

No longer put cloudabi mutexes in a box. Cloudabi mutexes may be moved safely.

view details

Mara Bos

commit sha 2f0386771d17703d8e5ea9abef3359770b51af3f

No longer put mutexes on the 'unsupported' platform in a box. These mutexes are just a bool (in a cell), so can be moved without problems.

view details

Mara Bos

commit sha 4f1353e54f9cdca82487b5e69f94e54047d8ea2f

No longer put wasm mutexes in a box. These mutexes are just an AtomicUsize, so can be moved without problems.

view details

Mara Bos

commit sha dc81cbdcb14bfaed773f0cd32f050caa108938e2

No longer put windows mutexes in a box. Windows SRW locks are movable (while not borrowed) according to their documentation.

view details

Mara Bos

commit sha b181f5a9231c133e2809277932d3a92cb2627b70

Make it possible to have unboxed condvars on specific platforms. This commit keeps all condvars boxed on all platforms, but makes it trivial to remove the box on some platforms later.

view details

Mara Bos

commit sha 5769a46788ec00338519fd8f87558419f0d6dd67

No longer put cloudabi condvars in a box. Cloudabi condvars may be moved safely.

view details

Mara Bos

commit sha 7f56a354114dffbbee8b12f134518d50d3aefe6a

No longer put condvars on the 'unsupported' platform in a box. These condvars are unsupported and implemented as a ZST, so can be moved without problems.

view details

Mara Bos

commit sha ec69a858e44992b37af3d559479777c0dfec1c7a

No longer put wasm condvars in a box. These condvars are just an AtomicUsize, so can be moved without problems.

view details

push time in 7 days

Pull request review commentrust-lang/rust

Tweak `if let` suggestion to be more liberal with suggestion and to not ICE

 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {             let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();             let lhs_ty = self.check_expr(&lhs);             let rhs_ty = self.check_expr(&rhs);-            if self.can_coerce(lhs_ty, rhs_ty) {-                if !lhs.is_syntactic_place_expr() {-                    // Do not suggest `if let x = y` as `==` is way more likely to be the intention.-                    if let hir::Node::Expr(hir::Expr {-                        kind: ExprKind::Match(_, _, hir::MatchSource::IfDesugar { .. }),-                        ..-                    }) = self.tcx.hir().get(-                        self.tcx.hir().get_parent_node(self.tcx.hir().get_parent_node(expr.hir_id)),-                    ) {-                        // Likely `if let` intended.-                        err.span_suggestion_verbose(-                            expr.span.shrink_to_lo(),-                            "you might have meant to use pattern matching",-                            "let ".to_string(),-                            Applicability::MaybeIncorrect,-                        );-                    }+            let (mut msg, applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) {

Yes, the expression we want to take as "ground truth" to detect if foo = bar when if let foo = bar was meant is the rhs.

estebank

comment created time in 7 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Tweak "object unsafe" errors

 error[E0038]: the trait `Trait` cannot be made into an object   --> $DIR/associated-const-in-trait.rs:9:6    |-LL | trait Trait {-   |       ----- this trait cannot be made into an object...-LL |     const N: usize;-   |           - ...because it contains this associated `const`-... LL | impl dyn Trait {    |      ^^^^^^^^^ the trait `Trait` cannot be made into an object

Changed the label to be less verbose, but it is still close to the main message.

estebank

comment created time in 7 days

PullRequestReviewEvent

push eventestebank/rust

Mark Rousskov

commit sha e023158145ece18176a2e93420600ccda0d0bc58

Permit uninhabited enums to cast into ints This essentially reverts part of #6204.

view details

Mark Rousskov

commit sha 990a39596cf3b33e550f2045f78a62970f8d78f8

Prevent ICE on uninhabited MIR interpretation

view details

Nathan West

commit sha a02014280586b53997622c501db00398376967a8

Refactor io/buffered.rs into submodules

view details

Nathan West

commit sha 96229f02402e82914ec6100b28ad2cbdd273a0d4

move buffered.rs to mod.rs

view details

Nathan West

commit sha 6d75cdfc9ed9e6987bd23add6cf3954d2499dce2

Added updated compiler diagnostic

view details

Amjad Alsharafi

commit sha da700cba08a2b194d19e63d3c51ebadce96fe46b

Stabilize move_ref_pattern

view details

Amjad Alsharafi

commit sha afb9eeb1b9ea16ca65e38673a0ef3e7be81d7252

Disabled error `E0007` from rustc_error_codes

view details

Mark Rousskov

commit sha 05c9c0ee5dcd935f518db151bee2dc88380fb92f

Modify executable checking to be more universal This uses a dummy file to check if the filesystem being used supports the executable bit in general.

view details

Nathan West

commit sha c4280af8285c61b367a87c8f6eef9876011a8150

Retry fix error reporting suggestions

view details

dylni

commit sha 1ff7da6551a7cdf6ace2a9d00e92bbab550334ee

Move `slice::check_range` to `RangeBounds`

view details

dylni

commit sha 1095dcab96d524e700b11edf366d45a0fd173fa0

Fix links

view details

dylni

commit sha eb63168e007058dad4af758faf1dca449c049777

Fix doctests

view details

dylni

commit sha f055b0bb0847ecf08fe452a270faae8324b55b05

Rename method to `assert_len`

view details

Camelid

commit sha 549f861f7d53811521cf929cf58fb6828a2a88d9

Use correct article in help message for conversion or cast Before it always used `an`; now it uses the correct article for the type.

view details

Camelid

commit sha 094f14c554c3a1f103a5d6778d4b4e131c297f11

Add article after "to" Also added missing backtick in "you can cast" message.

view details

Camelid

commit sha 8a6831a7fd3fc624643b50f494212e0ceaad3c28

Say "doesn't" instead of "wouldn't" in convert message

view details

Temirkhan Myrzamadi

commit sha 13dfbb64d313137b7d3c33067910e90f27bc6345

Suggest imports of unresolved macros

view details

Temirkhan Myrzamadi

commit sha 479298e05e8177b171c6d6bcd35fc7553b424bee

Re-run tests with --bless

view details

Temirkhan Myrzamadi

commit sha ea7cf6106864ce7929eb9f3cfe580f05ee418ac8

Don't suggest macros that out of scope

view details

Waffle

commit sha 0b923d3ca0b7f5a1a611564ee48c1e92f896d79e

add `str::{Split,RSplit}::as_str` methods This commit introduses 2 methods under "str_split_as_str" gate with common signature of `&Split<'a, _> -> &'a str'`. Both of them work like `Chars::as_str` - return unyield part of the inner string.

view details

push time in 7 days

pull request commentrust-lang/rust

Improve `skip_binder` usage during FlagComputation

@bors r+ rollup=never

Just in case this causes a regression, I'd like to have it merged on its own.

lcnr

comment created time in 7 days

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

 pub fn expand_assert<'cx>(     // `core::panic` and `std::panic` are different macros, so we use call-site     // context to pick up whichever is currently in scope.     let sp = cx.with_call_site_ctxt(sp);-    let tokens = custom_message.unwrap_or_else(|| {-        TokenStream::from(TokenTree::token(-            TokenKind::lit(-                token::Str,-                Symbol::intern(&format!(-                    "assertion failed: {}",-                    pprust::expr_to_string(&cond_expr).escape_debug()-                )),-                None,-            ),-            DUMMY_SP,-        ))-    });-    let args = P(MacArgs::Delimited(DelimSpan::from_single(sp), MacDelimiter::Parenthesis, tokens));-    let panic_call = MacCall {-        path: Path::from_ident(Ident::new(sym::panic, sp)),-        args,-        prior_type_ascription: None,++    let panic_call = {

Is the open brace here necessary for anything?

m-ou-se

comment created time in 7 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+use crate::{LateContext, LateLintPass, LintContext};+use rustc_ast as ast;+use rustc_errors::Applicability;+use rustc_hir as hir;+use rustc_middle::ty;+use rustc_span::sym;++declare_lint! {+    /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.+    ///+    /// ### Example+    ///+    /// ```rust,no_run+    /// panic!("{}");+    /// ```+    ///+    /// {{produces}}+    ///+    /// ### Explanation+    ///+    /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation+    /// with a single argument does not use `format_args!()`.+    /// A future version of Rust will interpret this string as format string,+    /// which would break this.+    PANIC_FMT,+    Warn,+    "detect braces in single-argument panic!() invocations",+    report_in_external_macro+}++declare_lint_pass!(PanicFmt => [PANIC_FMT]);++impl<'tcx> LateLintPass<'tcx> for PanicFmt {+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {+        if let hir::ExprKind::Call(f, [arg]) = &expr.kind {+            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {+                if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()+                    || Some(def_id) == cx.tcx.lang_items().panic_fn()+                {+                    check_panic(cx, f, arg);+                }+            }+        }+    }+}++fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {+    if let hir::ExprKind::Lit(lit) = &arg.kind {+        if let ast::LitKind::Str(sym, _) = lit.node {+            let mut expn = f.span.ctxt().outer_expn_data();+            if let Some(id) = expn.macro_def_id {+                if cx.tcx.is_diagnostic_item(sym::std_panic_macro, id)+                    || cx.tcx.is_diagnostic_item(sym::core_panic_macro, id)+                {+                    let s = sym.as_str();+                    if !s.contains(&['{', '}'][..]) {+                        return;+                    }+                    let s = s.replace("{{", "").replace("}}", "");+                    let looks_like_placeholder =+                        s.find('{').map_or(false, |i| s[i + 1..].contains('}'));+                    // Unwrap another level of macro expansion if this panic!()+                    // was expanded from assert!() or debug_assert!().+                    for &assert in &[sym::assert_macro, sym::debug_assert_macro] {+                        let parent = expn.call_site.ctxt().outer_expn_data();+                        if parent+                            .macro_def_id+                            .map_or(false, |id| cx.tcx.is_diagnostic_item(assert, id))+                        {+                            expn = parent;+                        }+                    }+                    if looks_like_placeholder {+                        cx.struct_span_lint(PANIC_FMT, arg.span.source_callsite(), |lint| {+                            let mut l = lint.build("Panic message contains an unused formatting placeholder");+                            l.note("This message is not used as a format string when given without arguments, but will be in a future Rust version");+                            if expn.call_site.contains(arg.span) {+                                l.span_suggestion(+                                    arg.span.shrink_to_hi(),+                                    "add the missing argument(s)",+                                    ", argument".into(),+                                    Applicability::HasPlaceholders,

We could actively parse the potential fmt string to get the accurate arg count, but this might be follow up work.

m-ou-se

comment created time in 7 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+use crate::{LateContext, LateLintPass, LintContext};+use rustc_ast as ast;+use rustc_errors::Applicability;+use rustc_hir as hir;+use rustc_middle::ty;+use rustc_span::sym;++declare_lint! {+    /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.+    ///+    /// ### Example+    ///+    /// ```rust,no_run+    /// panic!("{}");+    /// ```+    ///+    /// {{produces}}+    ///+    /// ### Explanation+    ///+    /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation+    /// with a single argument does not use `format_args!()`.+    /// A future version of Rust will interpret this string as format string,+    /// which would break this.+    PANIC_FMT,+    Warn,+    "detect braces in single-argument panic!() invocations",+    report_in_external_macro+}++declare_lint_pass!(PanicFmt => [PANIC_FMT]);++impl<'tcx> LateLintPass<'tcx> for PanicFmt {+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {+        if let hir::ExprKind::Call(f, [arg]) = &expr.kind {+            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {+                if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()+                    || Some(def_id) == cx.tcx.lang_items().panic_fn()+                {+                    check_panic(cx, f, arg);+                }+            }+        }+    }+}++fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {+    if let hir::ExprKind::Lit(lit) = &arg.kind {+        if let ast::LitKind::Str(sym, _) = lit.node {+            let mut expn = f.span.ctxt().outer_expn_data();+            if let Some(id) = expn.macro_def_id {+                if cx.tcx.is_diagnostic_item(sym::std_panic_macro, id)+                    || cx.tcx.is_diagnostic_item(sym::core_panic_macro, id)+                {

A common approach I take to avoid deeply nested fns is to use early returns like

let lit = match &arg.kind {
    hir::ExprKind::Lit(lit) => lit,
    _ => return,
};
}

Not necessary to do that now.

m-ou-se

comment created time in 7 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+use crate::{LateContext, LateLintPass, LintContext};+use rustc_ast as ast;+use rustc_errors::Applicability;+use rustc_hir as hir;+use rustc_middle::ty;+use rustc_span::sym;++declare_lint! {+    /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.+    ///+    /// ### Example+    ///+    /// ```rust,no_run+    /// panic!("{}");+    /// ```+    ///+    /// {{produces}}+    ///+    /// ### Explanation+    ///+    /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation+    /// with a single argument does not use `format_args!()`.+    /// A future version of Rust will interpret this string as format string,+    /// which would break this.+    PANIC_FMT,+    Warn,+    "detect braces in single-argument panic!() invocations",+    report_in_external_macro+}++declare_lint_pass!(PanicFmt => [PANIC_FMT]);++impl<'tcx> LateLintPass<'tcx> for PanicFmt {+    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {+        if let hir::ExprKind::Call(f, [arg]) = &expr.kind {+            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {+                if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()+                    || Some(def_id) == cx.tcx.lang_items().panic_fn()+                {+                    check_panic(cx, f, arg);+                }+            }+        }+    }+}++fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {+    if let hir::ExprKind::Lit(lit) = &arg.kind {+        if let ast::LitKind::Str(sym, _) = lit.node {+            let mut expn = f.span.ctxt().outer_expn_data();+            if let Some(id) = expn.macro_def_id {+                if cx.tcx.is_diagnostic_item(sym::std_panic_macro, id)+                    || cx.tcx.is_diagnostic_item(sym::core_panic_macro, id)+                {+                    let s = sym.as_str();+                    if !s.contains(&['{', '}'][..]) {+                        return;+                    }+                    let s = s.replace("{{", "").replace("}}", "");+                    let looks_like_placeholder =+                        s.find('{').map_or(false, |i| s[i + 1..].contains('}'));+                    // Unwrap another level of macro expansion if this panic!()+                    // was expanded from assert!() or debug_assert!().+                    for &assert in &[sym::assert_macro, sym::debug_assert_macro] {+                        let parent = expn.call_site.ctxt().outer_expn_data();+                        if parent+                            .macro_def_id+                            .map_or(false, |id| cx.tcx.is_diagnostic_item(assert, id))+                        {+                            expn = parent;+                        }+                    }+                    if looks_like_placeholder {+                        cx.struct_span_lint(PANIC_FMT, arg.span.source_callsite(), |lint| {+                            let mut l = lint.build("Panic message contains an unused formatting placeholder");+                            l.note("This message is not used as a format string when given without arguments, but will be in a future Rust version");
                            let mut l = lint.build("panic message contains an unused formatting placeholder");
                            l.span_label(arg.span, "this is not used as a format string when given without arguments, but will be in a future Rust version");
m-ou-se

comment created time in 7 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {         mbe::TokenTree::MetaVar(_, name) => format!("${}", name),         mbe::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),         _ => panic!(-            "unexpected mbe::TokenTree::{{Sequence or Delimited}} \+            "{}",+            "unexpected mbe::TokenTree::{Sequence or Delimited} \              in follow set checker"         ),

Oh! I see. Makes sense.

m-ou-se

comment created time in 7 days

PullRequestReviewEvent

pull request commentrust-lang/rust

Improve wording of "cannot multiply" type error

@bors r+

camelid

comment created time in 7 days

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

+warning: Panic message contains a brace+  --> $DIR/panic-brace.rs:5:5+   |+LL |     panic!("here's a brace: {");+   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^+   |+   = note: `#[warn(panic_fmt)]` on by default+   = note: This message is not used as a format string, but will be in a future Rust version+help: add a "{}" format string to use the message literally+   |+LL |     panic!("{}", "here's a brace: {");+   |            ^^^^^++warning: Panic message contains a brace+  --> $DIR/panic-brace.rs:6:5+   |+LL |     std::panic!("another one: }");+   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+   |+   = note: This message is not used as a format string, but will be in a future Rust version+help: add a "{}" format string to use the message literally+   |+LL |     std::panic!("{}", "another one: }");+   |                 ^^^^^++warning: Panic message contains an unused formatting placeholder+  --> $DIR/panic-brace.rs:7:18+   |+LL |     core::panic!("Hello {}");+   |                  ^^^^^^^^^^+   |+   = note: This message is not used as a format string when given without arguments, but will be in a future Rust version+help: add the missing argument(s)+   |+LL |     core::panic!("Hello {}", argument);+   |                            ^^^^^^^^^^+help: or add a "{}" format string to use the message literally+   |+LL |     core::panic!("{}", "Hello {}");+   |                  ^^^^^++warning: Panic message contains an unused formatting placeholder+  --> $DIR/panic-brace.rs:8:20+   |+LL |     assert!(false, "{:03x} bla");+   |                    ^^^^^^^^^^^^+   |+   = note: This message is not used as a format string when given without arguments, but will be in a future Rust version+help: add the missing argument(s)+   |+LL |     assert!(false, "{:03x} bla", argument);+   |                                ^^^^^^^^^^+help: or add a "{}" format string to use the message literally+   |+LL |     assert!(false, "{}", "{:03x} bla");+   |                    ^^^^^

I feel that the second suggestion should be for assert!(false, "{{:03x}} bla"); instead.

m-ou-se

comment created time in 7 days

PullRequestReviewEvent

Pull request review commentrust-lang/rust

Add lint for panic!("{}")

 fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {         mbe::TokenTree::MetaVar(_, name) => format!("${}", name),         mbe::TokenTree::MetaVarDecl(_, name, kind) => format!("${}:{}", name, kind),         _ => panic!(-            "unexpected mbe::TokenTree::{{Sequence or Delimited}} \+            "{}",+            "unexpected mbe::TokenTree::{Sequence or Delimited} \              in follow set checker"         ),

I would have imagined that this case would be accepted as correct: the panic message is explicitly escaping the braces.

m-ou-se

comment created time in 7 days

more