Skip to content
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

Rollup of 9 pull requests #100740

Merged
merged 24 commits into from
Aug 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
ee3fc9d
never consider unsafe blocks unused if they would be required with un…
RalfJung Aug 2, 2022
3e44ca9
remove some unused code and types
RalfJung Aug 2, 2022
35a35d8
update comment
RalfJung Aug 2, 2022
86e2ca3
add link to discussion
RalfJung Aug 2, 2022
3c8563a
make NOP dyn casts not require anything about the vtable
RalfJung Aug 6, 2022
4a5c46f
Manually implement Debug for ImportKind.
cjgillot Aug 15, 2022
611221d
Update compiler/rustc_resolve/src/imports.rs
cjgillot Aug 15, 2022
fd934c9
Do not allow Drop impl on foreign fundamental types
compiler-errors Jul 21, 2022
7b45718
pass when where clause found
ouz-a Aug 13, 2022
86645c9
Ignore substs when checking inlining history.
cjgillot Aug 14, 2022
2d968a1
Simplify rustdoc themes by relying more on CSS variables
GuillaumeGomez Aug 13, 2022
9898793
Update existing rustdoc-gui tests and add a new one
GuillaumeGomez Aug 13, 2022
09396fc
Remove unused CSS rule
GuillaumeGomez Aug 18, 2022
05ed13b
ADD - diagnostic lints to type_ir
JhonnyBillM Aug 18, 2022
748c606
rustdoc: count deref and non-deref as same set of used methods
notriddle Aug 18, 2022
0788442
Rollup merge of #99576 - compiler-errors:foreign-fundamental-drop-is-…
Dylan-DPC Aug 19, 2022
2fe2975
Rollup merge of #100081 - RalfJung:unused-unsafe-in-unsafe-fn, r=jack…
Dylan-DPC Aug 19, 2022
c4707ff
Rollup merge of #100208 - RalfJung:dyn-upcast-nop, r=petrochenkov
Dylan-DPC Aug 19, 2022
3cebcba
Rollup merge of #100494 - GuillaumeGomez:cleanup-themes, r=jsha
Dylan-DPC Aug 19, 2022
d83abe8
Rollup merge of #100522 - cjgillot:inline-polymorphic-recursion, r=tm…
Dylan-DPC Aug 19, 2022
769ad70
Rollup merge of #100592 - cjgillot:debug-import-kind, r=TaKO8Ki
Dylan-DPC Aug 19, 2022
490d04b
Rollup merge of #100598 - ouz-a:91633, r=compiler-errors
Dylan-DPC Aug 19, 2022
30e65ce
Rollup merge of #100721 - JhonnyBillM:enable-diag-lint-in-type-ir, r=…
Dylan-DPC Aug 19, 2022
ecd2885
Rollup merge of #100731 - notriddle:notriddle/deref-methods-1, r=jsha
Dylan-DPC Aug 19, 2022
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
1 change: 1 addition & 0 deletions compiler/rustc_codegen_cranelift/src/unsize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub(crate) fn unsized_info<'tcx>(
let old_info =
old_info.expect("unsized_info: missing old info for trait upcasting coercion");
if data_a.principal_def_id() == data_b.principal_def_id() {
// A NOP cast that doesn't actually change anything, should be allowed even with invalid vtables.
return old_info;
}

Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_codegen_ssa/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ pub fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
let old_info =
old_info.expect("unsized_info: missing old info for trait upcasting coercion");
if data_a.principal_def_id() == data_b.principal_def_id() {
// A NOP cast that doesn't actually change anything, should be allowed even with invalid vtables.
return old_info;
}

Expand Down
7 changes: 6 additions & 1 deletion compiler/rustc_const_eval/src/interpret/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
self.write_immediate(val, dest)
}
(&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => {
let (old_data, old_vptr) = self.read_immediate(src)?.to_scalar_pair()?;
let val = self.read_immediate(src)?;
if data_a.principal() == data_b.principal() {
// A NOP cast that doesn't actually change anything, should be allowed even with mismatching vtables.
return self.write_immediate(*val, dest);
}
let (old_data, old_vptr) = val.to_scalar_pair()?;
let old_vptr = old_vptr.to_pointer(self)?;
let (ty, old_trait) = self.get_ptr_vtable(old_vptr)?;
if old_trait != data_a.principal() {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_error_messages/locales/en-US/typeck.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ typeck_lifetimes_or_bounds_mismatch_on_trait =
.generics_label = lifetimes in impl do not match this {$item_kind} in trait

typeck_drop_impl_on_wrong_item =
the `Drop` trait may only be implemented for structs, enums, and unions
.label = must be a struct, enum, or union
the `Drop` trait may only be implemented for local structs, enums, and unions
.label = must be a struct, enum, or union in the current crate

typeck_field_already_declared =
field `{$field_name}` is already declared
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_errors/src/diagnostic_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ impl Drop for DiagnosticBuilderInner<'_> {
),
));
handler.emit_diagnostic(&mut self.diagnostic);
panic!();
panic!("error was constructed but not emitted");
}
}
// `.emit()` was previously called, or maybe we're during `.cancel()`.
Expand Down
22 changes: 2 additions & 20 deletions compiler/rustc_middle/src/mir/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use crate::mir::{Body, ConstantKind, Promoted};
use crate::ty::{self, OpaqueHiddenType, Ty, TyCtxt};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::vec_map::VecMap;
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
Expand Down Expand Up @@ -115,21 +115,6 @@ pub enum UnusedUnsafe {
/// `unsafe` block nested under another (used) `unsafe` block
/// > ``… because it's nested under this `unsafe` block``
InUnsafeBlock(hir::HirId),
/// `unsafe` block nested under `unsafe fn`
/// > ``… because it's nested under this `unsafe fn` ``
///
/// the second HirId here indicates the first usage of the `unsafe` block,
/// which allows retrieval of the LintLevelSource for why that operation would
/// have been permitted without the block
InUnsafeFn(hir::HirId, hir::HirId),
}

#[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
pub enum UsedUnsafeBlockData {
SomeDisallowedInUnsafeFn,
// the HirId here indicates the first usage of the `unsafe` block
// (i.e. the one that's first encountered in the MIR traversal of the unsafety check)
AllAllowedInUnsafeFn(hir::HirId),
}

#[derive(TyEncodable, TyDecodable, HashStable, Debug)]
Expand All @@ -138,10 +123,7 @@ pub struct UnsafetyCheckResult {
pub violations: Vec<UnsafetyViolation>,

/// Used `unsafe` blocks in this function. This is used for the "unused_unsafe" lint.
///
/// The keys are the used `unsafe` blocks, the UnusedUnsafeKind indicates whether
/// or not any of the usages happen at a place that doesn't allow `unsafe_op_in_unsafe_fn`.
pub used_unsafe_blocks: FxHashMap<hir::HirId, UsedUnsafeBlockData>,
pub used_unsafe_blocks: FxHashSet<hir::HirId>,

/// This is `Some` iff the item is not a closure.
pub unused_unsafes: Option<Vec<(hir::HirId, UnusedUnsafe)>>,
Expand Down
9 changes: 5 additions & 4 deletions compiler/rustc_mir_build/src/check_unsafety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,11 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
match self.safety_context {
SafetyContext::BuiltinUnsafeBlock => {}
SafetyContext::UnsafeBlock { ref mut used, .. } => {
if !self.body_unsafety.is_unsafe() || !unsafe_op_in_unsafe_fn_allowed {
// Mark this block as useful
*used = true;
}
// Mark this block as useful (even inside `unsafe fn`, where it is technically
// redundant -- but we want to eventually enable `unsafe_op_in_unsafe_fn` by
// default which will require those blocks:
// https://github.com/rust-lang/rust/issues/71668#issuecomment-1203075594).
*used = true;
}
SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
SafetyContext::UnsafeFn => {
Expand Down
88 changes: 17 additions & 71 deletions compiler/rustc_mir_transform/src/check_unsafety.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::struct_span_err;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::hir_id::HirId;
use rustc_hir::intravisit;
use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
use rustc_middle::mir::*;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, TyCtxt};
use rustc_middle::{lint, mir::*};
use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
use rustc_session::lint::Level;

use std::collections::hash_map;
use std::ops::Bound;

pub struct UnsafetyChecker<'a, 'tcx> {
Expand All @@ -23,10 +22,7 @@ pub struct UnsafetyChecker<'a, 'tcx> {
param_env: ty::ParamEnv<'tcx>,

/// Used `unsafe` blocks in this function. This is used for the "unused_unsafe" lint.
///
/// The keys are the used `unsafe` blocks, the UnusedUnsafeKind indicates whether
/// or not any of the usages happen at a place that doesn't allow `unsafe_op_in_unsafe_fn`.
used_unsafe_blocks: FxHashMap<HirId, UsedUnsafeBlockData>,
used_unsafe_blocks: FxHashSet<HirId>,
}

impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
Expand Down Expand Up @@ -130,10 +126,7 @@ impl<'tcx> Visitor<'tcx> for UnsafetyChecker<'_, 'tcx> {
&AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
self.tcx.unsafety_check_result(def_id);
self.register_violations(
violations,
used_unsafe_blocks.iter().map(|(&h, &d)| (h, d)),
);
self.register_violations(violations, used_unsafe_blocks.iter().copied());
}
},
_ => {}
Expand Down Expand Up @@ -257,22 +250,8 @@ impl<'tcx> UnsafetyChecker<'_, 'tcx> {
fn register_violations<'a>(
&mut self,
violations: impl IntoIterator<Item = &'a UnsafetyViolation>,
new_used_unsafe_blocks: impl IntoIterator<Item = (HirId, UsedUnsafeBlockData)>,
new_used_unsafe_blocks: impl IntoIterator<Item = HirId>,
) {
use UsedUnsafeBlockData::{AllAllowedInUnsafeFn, SomeDisallowedInUnsafeFn};

let update_entry = |this: &mut Self, hir_id, new_usage| {
match this.used_unsafe_blocks.entry(hir_id) {
hash_map::Entry::Occupied(mut entry) => {
if new_usage == SomeDisallowedInUnsafeFn {
*entry.get_mut() = SomeDisallowedInUnsafeFn;
}
}
hash_map::Entry::Vacant(entry) => {
entry.insert(new_usage);
}
};
};
let safety = self.body.source_scopes[self.source_info.scope]
.local_data
.as_ref()
Expand All @@ -299,22 +278,14 @@ impl<'tcx> UnsafetyChecker<'_, 'tcx> {
}
}),
Safety::BuiltinUnsafe => {}
Safety::ExplicitUnsafe(hir_id) => violations.into_iter().for_each(|violation| {
update_entry(
self,
hir_id,
match self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, violation.lint_root).0
{
Level::Allow => AllAllowedInUnsafeFn(violation.lint_root),
_ => SomeDisallowedInUnsafeFn,
},
)
Safety::ExplicitUnsafe(hir_id) => violations.into_iter().for_each(|_violation| {
self.used_unsafe_blocks.insert(hir_id);
}),
};

new_used_unsafe_blocks
.into_iter()
.for_each(|(hir_id, usage_data)| update_entry(self, hir_id, usage_data));
new_used_unsafe_blocks.into_iter().for_each(|hir_id| {
self.used_unsafe_blocks.insert(hir_id);
});
}
fn check_mut_borrowing_layout_constrained_field(
&mut self,
Expand Down Expand Up @@ -411,34 +382,28 @@ enum Context {

struct UnusedUnsafeVisitor<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
used_unsafe_blocks: &'a FxHashMap<HirId, UsedUnsafeBlockData>,
used_unsafe_blocks: &'a FxHashSet<HirId>,
context: Context,
unused_unsafes: &'a mut Vec<(HirId, UnusedUnsafe)>,
}

impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_, 'tcx> {
fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
use UsedUnsafeBlockData::{AllAllowedInUnsafeFn, SomeDisallowedInUnsafeFn};

if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
let used = match self.tcx.lint_level_at_node(UNUSED_UNSAFE, block.hir_id) {
(Level::Allow, _) => Some(SomeDisallowedInUnsafeFn),
_ => self.used_unsafe_blocks.get(&block.hir_id).copied(),
(Level::Allow, _) => true,
_ => self.used_unsafe_blocks.contains(&block.hir_id),
};
let unused_unsafe = match (self.context, used) {
(_, None) => UnusedUnsafe::Unused,
(Context::Safe, Some(_))
| (Context::UnsafeFn(_), Some(SomeDisallowedInUnsafeFn)) => {
(_, false) => UnusedUnsafe::Unused,
(Context::Safe, true) | (Context::UnsafeFn(_), true) => {
let previous_context = self.context;
self.context = Context::UnsafeBlock(block.hir_id);
intravisit::walk_block(self, block);
self.context = previous_context;
return;
}
(Context::UnsafeFn(hir_id), Some(AllAllowedInUnsafeFn(lint_root))) => {
UnusedUnsafe::InUnsafeFn(hir_id, lint_root)
}
(Context::UnsafeBlock(hir_id), Some(_)) => UnusedUnsafe::InUnsafeBlock(hir_id),
(Context::UnsafeBlock(hir_id), true) => UnusedUnsafe::InUnsafeBlock(hir_id),
};
self.unused_unsafes.push((block.hir_id, unused_unsafe));
}
Expand All @@ -462,7 +427,7 @@ impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_, 'tcx> {
fn check_unused_unsafe(
tcx: TyCtxt<'_>,
def_id: LocalDefId,
used_unsafe_blocks: &FxHashMap<HirId, UsedUnsafeBlockData>,
used_unsafe_blocks: &FxHashSet<HirId>,
) -> Vec<(HirId, UnusedUnsafe)> {
let body_id = tcx.hir().maybe_body_owned_by(def_id);

Expand Down Expand Up @@ -535,25 +500,6 @@ fn report_unused_unsafe(tcx: TyCtxt<'_>, kind: UnusedUnsafe, id: HirId) {
"because it's nested under this `unsafe` block",
);
}
UnusedUnsafe::InUnsafeFn(id, usage_lint_root) => {
db.span_label(
tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
"because it's nested under this `unsafe` fn",
)
.note(
"this `unsafe` block does contain unsafe operations, \
but those are already allowed in an `unsafe fn`",
);
let (level, source) =
tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, usage_lint_root);
assert_eq!(level, Level::Allow);
lint::explain_lint_level_source(
UNSAFE_OP_IN_UNSAFE_FN,
Level::Allow,
source,
&mut db,
);
}
}

db.emit();
Expand Down
13 changes: 9 additions & 4 deletions compiler/rustc_mir_transform/src/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use rustc_middle::mir::*;
use rustc_middle::ty::subst::Subst;
use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
use rustc_session::config::OptLevel;
use rustc_span::def_id::DefId;
use rustc_span::{hygiene::ExpnKind, ExpnData, LocalExpnId, Span};
use rustc_target::spec::abi::Abi;

Expand Down Expand Up @@ -103,8 +104,12 @@ struct Inliner<'tcx> {
param_env: ParamEnv<'tcx>,
/// Caller codegen attributes.
codegen_fn_attrs: &'tcx CodegenFnAttrs,
/// Stack of inlined Instances.
history: Vec<ty::Instance<'tcx>>,
/// Stack of inlined instances.
/// We only check the `DefId` and not the substs because we want to
/// avoid inlining cases of polymorphic recursion.
/// The number of `DefId`s is finite, so checking history is enough
/// to ensure that we do not loop endlessly while inlining.
history: Vec<DefId>,
/// Indicates that the caller body has been modified.
changed: bool,
}
Expand Down Expand Up @@ -132,7 +137,7 @@ impl<'tcx> Inliner<'tcx> {
Ok(new_blocks) => {
debug!("inlined {}", callsite.callee);
self.changed = true;
self.history.push(callsite.callee);
self.history.push(callsite.callee.def_id());
self.process_blocks(caller_body, new_blocks);
self.history.pop();
}
Expand Down Expand Up @@ -308,7 +313,7 @@ impl<'tcx> Inliner<'tcx> {
return None;
}

if self.history.contains(&callee) {
if self.history.contains(&callee.def_id()) {
return None;
}

Expand Down
40 changes: 39 additions & 1 deletion compiler/rustc_resolve/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use std::{mem, ptr};
type Res = def::Res<NodeId>;

/// Contains data for specific kinds of imports.
#[derive(Clone, Debug)]
#[derive(Clone)]
pub enum ImportKind<'a> {
Single {
/// `source` in `use prefix::source as target`.
Expand Down Expand Up @@ -62,6 +62,44 @@ pub enum ImportKind<'a> {
MacroUse,
}

/// Manually implement `Debug` for `ImportKind` because the `source/target_bindings`
/// contain `Cell`s which can introduce infinite loops while printing.
impl<'a> std::fmt::Debug for ImportKind<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use ImportKind::*;
match self {
Single {
ref source,
ref target,
ref type_ns_only,
ref nested,
ref additional_ids,
// Ignore the following to avoid an infinite loop while printing.
source_bindings: _,
target_bindings: _,
} => f
.debug_struct("Single")
.field("source", source)
.field("target", target)
.field("type_ns_only", type_ns_only)
.field("nested", nested)
.field("additional_ids", additional_ids)
.finish_non_exhaustive(),
Glob { ref is_prelude, ref max_vis } => f
.debug_struct("Glob")
.field("is_prelude", is_prelude)
.field("max_vis", max_vis)
.finish(),
ExternCrate { ref source, ref target } => f
.debug_struct("ExternCrate")
.field("source", source)
.field("target", target)
.finish(),
MacroUse => f.debug_struct("MacroUse").finish(),
}
}
}

/// One import.
#[derive(Debug, Clone)]
pub(crate) struct Import<'a> {
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_type_ir/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#![feature(fmt_helpers_for_derive)]
#![feature(min_specialization)]
#![feature(rustc_attrs)]
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]

#[macro_use]
extern crate bitflags;
Expand Down
Loading