Commit graph

122 commits

Author SHA1 Message Date
Aaron Hill
f916b0474a
Implement span quoting for proc-macros
This PR implements span quoting, allowing proc-macros to produce spans
pointing *into their own crate*. This is used by the unstable
`proc_macro::quote!` macro, allowing us to get error messages like this:

```
error[E0412]: cannot find type `MissingType` in this scope
  --> $DIR/auxiliary/span-from-proc-macro.rs:37:20
   |
LL | pub fn error_from_attribute(_args: TokenStream, _input: TokenStream) -> TokenStream {
   | ----------------------------------------------------------------------------------- in this expansion of procedural macro `#[error_from_attribute]`
...
LL |             field: MissingType
   |                    ^^^^^^^^^^^ not found in this scope
   |
  ::: $DIR/span-from-proc-macro.rs:8:1
   |
LL | #[error_from_attribute]
   | ----------------------- in this macro invocation
```

Here, `MissingType` occurs inside the implementation of the proc-macro
`#[error_from_attribute]`. Previosuly, this would always result in a
span pointing at `#[error_from_attribute]`

This will make many proc-macro-related error message much more useful -
when a proc-macro generates code containing an error, users will get an
error message pointing directly at that code (within the macro
definition), instead of always getting a span pointing at the macro
invocation site.

This is implemented as follows:
* When a proc-macro crate is being *compiled*, it causes the `quote!`
  macro to get run. This saves all of the sapns in the input to `quote!`
  into the metadata of *the proc-macro-crate* (which we are currently
  compiling). The `quote!` macro then expands to a call to
  `proc_macro::Span::recover_proc_macro_span(id)`, where `id` is an
opaque identifier for the span in the crate metadata.
* When the same proc-macro crate is *run* (e.g. it is loaded from disk
  and invoked by some consumer crate), the call to
`proc_macro::Span::recover_proc_macro_span` causes us to load the span
from the proc-macro crate's metadata. The proc-macro then produces a
`TokenStream` containing a `Span` pointing into the proc-macro crate
itself.

The recursive nature of 'quote!' can be difficult to understand at
first. The file `src/test/ui/proc-macro/quote-debug.stdout` shows
the output of the `quote!` macro, which should make this eaier to
understand.

This PR also supports custom quoting spans in custom quote macros (e.g.
the `quote` crate). All span quoting goes through the
`proc_macro::quote_span` method, which can be called by a custom quote
macro to perform span quoting. An example of this usage is provided in
`src/test/ui/proc-macro/auxiliary/custom-quote.rs`

Custom quoting currently has a few limitations:

In order to quote a span, we need to generate a call to
`proc_macro::Span::recover_proc_macro_span`. However, proc-macros
support renaming the `proc_macro` crate, so we can't simply hardcode
this path. Previously, the `quote_span` method used the path
`crate::Span` - however, this only works when it is called by the
builtin `quote!` macro in the same crate. To support being called from
arbitrary crates, we need access to the name of the `proc_macro` crate
to generate a path. This PR adds an additional argument to `quote_span`
to specify the name of the `proc_macro` crate. Howver, this feels kind
of hacky, and we may want to change this before stabilizing anything
quote-related.

Additionally, using `quote_span` currently requires enabling the
`proc_macro_internals` feature. The builtin `quote!` macro
has an `#[allow_internal_unstable]` attribute, but this won't work for
custom quote implementations. This will likely require some additional
tricks to apply `allow_internal_unstable` to the span of
`proc_macro::Span::recover_proc_macro_span`.
2021-05-12 00:51:31 -04:00
Dylan DPC
0740015d59
Rollup merge of #85050 - FabianWolff:issue-84592, r=jackh726
Fix suggestions for missing return type lifetime specifiers

This pull request aims to fix #84592. The issue is that the current code seems to assume that there is only a single relevant span pointing to the missing lifetime, and only looks at the first one:
e5f83d24ae/compiler/rustc_resolve/src/late/lifetimes.rs (L2959)

This is incorrect, though, and leads to incorrect error messages and invalid suggestions. For instance, the example from #84592:
```rust
struct TwoLifetimes<'x, 'y> {
    x: &'x (),
    y: &'y (),
}

fn two_lifetimes_needed(a: &(), b: &()) -> TwoLifetimes<'_, '_> {
    TwoLifetimes { x: &(), y: &() }
}
```
currently leads to:
```
error[E0106]: missing lifetime specifiers
 --> src/main.rs:6:57
  |
6 | fn two_lifetimes_needed(a: &(), b: &()) -> TwoLifetimes<'_, '_> {
  |                            ---     ---                  ^^ expected 2 lifetime parameters
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
  |
6 | fn two_lifetimes_needed<'a>(a: &'a (), b: &'a ()) -> TwoLifetimes<'_<'a, 'a>, '_> {
  |                        ^^^^    ^^^^^^     ^^^^^^                  ^^^^^^^^^^
```
There are two problems:
- The error message is wrong. There is only _one_ lifetime parameter expected at the location pointed to by the error message (and another one at a separate location).
- The suggestion is incorrect and will not lead to correct code.

With the changes in this PR, I get the following output:
```
error[E0106]: missing lifetime specifiers
 --> p.rs:6:57
  |
6 | fn two_lifetimes_needed(a: &(), b: &()) -> TwoLifetimes<'_, '_> {
  |                            ---     ---                  ^^  ^^ expected named lifetime parameter
  |                                                         |
  |                                                         expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
  |
6 | fn two_lifetimes_needed<'a>(a: &'a (), b: &'a ()) -> TwoLifetimes<'a, 'a> {
  |                        ^^^^    ^^^^^^     ^^^^^^                  ^^  ^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0106`.
```
Mainly, I changed `add_missing_lifetime_specifiers_label()` to receive a _vector_ of spans (and counts) instead of just one, and adjusted its body accordingly.
2021-05-10 16:15:00 +02:00
Fabian Wolff
2448c7698e More minor fixes suggested by @jackh726 2021-05-10 15:02:15 +02:00
Joshua Nelson
ebbc949575 Note why Handler::fatal is different from Sesssion::fatal 2021-05-08 23:13:04 -04:00
Joshua Nelson
96509b4835 Make Diagnostic::span_fatal unconditionally raise an error
It had no callers which didn't immediately call `raise()`, and this
unifies the behavior with `Session`.
2021-05-08 23:12:04 -04:00
Fabian Wolff
439ef6d762 Fix suggestions for missing return type lifetime parameters 2021-05-07 20:46:49 +02:00
The8472
b98629bfbc lazify backtrace formatting for delayed diagnostics
This defers backtrace formatting to the point where we
actually want to flush delayed diagnostics. If they are discarded
before that point then we can avoid invoking the backtrace formatting
machinery which will parse debug info and symbol tables.

for debuginfo=2 this leads to a 20% walltime reduction of the UI testsuite
2021-05-05 22:57:48 +02:00
Andy Wang
5417b45c26
Use local and remapped paths where appropriate 2021-05-05 15:31:28 +01:00
Dylan DPC
e7e22b47ad
Rollup merge of #84235 - klensy:styled-buffer, r=lcnr
refactor StyledBuffer

Refactors StyledBuffer `text` and `styles` fields content into StyledChar and touches some other stuff.
2021-04-25 23:15:10 +02:00
klensy
8ebd811b32 review 2021-04-24 22:37:42 +03:00
klensy
f43ee8ebf6 fix few typos 2021-04-19 15:57:08 +03:00
klensy
cb2d52282f rename StyledBuffer.text to lines 2021-04-16 05:38:32 +03:00
klensy
247d74f207 StyledBuffer::set_style: check overwrite first 2021-04-16 05:23:40 +03:00
klensy
7e9d3c6f6c StyledBuffer::prepend: if line is empty, insert content without inserting spaces 2021-04-16 05:11:45 +03:00
klensy
e97ddedac6 added some docs for StyledBuffer 2021-04-16 04:14:59 +03:00
klensy
f5229916e3 added default for StyledChar 2021-04-16 03:20:07 +03:00
klensy
756be4a052 refactored StyledBuffer parts into StyledChar 2021-04-16 03:14:05 +03:00
Joshua Nelson
0a351abf83 Document compiler/ with -Aprivate-intra-doc-links
Since compiler/ always passes --document-private-items, it's ok to link
to items that are private.
2021-04-05 08:38:09 -04:00
Dylan DPC
a1c34493d4
Rollup merge of #73945 - est31:unused_externs, r=Mark-Simulacrum
Add an unstable --json=unused-externs flag to print unused externs

This adds an unstable flag to print a list of the extern names not used by cargo.

This PR will enable cargo to collect unused dependencies from all units and provide warnings.
The companion PR to cargo is: https://github.com/rust-lang/cargo/pull/8437

The goal is eventual stabilization of this flag in rustc as well as in cargo.

Discussion of this feature is mostly contained inside these threads: #57274 #72342 #72603

The feature builds upon the internal datastructures added by #72342

Externs are uniquely identified by name and the information is sufficient for cargo.
If the mode is enabled, rustc will print json messages like:

```
{"unused_extern_names":["byteorder","openssl","webpki"]}
```

For a crate that got passed byteorder, openssl and webpki dependencies but needed none of them.

### Q: Why not pass -Wunused-crate-dependencies?
A: See [ehuss's comment here](https://github.com/rust-lang/rust/issues/57274#issuecomment-624839355)
   TLDR: it's cleaner. Rust's warning system wasn't built to be filtered or edited by cargo.
   Even a basic implementation of the feature would have to change the "n warnings emitted" line that rustc prints at the end.
   Cargo ideally wants to synthesize its own warnings anyways. For example, it would be hard for rustc to emit warnings like
   "dependency foo is only used by dev targets", suggesting to make it a dev-dependency instead.

### Q: Make rustc emit used or unused externs?
A: Emitting used externs has the advantage that it simplifies cargo's collection job.
   However, emitting unused externs creates less data to be communicated between rustc and cargo.
   Often you want to paste a cargo command obtained from `cargo build -vv` for doing something
   completely unrelated. The message is emitted always, even if no warning or error is emitted.
   At that point, even this tiny difference in "noise" matters. That's why I went with emitting unused externs.

### Q: One json msg per extern or a collective json msg?
A: Same as above, the data format should be concise. Having 30 lines for the 30 crates a crate uses would be disturbing to readers.
   Also it helps the cargo implementation to know that there aren't more unused deps coming.

### Q: Why use names of externs instead of e.g. paths?
A: Names are both sufficient as well as neccessary to uniquely identify a passed `--extern` arg.
   Names are sufficient because you *must* pass a name when passing an `--extern` arg.
   Passing a path is optional on the other hand so rustc might also figure out a crate's location from the file system.
   You can also put multiple paths for the same extern name, via e.g. `--extern hello=/usr/lib/hello.rmeta --extern hello=/usr/local/lib/hello.rmeta`,
   but rustc will only ever use one of those paths.
   Also, paths don't identify a dependency uniquely as it is possible to have multiple different extern names point to the same path.
   So paths are ill-suited for identification.

### Q: What about 2015 edition crates?
A: They are fully supported.
   Even on the 2015 edition, an explicit `--extern` flag is is required to enable `extern crate foo;` to work (outside of sysroot crates, which this flag doesn't warn about anyways).
   So the lint would still fire on 2015 edition crates if you haven't included a dependency specified in Cargo.toml using `extern crate foo;` or similar.
   The lint won't fire if your sole use in the crate is through a `extern crate foo;`   statement, but that's not its job.
   For detecting unused `extern crate foo` statements, there is the `unused_extern_crates` lint
   which can be enabled by `#![warn(unused_extern_crates)]` or similar.

cc ```@jsgf``` ```@ehuss``` ```@petrochenkov``` ```@estebank```
2021-04-04 19:19:58 +02:00
bors
926ec1cb8b Auto merge of #83639 - osa1:issue83638, r=estebank
Replace tabs in err messages before rendering

This is done in other call sites, but was missing in one place.

Fixes #83638
2021-03-30 17:07:19 +00:00
Ömer Sinan Ağacan
8d7432af7b Replace tabs in err messages before rendering
This is done in other call sites, but was missing in one place.

Fixes #83638
2021-03-29 13:38:36 +03:00
Joshua Nelson
230e396a76 Fix compiler docs 2021-03-27 22:16:34 -04:00
Joshua Nelson
441dc3640a Remove (lots of) dead code
Found with https://github.com/est31/warnalyzer.

Dubious changes:
- Is anyone else using rustc_apfloat? I feel weird completely deleting
  x87 support.
- Maybe some of the dead code in rustc_data_structures, in case someone
  wants to use it in the future?
- Don't change rustc_serialize

  I plan to scrap most of the json module in the near future (see
  https://github.com/rust-lang/compiler-team/issues/418) and fixing the
  tests needed more work than I expected.

TODO: check if any of the comments on the deleted code should be kept.
2021-03-27 22:16:33 -04:00
Joshua Nelson
785aeac521 Remove unused DiagnosticBuilder::sub function
`Diagnostic::sub` is only ever used directly; it doesn't need to be
included in the builder.
2021-03-27 22:16:33 -04:00
Dylan DPC
b2e254318d
Rollup merge of #82917 - cuviper:iter-zip, r=m-ou-se
Add function core::iter::zip

This makes it a little easier to `zip` iterators:

```rust
for (x, y) in zip(xs, ys) {}
// vs.
for (x, y) in xs.into_iter().zip(ys) {}
```

You can `zip(&mut xs, &ys)` for the conventional `iter_mut()` and
`iter()`, respectively. This can also support arbitrary nesting, where
it's easier to see the item layout than with arbitrary `zip` chains:

```rust
for ((x, y), z) in zip(zip(xs, ys), zs) {}
for (x, (y, z)) in zip(xs, zip(ys, zs)) {}
// vs.
for ((x, y), z) in xs.into_iter().zip(ys).zip(xz) {}
for (x, (y, z)) in xs.into_iter().zip((ys.into_iter().zip(xz)) {}
```

It may also format more nicely, especially when the first iterator is a
longer chain of methods -- for example:

```rust
    iter::zip(
        trait_ref.substs.types().skip(1),
        impl_trait_ref.substs.types().skip(1),
    )
    // vs.
    trait_ref
        .substs
        .types()
        .skip(1)
        .zip(impl_trait_ref.substs.types().skip(1))
```

This replaces the tuple-pair `IntoIterator` in #78204.
There is prior art for the utility of this in [`itertools::zip`].

[`itertools::zip`]: https://docs.rs/itertools/0.10.0/itertools/fn.zip.html
2021-03-27 20:37:07 +01:00
klensy
229d199994 lazily calls some fns 2021-03-27 10:20:32 +03:00
Josh Stone
72ebebe474 Use iter::zip in compiler/ 2021-03-26 09:32:31 -07:00
Andre Bogus
f1807216f0 small cleanups in rustc_errors / emitter 2021-03-24 00:09:11 +01:00
Joshua Nelson
bb7c04ae9c Remove unnecessary forward_inner_docs hack
and replace it with `extended_key_value_attributes` feature.
2021-03-17 09:52:45 -04:00
est31
d018ef180d Add notes to keep the UnusedExterns structs synced up 2021-03-08 08:18:50 +01:00
est31
3a62eb74db Emit the lint level of the unused-crate-dependencies
Also, turn off the lint when the unused dependencies json flag
is specified so that cargo doesn't have to supress the lint
2021-03-08 08:18:46 +01:00
est31
aef1e35edc Emit unused externs 2021-03-08 08:17:48 +01:00
Harald van Dijk
95e096d623
Change x64 size checks to not apply to x32.
Rust contains various size checks conditional on target_arch = "x86_64",
but these checks were never intended to apply to
x86_64-unknown-linux-gnux32. Add target_pointer_width = "64" to the
conditions.
2021-03-06 16:02:48 +00:00
Andre Bogus
8abc5fd3be Even faster counting of digits for error line numbers 2021-02-27 15:28:58 +01:00
Dylan DPC
568ae3aee7
Rollup merge of #82087 - estebank:abolish-ice, r=oli-obk
Fix ICE caused by suggestion with no code substitutions

Change suggestion logic to filter and checking _before_ creating
specific resolution suggestion.

Assert earlier that suggestions contain code substitions to make it
easier in the future to debug invalid uses. If we find this becomes too
noisy in the wild, we can always make the emitter resilient to these
cases and remove the assertions.

Fix #78651.
2021-02-25 14:33:56 +01:00
Dylan DPC
0e5bca5f51
Rollup merge of #82255 - nhwn:nonzero-err-as-bug, r=davidtwco
Make `treat_err_as_bug` Option<NonZeroUsize>

`rustc -Z treat-err-as-bug=N` already requires `N` to be nonzero when the argument is parsed, so changing the type from `Option<usize>` to `Option<NonZeroUsize>` is a low-hanging fruit in terms of layout optimization.
2021-02-23 02:51:55 +01:00
Nathan Nguyen
8a5c5681da nhwn: optimize counting digits in line numbers 2021-02-18 08:20:07 -06:00
Nathan Nguyen
8ddd846ce1 nhwn: make treat_err_as_bug Option<NonZeroUsize> 2021-02-18 05:27:20 -06:00
Esteban Küber
04c2454b1e Fix ICE caused by suggestion with no code substitutions
Change suggestion logic to filter and checking _before_ creating
specific resolution suggestion.

Assert earlier that suggestions contain code substitions to make it
easier in the future to debug invalid uses. If we find this becomes too
noisy in the wild, we can always make the emitter resilient to these
cases and remove the assertions.

Fix #78651.
2021-02-13 19:52:12 -08:00
Jeremy Fitzhardinge
91d8c3b521 Make sure all fields are accounted for in encode_fields!
This will make sure the encoder will get updated if any new fields are
added to Diagnostic.
2021-02-07 14:54:22 -08:00
Jeremy Fitzhardinge
50572d6629 Implement Encoder for Diagnostic manually
...so we can skip serializing `tool_metadata` if it hasn't been set.
This makes the output a bit cleaner, and avoiding having to update a
bunch of unrelated tests.
2021-02-07 14:54:22 -08:00
Jeremy Fitzhardinge
82ccb6582a Add --extern-loc to augment unused crate dependency diagnostics
This allows a build system to indicate a location in its own dependency
specification files (eg Cargo's `Cargo.toml`) which can be reported
along side any unused crate dependency.

This supports several types of location:
 - 'json' - provide some json-structured data, which is included in the json diagnostics
     in a `tool_metadata` field
 - 'raw' - emit the provided string into the output. This also appears as a json string in
     `tool_metadata`.

If no `--extern-location` is explicitly provided then a default json entry of the form
`"tool_metadata":{"name":<cratename>,"path":<cratepath>}` is emitted.
2021-02-07 14:54:20 -08:00
Mara Bos
34d5ac25c5 Make panic/assert calls in rustc compatible with Rust 2021. 2021-02-03 22:42:53 +01:00
J. Ryan Stinnett
18f6cc6c5d Reduce tab formatting assertions to debug only
The tab replacement for diagnostics added in #79757 included a few assertions to
ensure all tab characters are handled appropriately. We've started getting
reports of these assertions firing (#81614). Since it's only a cosmetic issue,
this downgrades the assertions to debug only, so we at least continue compiling
even if the diagnostics might be a tad wonky.

Fixes #81614
2021-02-03 17:17:15 +00:00
Mark Rousskov
d5b760ba62 Bump rustfmt version
Also switches on formatting of the mir build module
2021-02-02 09:09:52 -05:00
Aaron Hill
dea8a16af5
Avoid describing a method as 'not found' when bounds are unsatisfied
Fixes #76267

When there is a single applicable method candidate, but its trait bounds
are not satisfied, we avoid saying that the method is "not found".
Insted, we update the error message to directly mention which bounds are
not satisfied, rather than mentioning them in a note.
2021-01-26 23:59:50 -05:00
LingMan
a56bffb4f9 Use Option::map_or instead of .map(..).unwrap_or(..) 2021-01-14 19:23:59 +01:00
Yuki Okushi
86b900a3ea
Rollup merge of #79757 - jryans:long-line-tab-handling-early-expand, r=estebank
Replace tabs earlier in diagnostics

This replaces tabs earlier in the diagnostics emitting process, which allows various margin calculations to ignore the existence of tabs. It does add a string copy for the source lines that are emitted.

Fixes https://github.com/rust-lang/rust/issues/78438

r? `@estebank`
2021-01-12 16:13:15 +09:00
Joshua Nelson
35f16c60e7 Switch compiler/ to intra-doc links
rustc_lint and rustc_lint_defs weren't switched because they're included
in the compiler book and so can't use intra-doc links.
2020-12-18 15:22:51 -05:00
Camelid
10487cd784 Fix typo in method name
unsuccessfull -> unsuccessful
2020-12-16 14:59:12 -08:00
Camelid
60b4082d5f Add more documentation to Diagnostic and DiagnosticBuilder 2020-12-16 14:59:11 -08:00
J. Ryan Stinnett
3537bd80ff Replace tabs earlier in diagnostics
This replaces tabs earlier in the diagnostics emitting process, which allows
various margin calculations to ignore the existence of tabs. It does add a
string copy for the source lines that are emitted.
2020-12-09 10:12:15 +00:00
Mara Bos
81f9feba97
Rollup merge of #74293 - GuillaumeGomez:rustdoc-test-compiler-output-color, r=jyn514
Rustdoc test compiler output color

Fixes #72915

We just need to be sure it doesn't break rustdoc doctests' compilation checks. Maybe some other unforeseen consequences too?

r? `@ehuss`
cc `@rust-lang/rustdoc`
2020-11-17 16:13:46 +01:00
Guillaume Gomez
32d64edcf9 Simplfy color availability check 2020-11-17 10:33:14 +01:00
Andy Russell
a78966df83
clarify span_label documentation 2020-11-16 18:05:45 -05:00
bors
5cdf5b882d Auto merge of #76931 - oli-obk:const_prop_inline_lint_madness, r=wesleywiser
Properly handle lint spans after MIR inlining

The first commit shows what happens when we apply mir inlining and then cause lints on the inlined MIR.
The second commit fixes that.

r? `@wesleywiser`
2020-11-03 16:32:34 +00:00
Aaron Hill
6bdb4e3206
Some work 2020-10-30 20:02:14 -04:00
Aaron Hill
23018a55d9
Implement rustc side of report-future-incompat 2020-10-30 20:02:14 -04:00
Joshua Nelson
57c6ed0c07 Fix even more clippy warnings 2020-10-30 10:13:39 -04:00
Dániel Buga
3fba948510 Fix typos 2020-10-29 16:51:46 +01:00
oli
888ef24c22 Address review comment 2020-10-27 14:16:23 +00:00
Oliver Scherer
c8a866ea17 Show the inline stack of MIR lints that only occur after inlining 2020-10-27 14:08:07 +00:00
est31
215cd36e1c Remove unused code from remaining compiler crates 2020-10-14 04:14:32 +02:00
Erik Hofmayer
138a2e5eaa /nightly/nightly-rustc 2020-09-23 21:51:56 +02:00
Erik Hofmayer
dd66ea2d3d Updated html_root_url for compiler crates 2020-09-23 21:14:43 +02:00
Ralf Jung
c2d9af68a0
Rollup merge of #76846 - botika:master, r=davidtwco
Avoiding unnecesary allocations at rustc_errors

Simplify the code avoiding allocations with easy alternative
2020-09-21 10:40:30 +02:00
Matthias Krüger
40dddd3305 use matches!() macro for simple if let conditions 2020-09-18 20:28:35 +02:00
Juan Aguilar Santillana
28cfa9730e Simplify panic_if_treat_err_as_bug avoiding allocations 2020-09-18 05:57:01 +00:00
Juan Aguilar Santillana
7b5d9836c4 Remove redundant to_string 2020-09-17 10:27:04 +00:00
Aurélien Deharbe
439b766161 replacing sub's that can wrap by saturating_sub's 2020-09-11 11:11:11 +02:00
Dan Aloni
7b2deb5628 rustc_{errors,session}: add delay_good_path_bug
The first use case of this detection of regression for trimmed paths
computation, that is in the case of rustc, which should be computed only
in case of errors or warnings.

Our current user of this method is deeply nested, being a side effect
from `Display` formatting on lots of rustc types. So taking only the
caller to the error message is not enough - we should collect the
traceback instead.
2020-09-02 10:43:17 +03:00
mark
9e5f7d5631 mv compiler to compiler/ 2020-08-30 18:45:07 +03:00