Auto merge of #70296 - Centril:rollup-wvfmb3n, r=Centril

Rollup of 9 pull requests

Successful merges:

 - #69251 (#[track_caller] in traits)
 - #69880 (miri engine: turn error sanity checks into assertions)
 - #70207 (Use getentropy(2) on macos)
 - #70227 (Only display definition when suggesting a typo)
 - #70236 (resolve: Avoid "self-confirming" import resolutions in one more case)
 - #70248 (parser: simplify & remove unused field)
 - #70249 (handle ConstKind::Unresolved after monomorphizing)
 - #70269 (remove redundant closures (clippy::redundant_closure))
 - #70270 (Clean up E0449 explanation)

Failed merges:

r? @ghost
This commit is contained in:
bors 2020-03-23 06:02:34 +00:00
commit 8ff785011b
67 changed files with 468 additions and 340 deletions

View file

@ -196,7 +196,7 @@ impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
(root, length)
};
out_node.push(k, v, subroot.unwrap_or_else(|| node::Root::new_leaf()));
out_node.push(k, v, subroot.unwrap_or_else(node::Root::new_leaf));
out_tree.length += 1 + sublength;
}
}
@ -2147,7 +2147,7 @@ impl<K, V> BTreeMap<K, V> {
/// If the root node is the empty (non-allocated) root node, allocate our
/// own node.
fn ensure_root_is_owned(&mut self) -> &mut node::Root<K, V> {
self.root.get_or_insert_with(|| node::Root::new_leaf())
self.root.get_or_insert_with(node::Root::new_leaf)
}
}

View file

@ -245,7 +245,7 @@ impl DepGraph {
C: DepGraphSafe + StableHashingContextProvider<'a>,
{
if let Some(ref data) = self.data {
let task_deps = create_task(key).map(|deps| Lock::new(deps));
let task_deps = create_task(key).map(Lock::new);
// In incremental mode, hash the result of the task. We don't
// do anything with the hash yet, but we are computing it

View file

@ -38,6 +38,7 @@
#![feature(extern_types)]
#![feature(nll)]
#![feature(option_expect_none)]
#![feature(or_patterns)]
#![feature(range_is_empty)]
#![feature(specialization)]
#![feature(trusted_len)]

View file

@ -796,7 +796,7 @@ impl UndefMask {
}
// FIXME(oli-obk): optimize this for allocations larger than a block.
let idx = (start.bytes()..end.bytes()).map(|i| Size::from_bytes(i)).find(|&i| !self.get(i));
let idx = (start.bytes()..end.bytes()).map(Size::from_bytes).find(|&i| !self.get(i));
match idx {
Some(idx) => Err(idx),

View file

@ -35,7 +35,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_data_structures::sync::{self, par_iter, Lrc, ParallelIterator};
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Namespace, Res};
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, CRATE_DEF_INDEX};
use rustc_hir::{Constness, GlobMap, Node, TraitMap};
use rustc_index::vec::{Idx, IndexVec};
use rustc_macros::HashStable;
@ -2875,8 +2875,8 @@ impl<'tcx> TyCtxt<'tcx> {
_ => false,
}
} else {
match self.def_kind(def_id).expect("no def for `DefId`") {
DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy => true,
match self.def_kind(def_id) {
Some(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy) => true,
_ => false,
}
};
@ -3054,17 +3054,7 @@ impl<'tcx> TyCtxt<'tcx> {
/// If the given defid describes a method belonging to an impl, returns the
/// `DefId` of the impl that the method belongs to; otherwise, returns `None`.
pub fn impl_of_method(self, def_id: DefId) -> Option<DefId> {
let item = if def_id.krate != LOCAL_CRATE {
if let Some(DefKind::AssocFn) = self.def_kind(def_id) {
Some(self.associated_item(def_id))
} else {
None
}
} else {
self.opt_associated_item(def_id)
};
item.and_then(|trait_item| match trait_item.container {
self.opt_associated_item(def_id).and_then(|trait_item| match trait_item.container {
TraitContainer(_) => None,
ImplContainer(def_id) => Some(def_id),
})

View file

@ -250,7 +250,7 @@ impl ParenthesizedArgs {
pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs {
AngleBracketedArgs {
span: self.span,
args: self.inputs.iter().cloned().map(|input| GenericArg::Type(input)).collect(),
args: self.inputs.iter().cloned().map(GenericArg::Type).collect(),
constraints: vec![],
}
}

View file

@ -274,7 +274,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
if !generic_args.parenthesized && !has_lifetimes {
generic_args.args = self
.elided_path_lifetimes(path_span, expected_lifetimes)
.map(|lt| GenericArg::Lifetime(lt))
.map(GenericArg::Lifetime)
.chain(generic_args.args.into_iter())
.collect();
if expected_lifetimes > 0 && param_mode == ParamMode::Explicit {

View file

@ -76,8 +76,8 @@ impl<'a> Path<'a> {
self.params.iter().map(|t| t.to_ty(cx, span, self_ty, self_generics)).collect();
let params = lt
.into_iter()
.map(|lt| GenericArg::Lifetime(lt))
.chain(tys.into_iter().map(|ty| GenericArg::Type(ty)))
.map(GenericArg::Lifetime)
.chain(tys.into_iter().map(GenericArg::Type))
.collect();
match self.kind {

View file

@ -6,7 +6,7 @@ use rustc_ast_pretty::pprust;
use rustc_expand::base::{self, *};
use rustc_expand::module::DirectoryOwnership;
use rustc_expand::panictry;
use rustc_parse::{self, new_sub_parser_from_file, parser::Parser};
use rustc_parse::{self, new_parser_from_file, parser::Parser};
use rustc_session::lint::builtin::INCOMPLETE_INCLUDE;
use rustc_span::symbol::Symbol;
use rustc_span::{self, Pos, Span};
@ -110,7 +110,7 @@ pub fn expand_include<'cx>(
return DummyResult::any(sp);
}
};
let p = new_sub_parser_from_file(cx.parse_sess(), &file, None, sp);
let p = new_parser_from_file(cx.parse_sess(), &file, Some(sp));
// If in the included file we have e.g., `mod bar;`,
// then the path of `bar.rs` should be relative to the directory of `file`.

View file

@ -40,31 +40,26 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
&mut self,
constant: &mir::Constant<'tcx>,
) -> Result<ConstValue<'tcx>, ErrorHandled> {
match constant.literal.val {
ty::ConstKind::Unevaluated(def_id, substs, promoted) => {
let substs = self.monomorphize(&substs);
self.cx
.tcx()
.const_eval_resolve(ty::ParamEnv::reveal_all(), def_id, substs, promoted, None)
.map_err(|err| {
if promoted.is_none() {
self.cx
.tcx()
.sess
.span_err(constant.span, "erroneous constant encountered");
}
err
})
}
match self.monomorphize(&constant.literal).val {
ty::ConstKind::Unevaluated(def_id, substs, promoted) => self
.cx
.tcx()
.const_eval_resolve(ty::ParamEnv::reveal_all(), def_id, substs, promoted, None)
.map_err(|err| {
if promoted.is_none() {
self.cx
.tcx()
.sess
.span_err(constant.span, "erroneous constant encountered");
}
err
}),
ty::ConstKind::Value(value) => Ok(value),
_ => {
let const_ = self.monomorphize(&constant.literal);
if let ty::ConstKind::Value(value) = const_.val {
Ok(value)
} else {
span_bug!(constant.span, "encountered bad ConstKind in codegen: {:?}", const_);
}
}
err => span_bug!(
constant.span,
"encountered bad ConstKind after monomorphizing: {:?}",
err
),
}
}

View file

@ -30,7 +30,7 @@ pub struct Sharded<T> {
impl<T: Default> Default for Sharded<T> {
#[inline]
fn default() -> Self {
Self::new(|| T::default())
Self::new(T::default)
}
}

View file

@ -1,5 +1,6 @@
A visibility qualifier was used when it was unnecessary. Erroneous code
examples:
A visibility qualifier was used when it was unnecessary.
Erroneous code examples:
```compile_fail,E0449
struct Bar;

View file

@ -1,48 +1,11 @@
`#[track_caller]` cannot be used in traits yet. This is due to limitations in
the compiler which are likely to be temporary. See [RFC 2091] for details on
this and other restrictions.
`#[track_caller]` cannot be used to annotate foreign functions.
Erroneous example with a trait method implementation:
Erroneous example:
```compile_fail,E0738
#![feature(track_caller)]
trait Foo {
fn bar(&self);
}
impl Foo for u64 {
extern "Rust" {
#[track_caller]
fn bar(&self) {}
fn bar();
}
```
Erroneous example with a blanket trait method implementation:
```compile_fail,E0738
#![feature(track_caller)]
trait Foo {
#[track_caller]
fn bar(&self) {}
fn baz(&self);
}
```
Erroneous example with a trait method declaration:
```compile_fail,E0738
#![feature(track_caller)]
trait Foo {
fn bar(&self) {}
#[track_caller]
fn baz(&self);
}
```
Note that while the compiler may be able to support the attribute in traits in
the future, [RFC 2091] prohibits their implementation without a follow-up RFC.
[RFC 2091]: https://github.com/rust-lang/rfcs/blob/master/text/2091-inline-semantic.md

View file

@ -162,7 +162,7 @@ impl<'a> DiagnosticBuilder<'a> {
message: &str,
span: Option<S>,
) -> &mut Self {
let span = span.map(|s| s.into()).unwrap_or_else(|| MultiSpan::new());
let span = span.map(|s| s.into()).unwrap_or_else(MultiSpan::new);
self.0.diagnostic.sub(level, message, span, None);
self
}

View file

@ -259,8 +259,6 @@ fn generic_extension<'cx>(
}
let mut p = Parser::new(sess, tts, false, None);
p.root_module_name =
cx.current_expansion.module.mod_path.last().map(|id| id.to_string());
p.last_type_ascription = cx.current_expansion.prior_type_ascription;
// Let the context choose how to interpret the result.

View file

@ -1,7 +1,7 @@
use rustc_ast::ast::{self, Attribute, Ident, Mod};
use rustc_ast::{attr, token};
use rustc_errors::{struct_span_err, PResult};
use rustc_parse::new_sub_parser_from_file;
use rustc_parse::new_parser_from_file;
use rustc_session::parse::ParseSess;
use rustc_span::source_map::{FileName, Span};
use rustc_span::symbol::sym;
@ -59,9 +59,8 @@ crate fn parse_external_mod(
*pop_mod_stack = true; // We have pushed, so notify caller.
drop(included_mod_stack);
// Actually parse the external file as amodule.
let mut p0 = new_sub_parser_from_file(sess, &mp.path, Some(id.to_string()), span);
let mut module = p0.parse_mod(&token::Eof)?;
// Actually parse the external file as a module.
let mut module = new_parser_from_file(sess, &mp.path, Some(span)).parse_mod(&token::Eof)?;
module.0.inline = false;
module
};

View file

@ -51,7 +51,7 @@ pub struct Feature {
impl Feature {
fn issue(&self) -> Option<NonZeroU32> {
self.issue.and_then(|i| NonZeroU32::new(i))
self.issue.and_then(NonZeroU32::new)
}
}

View file

@ -707,7 +707,7 @@ impl<'tcx> QueryContext<'tcx> {
where
F: FnOnce(TyCtxt<'tcx>) -> R,
{
ty::tls::enter_global(self.0, |tcx| f(tcx))
ty::tls::enter_global(self.0, f)
}
pub fn print_stats(&mut self) {

View file

@ -327,7 +327,7 @@ impl<'a> CrateLocator<'a> {
.into_iter()
.filter_map(|entry| entry.files())
.flatten()
.map(|location| PathBuf::from(location))
.map(PathBuf::from)
.collect()
} else {
// SVH being specified means this is a transitive dependency,

View file

@ -577,7 +577,7 @@ fn write_diff<A: Analysis<'tcx>>(
let mut clear = HybridBitSet::new_empty(len);
// FIXME: Implement a lazy iterator over the symmetric difference of two bitsets.
for i in (0..len).map(|i| A::Idx::new(i)) {
for i in (0..len).map(A::Idx::new) {
match (from.contains(i), to.contains(i)) {
(false, true) => set.insert(i),
(true, false) => clear.insert(i),

View file

@ -825,11 +825,10 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
// Run it.
match visitor.visit_value(op) {
Ok(()) => Ok(()),
// We should only get validation errors here. Avoid other errors as
// those do not show *where* in the value the issue lies.
Err(err) if matches!(err.kind, err_ub!(ValidationFailure { .. })) => Err(err),
Err(err) if cfg!(debug_assertions) => {
bug!("Unexpected error during validation: {}", err)
}
Err(err) => Err(err),
Err(err) => bug!("Unexpected error during validation: {}", err),
}
}

View file

@ -895,7 +895,7 @@ fn create_mono_items_for_vtable_methods<'tcx>(
.unwrap()
})
.filter(|&instance| should_monomorphize_locally(tcx, &instance))
.map(|instance| create_fn_mono_item(instance));
.map(create_fn_mono_item);
output.extend(methods);
}

View file

@ -404,8 +404,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
// Some errors shouldn't come up because creating them causes
// an allocation, which we should avoid. When that happens,
// dedicated error variants should be introduced instead.
// Only test this in debug builds though to avoid disruptions.
debug_assert!(
assert!(
!error.kind.allocates(),
"const-prop encountered allocating error: {}",
error

View file

@ -2066,7 +2066,7 @@ fn split_grouped_constructors<'p, 'tcx>(
}
intersection
})
.flat_map(|range| range_borders(range));
.flat_map(range_borders);
let ctor_borders = range_borders(ctor_range.clone());
let mut borders: Vec<_> = row_borders.chain(ctor_borders).collect();
borders.sort_unstable();

View file

@ -50,7 +50,7 @@ macro_rules! panictry_buffer {
}
pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> {
let mut parser = new_parser_from_file(sess, input);
let mut parser = new_parser_from_file(sess, input, None);
parser.parse_crate_mod()
}
@ -58,7 +58,7 @@ pub fn parse_crate_attrs_from_file<'a>(
input: &Path,
sess: &'a ParseSess,
) -> PResult<'a, Vec<ast::Attribute>> {
let mut parser = new_parser_from_file(sess, input);
let mut parser = new_parser_from_file(sess, input, None);
parser.parse_inner_attributes()
}
@ -106,8 +106,9 @@ pub fn maybe_new_parser_from_source_str(
}
/// Creates a new parser, handling errors as appropriate if the file doesn't exist.
pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path) -> Parser<'a> {
source_file_to_parser(sess, file_to_source_file(sess, path, None))
/// If a span is given, that is used on an error as the as the source of the problem.
pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Span>) -> Parser<'a> {
source_file_to_parser(sess, file_to_source_file(sess, path, sp))
}
/// Creates a new parser, returning buffered diagnostics if the file doesn't exist,
@ -120,20 +121,6 @@ pub fn maybe_new_parser_from_file<'a>(
maybe_source_file_to_parser(sess, file)
}
/// Given a session, a crate config, a path, and a span, add
/// the file at the given path to the `source_map`, and returns a parser.
/// On an error, uses the given span as the source of the problem.
pub fn new_sub_parser_from_file<'a>(
sess: &'a ParseSess,
path: &Path,
module_name: Option<String>,
sp: Span,
) -> Parser<'a> {
let mut p = source_file_to_parser(sess, file_to_source_file(sess, path, Some(sp)));
p.root_module_name = module_name;
p
}
/// Given a `source_file` and config, returns a parser.
fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file))

View file

@ -88,10 +88,6 @@ pub struct Parser<'a> {
/// The previous token.
pub prev_token: Token,
restrictions: Restrictions,
/// Name of the root module this parser originated from. If `None`, then the
/// name is not known. This does not change while the parser is descending
/// into modules, and sub-parsers have new values for this name.
pub root_module_name: Option<String>,
expected_tokens: Vec<TokenType>,
token_cursor: TokenCursor,
desugar_doc_comments: bool,
@ -350,7 +346,6 @@ impl<'a> Parser<'a> {
token: Token::dummy(),
prev_token: Token::dummy(),
restrictions: Restrictions::empty(),
root_module_name: None,
expected_tokens: Vec::new(),
token_cursor: TokenCursor {
frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens),

View file

@ -151,17 +151,17 @@ impl CheckAttrVisitor<'tcx> {
.emit();
false
}
Target::Fn | Target::Method(MethodKind::Inherent) => true,
Target::Method(_) => {
Target::ForeignFn => {
struct_span_err!(
self.tcx.sess,
*attr_span,
E0738,
"`#[track_caller]` may not be used on trait methods",
"`#[track_caller]` is not supported on foreign functions",
)
.emit();
false
}
Target::Fn | Target::Method(..) => true,
_ => {
struct_span_err!(
self.tcx.sess,

View file

@ -796,7 +796,7 @@ impl<'a> Resolver<'a> {
});
if let Some(span) = def_span {
err.span_label(
span,
self.session.source_map().def_span(span),
&format!(
"similarly named {} `{}` defined here",
suggestion.res.descr(),

View file

@ -874,6 +874,12 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
/// consolidate multiple unresolved import errors into a single diagnostic.
fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
let orig_vis = import.vis.replace(ty::Visibility::Invisible);
let orig_blacklisted_binding = match &import.kind {
ImportKind::Single { target_bindings, .. } => {
Some(mem::replace(&mut self.r.blacklisted_binding, target_bindings[TypeNS].get()))
}
_ => None,
};
let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
let path_res = self.r.resolve_path(
&import.module_path,
@ -884,6 +890,9 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
import.crate_lint(),
);
let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
if let Some(orig_blacklisted_binding) = orig_blacklisted_binding {
self.r.blacklisted_binding = orig_blacklisted_binding;
}
import.vis.set(orig_vis);
if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
// Consider erroneous imports used to avoid duplicate diagnostics.

View file

@ -1148,7 +1148,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> {
let sub_span = path.segments.last().unwrap().ident.span;
if !self.span.filter_generated(sub_span) {
let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
let ref_id = self.lookup_def_id(id).map(id_from_def_id);
let alias_span = alias.map(|i| self.span_from_span(i.span));
let span = self.span_from_span(sub_span);
self.dumper.import(

View file

@ -326,7 +326,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
.as_ref()
.and_then(|t| self.lookup_def_id(t.ref_id))
.map(id_from_def_id)
.unwrap_or_else(|| null_id()),
.unwrap_or_else(null_id),
},
Impl {
id: impl_id,
@ -487,9 +487,9 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
qualname,
// FIXME you get better data here by using the visitor.
value: String::new(),
parent: parent_scope.map(|id| id_from_def_id(id)),
parent: parent_scope.map(id_from_def_id),
children: vec![],
decl_id: decl_id.map(|id| id_from_def_id(id)),
decl_id: decl_id.map(id_from_def_id),
docs,
sig: None,
attributes: lower_attributes(attributes, self),
@ -541,7 +541,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
.tcx
.find_field_index(ident, variant)
.map(|index| id_from_def_id(variant.fields[index].did))
.unwrap_or_else(|| null_id()),
.unwrap_or_else(null_id),
}))
}
ty::Tuple(..) => None,
@ -590,14 +590,11 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> {
Some(Data::RefData(Ref {
kind: RefKind::Function,
span,
ref_id: def_id
.or(decl_id)
.map(|id| id_from_def_id(id))
.unwrap_or_else(|| null_id()),
ref_id: def_id.or(decl_id).map(id_from_def_id).unwrap_or_else(|| null_id()),
}))
}
ast::ExprKind::Path(_, ref path) => {
self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
self.get_path_data(expr.id, path).map(Data::RefData)
}
_ => {
// FIXME
@ -1075,7 +1072,7 @@ fn id_from_def_id(id: DefId) -> rls_data::Id {
fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
let def_id = scx.tcx.hir().opt_local_def_id_from_node_id(id);
def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
def_id.map(id_from_def_id).unwrap_or_else(|| {
// Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
// out of the maximum u32 value. This will work unless you have *billions*
// of definitions in a single crate (very unlikely to actually happen).

View file

@ -1310,7 +1310,7 @@ fn select_incremental_path(
(None, Some(path)) => Some(path),
(None, None) => None,
}
.map(|m| PathBuf::from(m))
.map(PathBuf::from)
}
fn collect_print_requests(

View file

@ -131,7 +131,7 @@ impl<'a, 'tcx> FulfillmentContext<'tcx> {
// FIXME: if we kept the original cache key, we could mark projection
// obligations as complete for the projection cache here.
errors.extend(outcome.errors.into_iter().map(|e| to_fulfillment_error(e)));
errors.extend(outcome.errors.into_iter().map(to_fulfillment_error));
// If nothing new was added, no need to keep looping.
if outcome.stalled {
@ -214,7 +214,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> {
.predicates
.to_errors(CodeAmbiguity)
.into_iter()
.map(|e| to_fulfillment_error(e))
.map(to_fulfillment_error)
.collect();
if errors.is_empty() { Ok(()) } else { Err(errors) }
}

View file

@ -39,7 +39,7 @@ pub fn astconv_object_safety_violations(
let violations = traits::supertrait_def_ids(tcx, trait_def_id)
.map(|def_id| predicates_reference_self(tcx, def_id, true))
.filter(|spans| !spans.is_empty())
.map(|spans| ObjectSafetyViolation::SupertraitSelf(spans))
.map(ObjectSafetyViolation::SupertraitSelf)
.collect();
debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);

View file

@ -2947,13 +2947,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
let existential_predicates = data_a.map_bound(|data_a| {
let iter = data_a
.principal()
.map(|x| ty::ExistentialPredicate::Trait(x))
.map(ty::ExistentialPredicate::Trait)
.into_iter()
.chain(
data_a
.projection_bounds()
.map(|x| ty::ExistentialPredicate::Projection(x)),
)
.chain(data_a.projection_bounds().map(ty::ExistentialPredicate::Projection))
.chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
tcx.mk_existential_predicates(iter)
});

View file

@ -1693,9 +1693,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
};
// Erase the `dummy_self` (`trait_object_dummy_self`) used above.
let existential_trait_refs = regular_traits
.iter()
.map(|i| i.trait_ref().map_bound(|trait_ref| trait_ref_to_existential(trait_ref)));
let existential_trait_refs =
regular_traits.iter().map(|i| i.trait_ref().map_bound(trait_ref_to_existential));
let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
bound.map_bound(|b| {
let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));

View file

@ -677,7 +677,7 @@ fn compare_number_of_generics<'tcx>(
impl_count,
kind,
pluralize!(impl_count),
suffix.unwrap_or_else(|| String::new()),
suffix.unwrap_or_else(String::new),
),
);
}

View file

@ -2339,6 +2339,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
let attrs = tcx.get_attrs(id);
let mut codegen_fn_attrs = CodegenFnAttrs::new();
if should_inherit_track_caller(tcx, id) {
codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
}
let whitelist = tcx.target_features_whitelist(LOCAL_CRATE);
@ -2583,6 +2586,32 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
codegen_fn_attrs
}
/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
/// applied to the method prototype.
fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
if let Some(impl_item) = tcx.opt_associated_item(def_id) {
if let ty::AssocItemContainer::ImplContainer(impl_def_id) = impl_item.container {
if let Some(trait_def_id) = tcx.trait_id_of_impl(impl_def_id) {
if let Some(trait_item) = tcx
.associated_items(trait_def_id)
.filter_by_name_unhygienic(impl_item.ident.name)
.find(move |trait_item| {
trait_item.kind == ty::AssocKind::Method
&& tcx.hygienic_eq(impl_item.ident, trait_item.ident, trait_def_id)
})
{
return tcx
.codegen_fn_attrs(trait_item.def_id)
.flags
.intersects(CodegenFnAttrFlags::TRACK_CALLER);
}
}
}
}
false
}
fn check_link_ordinal(tcx: TyCtxt<'_>, attr: &ast::Attribute) -> Option<usize> {
use rustc_ast::ast::{Lit, LitIntType, LitKind};
let meta_item_list = attr.meta_item_list();

View file

@ -12,6 +12,7 @@ pub fn hashmap_random_keys() -> (u64, u64) {
#[cfg(all(
unix,
not(target_os = "macos"),
not(target_os = "ios"),
not(target_os = "openbsd"),
not(target_os = "freebsd"),
@ -92,6 +93,42 @@ mod imp {
}
}
#[cfg(target_os = "macos")]
mod imp {
use crate::fs::File;
use crate::io::Read;
use crate::sys::os::errno;
use libc::{c_int, c_void, size_t};
fn getentropy_fill_bytes(v: &mut [u8]) -> bool {
weak!(fn getentropy(*mut c_void, size_t) -> c_int);
getentropy
.get()
.map(|f| {
// getentropy(2) permits a maximum buffer size of 256 bytes
for s in v.chunks_mut(256) {
let ret = unsafe { f(s.as_mut_ptr() as *mut c_void, s.len()) };
if ret == -1 {
panic!("unexpected getentropy error: {}", errno());
}
}
true
})
.unwrap_or(false)
}
pub fn fill_bytes(v: &mut [u8]) {
if getentropy_fill_bytes(v) {
return;
}
// for older macos which doesn't support getentropy
let mut file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
file.read_exact(v).expect("failed to read /dev/urandom")
}
}
#[cfg(target_os = "openbsd")]
mod imp {
use crate::sys::os::errno;

View file

@ -28,6 +28,6 @@ fn parse() {
let path = Path::new(file!());
let path = path.canonicalize().unwrap();
let mut parser = new_parser_from_file(&parse_session, &path);
let mut parser = new_parser_from_file(&parse_session, &path, None);
let _ = parser.parse_crate_mod();
}

View file

@ -0,0 +1,19 @@
// run-pass
#![feature(const_generics)]
//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash
const L: usize = 4;
pub trait Print<const N: usize> {
fn print(&self) -> usize {
N
}
}
pub struct Printer;
impl Print<L> for Printer {}
fn main() {
let p = Printer;
assert_eq!(p.print(), 4);
}

View file

@ -0,0 +1,8 @@
warning: the feature `const_generics` is incomplete and may cause the compiler to crash
--> $DIR/issue-70125-1.rs:2:12
|
LL | #![feature(const_generics)]
| ^^^^^^^^^^^^^^
|
= note: `#[warn(incomplete_features)]` on by default

View file

@ -0,0 +1,16 @@
// run-pass
#![feature(const_generics)]
//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash
fn main() {
<()>::foo();
}
trait Foo<const X: usize> {
fn foo() -> usize {
X
}
}
impl Foo<{3}> for () {}

View file

@ -0,0 +1,8 @@
warning: the feature `const_generics` is incomplete and may cause the compiler to crash
--> $DIR/issue-70125-2.rs:3:12
|
LL | #![feature(const_generics)]
| ^^^^^^^^^^^^^^
|
= note: `#[warn(incomplete_features)]` on by default

View file

@ -29,20 +29,17 @@ LL | for _ in (std::ops::Range { start: 0, end: 10 }) {}
error[E0423]: expected function, tuple struct or tuple variant, found struct `Foo`
--> $DIR/E0423.rs:4:13
|
LL | struct Foo { a: bool };
| ---------------------- `Foo` defined here
LL | struct Foo { a: bool };
| ---------------------- `Foo` defined here
LL |
LL | let f = Foo();
| ^^^
| |
| did you mean `Foo { /* fields */ }`?
| help: a function with a similar name exists (notice the capitalization): `foo`
LL | let f = Foo();
| ^^^
| |
| did you mean `Foo { /* fields */ }`?
| help: a function with a similar name exists (notice the capitalization): `foo`
...
LL | / fn foo() {
LL | | for _ in std::ops::Range { start: 0, end: 10 } {}
LL | |
LL | | }
| |_- similarly named function `foo` defined here
LL | fn foo() {
| -------- similarly named function `foo` defined here
error[E0423]: expected value, found struct `T`
--> $DIR/E0423.rs:14:8

View file

@ -47,7 +47,7 @@ error[E0412]: cannot find type `A` in this scope
--> $DIR/glob-resolve1.rs:28:11
|
LL | pub enum B { B1 }
| ----------------- similarly named enum `B` defined here
| ---------- similarly named enum `B` defined here
...
LL | foo::<A>();
| ^
@ -65,7 +65,7 @@ error[E0412]: cannot find type `C` in this scope
--> $DIR/glob-resolve1.rs:29:11
|
LL | pub enum B { B1 }
| ----------------- similarly named enum `B` defined here
| ---------- similarly named enum `B` defined here
...
LL | foo::<C>();
| ^
@ -83,7 +83,7 @@ error[E0412]: cannot find type `D` in this scope
--> $DIR/glob-resolve1.rs:30:11
|
LL | pub enum B { B1 }
| ----------------- similarly named enum `B` defined here
| ---------- similarly named enum `B` defined here
...
LL | foo::<D>();
| ^

View file

@ -0,0 +1,15 @@
// check-pass
mod m {
pub enum Same {
Same,
}
}
use m::*;
// The variant `Same` introduced by this import is not considered when resolving the prefix
// `Same::` during import validation (issue #62767).
use Same::Same;
fn main() {}

View file

@ -1,11 +1,10 @@
error[E0425]: cannot find function `g` in this scope
--> $DIR/issue-31845.rs:7:12
|
LL | / fn h() {
LL | | g();
| | ^ help: a function with a similar name exists: `h`
LL | | }
| |_________- similarly named function `h` defined here
LL | fn h() {
| ------ similarly named function `h` defined here
LL | g();
| ^ help: a function with a similar name exists: `h`
error: aborting due to previous error

View file

@ -2,7 +2,7 @@ error[E0422]: cannot find struct, variant or union type `TyUInt` in this scope
--> $DIR/issue-46332.rs:9:5
|
LL | struct TyUint {}
| ---------------- similarly named struct `TyUint` defined here
| ------------- similarly named struct `TyUint` defined here
...
LL | TyUInt {};
| ^^^^^^ help: a struct with a similar name exists (notice the capitalization): `TyUint`

View file

@ -1,13 +1,11 @@
error: cannot find macro `k` in this scope
--> $DIR/macro_undefined.rs:11:5
|
LL | / macro_rules! kl {
LL | | () => ()
LL | | }
| |_____- similarly named macro `kl` defined here
LL | macro_rules! kl {
| --------------- similarly named macro `kl` defined here
...
LL | k!();
| ^ help: a macro with a similar name exists: `kl`
LL | k!();
| ^ help: a macro with a similar name exists: `kl`
error: aborting due to previous error

View file

@ -1,12 +1,10 @@
error[E0423]: expected function, tuple struct or tuple variant, found struct `S`
--> $DIR/legacy-ctor-visibility.rs:9:13
|
LL | / fn f() {
LL | | S(10);
| | ^ help: a function with a similar name exists: `f`
LL | |
LL | | }
| |_________- similarly named function `f` defined here
LL | fn f() {
| ------ similarly named function `f` defined here
LL | S(10);
| ^ help: a function with a similar name exists: `f`
error: aborting due to previous error

View file

@ -18,24 +18,20 @@ LL | Dlona!();
error: cannot find macro `attr_proc_macra` in this scope
--> $DIR/resolve-error.rs:58:5
|
LL | / macro_rules! attr_proc_mac {
LL | | () => {}
LL | | }
| |_- similarly named macro `attr_proc_mac` defined here
LL | macro_rules! attr_proc_mac {
| -------------------------- similarly named macro `attr_proc_mac` defined here
...
LL | attr_proc_macra!();
| ^^^^^^^^^^^^^^^ help: a macro with a similar name exists: `attr_proc_mac`
LL | attr_proc_macra!();
| ^^^^^^^^^^^^^^^ help: a macro with a similar name exists: `attr_proc_mac`
error: cannot find macro `FooWithLongNama` in this scope
--> $DIR/resolve-error.rs:55:5
|
LL | / macro_rules! FooWithLongNam {
LL | | () => {}
LL | | }
| |_- similarly named macro `FooWithLongNam` defined here
LL | macro_rules! FooWithLongNam {
| --------------------------- similarly named macro `FooWithLongNam` defined here
...
LL | FooWithLongNama!();
| ^^^^^^^^^^^^^^^ help: a macro with a similar name exists: `FooWithLongNam`
LL | FooWithLongNama!();
| ^^^^^^^^^^^^^^^ help: a macro with a similar name exists: `FooWithLongNam`
error: cannot find derive macro `attr_proc_macra` in this scope
--> $DIR/resolve-error.rs:49:10

View file

@ -8,7 +8,7 @@ error[E0404]: expected trait, found type alias `K`
--> $DIR/issue-5035.rs:3:6
|
LL | trait I {}
| ---------- similarly named trait `I` defined here
| ------- similarly named trait `I` defined here
LL | type K = dyn I;
LL | impl K for isize {}
| ^

View file

@ -8,7 +8,7 @@ error[E0412]: cannot find type `Baz` in this scope
--> $DIR/levenshtein.rs:14:10
|
LL | enum Bar { }
| ------------ similarly named enum `Bar` defined here
| -------- similarly named enum `Bar` defined here
LL |
LL | type A = Baz; // Misspelled type name.
| ^^^ help: an enum with a similar name exists: `Bar`
@ -43,7 +43,7 @@ error[E0425]: cannot find function `foobar` in this scope
--> $DIR/levenshtein.rs:30:5
|
LL | fn foo_bar() {}
| --------------- similarly named function `foo_bar` defined here
| ------------ similarly named function `foo_bar` defined here
...
LL | foobar(); // Misspelled function name.
| ^^^^^^ help: a function with a similar name exists: `foo_bar`

View file

@ -16,15 +16,11 @@ LL | m::Z::Unit;
error[E0423]: expected value, found enum `Z`
--> $DIR/privacy-enum-ctor.rs:25:9
|
LL | / fn f() {
LL | | n::Z;
LL | |
LL | | Z;
| | ^
... |
LL | | // This is ok, it is equivalent to not having braces
LL | | }
| |_____- similarly named function `f` defined here
LL | fn f() {
| ------ similarly named function `f` defined here
...
LL | Z;
| ^
|
help: a function with a similar name exists
|
@ -53,17 +49,11 @@ LL | let _: Z = Z::Struct;
error[E0423]: expected value, found enum `m::E`
--> $DIR/privacy-enum-ctor.rs:41:16
|
LL | / fn f() {
LL | | n::Z;
LL | |
LL | | Z;
... |
LL | | // This is ok, it is equivalent to not having braces
LL | | }
| |_____- similarly named function `f` defined here
LL | fn f() {
| ------ similarly named function `f` defined here
...
LL | let _: E = m::E;
| ^^^^
LL | let _: E = m::E;
| ^^^^
|
help: a function with a similar name exists
|
@ -130,17 +120,11 @@ LL | let _: E = E::Struct;
error[E0412]: cannot find type `Z` in this scope
--> $DIR/privacy-enum-ctor.rs:57:12
|
LL | / pub enum E {
LL | | Fn(u8),
LL | | Struct {
LL | | s: u8,
LL | | },
LL | | Unit,
LL | | }
| |_____- similarly named enum `E` defined here
LL | pub enum E {
| ---------- similarly named enum `E` defined here
...
LL | let _: Z = m::n::Z;
| ^
LL | let _: Z = m::n::Z;
| ^
|
help: an enum with a similar name exists
|
@ -169,17 +153,11 @@ LL | let _: Z = m::Z::Unit;
error[E0412]: cannot find type `Z` in this scope
--> $DIR/privacy-enum-ctor.rs:61:12
|
LL | / pub enum E {
LL | | Fn(u8),
LL | | Struct {
LL | | s: u8,
LL | | },
LL | | Unit,
LL | | }
| |_____- similarly named enum `E` defined here
LL | pub enum E {
| ---------- similarly named enum `E` defined here
...
LL | let _: Z = m::n::Z::Fn;
| ^
LL | let _: Z = m::n::Z::Fn;
| ^
|
help: an enum with a similar name exists
|
@ -193,17 +171,11 @@ LL | use m::n::Z;
error[E0412]: cannot find type `Z` in this scope
--> $DIR/privacy-enum-ctor.rs:64:12
|
LL | / pub enum E {
LL | | Fn(u8),
LL | | Struct {
LL | | s: u8,
LL | | },
LL | | Unit,
LL | | }
| |_____- similarly named enum `E` defined here
LL | pub enum E {
| ---------- similarly named enum `E` defined here
...
LL | let _: Z = m::n::Z::Struct;
| ^
LL | let _: Z = m::n::Z::Struct;
| ^
|
help: an enum with a similar name exists
|
@ -228,17 +200,11 @@ LL | let _: Z = m::n::Z::Struct;
error[E0412]: cannot find type `Z` in this scope
--> $DIR/privacy-enum-ctor.rs:68:12
|
LL | / pub enum E {
LL | | Fn(u8),
LL | | Struct {
LL | | s: u8,
LL | | },
LL | | Unit,
LL | | }
| |_____- similarly named enum `E` defined here
LL | pub enum E {
| ---------- similarly named enum `E` defined here
...
LL | let _: Z = m::n::Z::Unit {};
| ^
LL | let _: Z = m::n::Z::Unit {};
| ^
|
help: an enum with a similar name exists
|

View file

@ -0,0 +1,9 @@
#![feature(track_caller)]
#![allow(dead_code)]
extern "Rust" {
#[track_caller] //~ ERROR: `#[track_caller]` is not supported on foreign functions
fn bar();
}
fn main() {}

View file

@ -1,5 +1,5 @@
error[E0738]: `#[track_caller]` may not be used on trait methods
--> $DIR/error-with-trait-decl.rs:4:5
error[E0738]: `#[track_caller]` is not supported on foreign functions
--> $DIR/error-extern-fn.rs:5:5
|
LL | #[track_caller]
| ^^^^^^^^^^^^^^^

View file

@ -1,12 +0,0 @@
#![feature(track_caller)]
trait Trait {
#[track_caller] //~ ERROR: `#[track_caller]` may not be used on trait methods
fn unwrap(&self);
}
impl Trait for u64 {
fn unwrap(&self) {}
}
fn main() {}

View file

@ -1,8 +0,0 @@
#![feature(track_caller)]
trait Trait {
#[track_caller] //~ ERROR: `#[track_caller]` may not be used on trait methods
fn unwrap(&self) {}
}
fn main() {}

View file

@ -1,9 +0,0 @@
error[E0738]: `#[track_caller]` may not be used on trait methods
--> $DIR/error-with-trait-default-impl.rs:4:5
|
LL | #[track_caller]
| ^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0738`.

View file

@ -1,21 +0,0 @@
// check-fail
#![feature(track_caller)]
trait Trait {
fn unwrap(&self);
}
impl Trait for u64 {
#[track_caller] //~ ERROR: `#[track_caller]` may not be used on trait methods
fn unwrap(&self) {}
}
struct S;
impl S {
#[track_caller] // ok
fn foo() {}
}
fn main() {}

View file

@ -1,9 +0,0 @@
error[E0738]: `#[track_caller]` may not be used on trait methods
--> $DIR/error-with-trait-fn-impl.rs:10:5
|
LL | #[track_caller]
| ^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0738`.

View file

@ -14,6 +14,49 @@ fn tracked_unit(_: ()) {
assert_eq!(location.line(), expected_line, "call shims report location as fn definition");
}
trait Trait {
fn trait_tracked_unit(_: ());
}
impl Trait for () {
#[track_caller]
fn trait_tracked_unit(_: ()) {
let expected_line = line!() - 1;
let location = std::panic::Location::caller();
assert_eq!(location.file(), file!());
assert_eq!(location.line(), expected_line, "call shims report location as fn definition");
}
}
trait TrackedTrait {
#[track_caller]
fn trait_tracked_unit_default(_: ()) {
let expected_line = line!() - 1;
let location = std::panic::Location::caller();
assert_eq!(location.file(), file!());
assert_eq!(location.line(), expected_line, "call shims report location as fn definition");
}
}
impl TrackedTrait for () {}
trait BlanketTrackedTrait {
#[track_caller]
fn tracked_blanket(_: ());
}
impl BlanketTrackedTrait for () {
fn tracked_blanket(_: ()) {
let expected_line = line!() - 1;
let location = std::panic::Location::caller();
assert_eq!(location.file(), file!());
assert_eq!(location.line(), expected_line, "call shims report location as fn definition");
}
}
fn main() {
pass_to_ptr_call(tracked_unit, ());
pass_to_ptr_call(<() as Trait>::trait_tracked_unit, ());
pass_to_ptr_call(<() as TrackedTrait>::trait_tracked_unit_default, ());
pass_to_ptr_call(<() as BlanketTrackedTrait>::tracked_blanket, ());
}

View file

@ -14,6 +14,49 @@ fn tracked() {
assert_eq!(location.line(), expected_line, "call shims report location as fn definition");
}
trait Trait {
fn trait_tracked();
}
impl Trait for () {
#[track_caller]
fn trait_tracked() {
let expected_line = line!() - 1;
let location = std::panic::Location::caller();
assert_eq!(location.file(), file!());
assert_eq!(location.line(), expected_line, "call shims report location as fn definition");
}
}
trait TrackedTrait {
#[track_caller]
fn trait_tracked_default() {
let expected_line = line!() - 1;
let location = std::panic::Location::caller();
assert_eq!(location.file(), file!());
assert_eq!(location.line(), expected_line, "call shims report location as fn definition");
}
}
impl TrackedTrait for () {}
trait TraitBlanketTracked {
#[track_caller]
fn tracked_blanket();
}
impl TraitBlanketTracked for () {
fn tracked_blanket() {
let expected_line = line!() - 1;
let location = std::panic::Location::caller();
assert_eq!(location.file(), file!());
assert_eq!(location.line(), expected_line, "call shims report location as fn definition");
}
}
fn main() {
ptr_call(tracked);
ptr_call(<() as Trait>::trait_tracked);
ptr_call(<() as TrackedTrait>::trait_tracked_default);
ptr_call(<() as TraitBlanketTracked>::tracked_blanket);
}

View file

@ -0,0 +1,79 @@
// run-pass
#![feature(track_caller)]
macro_rules! assert_expansion_site_is_tracked {
() => {{
let location = std::panic::Location::caller();
assert_eq!(location.file(), file!());
assert_ne!(location.line(), line!(), "line should be outside this fn");
}}
}
trait Tracked {
fn local_tracked(&self);
#[track_caller]
fn blanket_tracked(&self);
#[track_caller]
fn default_tracked(&self) {
assert_expansion_site_is_tracked!();
}
}
impl Tracked for () {
#[track_caller]
fn local_tracked(&self) {
assert_expansion_site_is_tracked!();
}
fn blanket_tracked(&self) {
assert_expansion_site_is_tracked!();
}
}
impl Tracked for bool {
#[track_caller]
fn local_tracked(&self) {
assert_expansion_site_is_tracked!();
}
fn blanket_tracked(&self) {
assert_expansion_site_is_tracked!();
}
fn default_tracked(&self) {
assert_expansion_site_is_tracked!();
}
}
impl Tracked for u8 {
#[track_caller]
fn local_tracked(&self) {
assert_expansion_site_is_tracked!();
}
fn blanket_tracked(&self) {
assert_expansion_site_is_tracked!();
}
#[track_caller]
fn default_tracked(&self) {
assert_expansion_site_is_tracked!();
}
}
fn main() {
().local_tracked();
().default_tracked();
().blanket_tracked();
true.local_tracked();
true.default_tracked();
true.blanket_tracked();
0u8.local_tracked();
0u8.default_tracked();
0u8.blanket_tracked();
}

View file

@ -1,12 +1,11 @@
error[E0573]: expected type, found module `a`
--> $DIR/trait-impl-for-module.rs:7:12
|
LL | / trait A {
LL | | }
| |_- similarly named trait `A` defined here
LL |
LL | impl A for a {
| ^ help: a trait with a similar name exists: `A`
LL | trait A {
| ------- similarly named trait `A` defined here
...
LL | impl A for a {
| ^ help: a trait with a similar name exists: `A`
error: aborting due to previous error

View file

@ -35,7 +35,7 @@ error[E0576]: cannot find method or associated constant `N` in trait `Tr`
--> $DIR/ufcs-partially-resolved.rs:22:17
|
LL | fn Y() {}
| --------- similarly named associated function `Y` defined here
| ------ similarly named associated function `Y` defined here
...
LL | <u8 as Tr>::N;
| ^ help: an associated function with a similar name exists: `Y`
@ -181,7 +181,7 @@ error[E0575]: expected method or associated constant, found associated type `Dr:
--> $DIR/ufcs-partially-resolved.rs:53:5
|
LL | fn Z() {}
| --------- similarly named associated function `Z` defined here
| ------ similarly named associated function `Z` defined here
...
LL | <u8 as Dr>::X;
| ^^^^^^^^^^^^-