When struct_field_align_threshold is non-zero and trailing_comma is set to
"Never," struct field separators are omitted between field groups. This issue is
resolved by forcing separators between groups.
Fixes#4791.
A test is included with a minimal reproducible example.
then we just suggest the first legal position where you could inject a use.
To do this, I added `inject_use_span` field to `ModSpans`, and populate it in
parser (it is the span of the first token found after inner attributes, if any).
Then I rewrote the use-suggestion code to utilize it, and threw out some stuff
that is now unnecessary with this in place. (I think the result is easier to
understand.)
Then I added a test of issue 87613.
Fixes 5238
A markdown header is defined by a string that starts with `#`.
Previously, rustfmt would wrap long markdown headers when
`wrap_comments=true`. This lead to issues when rendering these headers
in HTML using rustdoc.
Now, rustfmt leaves markdown headers alone when wrapping comments.
We only want to fall back if two conditions are met:
1) Initial module resolution is performed relative to some nested
directory.
2) Module resolution fails because of a ModError::FileNotFound error.
When these conditions are met we can try to fallback to searching for
the module's file relative to the dir_path instead of the nested
relative directory.
Fixes 5198
As demonstrated by 5198, it's possible that a directory name conflicts
with a rust file name. For example, src/lib/ and src/lib.rs.
If src/lib.rs references an external module like ``mod foo;``, then
module resolution will try to resolve ``foo`` to src/lib/foo.rs or
src/lib/foo/mod.rs. Module resolution would fail with a file not
found error if the ``foo`` module were defined at src/foo.rs.
When encountering these kinds of module resolution issues we now fall
back to the current directory and attempt to resolve the module again.
Given the current example, this means that if we can't find the module
``foo`` at src/lib/foo.rs or src/lib/foo/mod.rs, we'll attempt
to resolve the module to src/foo.rs.
Fixes 5157
Doc comments support markdown, but rustfmt didn't previously assign any
semantic value to leading '> ' in comments. This lead to poor formatting
when using ``wrap_comments=true``.
Now, rustfmt treats block quotes as itemized blocks, which greatly
improves how block quotes are formatted when ``wrap_comments=true``.
Fixes 5042
Previously, trailing commas were removed from the last inline comment.
This lead to rustfmt refusing to format code snippets because
the original comment did not match the rewritten comment.
Now, when rustfmt extracts the last inline comment it leaves trailing
separators alone. Rustfmt does not need to remove these separators
because they are commented out.
Fixes 5125
Previously, a newline was always added, even if the parameter name was
not preceded by any param attrs.
Now a newline is only added if there were param attrs.
Remove deprecated LLVM-style inline assembly
The `llvm_asm!` was deprecated back in #87590 1.56.0, with intention to remove
it once `asm!` was stabilized, which already happened in #91728 1.59.0. Now it
is time to remove `llvm_asm!` to avoid continued maintenance cost.
Closes#70173.
Closes#92794.
Closes#87612.
Closes#82065.
cc `@rust-lang/wg-inline-asm`
r? `@Amanieu`
Mak DefId to AccessLevel map in resolve for export
hir_id to accesslevel in resolve and applied in privacy
using local def id
removing tracing probes
making function not recursive and adding comments
Move most of Exported/Public res to rustc_resolve
moving public/export res to resolve
fix missing stability attributes in core, std and alloc
move code to access_levels.rs
return for some kinds instead of going through them
Export correctness, macro changes, comments
add comment for import binding
add comment for import binding
renmae to access level visitor, remove comments, move fn as closure, remove new_key
fmt
fix rebase
fix rebase
fmt
fmt
fix: move macro def to rustc_resolve
fix: reachable AccessLevel for enum variants
fmt
fix: missing stability attributes for other architectures
allow unreachable pub in rustfmt
fix: missing impl access level + renaming export to reexport
Missing impl access level was found thanks to a test in clippy
* Fix newlines in JSON output
This changes the JSON output to be more consistent about where newlines are included. Previously it only included them between lines in a multiline diff. That meant single line changes were treated a bit weirdly. This changes it to append a newline to every line.
When feeding the results into `arc lint` this behaves correctly. I have only done limited testing though, in particular there's a possibility it might not work with files with `\r\n` endings (though that would have been the case before too).
Fixes#4259
* Update tests
# Conflicts:
# tests/writemode/target/output.json
* Fix some possible panics when using `--check` with stdin.
One case which doesn't work is when there are only line ending fixes;
with stdin rustfmt is unable to detect the difference as it stores
the input with Unix line endings.
* Add test for `rustfmt --check -l` with stdin.
Fixes 5119
When the directory structure was laid out as follows:
```
dir
|---mod_a
| |---sub_mod_1.rs
| |---sub_mod_2.rs
|---mod_a.rs
```
And ``mod_a.rs`` contains the following content:
```rust
mod mod_a {
mod sub_mod_1;
mod sub_mod_2;
}
```
rustfmt previously tried to find ``sub_mod_1.rs`` and ``sub_mod_2.rs``
in ``./mod_a/mod_a/``. This directory does not exist and this caused
rustfmt to fail with the error message:
Error writing files: failed to resolve mod
Now, both ``sub_mod_1.rs`` and ``sub_mod_2.rs`` are resolved correctly
and found at ``mod_a/sub_mod_1.rs`` and ``mod_a/sub_mod_2.rs``.
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.