Format Rust code

Overview

rustfmt Linux badge Mac badge Windows badge crates.io badge Travis config badge

A tool for formatting Rust code according to style guidelines.

If you'd like to help out (and you should, it's a fun project!), see Contributing.md and our Code of Conduct.

You can use rustfmt in Travis CI builds. We provide a minimal Travis CI configuration (see here) and verify its status using another repository. The status of that repository's build is reported by the "travis example" badge above.

Quick start

You can run rustfmt with Rust 1.24 and above.

On the Stable toolchain

To install:

rustup component add rustfmt

To run on a cargo project in the current working directory:

cargo fmt

On the Nightly toolchain

For the latest and greatest rustfmt, nightly is required.

To install:

rustup component add rustfmt --toolchain nightly

To run on a cargo project in the current working directory:

cargo +nightly fmt

Installing from source

To install from source (nightly required), first checkout to the tag or branch for the version of rustfmt you want.

The easiest way to install is via cargo make

cargo make install

Alternatively, you can run cargo install directly as long as you set the required environment variables and features.

export CFG_RELEASE=nightly
export CFG_RELEASE_CHANNEL=nightly
cargo install --path . --force --locked --features rustfmt,cargo-fmt

(Windows users can use set to specify the environment variable values)

This will install rustfmt in your ~/.cargo/bin. Make sure to add the ~/.cargo/bin directory to your PATH variable.

Usage

Please use rustfmt --help to see information about available arguments.

Running cargo fmt

The easiest way to run rustfmt against a project is with cargo fmt. cargo fmt works on both single-crate projects and cargo workspaces. Please see cargo fmt --help for usage information.

You can specify the path to your own rustfmt binary for cargo to use by setting theRUSTFMT environment variable. This was added in v1.4.22, so you must have this version or newer to leverage this feature (cargo fmt --version)

Running rustfmt directly

To format individual files or arbitrary codes from stdin, the rustfmt binary should be used. Some examples follow:

  • rustfmt lib.rs main.rs will format "lib.rs" and "main.rs" in place
  • rustfmt will read a code from stdin and write formatting to stdout
    • echo "fn main() {}" | rustfmt would emit "fn main() {}".

For more information, including arguments and emit options, see rustfmt --help.

Verifying code is formatted

When running with --check, Rustfmt will exit with 0 if Rustfmt would not make any formatting changes to the input, and 1 if Rustfmt would make changes.

Exit codes

In other modes, Rustfmt will exit with 1 if there was some error during formatting (for example a parsing or internal error) and 0 if formatting completed without error (whether or not changes were made).

Configuring Rustfmt

Rustfmt is designed to be very configurable. You can create a TOML file called rustfmt.toml or .rustfmt.toml, place it in the project or any other parent directory and it will apply the options in that file. See the config website for all available options.

By default, Rustfmt uses a style which conforms to the Rust style guide that has been formalized through the style RFC process.

Configuration options are either stable or unstable. Stable options can always be used on any channel. Unstable options are always available on nightly, but can only be used on stable and beta with an explicit opt-in (starting in Rustfmt v2.0).

Unstable options are not available on stable/beta with Rustfmt v1.x.

See the configuration documentation on the Rustfmt GitHub page for details (look for the unstable_features section).

Differences in rustfmt versions

Default formatting of submodules

On an invocation rustfmt lib.rs, rustfmt 1.x would format both "lib.rs" and any out-of-file submodules referenced in "lib.rs", unless the skip_children configuration option was true.

With rustfmt 2.x, this behavior requires the --recursive flag (#3587). By default, out-of-file submodules of given files are not formatted.

Note that this only applies to the rustfmt binary, and does not impact cargo fmt.

Construction of config options

Rustfmt 1.x uses only the configuration options declared in the rustfmt configuration file nearest the directory rustfmt is invoked.

Rustfmt 2.x merges configuration options from all configuration files in all parent directories, with configuration files nearer the current directory having priority.

Please see Configurations for more information and #3881 for the motivating issue.

Rust's Editions

Rustfmt is able to pick up the edition used by reading the Cargo.toml file if executed through the Cargo's formatting tool cargo fmt. Otherwise, the edition needs to be specified in rustfmt.toml, e.g., with edition = "2018".

Limitations

Rustfmt tries to work on as much Rust code as possible. Sometimes, the code doesn't even need to compile! However, there are some things that Rustfmt can't do or can't do well. The following list enumerates such limitations:

  • A program where any part of the program does not parse (parsing is an early stage of compilation and in Rust includes macro expansion).
  • Any fragment of a program (i.e., stability guarantees only apply to whole programs, even where fragments of a program can be formatted today).
  • Bugs in Rustfmt (like any software, Rustfmt has bugs, we do not consider bug fixes to break our stability guarantees).

Running Rustfmt from your editor

Checking style on a CI server

To keep your code base consistently formatted, it can be helpful to fail the CI build when a pull request contains unformatted code. Using --check instructs rustfmt to exit with an error code if the input is not formatted correctly. It will also print any found differences. (Older versions of Rustfmt don't support --check, use --write-mode diff).

A minimal Travis setup could look like this (requires Rust 1.31.0 or greater):

language: rust
before_script:
- rustup component add rustfmt
script:
- cargo build
- cargo test
- cargo fmt -- --check

See this blog post for more info.

How to build and test

We recommend using cargo make when working with the rustfmt codebase.

You can alternatively use cargo directly, but you'll have to set the CFG_RELEASE and CFG_RELEASE_CHANNEL environment variables and also provide the corresponding features.

For example:

export CFG_RELEASE=1.45.0-nightly
export CFG_RELEASE_CHANNEL=nightly

(Windows users can use set to specify the environment variable values)

To build with cargo make:

cargo make build

Or alternatively with cargo directly:

cargo build --all-features
# or
CFG_RELEASE_CHANNEL=nightly CFG_RELEASE=1.45.0-nightly cargo build --all-features

To run tests with cargo make:

cargo make test

Or alternatively with cargo directly:

cargo test --all-features
# or
CFG_RELEASE_CHANNEL=nightly CFG_RELEASE=1.45.0-nightly cargo test --all-features

To run rustfmt after this, use cargo run --bin rustfmt -- filename. See the notes above on running rustfmt.

Tips

  • For things you do not want rustfmt to mangle, use #[rustfmt::skip]

  • To prevent rustfmt from formatting a macro or an attribute, use #[rustfmt::skip::macros(target_macro_name)] or #[rustfmt::skip::attributes(target_attribute_name)]

    Example:

    #![rustfmt::skip::attributes(custom_attribute)]
    
    #[custom_attribute(formatting , here , should , be , Skipped)]
    #[rustfmt::skip::macros(html)]
    fn main() {
        let macro_result1 = html! { <div>
    Hello</div>
        }.to_string();
  • When you run rustfmt, place a file named rustfmt.toml or .rustfmt.toml in target file directory or its parents to override the default settings of rustfmt. You can generate a file containing the default configuration with rustfmt --print-config default rustfmt.toml and customize as needed.

  • After successful compilation, a rustfmt executable can be found in the target directory.

  • If you're having issues compiling Rustfmt (or compile errors when trying to install), make sure you have the most recent version of Rust installed.

  • You can change the way rustfmt emits the changes with the --emit flag:

    Example:

    cargo fmt -- --emit files

    Options:

    Flag Description Nightly Only
    files overwrites output to files No
    stdout writes output to stdout No
    checkstyle emits in a checkstyle format Yes
    json emits diffs in a json format Yes

License

Rustfmt is distributed under the terms of both the MIT license and the Apache License (Version 2.0).

See LICENSE-APACHE and LICENSE-MIT for details.

Issues
  • [unstable option] merge_imports

    [unstable option] merge_imports

    Tracking issue for unstable option: merge_imports

    unstable option 
    opened by scampi 61
  • Audit public API

    Audit public API

    opened by nrc 42
  • Fixed #215

    Fixed #215

    The code is a hack. That is the best way of putting it, but it works.

    I did think of maybe re-writing how WriteMode works as it seems, to me at lest, that not all the features are implemented/documented. That or I might have understood all of it, I'm pretty new at Rust.

    opened by svmnotn 33
  • Add project-specific configuration file support.

    Add project-specific configuration file support.

    It's now possible to create a file relative to a project that will override the default values. That file is called "rustfmt.toml". The default values are stored in a file called "default.toml" and are expected to be in the same folder as the binary, regardless of where the binary is stored.

    A "default.toml" is still written next to the manifest because the test suite needs it.

    opened by sbstp 27
  • rustfmt should avoid rightwards drifting big blocks of code

    rustfmt should avoid rightwards drifting big blocks of code

    Currently rustfmt formats from

                let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| {
                    let i_expr = cx.expr_usize(v_span, i);
                    let pat = cx.pat_lit(v_span, i_expr);
    
                    let path = cx.path(v_span, vec![substr.type_ident, ident]);
                    let thing = rand_thing(cx, v_span, path, summary, |cx, sp| rand_call(cx, sp));
                    cx.arm(v_span, vec!( pat ), thing)
                }).collect::<Vec<ast::Arm> >();
    

    to

                let mut arms = variants.iter()
                                       .enumerate()
                                       .map(|(i, &(ident, v_span, ref summary))| {
                                           let i_expr = cx.expr_usize(v_span, i);
                                           let pat = cx.pat_lit(v_span, i_expr);
    
                                           let path = cx.path(v_span, vec![substr.type_ident, ident]);
                                           let thing = rand_thing(cx,
                                                                  v_span,
                                                                  path,
                                                                  summary,
                                                                  |cx, sp| rand_call(cx, sp));
                                           cx.arm(v_span, vec!(pat), thing)
                                       })
                                       .collect::<Vec<ast::Arm>>();
    

    which is much worse than the original.

    poor-formatting p-high 
    opened by nagisa 25
  • Unclear error message: Rustfmt failed … line exceeded maximum length (sorry)

    Unclear error message: Rustfmt failed … line exceeded maximum length (sorry)

    This error message doesn't tell me what are the consequences, and what can I do to avoid the problem.

    Does "Rustfmt failed" mean the file could not be parsed and has not been formatted at all, or did it just skip that one line?

    Is that a bug/limitation of rustfmt, or a lint telling me to format code better?

    What's the maximum length? Can I configure it?

    I've got these errors pointing to a few lines that only contain comments, and are 100-109 characters long. I'm confused, because it doesn't seem like an excessive line length that could cause a tool to fail.

    opened by kornelski 25
  • Initial implementation of hard tab indentation.

    Initial implementation of hard tab indentation.

    This is a draft, as perhaps not all implementation choices I made are ideal. I also wasn't sure what to do with tests.

    The general idea of this change is to switch from using a plain usize to track indentation to a special Indent type which tracks block indentation and alignment (for visual alignment) separately. Adding the hard tab mode on top of that is then trivial. This increased type safety should prevent bugs where width is passed instead of offset and vice versa (e.g. see a possible bug in src/items.rs:61-62).

    I've tested the patch and it seems to work fine in most cases. It doesn't interact well with visual indentation for function arguments + closures, but I don't think there's expectation that every possible indentation configuration option should result in a sensible style.

    opened by SiegeLord 22
  • preparation for potential rustfmt 1.4.19

    preparation for potential rustfmt 1.4.19

    We don't have any explicit plans for another rustfmt 1.x release, but opening this against a 1.4.19 branch proactively in case we do end up having to do another release.

    This includes a bump of the rustc-ap-* crates to ~~v668~~ v669 which had some minor breaking changes, and also backports the fix from #3975 to ensure that fix will be in the next released version of rustfmt regardless of whether that's a 1.x or 2.x release (Refs #4282 and #3974)

    opened by calebcartwright 21
  • Add option space_before_fn_sig_paren

    Add option space_before_fn_sig_paren

    This option adds very little code, so it would be great to have it supported.

    It's an enum, because the tracking issue originally asked for a space before generics too, which is not part of this PR. This option can be extended later to add BeforeGenerics or AroundGenerics as other values. https://github.com/rust-lang/rustfmt/pull/4302#discussion_r448549821

    Tracking issue: #3564

    opened by dylni 21
  • Format stable macro_rules

    Format stable macro_rules

    I took an existing logic for Macros 2.0 and adapted for "legacy" (stable) macro_rules syntax. At this point it seems to produce quite consistent and expected results.

    Admittedly the code is quite hacky, but I guess that's what one should expect when attempting to format macros. If not, I'm open to suggestions :)

    Issue: #8

    opened by RReverser 21
  • In Configurations.md demonstrate both cases for noop selections

    In Configurations.md demonstrate both cases for noop selections

    Continuing on from discussion in https://github.com/rust-lang/rustfmt/issues/4948 This PR improves both the idempotentency test and the users comprehension of the documentation.

    condense_wildcard_suffixes is an example where this approach is already used. I'm not sure if the new code added to the noop cases should also be added to the non-noop cases as well. condense_wildcard_suffixes doesnt do that, so I did the same. Let me know if I should change that though.

    I havent touched configuration that sorts elements into alphabetical order, as the unsorted elements in the noop case should demonstrate that its not touched by rustfmt just fine.

    brace_style: SameLineWhere doesn't seem to fit its own description , so I just skipped that one...

    pr-not-reviewed 
    opened by rukai 1
  • Syntax error after formatting a derive attribute that contains a block comment

    Syntax error after formatting a derive attribute that contains a block comment

    Formatting this code:

    #[derive(/*Debug, */Clone)]
    struct Foo;
    

    generates this syntax error:

    #[derive(#[derive(/*Debug, */ Clone)]
    struct Foo;
    

    I tested rustfmt 1.4.37 stable and nightly.

    bug a-comments 
    opened by SamRodri 0
  • rustfmt.toml in Windows cannot apply

    rustfmt.toml in Windows cannot apply

    Version: 1.4.37 OS: Window 10 IDE: Vim 8.2

    I put my custom rustfmt.toml in my project, beside Cargo.toml but rustfmt still use the default.

    I try to put it in %Appdata%/rustfmt but didn't work.

    needs-mcve 
    opened by HungPham3112 5
  • New option to style `+` in `where` bounds

    New option to style `+` in `where` bounds

    Coming from #4941. In that issue I suggested that binop_separator be used to control situations such as the following:

    pub async fn retrieve_views<'err, E, L, O, P>() -> DynResult<'err, Vec<EmployeeView>>
    where
    	<E as EmployeeAdapter>::Error: 'err
    		+ From<<L as LocationAdapter>::Error>
    		+ From<<O as OrganizationAdapter>::Error>
    		+ From<<P as PersonAdapter>::Error>
    		+ Send,
    {
    

    On the above, @calebcartwright said:

    Thanks for sharing this observation but binop_separator is by design only applicable to binary expressions, and does not apply to compound constraints regardless of the fact that the latter utilizes one of the same symbols.

    […] If you'd like to have a new config option that could be used to control that behavior in bounds then please open a new issue and we'll take that through the standard process to consider new options.

    …which makes sense. However, it leaves rustfmt without a way to configure how constraints are formatted, whereas there are similar options for other contexts (i.e. binop_separator). I personally think this should be configurable, as setting binop_separator to "Back" in a project leaves +-signs at the front in only this case.

    I would propose that this new option have the same "Front" and "Back" values available in order to maintain a consistent style across projects.

    Thanks for your consideration!

    feature-request 
    opened by Iron-E 0
  • `normalize_comments = true` causes malformed comments

    `normalize_comments = true` causes malformed comments

    Input:

    struct A {
        x: usize,
        /* protected int[] observed; */
        /* (int, int)[] stack; */
    }
    

    Expected output:

    struct A {
        x: usize,
        /* protected int[] observed;
         * (int, int)[] stack; */
    }
    

    or

    struct A {
        x: usize,
        // protected int[] observed;
        // (int, int)[] stack;
    }
    

    Actual output:

    struct A {
        x: usize,
        /* protected int[] observed; */
         * (int, int)[] stack; */
    }
    
    a-comments only-with-option 
    opened by mbartlett21 1
  • panic in annotated_snippet dep

    panic in annotated_snippet dep

    When I run rustfmt ./src/tools/rustfmt/tests/source/cfg_if/mod.rs inside the rustc repo, I get a panic inside the annotated-snipped dependency. Note: it seems that the version that rustfmt uses is outdated (0.8.0 vs 0.9.0) but I don't know if a dependency update will fix the crash.

    code:

    //! `std_detect`
    
    #[doc(hidden)] // unstable implementation detail
    #[unstable(feature = "stdsimd", issue = "27731")]
    pub mod detect;
    

    stacktrace:

    error[internal]: line formatted, but exceeded maximum width (maximum: 100 (see `max_width` option), found: 272)
       --> /home/matthias/vcs/github/rust_icemaker_rustdoc/src/tools/rustfmt/tests/source/cfg_if/detect/os/linux/cpuinfo.rs:125:125:101
        |
    125 | flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm constant_tsc arch_perfmon pebs bts aperfmperf pni dtes64 monitor ds_cpl est tm2 ssse3 cx16 xtpr pdcm sse4_1 xsave lahf_lm dtherm
        |                                                                                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        |
        = note: set `error_on_unformatted = false` to suppress the warning against comments or string literals
    
    error[internal]: line formatted, but exceeded maximum width (maximum: 100 (see `max_width` option), found: 268)
       --> /home/matthias/vcs/github/rust_icemaker_rustdoc/src/tools/rustfmt/tests/source/cfg_if/detect/os/linux/cpuinfo.rs:145:145:101
        |
    145 |             "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm constant_tsc arch_perfmon pebs bts aperfmperf pni dtes64 monitor ds_cpl est tm2 ssse3 cx16 xtpr pdcm sse4_1 xsave lahf_lm dtherm"
        |                                                                                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        |
        = note: set `error_on_unformatted = false` to suppress the warning against comments or string literals
    
    thread 'main' panicked at 'SourceAnnotation range `(100, 114)` is bigger than source length `111`', /cargo/registry/src/github.com-1ecc6299db9ec823/annotate-snippets-0.8.0/src/display_list/from_snippet.rs:273:9
    stack backtrace:
       0:     0x564977f29ebc - std::backtrace_rs::backtrace::libunwind::trace::hf16bab017f241aa7
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/../../backtrace/src/backtrace/libunwind.rs:90:5
       1:     0x564977f29ebc - std::backtrace_rs::backtrace::trace_unsynchronized::hfc27e8424e499412
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/../../backtrace/src/backtrace/mod.rs:66:5
       2:     0x564977f29ebc - std::sys_common::backtrace::_print_fmt::h5be1efcd85b410a6
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/sys_common/backtrace.rs:67:5
       3:     0x564977f29ebc - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h73cf7b443adc9274
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/sys_common/backtrace.rs:46:22
       4:     0x564977f4ca5c - core::fmt::write::h9a6d9c74526a6c1b
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/core/src/fmt/mod.rs:1150:17
       5:     0x564977f26ca5 - std::io::Write::write_fmt::hb955fdedb1f691a8
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/io/mod.rs:1667:15
       6:     0x564977f2b820 - std::sys_common::backtrace::_print::hd5ba2c14c2d68f09
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/sys_common/backtrace.rs:49:5
       7:     0x564977f2b820 - std::sys_common::backtrace::print::h3b3d8e691bd3d5e8
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/sys_common/backtrace.rs:36:9
       8:     0x564977f2b820 - std::panicking::default_hook::{{closure}}::h703c292cd78e95a9
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:210:50
       9:     0x564977f2b3db - std::panicking::default_hook::h23aea4a9b2140559
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:227:9
      10:     0x564977f2bed4 - std::panicking::rust_panic_with_hook::hde97eb7782db5504
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:624:17
      11:     0x564977f2b9b0 - std::panicking::begin_panic_handler::{{closure}}::h531b374cb1cba3c4
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:521:13
      12:     0x564977f2a364 - std::sys_common::backtrace::__rust_end_short_backtrace::h170e7849f1857b98
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/sys_common/backtrace.rs:141:18
      13:     0x564977f2b919 - rust_begin_unwind
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:517:5
      14:     0x564977b5838b - std::panicking::begin_panic_fmt::h5a33c3bbb692c362
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:460:5
      15:     0x564977e094b6 - annotate_snippets::display_list::from_snippet::format_slice::h24bf7eb1bf1178b3
      16:     0x564977e066f2 - annotate_snippets::display_list::from_snippet::<impl core::convert::From<annotate_snippets::snippet::Snippet> for annotate_snippets::display_list::structs::DisplayList>::from::h664ae91e8dd31293
      17:     0x564977d0a325 - <rustfmt_nightly::format_report_formatter::FormatReportFormatter as core::fmt::Display>::fmt::hb9ce9897fba5017f
      18:     0x564977f4ca5c - core::fmt::write::h9a6d9c74526a6c1b
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/core/src/fmt/mod.rs:1150:17
      19:     0x564977f258fe - std::io::Write::write_fmt::h53a022fee3f9ba4e
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/io/mod.rs:1667:15
      20:     0x564977f258fe - <&std::io::stdio::Stderr as std::io::Write>::write_fmt::h8a7567a28964690a
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/io/stdio.rs:1112:9
      21:     0x564977f2610c - <std::io::stdio::Stderr as std::io::Write>::write_fmt::h9846093f0899bb34
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/io/stdio.rs:1086:9
      22:     0x564977f2610c - std::io::stdio::print_to::h19f37ed4e2631fbe
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/io/stdio.rs:1192:21
      23:     0x564977f2610c - std::io::stdio::_eprint::hd5fe958f4b15fa3b
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/io/stdio.rs:1216:5
      24:     0x564977c05253 - rustfmt::format_and_emit_report::hf40926c488489c7b
      25:     0x564977bfb56e - rustfmt_nightly::Session<T>::override_config::hfdf1cc8b1ac2d5b8
      26:     0x564977c02b43 - rustfmt::execute::h3162d3eefd716678
      27:     0x564977c00155 - rustfmt::main::h08b90425a39c76c0
      28:     0x564977bfbec3 - std::sys_common::backtrace::__rust_begin_short_backtrace::h5fd028dd99929bcd
      29:     0x564977c162b9 - std::rt::lang_start::{{closure}}::h8fe9c6fdb5c6f511
      30:     0x564977f2c4da - core::ops::function::impls::<impl core::ops::function::FnOnce<A> for &F>::call_once::hf530eb2c396d070c
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/core/src/ops/function.rs:259:13
      31:     0x564977f2c4da - std::panicking::try::do_call::hbab0ca478e991868
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:403:40
      32:     0x564977f2c4da - std::panicking::try::hab10c61d9a934c4c
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:367:19
      33:     0x564977f2c4da - std::panic::catch_unwind::hda9242be086d4435
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panic.rs:129:14
      34:     0x564977f2c4da - std::rt::lang_start_internal::{{closure}}::h64b87dee3d403238
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/rt.rs:45:48
      35:     0x564977f2c4da - std::panicking::try::do_call::h281babfb4ef781cc
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:403:40
      36:     0x564977f2c4da - std::panicking::try::hc0b72d1eea0a1037
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panicking.rs:367:19
      37:     0x564977f2c4da - std::panic::catch_unwind::h6076a2dab44912c2
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/panic.rs:129:14
      38:     0x564977f2c4da - std::rt::lang_start_internal::h5ab5a505f676e733
                                   at /rustc/5eacec9ec7e112a0de1011519a57c45586d58414/library/std/src/rt.rs:45:20
      39:     0x564977c05dd2 - main
      40:     0x7fd322382b25 - __libc_start_main
      41:     0x564977bf4691 - <unknown>
    
    bug p-low help wanted 
    opened by matthiaskrgr 2
  • license should be from relative dir

    license should be from relative dir

    As mentioned in #3352, if the license file is set and we're not in the root dir when calling cargo fmt it currently falls in a heap.

    pr-not-reviewed 
    opened by gilescope 1
  • Add Together option to group_imports

    Add Together option to group_imports

    I gave a go at implementing my feature request at https://github.com/rust-lang/rustfmt/issues/4962, an option to group imports into one group. I mostly just copied the StdExternalCrate implementation.

    pr-not-reviewed 
    opened by Heliozoa 1
  • Formatting causes syntax error when indexing into return value of long unsafe block within a closure

    Formatting causes syntax error when indexing into return value of long unsafe block within a closure

    In rare cases, inserting braces around the body of a closure containing an unsafe block followed by indexing seems to cause a syntax error. Here is a minimal example for reproducing this behavior:

    unsafe fn very_long_unsafe_function(vec: &Vec<usize>) -> &Vec<usize> {
        vec
    }
    
    fn long_outer_function<'a, F>(index: usize, function: F) -> &'a usize
    where
        F: Fn(usize) -> &'a usize,
    {
        function(index)
    }
    
    fn main() {
        let vec = vec![1, 2, 3, 4];
        // Line which will be split up and reformatted by rust-fmt - compiles and runs without issues
        let output: Vec<_> = vec![0, 0, 1, 1, 2, 2].iter().map(|&index| long_outer_function(index, |index| &unsafe { very_long_unsafe_function(&vec) }[index])).collect();
        println!("{:?}", output);
    }
    

    Here is the formatted output using version 1.4.37-nightly (2021-08-25 0afc208)

    unsafe fn very_long_unsafe_function(vec: &Vec<usize>) -> &Vec<usize> {
        vec
    }
    
    fn long_outer_function<'a, F>(index: usize, function: F) -> &'a usize
    where
        F: Fn(usize) -> &'a usize,
    {
        function(index)
    }
    
    fn main() {
        let vec = vec![1, 2, 3, 4];
        let output: Vec<_> = vec![0, 0, 1, 1, 2, 2]
            .iter()
            // Rust format inserts braces around the bodies of both closures, breaking the inner closure
            .map(|&index| {
                long_outer_function(index, |index| {
                    &unsafe { very_long_unsafe_function(&vec) }[index]
                })
            })
            .collect();
        println!("{:?}", output);
    }
    

    This results in the following syntax error:

    error: expected one of `.`, `;`, `?`, `}`, or an operator, found `[`
      --> src/main.rs:18:60
       |
    18 |                 &unsafe { very_long_unsafe_function(&vec) }[index]
       |                                                            ^ expected one of `.`, `;`, `?`, `}`, or an operator
    

    Example code on the playground for reference: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=46a316d108e9686e425ee72b8bb4957e

    bug a-closures 
    opened by AimainaHito 1
  • `group_imports` option to remove grouping

    `group_imports` option to remove grouping

    Hi, thanks a lot for your work on rustfmt. I would like to have an option to always put all imports into a single group. I tried looking for an existing issue but I might have missed one

    use self::some_mod::SomeStruct;
    
    use crate::my_module;
    
    use diesel::prelude::*;
    
    use rocket::serde::json::Json;
    
    use std::env;
    
    use uuid::Uuid;
    

    would format to

    use self::some_mod::SomeStruct;
    use crate::my_module;
    use diesel::prelude::*;
    use rocket::serde::json::Json;
    use std::env;
    use uuid::Uuid;
    

    The rationale is that I like the idea of rustfmt enforcing the grouping, but find it nicer to have them all together, ordered inside the group the way rustfmt currently does it.

    If this is something that could be added to rustfmt, I could take a look at making a PR. At a glance it looks like I could just follow the implementation of the StdExternalCrate option and it wouldn't be too difficult.

    As for the name, maybe something like "Together"?

    group_imports = "Together"
    
    feature-request 
    opened by Heliozoa 0
Releases(v1.4.36)
Owner
The Rust Programming Language
The Rust Programming Language
Generate beautiful changelogs from your Git commit history

clog-cli A conventional changelog for the rest of us About clog creates a changelog automatically from your local git metadata. See the clogs changelo

Clog 721 Sep 13, 2021
🤖 Just a command runner

just just is a handy way to save and run project-specific commands. (非官方中文文档,这里,快看过来!) Commands, called recipes, are stored in a file called justfile

Casey Rodarmor 3.4k Sep 10, 2021
🎭 A CLI task runner defined by a simple markdown file

mask is a CLI task runner which is defined by a simple markdown file. It searches for a maskfile.md in the current directory which it then parses for

Jake Deichert 557 Sep 14, 2021
Git mirroring daemon

lohr lohr is a Git mirroring tool. I created it to solve a simple problem I had: I host my own git server at https://git.alarsyo.net, but want to mirr

Antoine Martin 15 Sep 4, 2021
A library to compile USDT probes into a Rust library

sonde sonde is a library to compile USDT probes into a Rust library, and to generate a friendly Rust idiomatic API around it. Userland Statically Defi

Wasmer 29 Aug 31, 2021
The Git Commit Message and Changelog Generation Framework :book:

git-journal ?? The Git Commit Message and Changelog Generation Framework Table of contents: TL;DR Installation Usage Default output Template output Co

Sascha Grunert 496 Sep 9, 2021
compile rust code into memes

cargo-memex Besides their size, rust binaries have a significant disadvantage: rust binaries are not memes yet. cargo-memex is a cargo subcommand that

Matthias Seitz 225 Aug 26, 2021
⚡️Lightning-fast linter for .env files. Written in Rust 🦀

⚡️ Lightning-fast linter for .env files. Written in Rust ?? Dotenv-linter can check / fix / compare .env files for problems that may cause the applica

null 1.2k Sep 15, 2021
Detects usage of unsafe Rust in a Rust crate and its dependencies.

cargo-geiger ☢️ A program that lists statistics related to the usage of unsafe Rust code in a Rust crate and all its dependencies. This cargo plugin w

Rust Secure Code Working Group 824 Sep 9, 2021
Automatically apply the suggestions made by rustc

rustfix The goal of this tool is to read and apply the suggestions made by rustc. Current status Currently, rustfix is split into two crates: rustfix,

The Rust Programming Language 648 Sep 14, 2021
Repository for the Rust Language Server (aka RLS)

Rust Language Server (RLS) The RLS provides a server that runs in the background, providing IDEs, editors, and other tools with information about Rust

The Rust Programming Language 3.4k Sep 14, 2021
Rust Code Completion utility

Racer - code completion for Rust RACER = Rust Auto-Complete-er. A utility intended to provide Rust code completion for editors and IDEs. Maybe one day

null 3.3k Sep 13, 2021
Create ctags/etags for a cargo project

rusty-tags A command line tool that creates tags - for source code navigation by using ctags - for a cargo project, all of its direct and indirect dep

Daniel Trstenjak 326 Sep 9, 2021
🧑🏻‍⚕️ Command-line utility which poll on remote addresses in order to perform status checks periodically

ナース (Nāsu) ????‍⚕️ Command-line utility which poll on remote addresses in order to perform status checks periodically Motivation Nāsu (from Japanese ナ

Esteban Borai 12 Aug 11, 2021
A scaffolding CLI

CRISPR ?? crispr is a CLI tool allowing to scaffold a project from a template with a .crispr.{toml,json} configuration file. The template uses tokens

Yoav Lavi 18 Sep 4, 2021
a freeform Rust build system

tinyrick: a freeform Rust build system .---. ^ o{__ω__ o{ ^0^ -Let me out! ~~ ( // *|* \xx\) xx`|' = =

Andrew 43 Sep 3, 2021
🦀 The ultimate search extension for Rust

Rust Search Extension 简体中文 The ultimate search extension for Rust Search docs, crates, builtin attributes, official books, and error codes, etc in you

Huhu 634 Sep 9, 2021
A parallel universal-ctags wrapper for git repository

ptags A parallel universal-ctags wrapper for git repository Description ptags is a universal-ctags wrapper to have the following features. Search git

null 96 Aug 31, 2021
:rocket: Automatic crate publishing done right

semantic-rs The purpose of this tool is to help people to publish crates following the semver specification. Right now if you're building a new crate

semantic-rs 165 Sep 3, 2021