By changing `as_str()` to take `&self` instead of `self`, we can just
return `&str`. We're still lying about lifetimes, but it's a smaller lie
than before, where `SymbolStr` contained a (fake) `&'static str`!
Fixes 5066
When a struct pattern that contained a ".." was formatted, it was
assumed that a trailing comma should always be added if the struct
fields weren't formatted vertically.
Now, a trailing comma is only added if not already included in the
reformatted struct fields.
Although the implementation is slightly different than the original PR,
the general idea is the same. After collecting all modules we want to
exclude formatting those that contain the #![rustfmt::skip] attribute.
Fixes 5088
Previously, rustfmt would add a new comment line anytime it reformatted
an itemized block within a comment when ``wrap_comments=true``. This
would lead to rustfmt adding empty comments with trailing whitespace.
Now, new comment lines are only added if the original comment spanned
multiple lines, if the comment needs to be wrapped, or if the comment
originally started with an empty comment line.
Adds the ``nightly_only_test`` and ``stable_only_test`` attribute macros
that prevent or allow certain tests to compile on nightly and stable
respectively. This is achieved through conditionally outputting the
tests TokenStream.
If CFG_RELEASE_CHANNEL is not set, it's assumed that we're running in a
nightly environment.
To mark a test as nightly only:
#[nightly_only_test]
#[test]
fn only_run_on_nightly() {
...
}
To mark a test a stable only:
#[stable_only_test]
#[test]
fn only_run_on_stable() {
...
}
TraitKind -> Trait
TyAliasKind -> TyAlias
ImplKind -> Impl
FnKind -> Fn
All `*Kind`s in AST are supposed to be enums.
Tuple structs are converted to braced structs for the types above, and fields are reordered in syntactic order.
Also, mutable AST visitor now correctly visit spans in defaultness, unsafety, impl polarity and constness.
resolves 5012
resolves 4850
This behavior was noticed when using the ``trailing_comma = "Never"``
configuration option (5012).
This behavior was also noticed when using default configurations (4850).
rustfmt would add a trailing space to where clause bounds that had an
empty right hand side.
Now no trailing space is added to the end of these where clause bounds.
Resolves 5033
Trailing comments at the end of the root Module were removed because the
module span did not extend until the end of the file.
The root Module's span now encompasses the entire file, which ensures
that no comments are lost when using ``#![rustfmt::skip]``
This is a follow up to 5f4811ed7b
The matches! macro expresses the condition more succinctly and avoids
the extra level of indentation introduced with the match arm body.
Resolves 4615
Previously only Vertical and Mixed enum variants of DefinitiveListTactic
were considered when rewriting pre-comments for inner items in
lists::write_list.
Because we failed to considering the SpecialMacro variant we ended up in
a scenario where a ListItem with a pre_comment and a pre_comment_style
of ListItemCommentStyle::DifferentLine was written on the same line as the
list item itself.
Now we apply the same pre-comment formatting to SpecialMacro, Vertical,
and Mixed variants of DefinitiveListTactic.
Resolves 5009
For loops represented by a ControlFlow object use " in" as their connector.
rustfmt searches for the first uncommented occurrence of the word "in" within the
current span and adjusts it's starting point to look for comments right after that.
visually this looks like this:
rustfmt starts looking for comments here
|
V
for x in /* ... */ 0..1 {}
This works well in most cases, however when the pattern also contains
the word "in", this leads to issues.
rustfmt starts looking for comments here
|
V
for in_here in /* ... */ 0..1 {}
-------
pattern
In order to correctly identify the connector, the new approach first
updates the span to start after the pattern and then searches for the
first uncommented occurrence of "in".
Resolves 5011
Tuple structs with visibility modifiers and comments before the first
field were incorrectly formatted. Comments would duplicate part of the
visibility modifier and struct name.
When trying to parse the tuple fields the ``items::Context`` searches
for the opening '(', but because the visibility modifier introduces
another '(' -- for example ``pub(crate)`` -- the parsing gets messed up.
Now the span is adjusted to start after the struct identifier, or after
any generics. Adjusting the span in this way ensures that the
``items::Contex`` will correctly find the tuple fields.
rustfmt should only support rewriting a struct in an expression
position with alignment (non-default behavior) when there is no rest
(with or without a base) and all of the fields are non-shorthand.
Servo has used this since forever, and it'd be useful to be able to use
rustfmt stable there so that we can use the same rustfmt version in
both Firefox and Servo.
Feel free to close this if there's any reason it shouldn't be done.
Fixes 4984
When parsing derive attributes we're only concerned about the traits
and comments listed between the opening and closing parentheses.
Derive attribute spans currently start at the '#'.
Span starts here
|
v
#[derive(...)]
After this update the derive spans start after the opening '('.
Span starts here
|
V
#[derive(...)]
Revert anon union parsing
Revert PR #84571 and #85515, which implemented anonymous union parsing in a manner that broke the context-sensitivity for the `union` keyword and thus broke stable Rust code.
Fix#88583.
This is a copy of #4296 with these changes:
* file is not reopened again to find if the file is generated
* first five lines are scanned for `@generated` marker instead of one
* no attempt is made to only search for marker in comments
`@generated` marker is used by certain tools to understand that the
file is generated, so it should be treated differently than a file
written by a human:
* linters should not be invoked on these files,
* diffs in these files are less important,
* and these files should not be reformatted.
This PR proposes builtin support for `@generated` marker.
I have not found a standard for a generated file marker, but:
* Facebook [uses `@generated` marker](https://tinyurl.com/fb-generated)
* Phabricator tool which was spawned from Facebook internal tool
[also understands `@generated` marker](https://git.io/JnVHa)
* Cargo inserts `@generated` marker into [generated Cargo.lock files](https://git.io/JnVHP)
My personal story is that rust-protobuf project which I maintain
was broken twice because of incompatibilities/bugs in rustfmt marker
handling: [one](https://github.com/stepancheg/rust-protobuf/issues/493),
[two](https://github.com/stepancheg/rust-protobuf/issues/551).
(Also, rust-protobuf started generating `@generated` marker
[6 years ago](https://git.io/JnV5h)).
While rustfmt AST markers are useful to apply to a certain AST
elements, disable whole-file-at-once all-tools-at-once text level
marker might be easier to use and more reliable for generated code.
Encode spans relative to the enclosing item
The aim of this PR is to avoid recomputing queries when code is moved without modification.
MCP at https://github.com/rust-lang/compiler-team/issues/443
This is achieved by :
1. storing the HIR owner LocalDefId information inside the span;
2. encoding and decoding spans relative to the enclosing item in the incremental on-disk cache;
3. marking a dependency to the `source_span(LocalDefId)` query when we translate a span from the short (`Span`) representation to its explicit (`SpanData`) representation.
Since all client code uses `Span`, step 3 ensures that all manipulations
of span byte positions actually create the dependency edge between
the caller and the `source_span(LocalDefId)`.
This query return the actual absolute span of the parent item.
As a consequence, any source code motion that changes the absolute byte position of a node will either:
- modify the distance to the parent's beginning, so change the relative span's hash;
- dirty `source_span`, and trigger the incremental recomputation of all code that
depends on the span's absolute byte position.
With this scheme, I believe the dependency tracking to be accurate.
For the moment, the spans are marked during lowering.
I'd rather do this during def-collection,
but the AST MutVisitor is not practical enough just yet.
The only difference is that we attach macro-expanded spans
to their expansion point instead of the macro itself.
Added test covering this. Chose to treat the code block
as rust if and only if all of the comma-separated attributes
are rust-valid. Chose to allow/preserve whitespace around commas
Fixes#3158
- [x] Removed `?const` and change uses of `?const`
- [x] Added `~const` to the AST. It is gated behind const_trait_impl.
- [x] Validate `~const` in ast_validation.
- [ ] Add enum `BoundConstness` to the HIR. (With variants `NotConst` and
`ConstIfConst` allowing future extensions)
- [ ] Adjust trait selection and pre-existing code to use `BoundConstness`.
- [ ] Optional steps (*for this PR, obviously*)
- [ ] Fix#88155
- [ ] Do something with constness bounds in chalk
In the event a pattern starts with a leading pipe
the pattern span will contain, and begin with, the pipe.
This updates the process to see if a match arm contains
a leading pipe by leveraging this recent(ish) change to
the patterns in the AST, and avoids an indexing bug that
occurs when a pattern starts with a non-ascii char in the
old implementation.
On stable, running with `--help|-h` shows information about `file-lines`
which is a nightly-only option. This commit removes all mention of
`file-lines` from the help message on stable.
There is room for improvement here; perhaps a new struct called, e.g.,
`StableOptions` could be added to complement the existing
`GetOptsOptions` struct. `StableOptions` could have a field for each
field in `GetOptsOptions`, with each field's value being a `bool` that
specifies whether or not the option exists on stable. Or is this adding
too much complexity?
This was added to Configurations.md in #4618, but the option wasn't
actually made available. This should let people who are using Rust 2021
on nightly rustc run `cargo fmt` again.
The recursion_limit attribute avoids the following error:
```
error[E0275]: overflow evaluating the requirement `std::ptr::Unique<rustc_ast::Pat>: std::marker::Send`
|
= help: consider adding a `#![recursion_limit="256"]` attribute to your crate (`rustfmt_nightly`)
```
rustfmt: load nested out-of-line mods correctly
This should address https://github.com/rust-lang/rustfmt/issues/4874
r? `@Mark-Simulacrum`
Decided to make the change directly in tree here for expediency/to minimize any potential backporting issues, and because there's some subtree sync items I need to get resolved before pulling from r-l/rustfmt
This renames the existing `true`/`false` options to `Crate`/`Never`, then adds a
new `Module` option which causes imports to be grouped together by their
originating module.
* Test cases and get spans
* Fixed type bounds
* Fixed issue of test cases
* Fixed first test case issue
* Removed unwanted whitespaces
* Removed tmp files
* Fixed Comment removed between type name and = issue
* Fixed where clause issue and pass the full span
* has_where condition inline
* Fixed indentation error on where clause
* Removed tmp file
* Pick up comments between visibility modifier and item name
I don't think this hurts to fix. #2781, which surfaced this issue, has
a number of comments relating to similar but slightly different issues
(i.e. dropped comments in other places). I can mark #2781 as closed and
then will open new issues for the comments that are not already resolved
or tracked.
Closes#2781
* fixup! Pick up comments between visibility modifier and item name
* fixup! Pick up comments between visibility modifier and item name
Previously the indetation of a line was compared with the configured
number of spaces per tab, which could cause lines that were formatted
with hard tabs not to be recognized as indented ("\t".len() < " ".len()).
Closes#4152
A code like
```rust
extern "C" {
fn f() {
fn g() {}
}
}
```
is incorrect and does not compile. Today rustfmt formats this in a way
that is correct:
```rust
extern "C" {
fn f();
}
```
But this loses information, and doesn't have to be done because we know
the content of the block if it is present. During development I don't
think rustfmt should drop the block in this context.
Closes#4313
* Added test cases
* Fixed if condition comment issue
* Fixed extern C issue
* Removed previous test case
* Removed tmp file
* honor the authors intent
* Changed the file name to its original name
* Removed extra whitespace
This commit partially reverts #3934, opting to create a span that covers
the entire body of a closure when formatting a closure body with a
block-formatting strategy, rather than having the block-formatting code
determine if the visitor pointer should be rewound. The problem with
rewinding the visitor pointer is it may be incorrect for other (i.e.
non-artificial) AST nodes, as in the case of #4382.
Closes#4382
We no longer flatten a block that looks like this:
```rust
match val {
pat => { macro_call!() }
}
```
Currently, rust ignores trailing semicolons in macro expansion in
expression position (see https://github.com/rust-lang/rust/issues/33953)
If this is changed, flattening a block with a macro call may break the
user's code - the trailing semicolon will no longer parse if the macro
call occurs immediately on the right-hand side of the match arm
(e.g. `pat => macro_call!()`)
Previously, non-trivial type aliases in extern blocks were dropped by
rustfmt because only the type alias name would be passed to a rewritter.
This commit fixes that by passing all type information (generics,
bounds, and assignments) to a type alias rewritter, and consolidates
`rewrite_type_alias` and `rewrite_associated_type` as one function.
Add `init_log()` function which attempts to init logger, and
ignores failure. The function is called at the beginning of
every test, and will fail if the logger is already initialized.
The logger must be initialized in every test, becuase cargo runs
the tests in parallel, with no garentees about the order and time
each starts.
Without this case, an ErrorKind::LicenseCheck results in a panic:
thread 'main' panicked at 'internal error: entered unreachable code', src/tools/rustfmt/src/formatting.rs:320:18
N.B.: errors of this type are only raised when the configuration file
contains `license_tempate_path = "TEMPLATE_FILE"`.
The `NotUnicode` branch was unecessarily put on a new line, although it
was within max width:
```diff
fn baz() {
let our_error_b = result_b_from_func.or_else(|e| match e {
NotPresent => Err(e).chain_err(|| "env var wasn't provided"),
- NotUnicode(_) => Err(e).chain_err(|| "env var was very very very borkæ–‡å—化ã"),
+ NotUnicode(_) => {
+ Err(e).chain_err(|| "env var was very very very borkæ–‡å—化ã")
+ }
});
}
```