Skip to content

Rollup of 5 pull requests #84368

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions compiler/rustc_error_codes/src/error_codes/E0404.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ struct Foo;
struct Bar;

impl Foo for Bar {} // error: `Foo` is not a trait
fn baz<T: Foo>(t: T) {} // error: `Foo` is not a trait
```

Another erroneous code example:

```compile_fail,E0404
struct Foo;
type Foo = Iterator<Item=String>;

fn bar<T: Foo>(t: T) {} // error: `Foo` is not a trait
fn bar<T: Foo>(t: T) {} // error: `Foo` is a type alias
```

Please verify that the trait's name was not misspelled or that the right
Expand All @@ -30,14 +31,27 @@ struct Bar;
impl Foo for Bar { // ok!
// functions implementation
}

fn baz<T: Foo>(t: T) {} // ok!
```

or:
Alternatively, you could introduce a new trait with your desired restrictions
as a super trait:

```
trait Foo {
// some functions
}
# trait Foo {}
# struct Bar;
# impl Foo for Bar {}
trait Qux: Foo {} // Anything that implements Qux also needs to implement Foo
fn baz<T: Qux>(t: T) {} // also ok!
```

Finally, if you are on nightly and want to use a trait alias
instead of a type alias, you should use `#![feature(trait_alias)]`:

```
#![feature(trait_alias)]
trait Foo = Iterator<Item=String>;

fn bar<T: Foo>(t: T) {} // ok!
```
61 changes: 52 additions & 9 deletions compiler/rustc_passes/src/dead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// from live codes are live, and everything else is dead.

use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::Applicability;
use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Res};
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
Expand All @@ -15,7 +16,7 @@ use rustc_middle::middle::privacy;
use rustc_middle::ty::{self, DefIdTree, TyCtxt};
use rustc_session::lint;

use rustc_span::symbol::{sym, Symbol};
use rustc_span::symbol::{sym, Ident, Symbol};

// Any local node that may call something in its body block should be
// explored. For example, if it's a live Node::Item that is a
Expand Down Expand Up @@ -505,6 +506,13 @@ fn find_live<'tcx>(
symbol_visitor.live_symbols
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ExtraNote {
/// Use this to provide some examples in the diagnostic of potential other purposes for a value
/// or field that is dead code
OtherPurposeExamples,
}

struct DeadVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
live_symbols: FxHashSet<hir::HirId>,
Expand Down Expand Up @@ -570,14 +578,42 @@ impl DeadVisitor<'tcx> {
&mut self,
id: hir::HirId,
span: rustc_span::Span,
name: Symbol,
name: Ident,
participle: &str,
extra_note: Option<ExtraNote>,
) {
if !name.as_str().starts_with('_') {
self.tcx.struct_span_lint_hir(lint::builtin::DEAD_CODE, id, span, |lint| {
let def_id = self.tcx.hir().local_def_id(id);
let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id());
lint.build(&format!("{} is never {}: `{}`", descr, participle, name)).emit()

let prefixed = vec![(name.span, format!("_{}", name))];

let mut diag =
lint.build(&format!("{} is never {}: `{}`", descr, participle, name));

diag.multipart_suggestion(
"if this is intentional, prefix it with an underscore",
prefixed,
Applicability::MachineApplicable,
);

let mut note = format!(
"the leading underscore signals that this {} serves some other \
purpose even if it isn't used in a way that we can detect.",
descr,
);
if matches!(extra_note, Some(ExtraNote::OtherPurposeExamples)) {
note += " (e.g. for its effect when dropped or in foreign code)";
}

diag.note(&note);

// Force the note we added to the front, before any other subdiagnostics
// added in lint.build(...)
diag.children.rotate_right(1);

diag.emit()
});
}
}
Expand Down Expand Up @@ -623,7 +659,7 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> {
hir::ItemKind::Struct(..) => "constructed", // Issue #52325
_ => "used",
};
self.warn_dead_code(item.hir_id(), span, item.ident.name, participle);
self.warn_dead_code(item.hir_id(), span, item.ident, participle, None);
} else {
// Only continue if we didn't warn
intravisit::walk_item(self, item);
Expand All @@ -637,22 +673,28 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> {
id: hir::HirId,
) {
if self.should_warn_about_variant(&variant) {
self.warn_dead_code(variant.id, variant.span, variant.ident.name, "constructed");
self.warn_dead_code(variant.id, variant.span, variant.ident, "constructed", None);
} else {
intravisit::walk_variant(self, variant, g, id);
}
}

fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) {
if self.should_warn_about_foreign_item(fi) {
self.warn_dead_code(fi.hir_id(), fi.span, fi.ident.name, "used");
self.warn_dead_code(fi.hir_id(), fi.span, fi.ident, "used", None);
}
intravisit::walk_foreign_item(self, fi);
}

fn visit_field_def(&mut self, field: &'tcx hir::FieldDef<'tcx>) {
if self.should_warn_about_field(&field) {
self.warn_dead_code(field.hir_id, field.span, field.ident.name, "read");
self.warn_dead_code(
field.hir_id,
field.span,
field.ident,
"read",
Some(ExtraNote::OtherPurposeExamples),
);
}
intravisit::walk_field_def(self, field);
}
Expand All @@ -664,8 +706,9 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> {
self.warn_dead_code(
impl_item.hir_id(),
impl_item.span,
impl_item.ident.name,
impl_item.ident,
"used",
None,
);
}
self.visit_nested_body(body_id)
Expand All @@ -683,7 +726,7 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> {
} else {
impl_item.ident.span
};
self.warn_dead_code(impl_item.hir_id(), span, impl_item.ident.name, "used");
self.warn_dead_code(impl_item.hir_id(), span, impl_item.ident, "used", None);
}
self.visit_nested_body(body_id)
}
Expand Down
9 changes: 8 additions & 1 deletion compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -930,7 +930,14 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
let msg = "you might have meant to use `#![feature(trait_alias)]` instead of a \
`type` alias";
if let Some(span) = self.def_span(def_id) {
err.span_help(span, msg);
if let Ok(snip) = self.r.session.source_map().span_to_snippet(span) {
// The span contains a type alias so we should be able to
// replace `type` with `trait`.
let snip = snip.replacen("type", "trait", 1);
err.span_suggestion(span, msg, snip, Applicability::MaybeIncorrect);
} else {
err.span_help(span, msg);
}
} else {
err.help(msg);
}
Expand Down
12 changes: 7 additions & 5 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,21 @@ impl_stable_hash_via_hash!(OptLevel);

/// This is what the `LtoCli` values get mapped to after resolving defaults and
/// and taking other command line options into account.
///
/// Note that linker plugin-based LTO is a different mechanism entirely.
#[derive(Clone, PartialEq)]
pub enum Lto {
/// Don't do any LTO whatsoever
/// Don't do any LTO whatsoever.
No,

/// Do a full crate graph LTO with ThinLTO
/// Do a full-crate-graph (inter-crate) LTO with ThinLTO.
Thin,

/// Do a local graph LTO with ThinLTO (only relevant for multiple codegen
/// units).
/// Do a local ThinLTO (intra-crate, over the CodeGen Units of the local crate only). This is
/// only relevant if multiple CGUs are used.
ThinLocal,

/// Do a full crate graph LTO with "fat" LTO
/// Do a full-crate-graph (inter-crate) LTO with "fat" LTO.
Fat,
}

Expand Down
15 changes: 12 additions & 3 deletions src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,7 @@ fn render_impl(
let cache = cx.cache();
let traits = &cache.traits;
let trait_ = i.trait_did_full(cache).map(|did| &traits[&did]);
let mut close_tags = String::new();

if render_mode == RenderMode::Normal {
let id = cx.derive_id(match i.inner_impl().trait_ {
Expand All @@ -1302,7 +1303,12 @@ fn render_impl(
format!(" aliases=\"{}\"", aliases.join(","))
};
if let Some(use_absolute) = use_absolute {
write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases);
write!(
w,
"<details class=\"rustdoc-toggle implementors-toggle\"><summary><h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">",
id, aliases
);
close_tags.insert_str(0, "</details>");
write!(w, "{}", i.inner_impl().print(use_absolute, cx));
if show_def_docs {
for it in &i.inner_impl().items {
Expand All @@ -1325,11 +1331,12 @@ fn render_impl(
} else {
write!(
w,
"<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
"<details class=\"rustdoc-toggle implementors-toggle\"><summary><h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>",
id,
aliases,
i.inner_impl().print(false, cx)
);
close_tags.insert_str(0, "</details>");
}
write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id);
render_stability_since_raw(
Expand All @@ -1341,6 +1348,7 @@ fn render_impl(
);
write_srclink(cx, &i.impl_item, w);
w.write_str("</h3>");
w.write_str("</summary>");

if trait_.is_some() {
if let Some(portability) = portability(&i.impl_item, Some(parent)) {
Expand Down Expand Up @@ -1542,6 +1550,7 @@ fn render_impl(
}

w.write_str("<div class=\"impl-items\">");
close_tags.insert_str(0, "</div>");
for trait_item in &i.inner_impl().items {
doc_impl_item(
w,
Expand Down Expand Up @@ -1612,7 +1621,7 @@ fn render_impl(
);
}
}
w.write_str("</div>");
w.write_str(&close_tags);
}

fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) {
Expand Down
27 changes: 7 additions & 20 deletions src/librustdoc/html/static/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -1196,31 +1196,18 @@ function hideThemeButtonState() {
if (!next) {
return;
}
if (hasClass(e, "impl") &&
(next.getElementsByClassName("method").length > 0 ||
next.getElementsByClassName("associatedconstant").length > 0)) {
var newToggle = toggle.cloneNode(true);
insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
// In case the option "auto-collapse implementors" is not set to false, we collapse
// all implementors.
if (hideImplementors === true && e.parentNode.id === "implementors-list") {
collapseDocs(newToggle, "hide");
}
}
};

onEachLazy(document.getElementsByClassName("method"), func);
onEachLazy(document.getElementsByClassName("associatedconstant"), func);
onEachLazy(document.getElementsByClassName("impl"), funcImpl);
var impl_call = function() {};
// Large items are hidden by default in the HTML. If the setting overrides that, show 'em.
if (!hideLargeItemContents) {
onEachLazy(document.getElementsByTagName("details"), function (e) {
if (hasClass(e, "type-contents-toggle")) {
e.open = true;
}
});
}
onEachLazy(document.getElementsByTagName("details"), function (e) {
var showLargeItem = !hideLargeItemContents && hasClass(e, "type-contents-toggle");
var showImplementor = !hideImplementors && hasClass(e, "implementors-toggle");
if (showLargeItem || showImplementor) {
e.open = true;
}
});
if (hideMethodDocs === true) {
impl_call = function(e, newToggle) {
if (e.id.match(/^impl(?:-\d+)?$/) === null) {
Expand Down
8 changes: 7 additions & 1 deletion src/librustdoc/html/static/rustdoc.css
Original file line number Diff line number Diff line change
Expand Up @@ -1567,6 +1567,10 @@ h4 > .notable-traits {
left: -10px;
}

.item-list > details.rustdoc-toggle > summary:not(.hideme)::before {
left: -10px;
}

#all-types {
margin: 10px;
}
Expand Down Expand Up @@ -1781,14 +1785,16 @@ details.rustdoc-toggle > summary::before {
font-weight: 300;
font-size: 0.8em;
letter-spacing: 1px;
cursor: pointer;
}

details.rustdoc-toggle > summary.hideme::before {
position: relative;
}

details.rustdoc-toggle > summary:not(.hideme)::before {
float: left;
position: absolute;
left: -23px;
}

/* When a "hideme" summary is open and the "Expand description" or "Show
Expand Down
2 changes: 1 addition & 1 deletion src/test/rustdoc/const-generics/add-impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct Simd<T, const WIDTH: usize> {
inner: T,
}

// @has foo/struct.Simd.html '//div[@id="trait-implementations-list"]/h3/code' 'impl Add<Simd<u8, 16_usize>> for Simd<u8, 16>'
// @has foo/struct.Simd.html '//div[@id="trait-implementations-list"]//h3/code' 'impl Add<Simd<u8, 16_usize>> for Simd<u8, 16>'
impl Add for Simd<u8, 16> {
type Output = Self;

Expand Down
4 changes: 2 additions & 2 deletions src/test/rustdoc/duplicate_impls/issue-33054.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// @has issue_33054/impls/struct.Foo.html
// @has - '//code' 'impl Foo'
// @has - '//code' 'impl Bar for Foo'
// @count - '//*[@id="trait-implementations-list"]/*[@class="impl"]' 1
// @count - '//*[@id="main"]/*[@class="impl"]' 1
// @count - '//*[@id="trait-implementations-list"]//*[@class="impl"]' 1
// @count - '//*[@id="main"]/details/summary/*[@class="impl"]' 1
// @has issue_33054/impls/bar/trait.Bar.html
// @has - '//code' 'impl Bar for Foo'
// @count - '//*[@class="struct"]' 1
Expand Down
2 changes: 1 addition & 1 deletion src/test/rustdoc/issue-21474.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ mod inner {
pub trait Blah { }

// @count issue_21474/struct.What.html \
// '//*[@id="trait-implementations-list"]/*[@class="impl"]' 1
// '//*[@id="trait-implementations-list"]//*[@class="impl"]' 1
pub struct What;
2 changes: 1 addition & 1 deletion src/test/rustdoc/issue-29503.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub trait MyTrait {
fn my_string(&self) -> String;
}

// @has - "//div[@id='implementors-list']/h3[@id='impl-MyTrait']//code" "impl<T> MyTrait for T where T: Debug"
// @has - "//div[@id='implementors-list']//h3[@id='impl-MyTrait']//code" "impl<T> MyTrait for T where T: Debug"
impl<T> MyTrait for T where T: fmt::Debug {
fn my_string(&self) -> String {
format!("{:?}", self)
Expand Down
Loading