Add test to prevent src link regression
Fixes#80502.
This PR is simply about adding a test to prevent a regression.
cc `@bugadani` `@CraftSpider`
r? `@camelid`
Unfortunately, this can't currently be tested. The problem is that we
need the file to be compiled first to then be used as dependency, which
cannot be done currently unfortunately in the rustdoc test suites.
Example:
```rust
// name this file "foo.rs"
/// ```
/// let x = foo::foo();
/// ```
pub fn foo() {}
```
If you run `rustdoc --test foo.rs`, you'll get:
```
running 1 test
test foo.rs - foo (line 1) ... FAILED
failures:
---- foo.rs - foo (line 1) stdout ----
error[E0463]: can't find crate for `foo`
--> foo.rs:0:1
|
2 | extern crate foo;
| ^^^^^^^^^^^^^^^^^ can't find crate
```
If a test were possible, it would look something like
````rust
#![crate_name = "mod"]
#![crate_type = "lib"]
//! ```
//! // NOTE: requires that the literal string 'mod' appears in the doctest for
//! // the bug to appear
//! assert_eq!(1, 1);
//! ```
````
The angle brackets were not rendered, so code like this:
some_func: for<'a> fn(val: &'a i32) -> i32
would be rendered as:
some_func: fn'a(val: &'a i32) -> i32
However, rendering with angle brackets is still invalid syntax:
some_func: fn<'a>(val: &'a i32) -> i32
so now it renders correctly as:
some_func: for<'a> fn(val: &'a i32) -> i32
-----
However, note that this code:
some_trait: dyn for<'a> Trait<'a>
will still render as:
some_trait: dyn Trait<'a>
which is not invalid syntax, but is still unclear. Unfortunately I think
it's hard to fix that case because there isn't enough information in the
`rustdoc::clean::Type` that this code operates on. Perhaps that case can
be fixed in a later PR.
Fix rendering of stabilization version for trait implementors
Rustdoc compares an item's stabilization version with its parent's to not render it if they are the same. Here, the implementor was compared with itself, resulting in the stabilization version never getting shown.
This probably needs a test.
Fixes#80777.
r? `@jyn514`
Deprecate-in-future the constants superceded by RFC 2700
Successor to #78335, re-opened after addressing the issues tracked in #68490.
This PR makes use of the new ability to explicitly annotate an item as triggering the deprecated-in-future lint (via `rustc_deprecated(since="TBD"`, see #78381). We might call this *soft deprecation*; unlike with deprecation, users will *not* receive warnings when compiling code that uses these items *unless* they opt-in via `#[warn(deprecated_in_future)]`. Like deprecation, soft deprecation causes documentation to formally acknowledge that an item is marked for eventual deprecation (at a non-specific point in the future).
With this new ability, we can sidestep all debate about when or on what timeframe something ought to be deprecated; as long as we can agree that something ought to be deprecated, we can receive much of the benefits of deprecation with none of the drawbacks. For these items specifically, the libs team has already agreed that they should be deprecated (see https://github.com/rust-lang/rust/issues/68490#issuecomment-747022696).
Don't try to add nested predicate to Rustdoc auto-trait `ParamEnv`
Fixes#80233
We already have logic in `evaluate_predicates` that tries to add
unimplemented predicates to our `ParamEnv`. Trying to add a predicate
that already holds can lead to errors later on, since projection
will prefer trait candidates from the `ParamEnv` to predicates from an
impl.
rustdoc: Resolve `&str` as `str`
People almost always are referring to `&str`, not `str`, so this will
save a manual link resolve in many cases.
Note that we already accept `&` (resolves to `reference`) in intra-doc
links, so this shouldn't cause breakage.
r? `@jyn514`
rustdoc: Remove `*` intra-doc alias for `pointer`
It's not valid Rust code and it can easily be confused with a wildcard
glob pattern or something else. People can always use `pointer` instead,
so it's just removing an alias.
It hasn't hit stable yet (I think it's still on nightly), so it's okay
to remove it. (We can always add it back later if we change our mind
too.)
r? `@jyn514`
cc https://github.com/rust-lang/rust/pull/80885#discussion_r554622737
It's not valid Rust code and it can easily be confused with a wildcard
glob pattern or something else. People can always use `pointer` instead,
so it's just removing an alias.
It hasn't hit stable yet (I think it's still on nightly), so it's okay
to remove it. (We can always add it back later if we change our mind
too.)
People almost always are referring to `&str`, not `str`, so this will
save a manual link resolve in many cases.
Note that we already accept `&` (resolves to `reference`) in intra-doc
links, so this shouldn't cause breakage.
Rustdoc: Fix macros 2.0 and built-in derives being shown at the wrong path
Fixes#74355
- ~~waiting on author + draft PR since my code ought to be cleaned up _w.r.t._ the way I avoid the `.unwrap()`s:~~
- ~~dummy items may avoid the first `?`,~~
- ~~but within the module traversal some tests did fail (hence the second `?`), meaning the crate did not possess the exact path of the containing module (`extern` / `impl` blocks maybe? I'll look into that).~~
r? `@jyn514`
This adjusts the `rustdoc` trait impl collection path to preserve `Deref` impls
from other crates. This adds a first pass to map all of the `Deref` type to
target edges and then recursively preserves all targets.
Properly handle primitive disambiguators in rustdoc
Fixes#80559
r? ``@jyn514``
Is there a way to test that the generated intra-doc link is what I expect?
Fix tests that incorrectly used `!@has` instead of `@!has`
The command is ``@!has`,` not `!`@has`.` I don't think these checks were
doing anything before! Ideally we would accept `!`@has`` as well, or at
least fail tests that use `!`@has`.` The current behavior seems to be
silently ignoring the check, which is very confusing.
r? `@GuillaumeGomez`
The command is `@!has`, not `!@has`. I don't think these checks were
doing anything before! Ideally we would accept `!@has` as well, or at
least fail tests that use `!@has`. The current behavior seems to be
silently ignoring the check, which is very confusing.
Fix intra-doc links for non-path primitives
This does *not* currently work for associated items that are
auto-implemented by the compiler (e.g. `never::eq`), because they aren't
present in the source code. I plan to fix this in a follow-up PR.
Fixes https://github.com/rust-lang/rust/issues/63351 using the approach mentioned in https://github.com/rust-lang/rust/issues/63351#issuecomment-683352130.
r? `@Manishearth`
cc `@petrochenkov` - this makes `rustc_resolve::Res` public, is that ok? I'd just add an identical type alias in rustdoc if not, which seems a waste.
Move tooltips messages out of html
First thing first: nothing in the output has changed. You still have the "i" on the left of code blocks examples when they have `ignore`, `compile_fail`, `should_panic` and `edition`. The behavior also remains the same: when you hover the "i", you have the corresponding message showing up.
So now, why this PR then? I realized recently that we were actually generating those messages into the HTML every time whereas all messages are the same (except for the edition ones, I'll come back to it later). So instead of generating more content, I simply moved it inside the CSS thanks to pseudo elements (`::before` and `::after`). The message is now inside `::after` and we use the `::before` to have the small triangle on the left of the message. So now, we have less HTML generated which is seems pretty nice.
So now, back to the `edition` change: the message is globally the same, but the "edition" itself can be different (2015 or 2018 currently, I expect 2021 to arrive not too far in the future). So the only difference for it is that I added a new attribute on the tooltip called `edition` which contains this information. Then, the `::after` uses it inside its `content` (you can get the content of an element's attribute by using `attr` and concat different strings by simply having them after the other).
Don't hesitate if a part of my explanations isn't clear.
r? `@jyn514`
This does *not* currently work for associated items that are
auto-implemented by the compiler (e.g. `never::eq`), because they aren't
present in the source code. I plan to fix this in a follow-up PR.
Fixes#80233
We already have logic in `evaluate_predicates` that tries to add
unimplemented predicates to our `ParamEnv`. Trying to add a predicate
that already holds can lead to errors later on, since projection
will prefer trait candidates from the `ParamEnv` to predicates from an
impl.
Apply `doc(cfg)` from parent items while collecting trait impls
Because trait impls bypass the standard `clean` hierarchy they do not participate in the `propagate_doc_cfg` pass, so instead we need to pre-collect all possible `doc(cfg)` attributes that will apply to them when cleaning.
fixes#79201
extend `WithOptConstParam` docs, move rustdoc test
This should hopefully make things a bit clearer, feel free to comment on anything which can still be improved.
cc `@ecstatic-morse` `@nikomatsakis` `@RalfJung`
Use `item_name` instead of pretty printing for resolving `Self` on intra-doc links
Pretty printing would add a `r#` prefix to raw identifiers, which was
not correct. In general I think this change makes sense -
pretty-printing is for showing to the *user*, `item_name` is suitable to
pass to resolve.
Fixes https://github.com/rust-lang/rust/issues/79633.
r? `@Manishearth`
Previously Markdown documentation was not rendered to HTML for search results,
which led to the output not being very readable, particularly for inline code.
This PR fixes that by rendering Markdown to HTML with the help of pulldown-cmark
(the library rustdoc uses to parse Markdown for the main text of documentation).
However, the text for the title attribute (the text shown when you hover over an
element) still uses the plain-text rendering since it is displayed in browsers
as plain-text.
Only these styles will be rendered; everything else is stripped away:
* *italics*
* **bold**
* `inline code`
Pretty printing would add a `r#` prefix to raw identifiers, which was
not correct. In general I think this change makes sense -
pretty-printing is for showing to the *user*, `item_name` is suitable to
pass to resolve.
Fix intra-doc links for `Self` on cross-crate items and primitives
- Remove the difference between `parent_item` and `current_item`; these
should never have been different.
- Remove `current_item` from `resolve` and `variant_field` so that
`Self` is only substituted in one place at the very start.
- Resolve the current item as a `DefId`, not a `HirId`. This is what
actually fixed the bug.
Hacks:
- `clean` uses `TypedefItem` when it _really_ should be
`AssociatedTypeItem`. I tried fixing this without success and hacked
around it instead (see comments)
- This second-guesses the `to_string()` impl since it wants
fully-qualified paths. Possibly there's a better way to do this.
- Remove the difference between `parent_item` and `current_item`; these
should never have been different.
- Remove `current_item` from `resolve` and `variant_field` so that
`Self` is only substituted in one place at the very start.
- Resolve the current item as a `DefId`, not a `HirId`. This is what
actually fixed the bug.
Hacks:
- `clean` uses `TypedefItem` when it _really_ should be
`AssociatedTypeItem`. I tried fixing this without success and hacked
around it instead (see comments)
- This stringifies DefIds, then resolves them a second time. This is
really silly and rustdoc should just use DefIds throughout. Fixing
this is a larger task than I want to take on right now.
Update tests to remove old numeric constants
Part of #68490.
Care has been taken to leave the old consts where appropriate, for testing backcompat regressions, module shadowing, etc. The intrinsics docs were accidentally referring to some methods on f64 as std::f64, which I changed due to being contrary with how we normally disambiguate the shadow module from the primitive. In one other place I changed std::u8 to std::ops since it was just testing path handling in macros.
For places which have legitimate uses of the old consts, deprecated attributes have been optimistically inserted. Although currently unnecessary, they exist to emphasize to any future deprecation effort the necessity of these specific symbols and prevent them from being accidentally removed.
Remove doctree::Macro and distinguish between `macro_rules!` and `pub macro`
This is a part of #78082, removing doctree::Macro. Uses the changes in #79372Fixes#76761
Part of #68490.
Care has been taken to leave the old consts where appropriate, for testing backcompat regressions, module shadowing, etc. The intrinsics docs were accidentally referring to some methods on f64 as std::f64, which I changed due to being contrary with how we normally disambiguate the shadow module from the primitive. In one other place I changed std::u8 to std::ops since it was just testing path handling in macros.
For places which have legitimate uses of the old consts, deprecated attributes have been optimistically inserted. Although currently unnecessary, they exist to emphasize to any future deprecation effort the necessity of these specific symbols and prevent them from being accidentally removed.
Extend doc keyword feature by allowing any ident
Part of #51315.
As suggested by ``@danielhenrymantilla`` in [this comment](https://github.com/rust-lang/rust/issues/51315#issuecomment-733879934), this PR extends `#[doc(keyword = "...")]` to allow any ident to be used as keyword. The final goal is to allow (proc-)macro crates' owners to write documentation of the keywords they might introduce.
r? ``@jyn514``
Rename "stability" CSS class to "item-info" and combine `document_stability` with `document_short`
Follow-up of #79300
The point of this PR is to make the CSS class more accurate since it's not only about stability anymore.
r? ``@jyn514``
Normalize `<X as Y>::T` for rustdoc
- Only run for `QPath::Resolved` with `Some` self parameter (`<X as Y>::T`)
- Fall back to the previous behavior if the path can't be resolved
The first commit is a pure refactor and should probably be reviewed by `@GuillaumeGomez.` I recommend reviewing the second commit on its own.
Fixes https://github.com/rust-lang/rust/issues/77459.
r? `@eddyb`
cc `@danielhenrymantilla` , `@lcnr`
Rename `optin_builtin_traits` to `auto_traits`
They were originally called "opt-in, built-in traits" (OIBITs), but
people realized that the name was too confusing and a mouthful, and so
they were renamed to just "auto traits". The feature flag's name wasn't
updated, though, so that's what this PR does.
There are some other spots in the compiler that still refer to OIBITs,
but I don't think changing those now is worth it since they are internal
and not particularly relevant to this PR.
Also see <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/opt-in.2C.20built-in.20traits.20(auto.20traits).20feature.20name>.
r? `@oli-obk` (feel free to re-assign if you're not the right reviewer for this)
- Only run for `QPath::Resolved` with `Some` self parameter (`<X as Y>::T`)
- Fall back to the previous behavior if the path can't be resolved
- Show what the behavior is if the type can't be normalized
- Run `resolve_vars_if_possible`
It's not clear whether or not this is necessary. See
https://github.com/rust-lang/rust/pull/77616 for more context.
- Add a test for cross-crate re-exports
- Use the same code for both `hir::Ty` and `Ty`
They were originally called "opt-in, built-in traits" (OIBITs), but
people realized that the name was too confusing and a mouthful, and so
they were renamed to just "auto traits". The feature flag's name wasn't
updated, though, so that's what this PR does.
There are some other spots in the compiler that still refer to OIBITs,
but I don't think changing those now is worth it since they are internal
and not particularly relevant to this PR.
Also see <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/opt-in.2C.20built-in.20traits.20(auto.20traits).20feature.20name>.
Because trait impls bypass the standard `clean` hierarchy they do not
participate in the `propagate_doc_cfg` pass, so instead we need to
pre-collect all possible `doc(cfg)` attributes that will apply to them
when cleaning.
Get rid of some doctree items
They can be derived directly from the `hir::Item`, there's no special logic.
- TypeDef
- OpaqueTy
- Constant
- Static
- TraitAlias
- Enum
- Union
- Struct
Part of #78082 (the easiest part, I'm still debugging some other changes).
r? `@GuillaumeGomez`
Fix links to extern types in rustdoc (fixes#78777)
r? `@jyn514`
Fixes#78777.
The initial fix we tried was:
```diff
diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs
index 8be9482acff..c4b7086fdb1 100644
--- a/src/librustdoc/passes/collect_intra_doc_links.rs
+++ b/src/librustdoc/passes/collect_intra_doc_links.rs
`@@` -433,8 +433,9 `@@` impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
Res::PrimTy(prim) => Some(
self.resolve_primitive_associated_item(prim, ns, module_id, item_name, item_str),
),
- Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::TyAlias, did) => {
+ Res::Def(kind, did) if kind.ns() == Some(Namespace::TypeNS) => {
debug!("looking for associated item named {} for item {:?}", item_name, did);
+
// Checks if item_name belongs to `impl SomeItem`
let assoc_item = cx
.tcx
```
However, this caused traits to be matched, resulting in a panic when `resolve_associated_trait_item` is called further down in this function.
This PR also adds an error message for that panic. Currently it will look something like:
```rust
thread 'rustc' panicked at 'Not a type: DefIndex(8624)', compiler/rustc_metadata/src/rmeta/decoder.rs:951:32
```
I wasn't sure how to get a better debug output than `DefIndex(...)`, and am open to suggestions.
- Add `Item::from_hir_id_and_kind` convenience wrapper
- Make name parameter mandatory
`tcx.opt_item_name` doesn't handle renames, so this is necessary
for any item that could be renamed, which is almost all of them.
- Override visibilities to be `Inherited` for enum variants
`tcx.visibility` returns the effective visibility, not the visibility
that was written in the source code. `pub enum E { A, B }` always has
public variants `A` and `B`, so there's no sense printing `pub` again.
- Don't duplicate handling of `Visibility::Crate`
Instead, represent it as just another `Restricted` path.
Visibility needs much less information than a full path, since modules
can never have generics. This allows constructing a Visibility from only
a DefId.
Note that this means that paths are now normalized to their DefPath.
In other words, `pub(self)` or `pub(super)` now always shows `pub(in
path)` instead of preserving the original text.
Add a test for r# identifiers
I'm not entirely sure I properly ran the test locally (I think so though), waiting for CI to confirm. :)
```````@rustbot``````` modify labels: T-rustdoc
r? ```````@jyn514```````
Rustdoc check option
The ultimate goal behind this option would be to have `rustdoc --check` being run when you use `cargo check` as a second step.
r? `@jyn514`
Reusing bindings causes errors later in lowering:
```
error[E0596]: cannot borrow `vec` as mutable, as it is not declared as mutable
--> /checkout/src/test/ui/async-await/argument-patterns.rs:12:20
|
LL | async fn b(n: u32, ref mut vec: A) {
| ^^^^^^^^^^^
| |
| cannot borrow as mutable
| help: consider changing this to be mutable: `mut vec`
```
extend const generics test suite
should implement most of #78433, especially all parts of [the hackmd](https://hackmd.io/WnFmN4MjRCqAjGmYfYcu2A?view) which I did not explicitly mention in that issue.
r? ``@varkor``
Previously the [src] link on types defined by a macro
pointed to the macro definition.
This commit makes the Clean-Implementation for Spans
aware of macro defined types,
so that the link points to the invocation instead.
(rustdoc) fix test for trait impl display
The test checks that parameters and return values with `impl Trait` types are correctly generated in rustdoc's output.
In essence, the previous version of the test checked the absence of values that would never be generated by rustdoc, so it could basically never fail. These values were adjusted to the expected output and are now required to exist in rustdoc's output. See https://github.com/rust-lang/rust/issues/55201#issuecomment-716182474 for a detailed explanation of the reasoning behind the changes.
Note that the output of rustdoc for `impl Trait`s in parameters and return values did not change since the inital test creation, so this PR only modifies the test.
Closes#55201
Avoid extraneous space between visibility kw and ident for statics
Today, given a static like `static mut FOO: usize = 1`, rustdoc would
emit `static mut FOO: usize = 1`, as it emits both the mutability kw
with a space and reserves a space after the mutability kw. This patch
fixes that misformatting.
This patch also adds some tests for emit of other statics, as I could
not find an existing test devoted to statics.
Today, given a static like `static mut FOO: usize = 1`, rustdoc would
emit `static mut FOO: usize = 1`, as it emits both the mutability kw
with a space and reserves a space after the mutability kw. This patch
fixes that misformatting.
This patch also adds some tests for emit of other statics, as I could
not find an existing test devoted to statics.
Allow generic parameters in intra-doc links
Fixes#62834.
---
The contents of the generics will be mostly ignored (except for warning
if fully-qualified syntax is used, which is currently unsupported in
intra-doc links - see issue #74563).
* Allow links like `Vec<T>`, `Result<T, E>`, and `Option<Box<T>>`
* Allow links like `Vec::<T>::new()`
* Warn on
* Unbalanced angle brackets (e.g. `Vec<T` or `Vec<T>>`)
* Missing type to apply generics to (`<T>` or `<Box<T>>`)
* Use of fully-qualified syntax (`<Vec as IntoIterator>::into_iter`)
* Invalid path separator (`Vec:<T>:new`)
* Too many angle brackets (`Vec<<T>>`)
* Empty angle brackets (`Vec<>`)
Note that this implementation *does* allow some constructs that aren't
valid in the actual Rust syntax, for example `Box::<T>new()`. That may
not be supported in rustdoc in the future; it is an implementation
detail.
The contents of the generics will be mostly ignored (except for warning
if fully-qualified syntax is used, which is currently unsupported in
intra-doc links - see issue #74563).
* Allow links like `Vec<T>`, `Result<T, E>`, and `Option<Box<T>>`
* Allow links like `Vec::<T>::new()`
* Warn on
* Unbalanced angle brackets (e.g. `Vec<T` or `Vec<T>>`)
* Missing type to apply generics to (`<T>` or `<Box<T>>`)
* Use of fully-qualified syntax (`<Vec as IntoIterator>::into_iter`)
* Invalid path separator (`Vec:<T>:new`)
* Too many angle brackets (`Vec<<T>>`)
* Empty angle brackets (`Vec<>`)
Note that this implementation *does* allow some constructs that aren't
valid in the actual Rust syntax, for example `Box::<T>new()`. That may
not be supported in rustdoc in the future; it is an implementation
detail.
- Make the parent module conditional on whether the docs are on a re-export
- Make `resolve_link` take `&Item` instead of `&mut Item`
Previously the borrow checker gave an error about multiple mutable
borrows, because `dox` borrowed from `item`.
- Fix `crate::` for re-exports
`crate` means something different depending on where the attribute
came from.
- Make it work for `#[doc]` attributes too
This required combining several attributes as one so they would keep
the links.
For sub-items on a page don't show cfg that has already been rendered on
a parent item. At its simplest this means not showing anything that is
shown in the portability message at the top of the page, but also for
things like fields of an enum variant if that variant itself is
cfg-gated then don't repeat those cfg on each field of the variant.
This does not touch trait implementation rendering, as that is more
complex and there are existing issues around how it deals with doc-cfg
that need to be fixed first.
Resolve `crate` in intra-doc links properly across crates
Closes https://github.com/rust-lang/rust/issues/77193; see https://github.com/rust-lang/rust/issues/77193#issuecomment-699065946 for an explanation of what's going on here.
~~This also fixes the BTreeMap docs that have been broken for a while; see the description on the second commit for why and how.~~ Nope, see the second commit for why the link had to be changed.
r? `@Manishearth`
cc `@dylni`
`@dylni` note that this doesn't solve your original problem - now _both_ `with_code` and `crate::with_code` will be broken links. However this will fix a lot of other broken links (in particular I think https://docs.rs/sqlx/0.4.0-beta.1/sqlx/query/struct.Query.html is because of this bug). I'll open another issue for resolving additional docs in the new scope.
This is not ideal because it means `deny(broken_intra_doc_links)` will
no longer `deny(private_intra_doc_links)`. However, it can't be fixed
with a new lint group, because `broken` is already in the `rustdoc` lint
group; there would need to be a way to nest groups somehow.
This also removes the early `return` so that the link will be generated
even though it gives a warning.
Now that `PrimTy::name()` exists, there's no need to carry around the
name of the primitive that failed to resolve. This removes the variants
special-casing primitives in favor of `NotResolved`.
- Remove `NoPrimitiveImpl` and `NoPrimitiveAssocItem`
- Remove hacky `has_primitive` check in `resolution_failure()`
- Fixup a couple tests that I forgot to `--bless` before
- Add `PrimTy::name` and `PrimTy::name_str`
- Use those new functions to distinguish between the name in scope and
the canonical name
- Fix diagnostics for primitive types
- Add tests for primitives
Previously, these were spread throughout the codebase. This had two
drawbacks:
1. It caused the fast path to be slower: even if a link resolved,
rustdoc would still perform various lookups for the error diagnostic.
2. It was inconsistent and didn't always give all diagnostics (https://github.com/rust-lang/rust/issues/76925)
Now, diagnostics only perform expensive lookups in the error case.
Additionally, the error handling is much more consistent, both in
wording and behavior.
- Remove `CannotHaveAssociatedItems`, `NotInScope`, `NoAssocItem`, and `NotAVariant`
in favor of the more general `NotResolved`
`resolution_failure` will now look up which of the four above
categories is relevant, instead of requiring the rest of the code to
be consistent and accurate in which it picked.
- Remove unnecessary lookups throughout the intra-doc link pass. These
are now done by `resolution_failure`.
+ Remove unnecessary `extra_fragment` argument to `variant_field()`;
it was only used to do lookups on failure.
+ Remove various lookups related to associated items
+ Remove distinction between 'not in scope' and 'no associated item'
- Don't perform unnecessary copies
- Remove unused variables and code
- Update tests
- Note why looking at other namespaces is still necessary
- 'has no inner item' -> 'contains no item'
bless tests
Ignore rustc_private items from std docs
By ignoring rustc_private items for non local impl block,
this may fix#74672 and fix#75588 .
This might suppress #76529 if it is simple enough for backport.
Use `is_unstable_const_fn` instead of `is_min_const_fn` in rustdoc where appropriate
This closes#76501. Specifically, it allows for nightly users with the `#![feature(const_fn)]` flag enabled to still have their `const fn` declarations documented as such, while retaining the desired behavior that rustdoc *not* document functions that have the `rustc_const_unstable` attribute as `const`.
Fix intra-doc links on pub re-exports
Partial fix for https://github.com/rust-lang/rust/issues/76073 - This removes the incorrect error, but doesn't show the documentation anywhere.
r? @GuillaumeGomez
Remove disambiguators from intra doc link text
Closes https://github.com/rust-lang/rust/issues/65354.
r? @Manishearth
The commits are mostly atomic, but there might be some mix between them here and there. I recommend reading 'refactor ItemLink' and 'refactor RenderedLink' on their own though, lots of churn without any logic changes.
- Preserve suffixes when displaying
- Rename test file to match `intra-link*`
- Remove unnecessary .clone()s
- Improve comments and naming
- Fix more bugs and add tests
- Escape intra-doc link example in public documentation
rustdoc: do not use plain summary for trait impls
Fixes#38386.
Fixes#48332.
Fixes#49430.
Fixes#62741.
Fixes#73474.
Unfortunately this is not quite ready to go because the newly-working links trigger a bunch of linkcheck failures. The failures are tough to fix because the links are resolved relative to the implementor, which could be anywhere in the module hierarchy.
(In the current docs, these links end up rendering as uninterpreted markdown syntax, so I don't think these failures are any worse than the status quo. It might be acceptable to just add them to the linkchecker whitelist.)
Ideally this could be fixed with intra-doc links ~~but it isn't working for me: I am currently investigating if it's possible to solve it this way.~~ Opened #73829.
EDIT: This is now ready!
Related to https://github.com/rust-lang/rust/issues/65354
- Pass through the replacement text to `markdown.rs`
- Add some tests
- Add a state machine that actually replaces the text when parsing Markdown
Fira Sans is what's used for module lists and other item lists.
Previously, the default body font, "Source Serif Pro", was used for
crate lists, which didn't visually match other item lists.
Fix intra-doc links for cross-crate re-exports of default trait methods
The original fix for this was very simple: https://github.com/rust-lang/rust/pull/58972 ignored `extern_traits` because before https://github.com/rust-lang/rust/issues/65983 was fixed, they would always fail to resolve, giving spurious warnings. So the first commit just undoes that change, so extern traits are now seen by the `collect_intra_doc_links` pass. There are also some minor changes in `librustdoc/fold.rs` to avoid borrowing the `extern_traits` RefCell more than once at a time.
However, that brought up a much more thorny problem. `rustc_resolve` started giving 'error: cannot find a built-in macro with name `cfg`' when documenting `libproc_macro` (I still haven't been able to reproduce on anything smaller than the full standard library). The chain of events looked like this (thanks @eddyb for the help debugging!):
0. `x.py build --stage 1` builds the standard library and creates a sysroot
1. `cargo doc` does something like `cargo check` to create `rmeta`s for all the crates (unrelated to what was built above)
2. the `cargo check`-like `libcore-*.rmeta` is loaded as a transitive dependency *and claims ownership* of builtin macros
3. `rustdoc` later tries to resolve some path in a doc link
4. suggestion logic fires and loads "extern prelude" crates by name
5. the sysroot `libcore-*.rlib` is loaded and *fails to claim ownership* of builtin macros
`rustc_resolve` gives the error after step 5. However, `rustdoc` doesn't need suggestions at all - `resolve_str_path_error` completely discards the `ResolutionError`! The fix implemented in this PR is to skip the suggestion logic for `resolve_ast_path`: pass `record_used: false` and skip `lookup_import_candidates` when `record_used` isn't set.
It's possible that if/when https://github.com/rust-lang/rust/issues/74207 is implemented this will need a more in-depth fix which returns a `ResolutionError` from `compile_macro`, to allow rustdoc to reuse the suggestions from rustc_resolve. However, that's a much larger change and there's no need for it yet, so I haven't implemented it here.
Fixes https://github.com/rust-lang/rust/issues/73829.
r? @GuillaumeGomez
Fix intra-doc links for associated constants
Previously, only associated functions would be resolved. Fixes the issues in https://github.com/rust-lang/rust/pull/75969#discussion_r477898003.
I'm a little uncomfortable hard-coding the string constants, but it looks like that's how it's done elsewhere. I might make a follow-up PR at some point putting it in one place.
Not sure how to test associated types, since AFAIK there aren't any on primitives.
r? @Manishearth
#58972 ignored extern_traits because before #65983 was fixed, they
would always fail to resolve, giving spurious warnings.
This undoes that change, so extern traits are now seen by the
`collect_intra_doc_links` pass. There are also some minor changes in
librustdoc/fold.rs to avoid borrowing the extern_traits RefCell more
than once at a time.
rustc_lexer is the lossless lexer, which is a better fit for
approximate syntax highlighting.
As a side-effect, we can now syntax-highlight even broken code.
Previously, associated items would only be available for linking
directly on the `impl Trait for Type`. Now they can be used anywhere.
- Make `item` for resolve mandatory
- Refactor resolving associated items into a separate function
- Remove broken trait_item logic
- Don't skip the type namespace for associated items
- Only call `variant_field` for `TypeNS`
- Add test for associated items
- Use exhaustive matches instead of wildcards
Wildcards caused several bugs while implementing this.
Handle projection predicates in the param env for auto-trait docs
Fixes#72213
Any predicates in the param env are guaranteed to hold, so we don't need
to do any additional processing of them if we come across them as
sub-obligations of a different predicate. This allows us to avoid adding
the same predicate to the computed ParamEnv multiple times (but with
different regions each time), which causes an ambiguity error during
fulfillment.
Display elided lifetime for non-reference type in doc
In edition 2018 we encourage writing `<'_>` explicitly, so rustdoc should display like such as well.
Fixes#75225
~~Somehow when I run the compiled rustdoc using `cargo +stage2 doc` on other crates, it correctly produces `<'_>`, but I couldn't get the std doc to do the same with `./x.py doc --stage 2`. Might this be related to the recent change to x.py about how the doc is built?~~
Fixes#72213
Any predicates in the param env are guaranteed to hold, so we don't need
to do any additional processing of them if we come across them as
sub-obligations of a different predicate. This allows us to avoid adding
the same predicate to the computed ParamEnv multiple times (but with
different regions each time), which causes an ambiguity error during
fulfillment.
This caused the following false positive:
```
warning: unresolved link to `Default::default`
--> /home/joshua/rustc2/default.rs:1:14
|
1 | /// Link to [Default::default()]
| ^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(broken_intra_doc_links)]` on by default
note: this item resolved to a trait, which did not match the disambiguator 'fn'
--> /home/joshua/rustc2/default.rs:1:14
|
1 | /// Link to [Default::default()]
| ^^^^^^^^^^^^^^^^^^
```
Instead, report the error.
This emits the errors on-demand, without special-casing `impl Trait`, so
it should catch all ICEs of this kind, including ones that haven't been
found yet.
Since the error is emitted during type-checking there is less info about
the error; see comments in the code for details.
- Add test case for -> impl Trait
- Add test for impl trait with alias
- Move EmitIgnoredResolutionErrors to rustdoc
This makes `fn typeck_item_bodies` public, which is not desired behavior.
That change should be removed once
https://github.com/rust-lang/rust/pull/74070 is merged.
- Don't visit nested closures twice
- Remove unnecessary `should_loop` variable
- Report errors for trait implementations
These should give resolution errors because they are visible outside the
current scope. Without these errors, rustdoc will give ICEs:
```
thread 'rustc' panicked at 'attempted .def_id() on invalid res: Err', /home/joshua/src/rust/src/libstd/macros.rs:16:9
15: rustc_hir::def::Res<Id>::def_id
at /home/joshua/src/rust/src/librustc_hir/def.rs:382
16: rustdoc::clean::utils::register_res
at src/librustdoc/clean/utils.rs:627
17: rustdoc::clean::utils::resolve_type
at src/librustdoc/clean/utils.rs:587
```
- Add much more extensive tests
+ fn -> impl -> fn
+ fn -> impl -> fn -> macro
+ errors in function parameters
+ errors in trait bounds
+ errors in the type implementing the trait
+ unknown bounds for the type
+ unknown types in function bodies
+ errors generated by macros
- Use explicit state instead of trying to reconstruct it from random info
- Use an enum instead of a boolean
- Add example of ignored error