to fix the issue.
* The dark blue **final-comment-period** label marks bugs that are using the
- RFC signoff functionality of [rfcbot][rfcbot] and are currenty in the final
+ RFC signoff functionality of [rfcbot][rfcbot] and are currently in the final
comment period.
* Red, **I**-prefixed labels indicate the **importance** of the issue. The
name = "rustc-workspace-hack"
version = "1.0.0"
dependencies = [
+ "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)",
+ "serde_json 1.0.31 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
version = "0.0.0"
dependencies = [
"arena 0.0.0",
+ "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc 0.0.0",
"rustc_data_structures 0.0.0",
- `freeze`: `libcore/marker.rs`
- `debug_trait`: `libcore/fmt/mod.rs`
- `non_zero`: `libcore/nonzero.rs`
+ - `arc`: `liballoc/sync.rs`
+ - `rc`: `liballoc/rc.rs`
use core::cmp::Ordering;
use core::fmt;
-use core::isize;
use core::iter::{repeat, FromIterator, FusedIterator};
use core::mem;
use core::ops::Bound::{Excluded, Included, Unbounded};
len);
}
- /// Copies all values from `src` to the back of `self`, wrapping around if needed.
- ///
- /// # Safety
- ///
- /// The capacity must be sufficient to hold self.len() + src.len() elements.
- /// If so, this function never panics.
- #[inline]
- unsafe fn copy_slice(&mut self, src: &[T]) {
- /// This is guaranteed by `RawVec`.
- debug_assert!(self.capacity() <= isize::MAX as usize);
-
- let expected_new_len = self.len() + src.len();
- debug_assert!(self.capacity() >= expected_new_len);
-
- let dst_high_ptr = self.ptr().add(self.head);
- let dst_high_len = self.cap() - self.head;
-
- let split = cmp::min(src.len(), dst_high_len);
- let (src_high, src_low) = src.split_at(split);
-
- ptr::copy_nonoverlapping(src_high.as_ptr(), dst_high_ptr, src_high.len());
- ptr::copy_nonoverlapping(src_low.as_ptr(), self.ptr(), src_low.len());
-
- self.head = self.wrap_add(self.head, src.len());
- debug_assert!(self.len() == expected_new_len);
- }
-
/// Copies a potentially wrapping block of memory len long from src to dest.
/// (abs(dst - src) + len) must be no larger than cap() (There must be at
/// most one continuous overlapping region between src and dest).
iter: Iter {
tail: drain_tail,
head: drain_head,
- ring: unsafe { self.buffer_as_slice() },
+ ring: unsafe { self.buffer_as_mut_slice() },
},
}
}
#[inline]
#[stable(feature = "append", since = "1.4.0")]
pub fn append(&mut self, other: &mut Self) {
- unsafe {
- // Guarantees there is space in `self` for `other`.
- self.reserve(other.len());
-
- {
- let (src_high, src_low) = other.as_slices();
-
- // This is only safe because copy_slice never panics when capacity is sufficient.
- self.copy_slice(src_low);
- self.copy_slice(src_high);
- }
-
- // Some values now exist in both `other` and `self` but are made inaccessible
- // in`other`.
- other.tail = other.head;
- }
+ // naive impl
+ self.extend(other.drain(..));
}
/// Retains only the elements specified by the predicate.
let mut right_offset = 0;
for i in left_edge..right_edge {
right_offset = (i - left_edge) % (cap - right_edge);
- let src = right_edge + right_offset;
- ptr::swap(buf.add(i), buf.add(src));
+ let src: isize = (right_edge + right_offset) as isize;
+ ptr::swap(buf.add(i), buf.offset(src));
}
let n_ops = right_edge - left_edge;
left_edge += n_ops;
/// type `T`.
///
/// [get_mut]: #method.get_mut
+#[cfg_attr(all(not(stage0), not(test)), lang = "rc")]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Rc<T: ?Sized> {
ptr: NonNull<RcBox<T>>,
/// counting in general.
///
/// [rc_examples]: ../../std/rc/index.html#examples
+#[cfg_attr(all(not(stage0), not(test)), lang = "arc")]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Arc<T: ?Sized> {
ptr: NonNull<ArcInner<T>>,
unsafe {
let mut ptr = self.as_mut_ptr().add(self.len());
let mut local_len = SetLenOnDrop::new(&mut self.len);
- for element in iterator {
+ iterator.for_each(move |element| {
ptr::write(ptr, element);
ptr = ptr.offset(1);
// NB can't overflow since we would have had to alloc the address space
local_len.increment_len(1);
- }
+ });
}
} else {
self.extend_desugared(iterator)
#![feature(powerpc_target_feature)]
#![feature(mips_target_feature)]
#![feature(aarch64_target_feature)]
+#![feature(wasm_target_feature)]
#![feature(const_slice_len)]
#![feature(const_str_as_bytes)]
#![feature(const_str_len)]
/// [`Relaxed`]: enum.Ordering.html#variant.Relaxed
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
+#[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
pub fn fence(order: Ordering) {
+ // On wasm32 it looks like fences aren't implemented in LLVM yet in that
+ // they will cause LLVM to abort. The wasm instruction set doesn't have
+ // fences right now. There's discussion online about the best way for tools
+ // to conventionally implement fences at
+ // https://github.com/WebAssembly/tool-conventions/issues/59. We should
+ // follow that discussion and implement a solution when one comes about!
+ #[cfg(not(target_arch = "wasm32"))]
unsafe {
match order {
Acquire => intrinsics::atomic_fence_acq(),
self.cur.next();
Some(pos)
} else {
- let pos = pos + padding + 1;
+ let pos = pos + raw + 1;
self.err(format!("expected `{:?}`, found `{:?}`", c, maybe),
format!("expected `{}`", c),
pos,
// runtime at all.
pub mod personalities {
#[no_mangle]
- #[cfg(not(all(target_os = "windows",
- target_env = "gnu",
- target_arch = "x86_64")))]
+ #[cfg(not(any(
+ target_arch = "wasm32",
+ all(
+ target_os = "windows",
+ target_env = "gnu",
+ target_arch = "x86_64",
+ ),
+ )))]
pub extern fn rust_eh_personality() {}
// On x86_64-pc-windows-gnu we use our own personality function that needs
Tool,
/// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`).
DeriveHelper,
+ /// Single-segment custom attriubte registered by a legacy plugin (`register_attribute`).
+ LegacyPluginHelper,
/// Single-segment custom attribute not registered in any way (`#[my_attr]`).
Custom,
}
NonMacroAttrKind::Builtin => "built-in attribute",
NonMacroAttrKind::Tool => "tool attribute",
NonMacroAttrKind::DeriveHelper => "derive helper attribute",
+ NonMacroAttrKind::LegacyPluginHelper => "legacy plugin helper attribute",
NonMacroAttrKind::Custom => "custom attribute",
}
}
TyKind::Path(ref qpath) => {
visitor.visit_qpath(qpath, typ.hir_id, typ.span);
}
+ TyKind::Def(item_id, ref lifetimes) => {
+ visitor.visit_nested_item(item_id);
+ walk_list!(visitor, visit_generic_arg, lifetimes);
+ }
TyKind::Array(ref ty, ref length) => {
visitor.visit_ty(ty);
visitor.visit_anon_const(length)
lctx.items.insert(exist_ty_id.node_id, exist_ty_item);
// `impl Trait` now just becomes `Foo<'a, 'b, ..>`
- let path = P(hir::Path {
- span: exist_ty_span,
- def: Def::Existential(DefId::local(exist_ty_def_index)),
- segments: hir_vec![hir::PathSegment {
- infer_types: false,
- ident: Ident::new(keywords::Invalid.name(), exist_ty_span),
- args: Some(P(hir::GenericArgs {
- parenthesized: false,
- bindings: HirVec::new(),
- args: lifetimes,
- }))
- }],
- });
- hir::TyKind::Path(hir::QPath::Resolved(None, path))
+ hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes)
})
}
}
}
- /// Lowers `impl Trait` items for a function and appends them to the list
- fn lower_fn_impl_trait_ids(
- &mut self,
- decl: &FnDecl,
- header: &FnHeader,
- ids: &mut SmallVec<[hir::ItemId; 1]>,
- ) {
- if let Some(id) = header.asyncness.opt_return_id() {
- ids.push(hir::ItemId { id });
- }
- let mut visitor = ImplTraitTypeIdVisitor { ids };
- match decl.output {
- FunctionRetTy::Default(_) => {},
- FunctionRetTy::Ty(ref ty) => visitor.visit_ty(ty),
- }
- }
-
fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
match i.node {
ItemKind::Use(ref use_tree) => {
vec
}
ItemKind::MacroDef(..) => SmallVec::new(),
- ItemKind::Fn(ref decl, ref header, ..) => {
- let mut ids = smallvec![hir::ItemId { id: i.id }];
- self.lower_fn_impl_trait_ids(decl, header, &mut ids);
- ids
- },
- ItemKind::Impl(.., None, _, ref items) => {
- let mut ids = smallvec![hir::ItemId { id: i.id }];
- for item in items {
- if let ImplItemKind::Method(ref sig, _) = item.node {
- self.lower_fn_impl_trait_ids(&sig.decl, &sig.header, &mut ids);
- }
- }
- ids
- },
+ ItemKind::Fn(..) |
+ ItemKind::Impl(.., None, _, _) => smallvec![hir::ItemId { id: i.id }],
ItemKind::Static(ref ty, ..) => {
let mut ids = smallvec![hir::ItemId { id: i.id }];
if self.sess.features_untracked().impl_trait_in_bindings {
// expand <head>
let head = self.lower_expr(head);
let head_sp = head.span;
+ let desugared_span = self.allow_internal_unstable(
+ CompilerDesugaringKind::ForLoop,
+ head_sp,
+ );
let iter = self.str_to_ident("iter");
let next_ident = self.str_to_ident("__next");
- let next_sp = self.allow_internal_unstable(
- CompilerDesugaringKind::ForLoop,
- head_sp,
- );
let next_pat = self.pat_ident_binding_mode(
- next_sp,
+ desugared_span,
next_ident,
hir::BindingAnnotation::Mutable,
);
};
// `mut iter`
- let iter_pat =
- self.pat_ident_binding_mode(head_sp, iter, hir::BindingAnnotation::Mutable);
+ let iter_pat = self.pat_ident_binding_mode(
+ desugared_span,
+ iter,
+ hir::BindingAnnotation::Mutable
+ );
// `match ::std::iter::Iterator::next(&mut iter) { ... }`
let match_expr = {
let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat.id));
// `let mut __next`
- let next_let =
- self.stmt_let_pat(head_sp, None, next_pat, hir::LocalSource::ForLoopDesugar);
+ let next_let = self.stmt_let_pat(
+ desugared_span,
+ None,
+ next_pat,
+ hir::LocalSource::ForLoopDesugar,
+ );
// `let <pat> = __next`
let pat = self.lower_pat(pat);
///
/// Type parameters may be stored in each `PathSegment`.
Path(QPath),
+ /// A type definition itself. This is currently only used for the `existential type`
+ /// item that `impl Trait` in return position desugars to.
+ ///
+ /// The generic arg list are the lifetimes (and in the future possibly parameters) that are
+ /// actually bound on the `impl Trait`.
+ Def(ItemId, HirVec<GenericArg>),
/// A trait object type `Bound1 + Bound2 + Bound3`
/// where `Bound` is a trait or a lifetime.
TraitObject(HirVec<PolyTraitRef>, Lifetime),
}
}
- /// True if `#[no_mangle]` or `#[export_name(...)]` is present.
+ /// True if it looks like this symbol needs to be exported, for example:
+ ///
+ /// * `#[no_mangle]` is present
+ /// * `#[export_name(...)]` is present
+ /// * `#[linkage]` is present
pub fn contains_extern_indicator(&self) -> bool {
- self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) || self.export_name.is_some()
+ self.flags.contains(CodegenFnAttrFlags::NO_MANGLE) ||
+ self.export_name.is_some() ||
+ match self.linkage {
+ // these are private, make sure we don't try to consider
+ // them external
+ None |
+ Some(Linkage::Internal) |
+ Some(Linkage::Private) => false,
+ Some(_) => true,
+ }
}
}
self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
&f.arg_names[..])?;
}
+ hir::TyKind::Def(..) => {},
hir::TyKind::Path(ref qpath) => {
self.print_qpath(qpath, false)?
}
Never,
Tup(ts),
Path(qpath),
+ Def(it, lt),
TraitObject(trait_refs, lifetime),
Typeof(body_id),
Err,
Builtin,
Tool,
DeriveHelper,
+ LegacyPluginHelper,
Custom,
});
source_info,
visibility_scope,
internal,
+ is_block_tail,
is_user_variable
});
impl_stable_hash_for!(struct mir::UpvarDecl { debug_name, var_hir_id, by_ref, mutability });
mir::TerminatorKind::Call { ref func,
ref args,
ref destination,
- cleanup } => {
+ cleanup,
+ from_hir_call, } => {
func.hash_stable(hcx, hasher);
args.hash_stable(hcx, hasher);
destination.hash_stable(hcx, hasher);
cleanup.hash_stable(hcx, hasher);
+ from_hir_call.hash_stable(hcx, hasher);
}
mir::TerminatorKind::Assert { ref cond,
expected,
}
ty::ReLateBound(..) |
ty::ReVar(..) |
- ty::ReSkolemized(..) => {
+ ty::RePlaceholder(..) => {
bug!("StableHasher: unexpected region {:?}", *self)
}
}
Tuple(inner_tys) => {
inner_tys.hash_stable(hcx, hasher);
}
- Projection(ref projection_ty) => {
- projection_ty.hash_stable(hcx, hasher);
+ Projection(ref data) | UnnormalizedProjection(ref data) => {
+ data.hash_stable(hcx, hasher);
}
Opaque(def_id, substs) => {
def_id.hash_stable(hcx, hasher);
ty::ReEarlyBound(..)
| ty::ReFree(_)
| ty::ReScope(_)
- | ty::ReSkolemized(..)
+ | ty::RePlaceholder(..)
| ty::ReEmpty
| ty::ReErased => {
if self.canonicalize_region_mode.other_free_regions {
| ty::Never
| ty::Tuple(..)
| ty::Projection(..)
+ | ty::UnnormalizedProjection(..)
| ty::Foreign(..)
| ty::Param(..)
| ty::Opaque(..) => {
return Ok(r);
}
- // Always make a fresh region variable for skolemized regions;
- // the higher-ranked decision procedures rely on this.
- ty::ReSkolemized(..) => { }
+ // Always make a fresh region variable for placeholder
+ // regions; the higher-ranked decision procedures rely on
+ // this.
+ ty::RePlaceholder(..) => { }
// For anything else, we make a region variable, unless we
// are *equating*, in which case it's just wasteful.
ty::ReEmpty => ("the empty lifetime".to_owned(), None),
- // FIXME(#13998) ReSkolemized should probably print like
+ // FIXME(#13998) RePlaceholder should probably print like
// ReFree rather than dumping Debug output on the user.
//
// We shouldn't really be having unification failures with ReVar
// and ReLateBound though.
- ty::ReSkolemized(..) | ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
+ ty::RePlaceholder(..) | ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
(format!("lifetime {:?}", region), None)
}
ty::ReFree(_) |
ty::ReScope(_) |
ty::ReVar(_) |
- ty::ReSkolemized(..) |
+ ty::RePlaceholder(..) |
ty::ReEmpty |
ty::ReErased => {
// replace all free regions with 'erased
ty::Never |
ty::Tuple(..) |
ty::Projection(..) |
+ ty::UnnormalizedProjection(..) |
ty::Foreign(..) |
ty::Param(..) |
ty::Closure(..) |
Here is the algorithm we use to perform the subtyping check:
1. Replace all bound regions in the subtype with new variables
-2. Replace all bound regions in the supertype with skolemized
- equivalents. A "skolemized" region is just a new fresh region
+2. Replace all bound regions in the supertype with placeholder
+ equivalents. A "placeholder" region is just a new fresh region
name.
3. Check that the parameter and return types match as normal
-4. Ensure that no skolemized regions 'leak' into region variables
+4. Ensure that no placeholder regions 'leak' into region variables
visible from "the outside"
Let's walk through some examples and see how this algorithm plays out.
Here the upper case `&A` indicates a *region variable*, that is, a
region whose value is being inferred by the system. I also replaced
`&b` with `&x`---I'll use letters late in the alphabet (`x`, `y`, `z`)
-to indicate skolemized region names. We can assume they don't appear
+to indicate placeholder region names. We can assume they don't appear
elsewhere. Note that neither the sub- nor the supertype bind any
region names anymore (as indicated by the absence of `<` and `>`).
must hold: but this does not hold. `self` and `x` are both distinct
free regions. So the subtype check fails.
-#### Checking for skolemization leaks
+#### Checking for placeholder leaks
You may be wondering about that mysterious last step in the algorithm.
So far it has not been relevant. The purpose of that last step is to
fn(&'A T) <: for<'b> fn(&'b T)?
-Here we skolemize the bound region in the supertype to yield:
+Here we replace the bound region in the supertype with a placeholder to yield:
fn(&'A T) <: fn(&'x T)?
is *necessary*, it was key to the first example we walked through.
The difference between this example and the first one is that the variable
-`A` already existed at the point where the skolemization occurred. In
+`A` already existed at the point where the placeholders were added. In
the first example, you had two functions:
for<'a> fn(&'a T) <: for<'b> fn(&'b T)
and hence `&A` and `&x` were created "together". In general, the
-intention of the skolemized names is that they are supposed to be
+intention of the placeholder names is that they are supposed to be
fresh names that could never be equal to anything from the outside.
But when inference comes into play, we might not be respecting this
rule.
So the way we solve this is to add a fourth step that examines the
-constraints that refer to skolemized names. Basically, consider a
+constraints that refer to placeholder names. Basically, consider a
non-directed version of the constraint graph. Let `Tainted(x)` be the
-set of all things reachable from a skolemized variable `x`.
+set of all things reachable from a placeholder variable `x`.
`Tainted(x)` should not contain any regions that existed before the
-step at which the skolemization was performed. So this case here
+step at which the placeholders were created. So this case here
would fail because `&x` was created alone, but is relatable to `&A`.
## Computing the LUB and GLB
InferCtxt,
HigherRankedType,
SubregionOrigin,
- SkolemizationMap};
+ PlaceholderMap};
use super::combine::CombineFields;
use super::region_constraints::{TaintDirections};
return self.infcx.commit_if_ok(|snapshot| {
let span = self.trace.cause.span;
- // First, we instantiate each bound region in the subtype with a fresh
- // region variable.
+ // First, we instantiate each bound region in the supertype with a
+ // fresh placeholder region.
+ let (b_prime, placeholder_map) =
+ self.infcx.replace_late_bound_regions_with_placeholders(b);
+
+ // Next, we instantiate each bound region in the subtype
+ // with a fresh region variable. These region variables --
+ // but no other pre-existing region variables -- can name
+ // the placeholders.
let (a_prime, _) =
self.infcx.replace_late_bound_regions_with_fresh_var(
span,
HigherRankedType,
a);
- // Second, we instantiate each bound region in the supertype with a
- // fresh concrete region.
- let (b_prime, skol_map) =
- self.infcx.skolemize_late_bound_regions(b);
-
debug!("a_prime={:?}", a_prime);
debug!("b_prime={:?}", b_prime);
let result = self.sub(a_is_expected).relate(&a_prime, &b_prime)?;
// Presuming type comparison succeeds, we need to check
- // that the skolemized regions do not "leak".
- self.infcx.leak_check(!a_is_expected, span, &skol_map, snapshot)?;
+ // that the placeholder regions do not "leak".
+ self.infcx.leak_check(!a_is_expected, span, &placeholder_map, snapshot)?;
- // We are finished with the skolemized regions now so pop
+ // We are finished with the placeholder regions now so pop
// them off.
- self.infcx.pop_skolemized(skol_map, snapshot);
+ self.infcx.pop_placeholders(placeholder_map, snapshot);
debug!("higher_ranked_sub: OK result={:?}", result);
// created as part of this type comparison".
return self.infcx.commit_if_ok(|snapshot| {
// First, we instantiate each bound region in the matcher
- // with a skolemized region.
- let ((a_match, a_value), skol_map) =
- self.infcx.skolemize_late_bound_regions(a_pair);
+ // with a placeholder region.
+ let ((a_match, a_value), placeholder_map) =
+ self.infcx.replace_late_bound_regions_with_placeholders(a_pair);
debug!("higher_ranked_match: a_match={:?}", a_match);
- debug!("higher_ranked_match: skol_map={:?}", skol_map);
+ debug!("higher_ranked_match: placeholder_map={:?}", placeholder_map);
// Equate types now that bound regions have been replaced.
self.equate(a_is_expected).relate(&a_match, &b_match)?;
- // Map each skolemized region to a vector of other regions that it
+ // Map each placeholder region to a vector of other regions that it
// must be equated with. (Note that this vector may include other
- // skolemized regions from `skol_map`.)
- let skol_resolution_map: FxHashMap<_, _> =
- skol_map
+ // placeholder regions from `placeholder_map`.)
+ let placeholder_resolution_map: FxHashMap<_, _> =
+ placeholder_map
.iter()
- .map(|(&br, &skol)| {
+ .map(|(&br, &placeholder)| {
let tainted_regions =
self.infcx.tainted_regions(snapshot,
- skol,
+ placeholder,
TaintDirections::incoming()); // [1]
- // [1] this routine executes after the skolemized
+ // [1] this routine executes after the placeholder
// regions have been *equated* with something
// else, so examining the incoming edges ought to
// be enough to collect all constraints
- (skol, (br, tainted_regions))
+ (placeholder, (br, tainted_regions))
})
.collect();
- // For each skolemized region, pick a representative -- which can
+ // For each placeholder region, pick a representative -- which can
// be any region from the sets above, except for other members of
- // `skol_map`. There should always be a representative if things
+ // `placeholder_map`. There should always be a representative if things
// are properly well-formed.
- let skol_representatives: FxHashMap<_, _> =
- skol_resolution_map
+ let placeholder_representatives: FxHashMap<_, _> =
+ placeholder_resolution_map
.iter()
- .map(|(&skol, &(_, ref regions))| {
+ .map(|(&placeholder, &(_, ref regions))| {
let representative =
regions.iter()
- .filter(|&&r| !skol_resolution_map.contains_key(r))
+ .filter(|&&r| !placeholder_resolution_map.contains_key(r))
.cloned()
.next()
.unwrap_or_else(|| {
bug!("no representative region for `{:?}` in `{:?}`",
- skol, regions)
+ placeholder, regions)
});
- (skol, representative)
+ (placeholder, representative)
})
.collect();
- // Equate all the members of each skolemization set with the
+ // Equate all the members of each placeholder set with the
// representative.
- for (skol, &(_br, ref regions)) in &skol_resolution_map {
- let representative = &skol_representatives[skol];
+ for (placeholder, &(_br, ref regions)) in &placeholder_resolution_map {
+ let representative = &placeholder_representatives[placeholder];
debug!("higher_ranked_match: \
- skol={:?} representative={:?} regions={:?}",
- skol, representative, regions);
+ placeholder={:?} representative={:?} regions={:?}",
+ placeholder, representative, regions);
for region in regions.iter()
- .filter(|&r| !skol_resolution_map.contains_key(r))
+ .filter(|&r| !placeholder_resolution_map.contains_key(r))
.filter(|&r| r != representative)
{
let origin = SubregionOrigin::Subtype(self.trace.clone());
}
}
- // Replace the skolemized regions appearing in value with
+ // Replace the placeholder regions appearing in value with
// their representatives
let a_value =
fold_regions_in(
self.tcx(),
&a_value,
- |r, _| skol_representatives.get(&r).cloned().unwrap_or(r));
+ |r, _| placeholder_representatives.get(&r).cloned().unwrap_or(r));
debug!("higher_ranked_match: value={:?}", a_value);
- // We are now done with these skolemized variables.
- self.infcx.pop_skolemized(skol_map, snapshot);
+ // We are now done with these placeholder variables.
+ self.infcx.pop_placeholders(placeholder_map, snapshot);
Ok(HrMatchResult { value: a_value })
});
* started. This is used in the sub/lub/glb computations. The
* idea here is that when we are computing lub/glb of two
* regions, we sometimes create intermediate region variables.
- * Those region variables may touch some of the skolemized or
+ * Those region variables may touch some of the placeholder or
* other "forbidden" regions we created to replace bound
* regions, but they don't really represent an "external"
* constraint.
* we're not careful, it will succeed.
*
* The reason is that when we walk through the subtyping
- * algorithm, we begin by replacing `'a` with a skolemized
+ * algorithm, we begin by replacing `'a` with a placeholder
* variable `'1`. We then have `fn(_#0t) <: fn(&'1 int)`. This
* can be made true by unifying `_#0t` with `&'1 int`. In the
- * process, we create a fresh variable for the skolemized
+ * process, we create a fresh variable for the placeholder
* region, `'$2`, and hence we have that `_#0t == &'$2
* int`. However, because `'$2` was created during the sub
* computation, if we're not careful we will erroneously
region_vars
}
- /// Replace all regions bound by `binder` with skolemized regions and
+ /// Replace all regions bound by `binder` with placeholder regions and
/// return a map indicating which bound-region was replaced with what
- /// skolemized region. This is the first step of checking subtyping
+ /// placeholder region. This is the first step of checking subtyping
/// when higher-ranked things are involved.
///
/// **Important:** you must call this function from within a snapshot.
/// Moreover, before committing the snapshot, you must eventually call
- /// either `plug_leaks` or `pop_skolemized` to remove the skolemized
+ /// either `plug_leaks` or `pop_placeholders` to remove the placeholder
/// regions. If you rollback the snapshot (or are using a probe), then
/// the pop occurs as part of the rollback, so an explicit call is not
/// needed (but is also permitted).
///
- /// For more information about how skolemization for HRTBs works, see
+ /// For more information about how placeholders and HRTBs work, see
/// the [rustc guide].
///
/// [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/hrtb.html
- pub fn skolemize_late_bound_regions<T>(&self,
- binder: &ty::Binder<T>)
- -> (T, SkolemizationMap<'tcx>)
- where T : TypeFoldable<'tcx>
+ pub fn replace_late_bound_regions_with_placeholders<T>(
+ &self,
+ binder: &ty::Binder<T>,
+ ) -> (T, PlaceholderMap<'tcx>)
+ where
+ T : TypeFoldable<'tcx>,
{
+ let new_universe = self.create_subuniverse();
+
let (result, map) = self.tcx.replace_late_bound_regions(binder, |br| {
- self.universe.set(self.universe().subuniverse());
- self.tcx.mk_region(ty::ReSkolemized(self.universe(), br))
+ self.tcx.mk_region(ty::RePlaceholder(ty::Placeholder {
+ universe: new_universe,
+ name: br,
+ }))
});
- debug!("skolemize_bound_regions(binder={:?}, result={:?}, map={:?})",
+ debug!("replace_late_bound_regions_with_placeholders(binder={:?}, result={:?}, map={:?})",
binder,
result,
map);
}
/// Searches the region constraints created since `snapshot` was started
- /// and checks to determine whether any of the skolemized regions created
- /// in `skol_map` would "escape" -- meaning that they are related to
+ /// and checks to determine whether any of the placeholder regions created
+ /// in `placeholder_map` would "escape" -- meaning that they are related to
/// other regions in some way. If so, the higher-ranked subtyping doesn't
/// hold. See `README.md` for more details.
pub fn leak_check(&self,
overly_polymorphic: bool,
_span: Span,
- skol_map: &SkolemizationMap<'tcx>,
+ placeholder_map: &PlaceholderMap<'tcx>,
snapshot: &CombinedSnapshot<'a, 'tcx>)
-> RelateResult<'tcx, ()>
{
- debug!("leak_check: skol_map={:?}",
- skol_map);
+ debug!("leak_check: placeholder_map={:?}",
+ placeholder_map);
// If the user gave `-Zno-leak-check`, then skip the leak
// check completely. This is wildly unsound and also not
}
let new_vars = self.region_vars_confined_to_snapshot(snapshot);
- for (&skol_br, &skol) in skol_map {
- // The inputs to a skolemized variable can only
+ for (&placeholder_br, &placeholder) in placeholder_map {
+ // The inputs to a placeholder variable can only
// be itself or other new variables.
let incoming_taints = self.tainted_regions(snapshot,
- skol,
+ placeholder,
TaintDirections::both());
for &tainted_region in &incoming_taints {
- // Each skolemized should only be relatable to itself
+ // Each placeholder should only be relatable to itself
// or new variables:
match *tainted_region {
ty::ReVar(vid) => {
}
}
_ => {
- if tainted_region == skol { continue; }
+ if tainted_region == placeholder { continue; }
}
};
debug!("{:?} (which replaced {:?}) is tainted by {:?}",
- skol,
- skol_br,
+ placeholder,
+ placeholder_br,
tainted_region);
return Err(if overly_polymorphic {
debug!("Overly polymorphic!");
- TypeError::RegionsOverlyPolymorphic(skol_br, tainted_region)
+ TypeError::RegionsOverlyPolymorphic(placeholder_br, tainted_region)
} else {
debug!("Not as polymorphic!");
- TypeError::RegionsInsufficientlyPolymorphic(skol_br, tainted_region)
+ TypeError::RegionsInsufficientlyPolymorphic(placeholder_br, tainted_region)
})
}
}
Ok(())
}
- /// This code converts from skolemized regions back to late-bound
+ /// This code converts from placeholder regions back to late-bound
/// regions. It works by replacing each region in the taint set of a
- /// skolemized region with a bound-region. The bound region will be bound
+ /// placeholder region with a bound-region. The bound region will be bound
/// by the outer-most binder in `value`; the caller must ensure that there is
/// such a binder and it is the right place.
///
/// where A : Clone
/// { ... }
///
- /// Here we will have replaced `'a` with a skolemized region
+ /// Here we will have replaced `'a` with a placeholder region
/// `'0`. This means that our substitution will be `{A=>&'0
/// int, R=>&'0 int}`.
///
/// to the depth of the predicate, in this case 1, so that the final
/// predicate is `for<'a> &'a int : Clone`.
pub fn plug_leaks<T>(&self,
- skol_map: SkolemizationMap<'tcx>,
+ placeholder_map: PlaceholderMap<'tcx>,
snapshot: &CombinedSnapshot<'a, 'tcx>,
value: T) -> T
where T : TypeFoldable<'tcx>
{
- debug!("plug_leaks(skol_map={:?}, value={:?})",
- skol_map,
+ debug!("plug_leaks(placeholder_map={:?}, value={:?})",
+ placeholder_map,
value);
- if skol_map.is_empty() {
+ if placeholder_map.is_empty() {
return value;
}
- // Compute a mapping from the "taint set" of each skolemized
+ // Compute a mapping from the "taint set" of each placeholder
// region back to the `ty::BoundRegion` that it originally
// represented. Because `leak_check` passed, we know that
// these taint sets are mutually disjoint.
- let inv_skol_map: FxHashMap<ty::Region<'tcx>, ty::BoundRegion> =
- skol_map
+ let inv_placeholder_map: FxHashMap<ty::Region<'tcx>, ty::BoundRegion> =
+ placeholder_map
.iter()
- .flat_map(|(&skol_br, &skol)| {
- self.tainted_regions(snapshot, skol, TaintDirections::both())
+ .flat_map(|(&placeholder_br, &placeholder)| {
+ self.tainted_regions(snapshot, placeholder, TaintDirections::both())
.into_iter()
- .map(move |tainted_region| (tainted_region, skol_br))
+ .map(move |tainted_region| (tainted_region, placeholder_br))
})
.collect();
- debug!("plug_leaks: inv_skol_map={:?}",
- inv_skol_map);
+ debug!("plug_leaks: inv_placeholder_map={:?}",
+ inv_placeholder_map);
// Remove any instantiated type variables from `value`; those can hide
// references to regions from the `fold_regions` code below.
let value = self.resolve_type_vars_if_possible(&value);
- // Map any skolemization byproducts back to a late-bound
+ // Map any placeholder byproducts back to a late-bound
// region. Put that late-bound region at whatever the outermost
// binder is that we encountered in `value`. The caller is
// responsible for ensuring that (a) `value` contains at least one
// binder and (b) that binder is the one we want to use.
let result = self.tcx.fold_regions(&value, &mut false, |r, current_depth| {
- match inv_skol_map.get(&r) {
+ match inv_placeholder_map.get(&r) {
None => r,
Some(br) => {
// It is the responsibility of the caller to ensure
- // that each skolemized region appears within a
+ // that each placeholder region appears within a
// binder. In practice, this routine is only used by
- // trait checking, and all of the skolemized regions
+ // trait checking, and all of the placeholder regions
// appear inside predicates, which always have
// binders, so this assert is satisfied.
assert!(current_depth > ty::INNERMOST);
- // since leak-check passed, this skolemized region
+ // since leak-check passed, this placeholder region
// should only have incoming edges from variables
// (which ought not to escape the snapshot, but we
// don't check that) or itself
assert!(
match *r {
ty::ReVar(_) => true,
- ty::ReSkolemized(_, ref br1) => br == br1,
+ ty::RePlaceholder(index) => index.name == *br,
_ => false,
},
"leak-check would have us replace {:?} with {:?}",
}
});
- self.pop_skolemized(skol_map, snapshot);
+ self.pop_placeholders(placeholder_map, snapshot);
debug!("plug_leaks: result={:?}", result);
result
}
- /// Pops the skolemized regions found in `skol_map` from the region
- /// inference context. Whenever you create skolemized regions via
- /// `skolemize_late_bound_regions`, they must be popped before you
+ /// Pops the placeholder regions found in `placeholder_map` from the region
+ /// inference context. Whenever you create placeholder regions via
+ /// `replace_late_bound_regions_with_placeholders`, they must be popped before you
/// commit the enclosing snapshot (if you do not commit, e.g. within a
/// probe or as a result of an error, then this is not necessary, as
/// popping happens as part of the rollback).
///
/// Note: popping also occurs implicitly as part of `leak_check`.
- pub fn pop_skolemized(&self,
- skol_map: SkolemizationMap<'tcx>,
- snapshot: &CombinedSnapshot<'a, 'tcx>) {
- debug!("pop_skolemized({:?})", skol_map);
- let skol_regions: FxHashSet<_> = skol_map.values().cloned().collect();
+ pub fn pop_placeholders(
+ &self,
+ placeholder_map: PlaceholderMap<'tcx>,
+ snapshot: &CombinedSnapshot<'a, 'tcx>,
+ ) {
+ debug!("pop_placeholders({:?})", placeholder_map);
+ let placeholder_regions: FxHashSet<_> = placeholder_map.values().cloned().collect();
self.borrow_region_constraints()
- .pop_skolemized(self.universe(), &skol_regions, &snapshot.region_constraints_snapshot);
+ .pop_placeholders(
+ &placeholder_regions,
+ &snapshot.region_constraints_snapshot,
+ );
self.universe.set(snapshot.universe);
- if !skol_map.is_empty() {
- self.projection_cache.borrow_mut().rollback_skolemized(
+ if !placeholder_map.is_empty() {
+ self.projection_cache.borrow_mut().rollback_placeholder(
&snapshot.projection_cache_snapshot);
}
}
use ty::fold::TypeFoldable;
use ty::{self, Ty, TyCtxt};
use ty::{ReEarlyBound, ReEmpty, ReErased, ReFree, ReStatic};
-use ty::{ReLateBound, ReScope, ReSkolemized, ReVar};
+use ty::{ReLateBound, ReScope, RePlaceholder, ReVar};
use ty::{Region, RegionVid};
mod graphviz;
// For these types, we cannot define any additional
// relationship:
- (&ReSkolemized(..), _) | (_, &ReSkolemized(..)) => if a == b {
+ (&RePlaceholder(..), _) | (_, &RePlaceholder(..)) => if a == b {
a
} else {
tcx.types.re_static
universe: Cell<ty::UniverseIndex>,
}
-/// A map returned by `skolemize_late_bound_regions()` indicating the skolemized
-/// region that each late-bound region was replaced with.
-pub type SkolemizationMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
+/// A map returned by `replace_late_bound_regions_with_placeholders()`
+/// indicating the placeholder region that each late-bound region was
+/// replaced with.
+pub type PlaceholderMap<'tcx> = BTreeMap<ty::BoundRegion, ty::Region<'tcx>>;
/// See `error_reporting` module for more details
#[derive(Clone, Debug)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum NLLRegionVariableOrigin {
- // During NLL region processing, we create variables for free
- // regions that we encounter in the function signature and
- // elsewhere. This origin indices we've got one of those.
+ /// During NLL region processing, we create variables for free
+ /// regions that we encounter in the function signature and
+ /// elsewhere. This origin indices we've got one of those.
FreeRegion,
- BoundRegion(ty::UniverseIndex),
+ /// "Universal" instantiation of a higher-ranked region (e.g.,
+ /// from a `for<'a> T` binder). Meant to represent "any region".
+ Placeholder(ty::Placeholder),
Existential,
}
pub fn is_universal(self) -> bool {
match self {
NLLRegionVariableOrigin::FreeRegion => true,
- NLLRegionVariableOrigin::BoundRegion(..) => true,
+ NLLRegionVariableOrigin::Placeholder(..) => true,
NLLRegionVariableOrigin::Existential => false,
}
}
a,
b,
},
- skol_map,
- ) = self.skolemize_late_bound_regions(predicate);
+ placeholder_map,
+ ) = self.replace_late_bound_regions_with_placeholders(predicate);
let cause_span = cause.span;
let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?;
- self.leak_check(false, cause_span, &skol_map, snapshot)?;
- self.pop_skolemized(skol_map, snapshot);
+ self.leak_check(false, cause_span, &placeholder_map, snapshot)?;
+ self.pop_placeholders(placeholder_map, snapshot);
Ok(ok.unit())
}))
}
predicate: &ty::PolyRegionOutlivesPredicate<'tcx>,
) -> UnitResult<'tcx> {
self.commit_if_ok(|snapshot| {
- let (ty::OutlivesPredicate(r_a, r_b), skol_map) =
- self.skolemize_late_bound_regions(predicate);
+ let (ty::OutlivesPredicate(r_a, r_b), placeholder_map) =
+ self.replace_late_bound_regions_with_placeholders(predicate);
let origin = SubregionOrigin::from_obligation_cause(cause, || {
RelateRegionParamBound(cause.span)
});
self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b`
- self.leak_check(false, cause.span, &skol_map, snapshot)?;
- Ok(self.pop_skolemized(skol_map, snapshot))
+ self.leak_check(false, cause.span, &placeholder_map, snapshot)?;
+ Ok(self.pop_placeholders(placeholder_map, snapshot))
})
}
//! See README.md
-use self::UndoLogEntry::*;
use self::CombineMapType::*;
+use self::UndoLogEntry::*;
-use super::{MiscVariable, RegionVariableOrigin, SubregionOrigin};
use super::unify_key;
+use super::{MiscVariable, RegionVariableOrigin, SubregionOrigin};
-use rustc_data_structures::indexed_vec::IndexVec;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
+use rustc_data_structures::indexed_vec::IndexVec;
use rustc_data_structures::unify as ut;
-use ty::{self, Ty, TyCtxt};
-use ty::{Region, RegionVid};
use ty::ReStatic;
+use ty::{self, Ty, TyCtxt};
use ty::{BrFresh, ReLateBound, ReVar};
+use ty::{Region, RegionVid};
use std::collections::BTreeMap;
use std::{cmp, fmt, mem, u32};
any_unifications: bool,
}
-/// When working with skolemized regions, we often wish to find all of
-/// the regions that are either reachable from a skolemized region, or
-/// which can reach a skolemized region, or both. We call such regions
-/// *tained* regions. This struct allows you to decide what set of
+/// When working with placeholder regions, we often wish to find all of
+/// the regions that are either reachable from a placeholder region, or
+/// which can reach a placeholder region, or both. We call such regions
+/// *tainted* regions. This struct allows you to decide what set of
/// tainted regions you want.
#[derive(Debug)]
pub struct TaintDirections {
}
}
- pub fn new_region_var(&mut self,
- universe: ty::UniverseIndex,
- origin: RegionVariableOrigin) -> RegionVid {
- let vid = self.var_infos.push(RegionVariableInfo {
- origin,
- universe,
- });
+ pub fn new_region_var(
+ &mut self,
+ universe: ty::UniverseIndex,
+ origin: RegionVariableOrigin,
+ ) -> RegionVid {
+ let vid = self.var_infos.push(RegionVariableInfo { origin, universe });
let u_vid = self.unification_table
.new_key(unify_key::RegionVidKey { min_vid: vid });
}
debug!(
"created new region variable {:?} with origin {:?}",
- vid,
- origin
+ vid, origin
);
return vid;
}
self.var_infos[vid].origin
}
- /// Removes all the edges to/from the skolemized regions that are
+ /// Removes all the edges to/from the placeholder regions that are
/// in `skols`. This is used after a higher-ranked operation
- /// completes to remove all trace of the skolemized regions
+ /// completes to remove all trace of the placeholder regions
/// created in that time.
- pub fn pop_skolemized(
+ pub fn pop_placeholders(
&mut self,
- skolemization_count: ty::UniverseIndex,
- skols: &FxHashSet<ty::Region<'tcx>>,
+ placeholders: &FxHashSet<ty::Region<'tcx>>,
snapshot: &RegionSnapshot,
) {
- debug!("pop_skolemized_regions(skols={:?})", skols);
+ debug!("pop_placeholders(placeholders={:?})", placeholders);
assert!(self.in_snapshot());
assert!(self.undo_log[snapshot.length] == OpenSnapshot);
- assert!(
- skolemization_count.as_usize() >= skols.len(),
- "popping more skolemized variables than actually exist, \
- sc now = {:?}, skols.len = {:?}",
- skolemization_count,
- skols.len()
- );
-
- let last_to_pop = skolemization_count.subuniverse();
- let first_to_pop = ty::UniverseIndex::from(last_to_pop.as_u32() - skols.len() as u32);
-
- debug_assert! {
- skols.iter()
- .all(|&k| match *k {
- ty::ReSkolemized(universe, _) =>
- universe >= first_to_pop &&
- universe < last_to_pop,
- _ =>
- false
- }),
- "invalid skolemization keys or keys out of range ({:?}..{:?}): {:?}",
- first_to_pop,
- last_to_pop,
- skols
- }
let constraints_to_kill: Vec<usize> = self.undo_log
.iter()
.enumerate()
.rev()
- .filter(|&(_, undo_entry)| kill_constraint(skols, undo_entry))
+ .filter(|&(_, undo_entry)| kill_constraint(placeholders, undo_entry))
.map(|(index, _)| index)
.collect();
return;
fn kill_constraint<'tcx>(
- skols: &FxHashSet<ty::Region<'tcx>>,
+ placeholders: &FxHashSet<ty::Region<'tcx>>,
undo_entry: &UndoLogEntry<'tcx>,
) -> bool {
match undo_entry {
&AddConstraint(Constraint::VarSubVar(..)) => false,
- &AddConstraint(Constraint::RegSubVar(a, _)) => skols.contains(&a),
- &AddConstraint(Constraint::VarSubReg(_, b)) => skols.contains(&b),
+ &AddConstraint(Constraint::RegSubVar(a, _)) => placeholders.contains(&a),
+ &AddConstraint(Constraint::VarSubReg(_, b)) => placeholders.contains(&b),
&AddConstraint(Constraint::RegSubReg(a, b)) => {
- skols.contains(&a) || skols.contains(&b)
+ placeholders.contains(&a) || placeholders.contains(&b)
}
&AddGiven(..) => false,
&AddVerify(_) => false,
&AddCombination(_, ref two_regions) => {
- skols.contains(&two_regions.a) || skols.contains(&two_regions.b)
+ placeholders.contains(&two_regions.a) || placeholders.contains(&two_regions.b)
}
&AddVar(..) | &OpenSnapshot | &Purged | &CommitedSnapshot => false,
}
// cannot add constraints once regions are resolved
debug!(
"RegionConstraintCollector: make_subregion({:?}, {:?}) due to {:?}",
- sub,
- sup,
- origin
+ sub, sup, origin
);
match (sub, sup) {
fn universe(&self, region: Region<'tcx>) -> ty::UniverseIndex {
match *region {
- ty::ReScope(..) |
- ty::ReStatic |
- ty::ReEmpty |
- ty::ReErased |
- ty::ReFree(..) |
- ty::ReEarlyBound(..) => ty::UniverseIndex::ROOT,
- ty::ReSkolemized(universe, _) => universe,
- ty::ReClosureBound(vid) |
- ty::ReVar(vid) => self.var_universe(vid),
- ty::ReLateBound(..) =>
- bug!("universe(): encountered bound region {:?}", region),
- ty::ReCanonical(..) =>
- bug!("region_universe(): encountered canonical region {:?}", region),
+ ty::ReScope(..)
+ | ty::ReStatic
+ | ty::ReEmpty
+ | ty::ReErased
+ | ty::ReFree(..)
+ | ty::ReEarlyBound(..) => ty::UniverseIndex::ROOT,
+ ty::RePlaceholder(placeholder) => placeholder.universe,
+ ty::ReClosureBound(vid) | ty::ReVar(vid) => self.var_universe(vid),
+ ty::ReLateBound(..) => bug!("universe(): encountered bound region {:?}", region),
+ ty::ReCanonical(..) => bug!(
+ "region_universe(): encountered canonical region {:?}",
+ region
+ ),
}
}
/// relations are considered. For example, one can say that only
/// "incoming" edges to `r0` are desired, in which case one will
/// get the set of regions `{r|r <= r0}`. This is used when
- /// checking whether skolemized regions are being improperly
+ /// checking whether placeholder regions are being improperly
/// related to other regions.
pub fn tainted(
&self,
) -> FxHashSet<ty::Region<'tcx>> {
debug!(
"tainted(mark={:?}, r0={:?}, directions={:?})",
- mark,
- r0,
- directions
+ mark, r0, directions
);
// `result_set` acts as a worklist: we explore all outgoing
use hir::itemlikevisit::ItemLikeVisitor;
use hir::def::Def;
+use hir::CodegenFnAttrFlags;
use hir::def_id::{DefId, LOCAL_CRATE};
use lint;
use middle::privacy;
fn mark_live_symbols(&mut self) {
let mut scanned = FxHashSet();
- while !self.worklist.is_empty() {
- let id = self.worklist.pop().unwrap();
- if scanned.contains(&id) {
+ while let Some(id) = self.worklist.pop() {
+ if !scanned.insert(id) {
continue
}
- scanned.insert(id);
if let Some(ref node) = self.tcx.hir.find(id) {
self.live_symbols.insert(id);
}
fn visit_variant_data(&mut self, def: &'tcx hir::VariantData, _: ast::Name,
- _: &hir::Generics, _: ast::NodeId, _: syntax_pos::Span) {
+ _: &hir::Generics, _: ast::NodeId, _: syntax_pos::Span) {
let has_repr_c = self.repr_has_repr_c;
let inherited_pub_visibility = self.inherited_pub_visibility;
let live_fields = def.fields().iter().filter(|f| {
return true;
}
- // #[used] also keeps the item alive forcefully,
- // e.g. for placing it in a specific section.
- if attr::contains_name(attrs, "used") {
+ // Don't lint about global allocators
+ if attr::contains_name(attrs, "global_allocator") {
return true;
}
- // Don't lint about global allocators
- if attr::contains_name(attrs, "global_allocator") {
+ let def_id = tcx.hir.local_def_id(id);
+ let cg_attrs = tcx.codegen_fn_attrs(def_id);
+
+ // #[used], #[no_mangle], #[export_name], etc also keeps the item alive
+ // forcefully, e.g. for placing it in a specific section.
+ if cg_attrs.contains_extern_indicator() ||
+ cg_attrs.flags.contains(CodegenFnAttrFlags::USED) {
return true;
}
ctor_id: Option<ast::NodeId>)
-> bool {
if self.live_symbols.contains(&id)
- || ctor_id.map_or(false,
- |ctor| self.live_symbols.contains(&ctor)) {
+ || ctor_id.map_or(false, |ctor| self.live_symbols.contains(&ctor))
+ {
return true;
}
// If it's a type whose items are live, then it's live, too.
let src = tcx.used_crate_source(cnum);
if src.rlib.is_some() { continue }
sess.err(&format!("crate `{}` required to be available in rlib format, \
- but was not found in this form",
+ but was not found in this form",
tcx.crate_name(cnum)));
}
return Vec::new();
_ => "dylib",
};
sess.err(&format!("crate `{}` required to be available in {} format, \
- but was not found in this form",
+ but was not found in this form",
tcx.crate_name(cnum), kind));
}
}
}
- return ret;
+ ret
}
fn add_library(tcx: TyCtxt<'_, '_, '_>,
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-
use hir::map as hir_map;
use hir::def_id::{CRATE_DEF_INDEX};
use session::{config, Session};
ctxt.attr_main_fn = Some((item.id, item.span));
} else {
struct_span_err!(ctxt.session, item.span, E0137,
- "multiple functions with a #[main] attribute")
+ "multiple functions with a #[main] attribute")
.span_label(item.span, "additional #[main] function")
.span_label(ctxt.attr_main_fn.unwrap().1, "first #[main] function")
.emit();
if ctxt.start_fn.is_none() {
ctxt.start_fn = Some((item.id, item.span));
} else {
- struct_span_err!(
- ctxt.session, item.span, E0138,
- "multiple 'start' functions")
- .span_label(ctxt.start_fn.unwrap().1,
- "previous `start` function here")
+ struct_span_err!(ctxt.session, item.span, E0138, "multiple 'start' functions")
+ .span_label(ctxt.start_fn.unwrap().1, "previous `start` function here")
.span_label(item.span, "multiple `start` functions")
.emit();
}
impl SymbolExportLevel {
pub fn is_below_threshold(self, threshold: SymbolExportLevel) -> bool {
- if threshold == SymbolExportLevel::Rust {
- // We export everything from Rust dylibs
- true
- } else {
- self == SymbolExportLevel::C
- }
+ threshold == SymbolExportLevel::Rust // export everything from Rust dylibs
+ || self == SymbolExportLevel::C
}
}
region::Scope {
id: body.value.hir_id.local_id,
data: region::ScopeData::Node
- }));
+ }));
let arg_cmt = Rc::new(self.mc.cat_rvalue(
arg.hir_id,
arg.pat.span,
self.walk_expr(&subexpr)
}
- hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
+ hir::ExprKind::Unary(hir::UnDeref, ref base) => { // *base
self.select_from_expr(&base);
}
- hir::ExprKind::Field(ref base, _) => { // base.f
+ hir::ExprKind::Field(ref base, _) => { // base.f
self.select_from_expr(&base);
}
- hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
+ hir::ExprKind::Index(ref lhs, ref rhs) => { // lhs[rhs]
self.select_from_expr(&lhs);
self.consume_expr(&rhs);
}
- hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
+ hir::ExprKind::Call(ref callee, ref args) => { // callee(args)
self.walk_callee(expr, &callee);
self.consume_exprs(args);
}
self.walk_pat(discr_cmt.clone(), &pat, mode);
}
- if let Some(ref guard) = arm.guard {
- match guard {
- hir::Guard::If(ref e) => self.consume_expr(e),
- }
+ if let Some(hir::Guard::If(ref e)) = arm.guard {
+ self.consume_expr(e)
}
self.consume_expr(&arm.body);
cmt_discr: mc::cmt<'tcx>,
pat: &hir::Pat,
mode: &mut TrackMatchMode) {
- debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr,
- pat);
+ debug!("determine_pat_move_mode cmt_discr={:?} pat={:?}", cmt_discr, pat);
+
return_if_err!(self.mc.cat_pattern(cmt_discr, pat, |cmt_pat, pat| {
if let PatKind::Binding(..) = pat.node {
- let bm = *self.mc.tables.pat_binding_modes().get(pat.hir_id)
- .expect("missing binding mode");
+ let bm = *self.mc.tables.pat_binding_modes()
+ .get(pat.hir_id)
+ .expect("missing binding mode");
match bm {
ty::BindByReference(..) =>
mode.lub(BorrowingMatch),
}
Err(LayoutError::Unknown(bad)) => {
if bad == ty {
- "this type's size can vary".to_string()
+ "this type's size can vary".to_owned()
} else {
format!("size can vary because of {}", bad)
}
};
struct_span_err!(self.tcx.sess, span, E0512,
- "transmute called with types of different sizes")
+ "transmute called with types of different sizes")
.note(&format!("source type: {} ({})", from, skeleton_string(from, sk_from)))
.note(&format!("target type: {} ({})", to, skeleton_string(to, sk_to)))
.emit();
$( $variant:ident, $name:expr, $method:ident; )*
) => {
-
enum_from_u32! {
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
pub enum LangItem {
fn collect_item(&mut self, item_index: usize, item_def_id: DefId) {
// Check for duplicates.
- match self.items.items[item_index] {
- Some(original_def_id) if original_def_id != item_def_id => {
+ if let Some(original_def_id) = self.items.items[item_index] {
+ if original_def_id != item_def_id {
let name = LangItem::from_u32(item_index as u32).unwrap().name();
let mut err = match self.tcx.hir.span_if_local(item_def_id) {
Some(span) => struct_span_err!(
name)),
};
if let Some(span) = self.tcx.hir.span_if_local(original_def_id) {
- span_note!(&mut err, span,
- "first defined here.");
+ span_note!(&mut err, span, "first defined here.");
} else {
err.note(&format!("first defined in crate `{}`.",
self.tcx.crate_name(original_def_id.krate)));
}
err.emit();
}
- _ => {
- // OK.
- }
}
// Matched.
}
}
- return None;
+ None
}
pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LanguageItems {
AlignOffsetLangItem, "align_offset", align_offset_fn;
TerminationTraitLangItem, "termination", termination;
+
+ Arc, "arc", arc;
+ Rc, "rc", rc;
}
impl<'a, 'tcx, 'gcx> TyCtxt<'a, 'tcx, 'gcx> {
let msg = format!(
"feature `{}` is declared {}, but was previously declared {}",
feature,
- if since.is_some() { "stable"} else { "unstable" },
- if since.is_none() { "stable"} else { "unstable" },
+ if since.is_some() { "stable" } else { "unstable" },
+ if since.is_none() { "stable" } else { "unstable" },
);
self.tcx.sess.struct_span_err_with_code(span, &msg,
DiagnosticId::Error("E0711".into())).emit();
VarDefNode(s) => {
format!("Var def node [{}]", cm.span_to_string(s))
}
- ExitNode => "Exit node".to_string(),
+ ExitNode => "Exit node".to_owned(),
}
}
struct IrMaps<'a, 'tcx: 'a> {
tcx: TyCtxt<'a, 'tcx, 'tcx>,
-
num_live_nodes: usize,
num_vars: usize,
live_node_map: HirIdMap<LiveNode>,
Local(LocalInfo { name, .. }) | Arg(_, name) => {
name.to_string()
},
- CleanExit => "<clean-exit>".to_string()
+ CleanExit => "<clean-exit>".to_owned()
}
}
// construction site.
let mut call_caps = Vec::new();
ir.tcx.with_freevars(expr.id, |freevars| {
- for fv in freevars {
+ call_caps.extend(freevars.iter().filter_map(|fv| {
if let Def::Local(rv) = fv.def {
let fv_ln = ir.add_live_node(FreeVarNode(fv.span));
let var_hid = ir.tcx.hir.node_to_hir_id(rv);
- call_caps.push(CaptureInfo { ln: fv_ln, var_hid });
+ Some(CaptureInfo { ln: fv_ln, var_hid })
+ } else {
+ None
}
- }
+ }));
});
ir.set_captures(expr.id, call_caps);
self.rwu_table.assign_unpacked(idx, rwu);
}
- // _______________________________________________________________________
-
fn compute(&mut self, body: &hir::Expr) -> LiveNode {
// if there is a `break` or `again` at the top level, then it's
// effectively a return---this only occurs in `for` loops,
let entry_ln = self.propagate_through_expr(body, s.fallthrough_ln);
// hack to skip the loop unless debug! is enabled:
- debug!("^^ liveness computation results for body {} (entry={:?})",
- {
+ debug!("^^ liveness computation results for body {} (entry={:?})", {
for ln_idx in 0..self.ir.num_live_nodes {
- debug!("{:?}", self.ln_str(LiveNode(ln_idx as u32)));
+ debug!("{:?}", self.ln_str(LiveNode(ln_idx as u32)));
}
body.id
},
debug!("propagate_through_expr: {}", self.ir.tcx.hir.node_to_pretty_string(expr.id));
match expr.node {
- // Interesting cases with control flow or which gen/kill
- hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
- self.access_path(expr.hir_id, path, succ, ACC_READ | ACC_USE)
- }
+ // Interesting cases with control flow or which gen/kill
+ hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
+ self.access_path(expr.hir_id, path, succ, ACC_READ | ACC_USE)
+ }
- hir::ExprKind::Field(ref e, _) => {
- self.propagate_through_expr(&e, succ)
- }
+ hir::ExprKind::Field(ref e, _) => {
+ self.propagate_through_expr(&e, succ)
+ }
- hir::ExprKind::Closure(.., blk_id, _, _) => {
- debug!("{} is an ExprKind::Closure", self.ir.tcx.hir.node_to_pretty_string(expr.id));
-
- // The next-node for a break is the successor of the entire
- // loop. The next-node for a continue is the top of this loop.
- let node = self.live_node(expr.hir_id, expr.span);
-
- let break_ln = succ;
- let cont_ln = node;
- self.break_ln.insert(blk_id.node_id, break_ln);
- self.cont_ln.insert(blk_id.node_id, cont_ln);
-
- // the construction of a closure itself is not important,
- // but we have to consider the closed over variables.
- let caps = match self.ir.capture_info_map.get(&expr.id) {
- Some(caps) => caps.clone(),
- None => {
- span_bug!(expr.span, "no registered caps");
- }
- };
- caps.iter().rev().fold(succ, |succ, cap| {
- self.init_from_succ(cap.ln, succ);
- let var = self.variable(cap.var_hid, expr.span);
- self.acc(cap.ln, var, ACC_READ | ACC_USE);
- cap.ln
- })
- }
+ hir::ExprKind::Closure(.., blk_id, _, _) => {
+ debug!("{} is an ExprKind::Closure",
+ self.ir.tcx.hir.node_to_pretty_string(expr.id));
+
+ // The next-node for a break is the successor of the entire
+ // loop. The next-node for a continue is the top of this loop.
+ let node = self.live_node(expr.hir_id, expr.span);
+
+ let break_ln = succ;
+ let cont_ln = node;
+ self.break_ln.insert(blk_id.node_id, break_ln);
+ self.cont_ln.insert(blk_id.node_id, cont_ln);
+
+ // the construction of a closure itself is not important,
+ // but we have to consider the closed over variables.
+ let caps = self.ir.capture_info_map.get(&expr.id).cloned().unwrap_or_else(||
+ span_bug!(expr.span, "no registered caps"));
+
+ caps.iter().rev().fold(succ, |succ, cap| {
+ self.init_from_succ(cap.ln, succ);
+ let var = self.variable(cap.var_hid, expr.span);
+ self.acc(cap.ln, var, ACC_READ | ACC_USE);
+ cap.ln
+ })
+ }
- hir::ExprKind::If(ref cond, ref then, ref els) => {
- //
- // (cond)
- // |
- // v
- // (expr)
- // / \
- // | |
- // v v
- // (then)(els)
- // | |
- // v v
- // ( succ )
- //
- let else_ln = self.propagate_through_opt_expr(els.as_ref().map(|e| &**e), succ);
- let then_ln = self.propagate_through_expr(&then, succ);
- let ln = self.live_node(expr.hir_id, expr.span);
- self.init_from_succ(ln, else_ln);
- self.merge_from_succ(ln, then_ln, false);
- self.propagate_through_expr(&cond, ln)
- }
+ hir::ExprKind::If(ref cond, ref then, ref els) => {
+ //
+ // (cond)
+ // |
+ // v
+ // (expr)
+ // / \
+ // | |
+ // v v
+ // (then)(els)
+ // | |
+ // v v
+ // ( succ )
+ //
+ let else_ln = self.propagate_through_opt_expr(els.as_ref().map(|e| &**e), succ);
+ let then_ln = self.propagate_through_expr(&then, succ);
+ let ln = self.live_node(expr.hir_id, expr.span);
+ self.init_from_succ(ln, else_ln);
+ self.merge_from_succ(ln, then_ln, false);
+ self.propagate_through_expr(&cond, ln)
+ }
- hir::ExprKind::While(ref cond, ref blk, _) => {
- self.propagate_through_loop(expr, WhileLoop(&cond), &blk, succ)
- }
+ hir::ExprKind::While(ref cond, ref blk, _) => {
+ self.propagate_through_loop(expr, WhileLoop(&cond), &blk, succ)
+ }
- // Note that labels have been resolved, so we don't need to look
- // at the label ident
- hir::ExprKind::Loop(ref blk, _, _) => {
- self.propagate_through_loop(expr, LoopLoop, &blk, succ)
- }
+ // Note that labels have been resolved, so we don't need to look
+ // at the label ident
+ hir::ExprKind::Loop(ref blk, _, _) => {
+ self.propagate_through_loop(expr, LoopLoop, &blk, succ)
+ }
- hir::ExprKind::Match(ref e, ref arms, _) => {
- //
- // (e)
- // |
- // v
- // (expr)
- // / | \
- // | | |
- // v v v
- // (..arms..)
- // | | |
- // v v v
- // ( succ )
- //
- //
- let ln = self.live_node(expr.hir_id, expr.span);
- self.init_empty(ln, succ);
- let mut first_merge = true;
- for arm in arms {
- let body_succ =
- self.propagate_through_expr(&arm.body, succ);
- let guard_succ =
- self.propagate_through_opt_expr(
- arm.guard.as_ref().map(|g|
- match g {
- hir::Guard::If(e) => &**e,
- }),
- body_succ);
- // only consider the first pattern; any later patterns must have
- // the same bindings, and we also consider the first pattern to be
- // the "authoritative" set of ids
- let arm_succ =
- self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &**p),
- guard_succ);
- self.merge_from_succ(ln, arm_succ, first_merge);
- first_merge = false;
- };
- self.propagate_through_expr(&e, ln)
- }
+ hir::ExprKind::Match(ref e, ref arms, _) => {
+ //
+ // (e)
+ // |
+ // v
+ // (expr)
+ // / | \
+ // | | |
+ // v v v
+ // (..arms..)
+ // | | |
+ // v v v
+ // ( succ )
+ //
+ //
+ let ln = self.live_node(expr.hir_id, expr.span);
+ self.init_empty(ln, succ);
+ let mut first_merge = true;
+ for arm in arms {
+ let body_succ = self.propagate_through_expr(&arm.body, succ);
+
+ let guard_succ = self.propagate_through_opt_expr(
+ arm.guard.as_ref().map(|hir::Guard::If(e)| &**e),
+ body_succ
+ );
+ // only consider the first pattern; any later patterns must have
+ // the same bindings, and we also consider the first pattern to be
+ // the "authoritative" set of ids
+ let arm_succ =
+ self.define_bindings_in_arm_pats(arm.pats.first().map(|p| &**p),
+ guard_succ);
+ self.merge_from_succ(ln, arm_succ, first_merge);
+ first_merge = false;
+ };
+ self.propagate_through_expr(&e, ln)
+ }
- hir::ExprKind::Ret(ref o_e) => {
- // ignore succ and subst exit_ln:
- let exit_ln = self.s.exit_ln;
- self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), exit_ln)
- }
+ hir::ExprKind::Ret(ref o_e) => {
+ // ignore succ and subst exit_ln:
+ let exit_ln = self.s.exit_ln;
+ self.propagate_through_opt_expr(o_e.as_ref().map(|e| &**e), exit_ln)
+ }
- hir::ExprKind::Break(label, ref opt_expr) => {
- // Find which label this break jumps to
- let target = match label.target_id {
+ hir::ExprKind::Break(label, ref opt_expr) => {
+ // Find which label this break jumps to
+ let target = match label.target_id {
Ok(node_id) => self.break_ln.get(&node_id),
Err(err) => span_bug!(expr.span, "loop scope error: {}", err),
- }.map(|x| *x);
-
- // Now that we know the label we're going to,
- // look it up in the break loop nodes table
+ }.cloned();
- match target {
- Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b),
- None => span_bug!(expr.span, "break to unknown label")
- }
- }
+ // Now that we know the label we're going to,
+ // look it up in the break loop nodes table
- hir::ExprKind::Continue(label) => {
- // Find which label this expr continues to
- let sc = match label.target_id {
- Ok(node_id) => node_id,
- Err(err) => span_bug!(expr.span, "loop scope error: {}", err),
- };
+ match target {
+ Some(b) => self.propagate_through_opt_expr(opt_expr.as_ref().map(|e| &**e), b),
+ None => span_bug!(expr.span, "break to unknown label")
+ }
+ }
- // Now that we know the label we're going to,
- // look it up in the continue loop nodes table
+ hir::ExprKind::Continue(label) => {
+ // Find which label this expr continues to
+ let sc = label.target_id.unwrap_or_else(|err|
+ span_bug!(expr.span, "loop scope error: {}", err));
- match self.cont_ln.get(&sc) {
- Some(&b) => b,
- None => span_bug!(expr.span, "continue to unknown label")
- }
- }
-
- hir::ExprKind::Assign(ref l, ref r) => {
- // see comment on places in
- // propagate_through_place_components()
- let succ = self.write_place(&l, succ, ACC_WRITE);
- let succ = self.propagate_through_place_components(&l, succ);
- self.propagate_through_expr(&r, succ)
- }
+ // Now that we know the label we're going to,
+ // look it up in the continue loop nodes table
+ self.cont_ln.get(&sc).cloned().unwrap_or_else(||
+ span_bug!(expr.span, "continue to unknown label"))
+ }
- hir::ExprKind::AssignOp(_, ref l, ref r) => {
- // an overloaded assign op is like a method call
- if self.tables.is_method_call(expr) {
- let succ = self.propagate_through_expr(&l, succ);
- self.propagate_through_expr(&r, succ)
- } else {
+ hir::ExprKind::Assign(ref l, ref r) => {
// see comment on places in
// propagate_through_place_components()
- let succ = self.write_place(&l, succ, ACC_WRITE|ACC_READ);
- let succ = self.propagate_through_expr(&r, succ);
- self.propagate_through_place_components(&l, succ)
+ let succ = self.write_place(&l, succ, ACC_WRITE);
+ let succ = self.propagate_through_place_components(&l, succ);
+ self.propagate_through_expr(&r, succ)
}
- }
- // Uninteresting cases: just propagate in rev exec order
+ hir::ExprKind::AssignOp(_, ref l, ref r) => {
+ // an overloaded assign op is like a method call
+ if self.tables.is_method_call(expr) {
+ let succ = self.propagate_through_expr(&l, succ);
+ self.propagate_through_expr(&r, succ)
+ } else {
+ // see comment on places in
+ // propagate_through_place_components()
+ let succ = self.write_place(&l, succ, ACC_WRITE|ACC_READ);
+ let succ = self.propagate_through_expr(&r, succ);
+ self.propagate_through_place_components(&l, succ)
+ }
+ }
- hir::ExprKind::Array(ref exprs) => {
- self.propagate_through_exprs(exprs, succ)
- }
+ // Uninteresting cases: just propagate in rev exec order
- hir::ExprKind::Struct(_, ref fields, ref with_expr) => {
- let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ);
- fields.iter().rev().fold(succ, |succ, field| {
- self.propagate_through_expr(&field.expr, succ)
- })
- }
+ hir::ExprKind::Array(ref exprs) => {
+ self.propagate_through_exprs(exprs, succ)
+ }
- hir::ExprKind::Call(ref f, ref args) => {
- // FIXME(canndrew): This is_never should really be an is_uninhabited
- let succ = if self.tables.expr_ty(expr).is_never() {
- self.s.exit_ln
- } else {
- succ
- };
- let succ = self.propagate_through_exprs(args, succ);
- self.propagate_through_expr(&f, succ)
- }
+ hir::ExprKind::Struct(_, ref fields, ref with_expr) => {
+ let succ = self.propagate_through_opt_expr(with_expr.as_ref().map(|e| &**e), succ);
+ fields.iter().rev().fold(succ, |succ, field| {
+ self.propagate_through_expr(&field.expr, succ)
+ })
+ }
- hir::ExprKind::MethodCall(.., ref args) => {
- // FIXME(canndrew): This is_never should really be an is_uninhabited
- let succ = if self.tables.expr_ty(expr).is_never() {
- self.s.exit_ln
- } else {
- succ
- };
- self.propagate_through_exprs(args, succ)
- }
+ hir::ExprKind::Call(ref f, ref args) => {
+ // FIXME(canndrew): This is_never should really be an is_uninhabited
+ let succ = if self.tables.expr_ty(expr).is_never() {
+ self.s.exit_ln
+ } else {
+ succ
+ };
+ let succ = self.propagate_through_exprs(args, succ);
+ self.propagate_through_expr(&f, succ)
+ }
- hir::ExprKind::Tup(ref exprs) => {
- self.propagate_through_exprs(exprs, succ)
- }
+ hir::ExprKind::MethodCall(.., ref args) => {
+ // FIXME(canndrew): This is_never should really be an is_uninhabited
+ let succ = if self.tables.expr_ty(expr).is_never() {
+ self.s.exit_ln
+ } else {
+ succ
+ };
- hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => {
- let r_succ = self.propagate_through_expr(&r, succ);
+ self.propagate_through_exprs(args, succ)
+ }
- let ln = self.live_node(expr.hir_id, expr.span);
- self.init_from_succ(ln, succ);
- self.merge_from_succ(ln, r_succ, false);
+ hir::ExprKind::Tup(ref exprs) => {
+ self.propagate_through_exprs(exprs, succ)
+ }
- self.propagate_through_expr(&l, ln)
- }
+ hir::ExprKind::Binary(op, ref l, ref r) if op.node.is_lazy() => {
+ let r_succ = self.propagate_through_expr(&r, succ);
- hir::ExprKind::Index(ref l, ref r) |
- hir::ExprKind::Binary(_, ref l, ref r) => {
- let r_succ = self.propagate_through_expr(&r, succ);
- self.propagate_through_expr(&l, r_succ)
- }
+ let ln = self.live_node(expr.hir_id, expr.span);
+ self.init_from_succ(ln, succ);
+ self.merge_from_succ(ln, r_succ, false);
- hir::ExprKind::Box(ref e) |
- hir::ExprKind::AddrOf(_, ref e) |
- hir::ExprKind::Cast(ref e, _) |
- hir::ExprKind::Type(ref e, _) |
- hir::ExprKind::Unary(_, ref e) |
- hir::ExprKind::Yield(ref e) |
- hir::ExprKind::Repeat(ref e, _) => {
- self.propagate_through_expr(&e, succ)
- }
+ self.propagate_through_expr(&l, ln)
+ }
+
+ hir::ExprKind::Index(ref l, ref r) |
+ hir::ExprKind::Binary(_, ref l, ref r) => {
+ let r_succ = self.propagate_through_expr(&r, succ);
+ self.propagate_through_expr(&l, r_succ)
+ }
+
+ hir::ExprKind::Box(ref e) |
+ hir::ExprKind::AddrOf(_, ref e) |
+ hir::ExprKind::Cast(ref e, _) |
+ hir::ExprKind::Type(ref e, _) |
+ hir::ExprKind::Unary(_, ref e) |
+ hir::ExprKind::Yield(ref e) |
+ hir::ExprKind::Repeat(ref e, _) => {
+ self.propagate_through_expr(&e, succ)
+ }
- hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
- let succ = ia.outputs.iter().zip(outputs).rev().fold(succ, |succ, (o, output)| {
+ hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
+ let succ = ia.outputs.iter().zip(outputs).rev().fold(succ, |succ, (o, output)| {
// see comment on places
// in propagate_through_place_components()
if o.is_indirect {
let acc = if o.is_rw { ACC_WRITE|ACC_READ } else { ACC_WRITE };
let succ = self.write_place(output, succ, acc);
self.propagate_through_place_components(output, succ)
- }
- });
+ }});
- // Inputs are executed first. Propagate last because of rev order
- self.propagate_through_exprs(inputs, succ)
- }
+ // Inputs are executed first. Propagate last because of rev order
+ self.propagate_through_exprs(inputs, succ)
+ }
- hir::ExprKind::Lit(..) | hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => {
- succ
- }
+ hir::ExprKind::Lit(..) | hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => {
+ succ
+ }
- // Note that labels have been resolved, so we don't need to look
- // at the label ident
- hir::ExprKind::Block(ref blk, _) => {
- self.propagate_through_block(&blk, succ)
- }
+ // Note that labels have been resolved, so we don't need to look
+ // at the label ident
+ hir::ExprKind::Block(ref blk, _) => {
+ self.propagate_through_block(&blk, succ)
+ }
}
}
fn propagate_through_place_components(&mut self,
- expr: &Expr,
- succ: LiveNode)
- -> LiveNode {
+ expr: &Expr,
+ succ: LiveNode)
+ -> LiveNode {
// # Places
//
// In general, the full flow graph structure for an
}
// see comment on propagate_through_place()
- fn write_place(&mut self, expr: &Expr, succ: LiveNode, acc: u32)
- -> LiveNode {
+ fn write_place(&mut self, expr: &Expr, succ: LiveNode, acc: u32) -> LiveNode {
match expr.node {
- hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
- self.access_path(expr.hir_id, path, succ, acc)
- }
+ hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => {
+ self.access_path(expr.hir_id, path, succ, acc)
+ }
- // We do not track other places, so just propagate through
- // to their subcomponents. Also, it may happen that
- // non-places occur here, because those are detected in the
- // later pass borrowck.
- _ => succ
+ // We do not track other places, so just propagate through
+ // to their subcomponents. Also, it may happen that
+ // non-places occur here, because those are detected in the
+ // later pass borrowck.
+ _ => succ
}
}
fn access_path(&mut self, hir_id: HirId, path: &hir::Path, succ: LiveNode, acc: u32)
-> LiveNode {
match path.def {
- Def::Local(nid) => {
- self.access_var(hir_id, nid, succ, acc, path.span)
- }
- _ => succ
+ Def::Local(nid) => {
+ self.access_var(hir_id, nid, succ, acc, path.span)
+ }
+ _ => succ
}
}
body: &hir::Block,
succ: LiveNode)
-> LiveNode {
-
/*
We model control flow like this:
self.propagate_through_expr(&cond, ln)
}
};
- assert!(cond_ln == new_cond_ln);
- assert!(body_ln == self.propagate_through_block(body, cond_ln));
+ assert_eq!(cond_ln, new_cond_ln);
+ assert_eq!(body_ln, self.propagate_through_block(body, cond_ln));
}
cond_ln
fn check_expr<'a, 'tcx>(this: &mut Liveness<'a, 'tcx>, expr: &'tcx Expr) {
match expr.node {
- hir::ExprKind::Assign(ref l, _) => {
- this.check_place(&l);
-
- intravisit::walk_expr(this, expr);
- }
-
- hir::ExprKind::AssignOp(_, ref l, _) => {
- if !this.tables.is_method_call(expr) {
+ hir::ExprKind::Assign(ref l, _) => {
this.check_place(&l);
+
+ intravisit::walk_expr(this, expr);
}
- intravisit::walk_expr(this, expr);
- }
+ hir::ExprKind::AssignOp(_, ref l, _) => {
+ if !this.tables.is_method_call(expr) {
+ this.check_place(&l);
+ }
- hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
- for input in inputs {
- this.visit_expr(input);
+ intravisit::walk_expr(this, expr);
}
- // Output operands must be places
- for (o, output) in ia.outputs.iter().zip(outputs) {
- if !o.is_indirect {
- this.check_place(output);
- }
- this.visit_expr(output);
- }
+ hir::ExprKind::InlineAsm(ref ia, ref outputs, ref inputs) => {
+ for input in inputs {
+ this.visit_expr(input);
+ }
- intravisit::walk_expr(this, expr);
- }
+ // Output operands must be places
+ for (o, output) in ia.outputs.iter().zip(outputs) {
+ if !o.is_indirect {
+ this.check_place(output);
+ }
+ this.visit_expr(output);
+ }
- // no correctness conditions related to liveness
- hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) | hir::ExprKind::If(..) |
- hir::ExprKind::Match(..) | hir::ExprKind::While(..) | hir::ExprKind::Loop(..) |
- hir::ExprKind::Index(..) | hir::ExprKind::Field(..) |
- hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) | hir::ExprKind::Binary(..) |
- hir::ExprKind::Cast(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Ret(..) |
- hir::ExprKind::Break(..) | hir::ExprKind::Continue(..) | hir::ExprKind::Lit(_) |
- hir::ExprKind::Block(..) | hir::ExprKind::AddrOf(..) |
- hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
- hir::ExprKind::Closure(..) | hir::ExprKind::Path(_) | hir::ExprKind::Yield(..) |
- hir::ExprKind::Box(..) | hir::ExprKind::Type(..) => {
- intravisit::walk_expr(this, expr);
- }
+ intravisit::walk_expr(this, expr);
+ }
+
+ // no correctness conditions related to liveness
+ hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) | hir::ExprKind::If(..) |
+ hir::ExprKind::Match(..) | hir::ExprKind::While(..) | hir::ExprKind::Loop(..) |
+ hir::ExprKind::Index(..) | hir::ExprKind::Field(..) |
+ hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) | hir::ExprKind::Binary(..) |
+ hir::ExprKind::Cast(..) | hir::ExprKind::Unary(..) | hir::ExprKind::Ret(..) |
+ hir::ExprKind::Break(..) | hir::ExprKind::Continue(..) | hir::ExprKind::Lit(_) |
+ hir::ExprKind::Block(..) | hir::ExprKind::AddrOf(..) |
+ hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
+ hir::ExprKind::Closure(..) | hir::ExprKind::Path(_) | hir::ExprKind::Yield(..) |
+ hir::ExprKind::Box(..) | hir::ExprKind::Type(..) => {
+ intravisit::walk_expr(this, expr);
+ }
}
}
fn should_warn(&self, var: Variable) -> Option<String> {
let name = self.ir.variable_name(var);
- if name.is_empty() || name.as_bytes()[0] == ('_' as u8) {
+ if name.is_empty() || name.as_bytes()[0] == b'_' {
None
} else {
Some(name)
if !self.used_on_entry(ln, var) {
let r = self.should_warn(var);
if let Some(name) = r {
-
// annoying: for parameters in funcs like `fn(x: i32)
// {ret}`, there is only one node, so asking about
// assigned_on_exit() is not meaningful.
self.assigned_on_exit(ln, var).is_some()
};
- let suggest_underscore_msg = format!("consider using `_{}` instead",
- name);
+ let suggest_underscore_msg = format!("consider using `_{}` instead", name);
if is_assigned {
self.ir.tcx
use syntax::ast::{self, Name};
use syntax_pos::Span;
+use std::borrow::Cow;
use std::fmt;
use std::hash::{Hash, Hasher};
use rustc_data_structures::sync::Lrc;
#[derive(Clone, Debug, PartialEq)]
pub enum Categorization<'tcx> {
- Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
+ Rvalue(ty::Region<'tcx>), // temporary val, argument is its scope
StaticItem,
- Upvar(Upvar), // upvar referenced by closure env
- Local(ast::NodeId), // local variable
+ Upvar(Upvar), // upvar referenced by closure env
+ Local(ast::NodeId), // local variable
Deref(cmt<'tcx>, PointerKind<'tcx>), // deref of a ptr
- Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
- Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
+ Interior(cmt<'tcx>, InteriorKind), // something interior: field, tuple, etc
+ Downcast(cmt<'tcx>, DefId), // selects a particular enum variant (*1)
// (*1) downcast is only required if the enum has more than one variant
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum InteriorOffsetKind {
- Index, // e.g. `array_expr[index_expr]`
- Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
+ Index, // e.g. `array_expr[index_expr]`
+ Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }`
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
fn helper<'a, 'gcx, 'tcx>(mc: &MemCategorizationContext<'a, 'gcx, 'tcx>,
expr: &hir::Expr,
adjustments: &[adjustment::Adjustment<'tcx>])
- -> McResult<cmt_<'tcx>> {
+ -> McResult<cmt_<'tcx>> {
match adjustments.split_last() {
None => mc.cat_expr_unadjusted(expr),
Some((adjustment, previous)) => {
let expr_ty = self.expr_ty(expr)?;
match expr.node {
- hir::ExprKind::Unary(hir::UnDeref, ref e_base) => {
- if self.tables.is_method_call(expr) {
- self.cat_overloaded_place(expr, e_base, NoteNone)
- } else {
- let base_cmt = Rc::new(self.cat_expr(&e_base)?);
- self.cat_deref(expr, base_cmt, NoteNone)
+ hir::ExprKind::Unary(hir::UnDeref, ref e_base) => {
+ if self.tables.is_method_call(expr) {
+ self.cat_overloaded_place(expr, e_base, NoteNone)
+ } else {
+ let base_cmt = Rc::new(self.cat_expr(&e_base)?);
+ self.cat_deref(expr, base_cmt, NoteNone)
+ }
}
- }
-
- hir::ExprKind::Field(ref base, f_ident) => {
- let base_cmt = Rc::new(self.cat_expr(&base)?);
- debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
- expr.id,
- expr,
- base_cmt);
- let f_index = self.tcx.field_index(expr.id, self.tables);
- Ok(self.cat_field(expr, base_cmt, f_index, f_ident, expr_ty))
- }
-
- hir::ExprKind::Index(ref base, _) => {
- if self.tables.is_method_call(expr) {
- // If this is an index implemented by a method call, then it
- // will include an implicit deref of the result.
- // The call to index() returns a `&T` value, which
- // is an rvalue. That is what we will be
- // dereferencing.
- self.cat_overloaded_place(expr, base, NoteIndex)
- } else {
+
+ hir::ExprKind::Field(ref base, f_ident) => {
let base_cmt = Rc::new(self.cat_expr(&base)?);
- self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
+ debug!("cat_expr(cat_field): id={} expr={:?} base={:?}",
+ expr.id,
+ expr,
+ base_cmt);
+ let f_index = self.tcx.field_index(expr.id, self.tables);
+ Ok(self.cat_field(expr, base_cmt, f_index, f_ident, expr_ty))
+ }
+
+ hir::ExprKind::Index(ref base, _) => {
+ if self.tables.is_method_call(expr) {
+ // If this is an index implemented by a method call, then it
+ // will include an implicit deref of the result.
+ // The call to index() returns a `&T` value, which
+ // is an rvalue. That is what we will be
+ // dereferencing.
+ self.cat_overloaded_place(expr, base, NoteIndex)
+ } else {
+ let base_cmt = Rc::new(self.cat_expr(&base)?);
+ self.cat_index(expr, base_cmt, expr_ty, InteriorOffsetKind::Index)
+ }
+ }
+
+ hir::ExprKind::Path(ref qpath) => {
+ let def = self.tables.qpath_def(qpath, expr.hir_id);
+ self.cat_def(expr.hir_id, expr.span, expr_ty, def)
+ }
+
+ hir::ExprKind::Type(ref e, _) => {
+ self.cat_expr(&e)
+ }
+
+ hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) |
+ hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) |
+ hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) |
+ hir::ExprKind::Unary(..) | hir::ExprKind::Yield(..) |
+ hir::ExprKind::MethodCall(..) | hir::ExprKind::Cast(..) |
+ hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) | hir::ExprKind::If(..) |
+ hir::ExprKind::Binary(..) | hir::ExprKind::While(..) |
+ hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) |
+ hir::ExprKind::Lit(..) | hir::ExprKind::Break(..) |
+ hir::ExprKind::Continue(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
+ hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) => {
+ Ok(self.cat_rvalue_node(expr.hir_id, expr.span, expr_ty))
}
- }
-
- hir::ExprKind::Path(ref qpath) => {
- let def = self.tables.qpath_def(qpath, expr.hir_id);
- self.cat_def(expr.hir_id, expr.span, expr_ty, def)
- }
-
- hir::ExprKind::Type(ref e, _) => {
- self.cat_expr(&e)
- }
-
- hir::ExprKind::AddrOf(..) | hir::ExprKind::Call(..) |
- hir::ExprKind::Assign(..) | hir::ExprKind::AssignOp(..) |
- hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) |
- hir::ExprKind::Unary(..) | hir::ExprKind::Yield(..) |
- hir::ExprKind::MethodCall(..) | hir::ExprKind::Cast(..) |
- hir::ExprKind::Array(..) | hir::ExprKind::Tup(..) | hir::ExprKind::If(..) |
- hir::ExprKind::Binary(..) | hir::ExprKind::While(..) |
- hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) |
- hir::ExprKind::Lit(..) | hir::ExprKind::Break(..) |
- hir::ExprKind::Continue(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Repeat(..) |
- hir::ExprKind::InlineAsm(..) | hir::ExprKind::Box(..) => {
- Ok(self.cat_rvalue_node(expr.hir_id, expr.span, expr_ty))
- }
}
}
hir_id, expr_ty, def);
match def {
- Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
- Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) | Def::SelfCtor(..) => {
+ Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) |
+ Def::AssociatedConst(..) | Def::Fn(..) | Def::Method(..) | Def::SelfCtor(..) => {
Ok(self.cat_rvalue_node(hir_id, span, expr_ty))
- }
+ }
- Def::Static(def_id, mutbl) => {
- // `#[thread_local]` statics may not outlive the current function.
- for attr in &self.tcx.get_attrs(def_id)[..] {
- if attr.check_name("thread_local") {
- return Ok(self.cat_rvalue_node(hir_id, span, expr_ty));
+ Def::Static(def_id, mutbl) => {
+ // `#[thread_local]` statics may not outlive the current function.
+ for attr in &self.tcx.get_attrs(def_id)[..] {
+ if attr.check_name("thread_local") {
+ return Ok(self.cat_rvalue_node(hir_id, span, expr_ty));
+ }
}
+
+ Ok(cmt_ {
+ hir_id,
+ span:span,
+ cat:Categorization::StaticItem,
+ mutbl: if mutbl { McDeclared } else { McImmutable},
+ ty:expr_ty,
+ note: NoteNone
+ })
+ }
+
+ Def::Upvar(var_id, _, fn_node_id) => {
+ self.cat_upvar(hir_id, span, var_id, fn_node_id)
}
- Ok(cmt_ {
- hir_id,
- span:span,
- cat:Categorization::StaticItem,
- mutbl: if mutbl { McDeclared } else { McImmutable},
- ty:expr_ty,
- note: NoteNone
- })
- }
-
- Def::Upvar(var_id, _, fn_node_id) => {
- self.cat_upvar(hir_id, span, var_id, fn_node_id)
- }
-
- Def::Local(vid) => {
- Ok(cmt_ {
- hir_id,
- span,
- cat: Categorization::Local(vid),
- mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
- ty: expr_ty,
- note: NoteNone
- })
- }
- def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
+ Def::Local(vid) => {
+ Ok(cmt_ {
+ hir_id,
+ span,
+ cat: Categorization::Local(vid),
+ mutbl: MutabilityCategory::from_local(self.tcx, self.tables, vid),
+ ty: expr_ty,
+ note: NoteNone
+ })
+ }
+
+ def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def)
}
}
span: Span,
expr_ty: Ty<'tcx>)
-> cmt_<'tcx> {
- debug!(
- "cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})",
- hir_id,
- span,
- expr_ty,
- );
+ debug!("cat_rvalue_node(id={:?}, span={:?}, expr_ty={:?})",
+ hir_id, span, expr_ty);
+
let promotable = self.rvalue_promotable_map.as_ref().map(|m| m.contains(&hir_id.local_id))
.unwrap_or(false);
- debug!(
- "cat_rvalue_node: promotable = {:?}",
- promotable,
- );
+ debug!("cat_rvalue_node: promotable = {:?}", promotable);
// Always promote `[T; 0]` (even when e.g. borrowed mutably).
let promotable = match expr_ty.sty {
_ => promotable,
};
- debug!(
- "cat_rvalue_node: promotable = {:?} (2)",
- promotable,
- );
+ debug!("cat_rvalue_node: promotable = {:?} (2)", promotable);
// Compute maximum lifetime of this rvalue. This is 'static if
// we can promote to a constant, otherwise equal to enclosing temp
base: &hir::Expr,
note: Note,
) -> McResult<cmt_<'tcx>> {
- debug!(
- "cat_overloaded_place(expr={:?}, base={:?}, note={:?})",
- expr,
- base,
- note,
- );
+ debug!("cat_overloaded_place(expr={:?}, base={:?}, note={:?})",
+ expr,
+ base,
+ note);
// Reconstruct the output assuming it's a reference with the
// same region and mutability as the receiver. This holds for
let (region, mutbl) = match base_ty.sty {
ty::Ref(region, _, mutbl) => (region, mutbl),
- _ => {
- span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
- }
+ _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference")
};
let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut {
ty: place_ty,
let deref_ty = match base_cmt_ty.builtin_deref(true) {
Some(mt) => mt.ty,
None => {
- debug!("Explicit deref of non-derefable type: {:?}",
- base_cmt_ty);
+ debug!("Explicit deref of non-derefable type: {:?}", base_cmt_ty);
return Err(());
}
};
}
pub fn cat_imm_interior<N:HirNode>(&self,
- node: &N,
- base_cmt: cmt<'tcx>,
- interior_ty: Ty<'tcx>,
- interior: InteriorKind)
- -> cmt_<'tcx> {
+ node: &N,
+ base_cmt: cmt<'tcx>,
+ interior_ty: Ty<'tcx>,
+ interior: InteriorKind)
+ -> cmt_<'tcx> {
let ret = cmt_ {
hir_id: node.hir_id(),
span: node.span(),
}
pub fn cat_downcast_if_needed<N:HirNode>(&self,
- node: &N,
- base_cmt: cmt<'tcx>,
- variant_did: DefId)
- -> cmt<'tcx> {
+ node: &N,
+ base_cmt: cmt<'tcx>,
+ variant_did: DefId)
+ -> cmt<'tcx> {
// univariant enums do not need downcasts
let base_did = self.tcx.parent_def_id(variant_did).unwrap();
if self.tcx.adt_def(base_did).variants.len() != 1 {
op(cmt.clone(), pat);
match pat.node {
- PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
- let def = self.tables.qpath_def(qpath, pat.hir_id);
- let (cmt, expected_len) = match def {
- Def::Err => {
- debug!("access to unresolvable pattern {:?}", pat);
- return Err(())
- }
- Def::VariantCtor(def_id, CtorKind::Fn) => {
- let enum_def = self.tcx.parent_def_id(def_id).unwrap();
- (self.cat_downcast_if_needed(pat, cmt, def_id),
- self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
- }
- Def::StructCtor(_, CtorKind::Fn) | Def::SelfCtor(..) => {
- match self.pat_ty_unadjusted(&pat)?.sty {
- ty::Adt(adt_def, _) => {
- (cmt, adt_def.non_enum_variant().fields.len())
- }
- ref ty => {
- span_bug!(pat.span, "tuple struct pattern unexpected type {:?}", ty);
+ PatKind::TupleStruct(ref qpath, ref subpats, ddpos) => {
+ let def = self.tables.qpath_def(qpath, pat.hir_id);
+ let (cmt, expected_len) = match def {
+ Def::Err => {
+ debug!("access to unresolvable pattern {:?}", pat);
+ return Err(())
+ }
+ Def::VariantCtor(def_id, CtorKind::Fn) => {
+ let enum_def = self.tcx.parent_def_id(def_id).unwrap();
+ (self.cat_downcast_if_needed(pat, cmt, def_id),
+ self.tcx.adt_def(enum_def).variant_with_id(def_id).fields.len())
+ }
+ Def::StructCtor(_, CtorKind::Fn) | Def::SelfCtor(..) => {
+ match self.pat_ty_unadjusted(&pat)?.sty {
+ ty::Adt(adt_def, _) => {
+ (cmt, adt_def.non_enum_variant().fields.len())
+ }
+ ref ty => {
+ span_bug!(pat.span,
+ "tuple struct pattern unexpected type {:?}", ty);
+ }
}
}
+ def => {
+ span_bug!(pat.span, "tuple struct pattern didn't resolve \
+ to variant or struct {:?}", def);
+ }
+ };
+
+ for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
+ let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
+ let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
+ let subcmt = Rc::new(
+ self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
+ self.cat_pattern_(subcmt, &subpat, op)?;
}
- def => {
- span_bug!(pat.span, "tuple struct pattern didn't resolve \
- to variant or struct {:?}", def);
+ }
+
+ PatKind::Struct(ref qpath, ref field_pats, _) => {
+ // {f1: p1, ..., fN: pN}
+ let def = self.tables.qpath_def(qpath, pat.hir_id);
+ let cmt = match def {
+ Def::Err => {
+ debug!("access to unresolvable pattern {:?}", pat);
+ return Err(())
+ },
+ Def::Variant(variant_did) |
+ Def::VariantCtor(variant_did, ..) => {
+ self.cat_downcast_if_needed(pat, cmt, variant_did)
+ },
+ _ => cmt
+ };
+
+ for fp in field_pats {
+ let field_ty = self.pat_ty_adjusted(&fp.node.pat)?; // see (*2)
+ let f_index = self.tcx.field_index(fp.node.id, self.tables);
+ let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
+ fp.node.ident, field_ty));
+ self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
}
- };
+ }
- for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
- let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
- let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
- let subcmt = Rc::new(self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
- self.cat_pattern_(subcmt, &subpat, op)?;
+ PatKind::Binding(.., Some(ref subpat)) => {
+ self.cat_pattern_(cmt, &subpat, op)?;
}
- }
-
- PatKind::Struct(ref qpath, ref field_pats, _) => {
- // {f1: p1, ..., fN: pN}
- let def = self.tables.qpath_def(qpath, pat.hir_id);
- let cmt = match def {
- Def::Err => {
- debug!("access to unresolvable pattern {:?}", pat);
- return Err(())
- },
- Def::Variant(variant_did) |
- Def::VariantCtor(variant_did, ..) => {
- self.cat_downcast_if_needed(pat, cmt, variant_did)
- },
- _ => cmt
- };
-
- for fp in field_pats {
- let field_ty = self.pat_ty_adjusted(&fp.node.pat)?; // see (*2)
- let f_index = self.tcx.field_index(fp.node.id, self.tables);
- let cmt_field = Rc::new(self.cat_field(pat, cmt.clone(), f_index,
- fp.node.ident, field_ty));
- self.cat_pattern_(cmt_field, &fp.node.pat, op)?;
+
+ PatKind::Tuple(ref subpats, ddpos) => {
+ // (p1, ..., pN)
+ let expected_len = match self.pat_ty_unadjusted(&pat)?.sty {
+ ty::Tuple(ref tys) => tys.len(),
+ ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
+ };
+ for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
+ let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
+ let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
+ let subcmt = Rc::new(
+ self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
+ self.cat_pattern_(subcmt, &subpat, op)?;
+ }
}
- }
-
- PatKind::Binding(.., Some(ref subpat)) => {
- self.cat_pattern_(cmt, &subpat, op)?;
- }
-
- PatKind::Tuple(ref subpats, ddpos) => {
- // (p1, ..., pN)
- let expected_len = match self.pat_ty_unadjusted(&pat)?.sty {
- ty::Tuple(ref tys) => tys.len(),
- ref ty => span_bug!(pat.span, "tuple pattern unexpected type {:?}", ty),
- };
- for (i, subpat) in subpats.iter().enumerate_and_adjust(expected_len, ddpos) {
- let subpat_ty = self.pat_ty_adjusted(&subpat)?; // see (*2)
- let interior = InteriorField(FieldIndex(i, Name::intern(&i.to_string())));
- let subcmt = Rc::new(self.cat_imm_interior(pat, cmt.clone(), subpat_ty, interior));
+
+ PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
+ // box p1, &p1, &mut p1. we can ignore the mutability of
+ // PatKind::Ref since that information is already contained
+ // in the type.
+ let subcmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
self.cat_pattern_(subcmt, &subpat, op)?;
}
- }
-
- PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => {
- // box p1, &p1, &mut p1. we can ignore the mutability of
- // PatKind::Ref since that information is already contained
- // in the type.
- let subcmt = Rc::new(self.cat_deref(pat, cmt, NoteNone)?);
- self.cat_pattern_(subcmt, &subpat, op)?;
- }
-
- PatKind::Slice(ref before, ref slice, ref after) => {
- let element_ty = match cmt.ty.builtin_index() {
- Some(ty) => ty,
- None => {
- debug!("Explicit index of non-indexable type {:?}", cmt);
- return Err(());
+
+ PatKind::Slice(ref before, ref slice, ref after) => {
+ let element_ty = match cmt.ty.builtin_index() {
+ Some(ty) => ty,
+ None => {
+ debug!("Explicit index of non-indexable type {:?}", cmt);
+ return Err(());
+ }
+ };
+ let context = InteriorOffsetKind::Pattern;
+ let elt_cmt = Rc::new(self.cat_index(pat, cmt, element_ty, context)?);
+ for before_pat in before {
+ self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
+ }
+ if let Some(ref slice_pat) = *slice {
+ self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
+ }
+ for after_pat in after {
+ self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
}
- };
- let context = InteriorOffsetKind::Pattern;
- let elt_cmt = Rc::new(self.cat_index(pat, cmt, element_ty, context)?);
- for before_pat in before {
- self.cat_pattern_(elt_cmt.clone(), &before_pat, op)?;
- }
- if let Some(ref slice_pat) = *slice {
- self.cat_pattern_(elt_cmt.clone(), &slice_pat, op)?;
- }
- for after_pat in after {
- self.cat_pattern_(elt_cmt.clone(), &after_pat, op)?;
}
- }
- PatKind::Path(_) | PatKind::Binding(.., None) |
- PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
- // always ok
- }
+ PatKind::Path(_) | PatKind::Binding(.., None) |
+ PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild => {
+ // always ok
+ }
}
Ok(())
}
}
- pub fn descriptive_string(&self, tcx: TyCtxt<'_, '_, '_>) -> String {
+ pub fn descriptive_string(&self, tcx: TyCtxt<'_, '_, '_>) -> Cow<'static, str> {
match self.cat {
Categorization::StaticItem => {
- "static item".to_string()
+ "static item".into()
}
Categorization::Rvalue(..) => {
- "non-place".to_string()
+ "non-place".into()
}
Categorization::Local(vid) => {
if tcx.hir.is_argument(vid) {
- "argument".to_string()
+ "argument"
} else {
- "local variable".to_string()
- }
+ "local variable"
+ }.into()
}
Categorization::Deref(_, pk) => {
match self.upvar_cat() {
Some(&Categorization::Upvar(ref var)) => {
- var.to_string()
+ var.to_string().into()
}
Some(_) => bug!(),
None => {
match pk {
Unique => {
- "`Box` content".to_string()
+ "`Box` content"
}
UnsafePtr(..) => {
- "dereference of raw pointer".to_string()
+ "dereference of raw pointer"
}
BorrowedPtr(..) => {
match self.note {
- NoteIndex => "indexed content".to_string(),
- _ => "borrowed content".to_string(),
+ NoteIndex => "indexed content",
+ _ => "borrowed content"
}
}
- }
+ }.into()
}
}
}
Categorization::Interior(_, InteriorField(..)) => {
- "field".to_string()
+ "field".into()
}
Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Index)) => {
- "indexed content".to_string()
+ "indexed content".into()
}
Categorization::Interior(_, InteriorElement(InteriorOffsetKind::Pattern)) => {
- "pattern-bound indexed content".to_string()
+ "pattern-bound indexed content".into()
}
Categorization::Upvar(ref var) => {
- var.to_string()
+ var.to_string().into()
}
Categorization::Downcast(ref cmt, _) => {
- cmt.descriptive_string(tcx)
+ cmt.descriptive_string(tcx).into()
}
}
}
// which are currently akin to allocator symbols.
let def_id = self.tcx.hir.local_def_id(item.id);
let codegen_attrs = self.tcx.codegen_fn_attrs(def_id);
- if codegen_attrs.linkage.is_some() ||
+ if codegen_attrs.contains_extern_indicator() ||
codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
self.worklist.push(item.id);
}
return
}
- for default_method in self.tcx.provided_trait_methods(trait_def_id) {
+ let provided_trait_methods = self.tcx.provided_trait_methods(trait_def_id);
+ self.worklist.reserve(provided_trait_methods.len());
+ for default_method in provided_trait_methods {
let node_id = self.tcx
.hir
.as_local_node_id(default_method.def_id)
#[derive(Clone)]
pub struct ReachableSet(pub Lrc<NodeSet>);
-
fn reachable_set<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> ReachableSet {
debug_assert!(crate_num == LOCAL_CRATE);
}
}
- pub fn each_encl_scope<E>(&self, mut e:E) where E: FnMut(Scope, Scope) {
+ pub fn each_encl_scope<E>(&self, mut e: E) where E: FnMut(Scope, Scope) {
for (&child, &parent) in &self.parent_map {
e(child, parent.0)
}
}
- pub fn each_var_scope<E>(&self, mut e:E) where E: FnMut(&hir::ItemLocalId, Scope) {
+ pub fn each_var_scope<E>(&self, mut e: E) where E: FnMut(&hir::ItemLocalId, Scope) {
for (child, &parent) in self.var_map.iter() {
e(child, parent)
}
/// Returns the lifetime of the local variable `var_id`
pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope {
- match self.var_map.get(&var_id) {
- Some(&r) => r,
- None => { bug!("no enclosing scope for id {:?}", var_id); }
- }
+ self.var_map.get(&var_id).cloned().unwrap_or_else(||
+ bug!("no enclosing scope for id {:?}", var_id))
}
pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option<Scope> {
scope
}
- pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope)
- -> bool {
+ pub fn scopes_intersect(&self, scope1: Scope, scope2: Scope) -> bool {
self.is_subscope_of(scope1, scope2) ||
self.is_subscope_of(scope2, scope1)
}
}
}
- debug!("is_subscope_of({:?}, {:?})=true",
- subscope, superscope);
+ debug!("is_subscope_of({:?}, {:?})=true", subscope, superscope);
return true;
}
/// Returns the id of the innermost containing body
- pub fn containing_body(&self, mut scope: Scope)-> Option<hir::ItemLocalId> {
+ pub fn containing_body(&self, mut scope: Scope) -> Option<hir::ItemLocalId> {
loop {
if let ScopeData::CallSite = scope.data {
return Some(scope.item_local_id());
/// Assuming that the provided region was defined within this `ScopeTree`,
/// returns the outermost `Scope` that the region outlives.
pub fn early_free_scope<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
- br: &ty::EarlyBoundRegion)
- -> Scope {
+ br: &ty::EarlyBoundRegion)
+ -> Scope {
let param_owner = tcx.parent_def_id(br.def_id).unwrap();
let param_owner_id = tcx.hir.as_local_node_id(param_owner).unwrap();
fn resolve_arm<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, arm: &'tcx hir::Arm) {
visitor.terminating_scopes.insert(arm.body.hir_id.local_id);
- if let Some(ref g) = arm.guard {
- match g {
- hir::Guard::If(ref expr) => visitor.terminating_scopes.insert(expr.hir_id.local_id),
- };
+ if let Some(hir::Guard::If(ref expr)) = arm.guard {
+ visitor.terminating_scopes.insert(expr.hir_id.local_id);
}
intravisit::walk_arm(visitor, arm);
// This ensures fixed size stacks.
hir::ExprKind::Binary(
- source_map::Spanned { node: hir::BinOpKind::And, .. },
- _, ref r) |
+ source_map::Spanned { node: hir::BinOpKind::And, .. }, _, ref r) |
hir::ExprKind::Binary(
- source_map::Spanned { node: hir::BinOpKind::Or, .. },
- _, ref r) => {
+ source_map::Spanned { node: hir::BinOpKind::Or, .. }, _, ref r) => {
// For shortcircuiting operators, mark the RHS as a terminating
// scope since it only executes conditionally.
terminating(r.hir_id.local_id);
use rustc::lint;
use rustc_data_structures::sync::Lrc;
use session::Session;
+use std::borrow::Cow;
use std::cell::Cell;
use std::mem::replace;
use syntax::ast;
is_late_bound_map: |tcx, id| {
let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
tcx.resolve_lifetimes(LOCAL_CRATE)
- .late_bound
- .get(&id)
- .cloned()
+ .late_bound
+ .get(&id)
+ .cloned()
},
object_lifetime_defaults_map: |tcx, id| {
let id = LocalDefId::from_def_id(DefId::local(id)); // (*)
tcx.resolve_lifetimes(LOCAL_CRATE)
- .object_lifetime_defaults
- .get(&id)
- .cloned()
+ .object_lifetime_defaults
+ .get(&id)
+ .cloned()
},
..*providers
for (k, v) in named_region_map.object_lifetime_defaults {
let hir_id = tcx.hir.node_to_hir_id(k);
let map = rl.object_lifetime_defaults
- .entry(hir_id.owner_local_def_id())
- .or_default();
+ .entry(hir_id.owner_local_def_id())
+ .or_default();
Lrc::get_mut(map)
.unwrap()
.insert(hir_id.local_id, Lrc::new(v));
};
self.with(scope, |_, this| this.visit_ty(&mt.ty));
}
- hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
- if let Def::Existential(exist_ty_did) = path.def {
- let id = self.tcx.hir.as_local_node_id(exist_ty_did).unwrap();
-
- // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
- // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
- // `abstract type MyAnonTy<'b>: MyTrait<'b>;`
- // ^ ^ this gets resolved in the scope of
- // the exist_ty generics
- let (generics, bounds) = match self.tcx.hir.expect_item(id).node {
- // named existential types don't need these hacks
- hir::ItemKind::Existential(hir::ExistTy{ impl_trait_fn: None, .. }) => {
- intravisit::walk_ty(self, ty);
- return;
- },
- hir::ItemKind::Existential(hir::ExistTy{
- ref generics,
- ref bounds,
- ..
- }) => (
- generics,
- bounds,
- ),
- ref i => bug!("impl Trait pointed to non-existential type?? {:#?}", i),
- };
+ hir::TyKind::Def(item_id, ref lifetimes) => {
+ // Resolve the lifetimes in the bounds to the lifetime defs in the generics.
+ // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
+ // `abstract type MyAnonTy<'b>: MyTrait<'b>;`
+ // ^ ^ this gets resolved in the scope of
+ // the exist_ty generics
+ let (generics, bounds) = match self.tcx.hir.expect_item(item_id.id).node {
+ // named existential types are reached via TyKind::Path
+ // this arm is for `impl Trait` in the types of statics, constants and locals
+ hir::ItemKind::Existential(hir::ExistTy{ impl_trait_fn: None, .. }) => {
+ intravisit::walk_ty(self, ty);
+ return;
+ },
+ // RPIT (return position impl trait)
+ hir::ItemKind::Existential(hir::ExistTy{
+ ref generics,
+ ref bounds,
+ ..
+ }) => (
+ generics,
+ bounds,
+ ),
+ ref i => bug!("impl Trait pointed to non-existential type?? {:#?}", i),
+ };
- assert!(exist_ty_did.is_local());
- // Resolve the lifetimes that are applied to the existential type.
- // These are resolved in the current scope.
- // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
- // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
- // ^ ^this gets resolved in the current scope
- for lifetime in &path.segments[0].args.as_ref().unwrap().args {
- if let hir::GenericArg::Lifetime(lifetime) = lifetime {
- self.visit_lifetime(lifetime);
-
- // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
- // and ban them. Type variables instantiated inside binders aren't
- // well-supported at the moment, so this doesn't work.
- // In the future, this should be fixed and this error should be removed.
- let def = self.map.defs.get(&lifetime.id).cloned();
- if let Some(Region::LateBound(_, def_id, _)) = def {
- if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
- // Ensure that the parent of the def is an item, not HRTB
- let parent_id = self.tcx.hir.get_parent_node(node_id);
- let parent_impl_id = hir::ImplItemId { node_id: parent_id };
- let parent_trait_id = hir::TraitItemId { node_id: parent_id };
- let krate = self.tcx.hir.forest.krate();
- if !(krate.items.contains_key(&parent_id)
- || krate.impl_items.contains_key(&parent_impl_id)
- || krate.trait_items.contains_key(&parent_trait_id))
- {
- span_err!(
- self.tcx.sess,
- lifetime.span,
- E0657,
- "`impl Trait` can only capture lifetimes \
- bound at the fn or impl level"
- );
- self.uninsert_lifetime_on_error(lifetime, def.unwrap());
- }
+ // Resolve the lifetimes that are applied to the existential type.
+ // These are resolved in the current scope.
+ // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to
+ // `fn foo<'a>() -> MyAnonTy<'a> { ... }`
+ // ^ ^this gets resolved in the current scope
+ for lifetime in lifetimes {
+ if let hir::GenericArg::Lifetime(lifetime) = lifetime {
+ self.visit_lifetime(lifetime);
+
+ // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>`
+ // and ban them. Type variables instantiated inside binders aren't
+ // well-supported at the moment, so this doesn't work.
+ // In the future, this should be fixed and this error should be removed.
+ let def = self.map.defs.get(&lifetime.id).cloned();
+ if let Some(Region::LateBound(_, def_id, _)) = def {
+ if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
+ // Ensure that the parent of the def is an item, not HRTB
+ let parent_id = self.tcx.hir.get_parent_node(node_id);
+ let parent_impl_id = hir::ImplItemId { node_id: parent_id };
+ let parent_trait_id = hir::TraitItemId { node_id: parent_id };
+ let krate = self.tcx.hir.forest.krate();
+ if !(krate.items.contains_key(&parent_id)
+ || krate.impl_items.contains_key(&parent_impl_id)
+ || krate.trait_items.contains_key(&parent_trait_id))
+ {
+ span_err!(
+ self.tcx.sess,
+ lifetime.span,
+ E0657,
+ "`impl Trait` can only capture lifetimes \
+ bound at the fn or impl level"
+ );
+ self.uninsert_lifetime_on_error(lifetime, def.unwrap());
}
}
}
}
+ }
- // We want to start our early-bound indices at the end of the parent scope,
- // not including any parent `impl Trait`s.
- let mut index = self.next_early_index_for_abstract_type();
- debug!("visit_ty: index = {}", index);
+ // We want to start our early-bound indices at the end of the parent scope,
+ // not including any parent `impl Trait`s.
+ let mut index = self.next_early_index_for_abstract_type();
+ debug!("visit_ty: index = {}", index);
- let mut elision = None;
- let mut lifetimes = FxHashMap();
- let mut type_count = 0;
- for param in &generics.params {
- match param.kind {
- GenericParamKind::Lifetime { .. } => {
- let (name, reg) = Region::early(&self.tcx.hir, &mut index, ¶m);
- if let hir::ParamName::Plain(param_name) = name {
- if param_name.name == keywords::UnderscoreLifetime.name() {
- // Pick the elided lifetime "definition" if one exists
- // and use it to make an elision scope.
- elision = Some(reg);
- } else {
- lifetimes.insert(name, reg);
- }
+ let mut elision = None;
+ let mut lifetimes = FxHashMap();
+ let mut type_count = 0;
+ for param in &generics.params {
+ match param.kind {
+ GenericParamKind::Lifetime { .. } => {
+ let (name, reg) = Region::early(&self.tcx.hir, &mut index, ¶m);
+ if let hir::ParamName::Plain(param_name) = name {
+ if param_name.name == keywords::UnderscoreLifetime.name() {
+ // Pick the elided lifetime "definition" if one exists
+ // and use it to make an elision scope.
+ elision = Some(reg);
} else {
lifetimes.insert(name, reg);
}
- }
- GenericParamKind::Type { .. } => {
- type_count += 1;
+ } else {
+ lifetimes.insert(name, reg);
}
}
+ GenericParamKind::Type { .. } => {
+ type_count += 1;
+ }
}
- let next_early_index = index + type_count;
+ }
+ let next_early_index = index + type_count;
- if let Some(elision_region) = elision {
- let scope = Scope::Elision {
- elide: Elide::Exact(elision_region),
- s: self.scope,
- };
- self.with(scope, |_old_scope, this| {
- let scope = Scope::Binder {
- lifetimes,
- next_early_index,
- s: this.scope,
- track_lifetime_uses: true,
- abstract_type_parent: false,
- };
- this.with(scope, |_old_scope, this| {
- this.visit_generics(generics);
- for bound in bounds {
- this.visit_param_bound(bound);
- }
- });
- });
- } else {
+ if let Some(elision_region) = elision {
+ let scope = Scope::Elision {
+ elide: Elide::Exact(elision_region),
+ s: self.scope,
+ };
+ self.with(scope, |_old_scope, this| {
let scope = Scope::Binder {
lifetimes,
next_early_index,
- s: self.scope,
+ s: this.scope,
track_lifetime_uses: true,
abstract_type_parent: false,
};
- self.with(scope, |_old_scope, this| {
+ this.with(scope, |_old_scope, this| {
this.visit_generics(generics);
for bound in bounds {
this.visit_param_bound(bound);
}
});
- }
+ });
} else {
- intravisit::walk_ty(self, ty)
+ let scope = Scope::Binder {
+ lifetimes,
+ next_early_index,
+ s: self.scope,
+ track_lifetime_uses: true,
+ abstract_type_parent: false,
+ };
+ self.with(scope, |_old_scope, this| {
+ this.visit_generics(generics);
+ for bound in bounds {
+ this.visit_param_bound(bound);
+ }
+ });
}
}
_ => intravisit::walk_ty(self, ty),
let object_lifetime_default_reprs: String = result
.iter()
.map(|set| match *set {
- Set1::Empty => "BaseDefault".to_string(),
- Set1::One(Region::Static) => "'static".to_string(),
+ Set1::Empty => "BaseDefault".into(),
+ Set1::One(Region::Static) => "'static".into(),
Set1::One(Region::EarlyBound(mut i, _, _)) => {
generics.params.iter().find_map(|param| match param.kind {
- GenericParamKind::Lifetime { .. } => {
- if i == 0 {
- return Some(param.name.ident().to_string());
- }
- i -= 1;
- None
+ GenericParamKind::Lifetime { .. } => {
+ if i == 0 {
+ return Some(param.name.ident().to_string().into());
}
- _ => None,
- }).unwrap()
+ i -= 1;
+ None
+ }
+ _ => None,
+ }).unwrap()
}
Set1::One(_) => bug!(),
- Set1::Many => "Ambiguous".to_string(),
+ Set1::Many => "Ambiguous".into(),
})
- .collect::<Vec<String>>()
+ .collect::<Vec<Cow<'static, str>>>()
.join(",");
tcx.sess.span_err(item.span, &object_lifetime_default_reprs);
}
def_ids.sort_by_key(|&def_id| self.tcx.def_path_hash(def_id));
for def_id in def_ids {
- debug!(
- "check_uses_for_lifetimes_defined_by_scope: def_id = {:?}",
- def_id,
- );
+ debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id);
let lifetimeuseset = self.lifetime_uses.remove(&def_id);
- debug!(
- "check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
- lifetimeuseset
- );
+
+ debug!("check_uses_for_lifetimes_defined_by_scope: lifetimeuseset = {:?}",
+ lifetimeuseset);
+
match lifetimeuseset {
Some(LifetimeUseSet::One(lifetime)) => {
let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
"lifetimes used in `fn` or `Fn` syntax must be \
explicitly declared using `<...>` binders"
).span_label(lifetime_ref.span, "in-band lifetime definition")
- .emit();
+ .emit();
}
Region::Static
"use of undeclared lifetime name `{}`",
lifetime_ref
).span_label(lifetime_ref.span, "undeclared lifetime")
- .emit();
+ .emit();
}
}
node: hir::TraitItemKind::Method(_, ref m),
..
}) => {
- match self.tcx
+ if let hir::ItemKind::Trait(.., ref trait_items) = self.tcx
.hir
.expect_item(self.tcx.hir.get_parent(parent))
.node
{
- hir::ItemKind::Trait(.., ref trait_items) => {
- assoc_item_kind = trait_items
- .iter()
- .find(|ti| ti.id.node_id == parent)
- .map(|ti| ti.kind);
- }
- _ => {}
+ assoc_item_kind = trait_items
+ .iter()
+ .find(|ti| ti.id.node_id == parent)
+ .map(|ti| ti.kind);
}
match *m {
hir::TraitMethod::Required(_) => None,
node: hir::ImplItemKind::Method(_, body),
..
}) => {
- match self.tcx
+ if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = self.tcx
.hir
.expect_item(self.tcx.hir.get_parent(parent))
.node
{
- hir::ItemKind::Impl(.., ref self_ty, ref impl_items) => {
- impl_self = Some(self_ty);
- assoc_item_kind = impl_items
- .iter()
- .find(|ii| ii.id.node_id == parent)
- .map(|ii| ii.kind);
- }
- _ => {}
+ impl_self = Some(self_ty);
+ assoc_item_kind = impl_items
+ .iter()
+ .find(|ii| ii.id.node_id == parent)
+ .map(|ii| ii.kind);
}
Some(body)
}
Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return,
- Scope::ObjectLifetimeDefault {
- lifetime: Some(l), ..
- } => break l,
+ Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l,
}
};
self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth));
lifetime_i.name.ident(),
),
).help(&format!(
- "you can use the `'static` lifetime directly, in place \
- of `{}`",
+ "you can use the `'static` lifetime directly, in place of `{}`",
lifetime_i.name.ident(),
)).emit();
}
- hir::LifetimeName::Param(_)
- | hir::LifetimeName::Implicit => {
+ hir::LifetimeName::Param(_) | hir::LifetimeName::Implicit => {
self.resolve_lifetime_ref(lt);
}
}
}
}
-///////////////////////////////////////////////////////////////////////////
-
/// Detects late-bound lifetimes and inserts them into
/// `map.late_bound`.
///
decl: &hir::FnDecl,
generics: &hir::Generics,
) {
- debug!(
- "insert_late_bound_lifetimes(decl={:?}, generics={:?})",
- decl, generics
- );
+ debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})",
+ decl, generics);
let mut constrained_by_input = ConstrainedCollector {
regions: FxHashSet(),
};
intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output);
- debug!(
- "insert_late_bound_lifetimes: constrained_by_input={:?}",
- constrained_by_input.regions
- );
+ debug!("insert_late_bound_lifetimes: constrained_by_input={:?}",
+ constrained_by_input.regions);
// Walk the lifetimes that appear in where clauses.
//
appears_in_where_clause.visit_generics(generics);
for param in &generics.params {
- match param.kind {
- hir::GenericParamKind::Lifetime { .. } => {
- if !param.bounds.is_empty() {
- // `'a: 'b` means both `'a` and `'b` are referenced
- appears_in_where_clause
- .regions.insert(hir::LifetimeName::Param(param.name.modern()));
- }
+ if let hir::GenericParamKind::Lifetime { .. } = param.kind {
+ if !param.bounds.is_empty() {
+ // `'a: 'b` means both `'a` and `'b` are referenced
+ appears_in_where_clause
+ .regions.insert(hir::LifetimeName::Param(param.name.modern()));
}
- hir::GenericParamKind::Type { .. } => {}
}
}
if count > 1 { "s" } else { "" }
);
- let msg = if count > 1 {
- format!("expected {} lifetime parameters", count)
+ let msg: Cow<'static, str> = if count > 1 {
+ format!("expected {} lifetime parameters", count).into()
} else {
- "expected lifetime parameter".to_string()
+ "expected lifetime parameter".into()
};
err.span_label(span, msg);
if let (&Some(attr::RustcDeprecation {since: dep_since, ..}),
&attr::Stable {since: stab_since}) = (&stab.rustc_depr, &stab.level) {
// Explicit version of iter::order::lt to handle parse errors properly
- for (dep_v, stab_v) in
- dep_since.as_str().split('.').zip(stab_since.as_str().split('.')) {
+ for (dep_v, stab_v) in dep_since.as_str()
+ .split('.')
+ .zip(stab_since.as_str().split('.'))
+ {
if let (Ok(dep_v), Ok(stab_v)) = (dep_v.parse::<u64>(), stab_v.parse()) {
match dep_v.cmp(&stab_v) {
Ordering::Less => {
Some(Def::Method(_)) |
Some(Def::AssociatedTy(_)) |
Some(Def::AssociatedConst(_)) => {
- match self.associated_item(def_id).container {
- ty::TraitContainer(trait_def_id) => {
- // Trait methods do not declare visibility (even
- // for visibility info in cstore). Use containing
- // trait instead, so methods of pub traits are
- // themselves considered pub.
- def_id = trait_def_id;
- }
- _ => {}
+ if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container {
+ // Trait methods do not declare visibility (even
+ // for visibility info in cstore). Use containing
+ // trait instead, so methods of pub traits are
+ // themselves considered pub.
+ def_id = trait_def_id;
}
}
_ => {}
/// `id`.
pub fn eval_stability(self, def_id: DefId, id: Option<NodeId>, span: Span) -> EvalResult {
if span.allows_unstable() {
- debug!("stability: \
- skipping span={:?} since it is internal", span);
+ debug!("stability: skipping span={:?} since it is internal", span);
return EvalResult::Allow;
}
let param_env = self.tcx.param_env(def_id);
if !param_env.can_type_implement_copy(self.tcx, ty).is_ok() {
emit_feature_err(&self.tcx.sess.parse_sess,
- "untagged_unions", item.span, GateIssue::Language,
- "unions with non-`Copy` fields are unstable");
+ "untagged_unions", item.span, GateIssue::Language,
+ "unions with non-`Copy` fields are unstable");
}
}
}
items.$name().is_none() {
if lang_items::$item == lang_items::PanicImplLangItem {
tcx.sess.err(&format!("`#[panic_handler]` function required, \
- but not found"));
+ but not found"));
} else if lang_items::$item == lang_items::OomLangItem {
tcx.sess.err(&format!("`#[alloc_error_handler]` function required, \
- but not found"));
+ but not found"));
} else {
tcx.sess.err(&format!("language item required, but not found: `{}`",
- stringify!($name)));
+ stringify!($name)));
}
}
)*
pub fn from_uint(i: impl Into<u128>, size: Size) -> Self {
let i = i.into();
debug_assert_eq!(truncate(i, size), i,
- "Unsigned value {} does not fit in {} bits", i, size.bits());
+ "Unsigned value {} does not fit in {} bits", i, size.bits());
Scalar::Bits { bits: i, size: size.bytes() as u8 }
}
// `into` performed sign extension, we have to truncate
let truncated = truncate(i as u128, size);
debug_assert_eq!(sign_extend(truncated, size) as i128, i,
- "Signed value {} does not fit in {} bits", i, size.bits());
+ "Signed value {} does not fit in {} bits", i, size.bits());
Scalar::Bits { bits: truncated, size: size.bytes() as u8 }
}
//!
//! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/mir/index.html
-use graphviz::IntoCow;
use hir::def::CtorKind;
use hir::def_id::DefId;
use hir::{self, HirId, InlineAsm};
if idx < stmts.len() {
&stmts[idx].source_info
} else {
- assert!(idx == stmts.len());
+ assert_eq!(idx, stmts.len());
&block.terminator().source_info
}
}
/// Check if `sub` is a sub scope of `sup`
pub fn is_sub_scope(&self, mut sub: SourceScope, sup: SourceScope) -> bool {
- loop {
- if sub == sup {
- return true;
- }
+ while sub != sup {
match self.source_scopes[sub].parent_scope {
None => return false,
Some(p) => sub = p,
}
}
+ true
}
/// Return the return type, it always return first element from `local_decls` array
pub fn allows_two_phase_borrow(&self) -> bool {
match *self {
BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false,
- BorrowKind::Mut {
- allow_two_phase_borrow,
- } => allow_two_phase_borrow,
+ BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow,
}
}
}
}
}
+/// `BlockTailInfo` is attached to the `LocalDecl` for temporaries
+/// created during evaluation of expressions in a block tail
+/// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`.
+///
+/// It is used to improve diagnostics when such temporaries are
+/// involved in borrow_check errors, e.g. explanations of where the
+/// temporaries come from, when their destructors are run, and/or how
+/// one might revise the code to satisfy the borrow checker's rules.
+#[derive(Clone, Debug, RustcEncodable, RustcDecodable)]
+pub struct BlockTailInfo {
+ /// If `true`, then the value resulting from evaluating this tail
+ /// expression is ignored by the block's expression context.
+ ///
+ /// Examples include `{ ...; tail };` and `let _ = { ...; tail };`
+ /// but not e.g. `let _x = { ...; tail };`
+ pub tail_result_is_ignored: bool,
+}
+
+impl_stable_hash_for!(struct BlockTailInfo { tail_result_is_ignored });
+
/// A MIR local.
///
/// This can be a binding declared by the user, a temporary inserted by the compiler, a function
/// generator.
pub internal: bool,
+ /// If this local is a temporary and `is_block_tail` is `Some`,
+ /// then it is a temporary created for evaluation of some
+ /// subexpression of some block's tail expression (with no
+ /// intervening statement context).
+ pub is_block_tail: Option<BlockTailInfo>,
+
/// Type of this local.
pub ty: Ty<'tcx>,
Self::new_local(ty, Mutability::Mut, false, span)
}
- /// Create a new immutable `LocalDecl` for a temporary.
+ /// Converts `self` into same `LocalDecl` except tagged as immutable.
+ #[inline]
+ pub fn immutable(mut self) -> Self {
+ self.mutability = Mutability::Not;
+ self
+ }
+
+ /// Converts `self` into same `LocalDecl` except tagged as internal temporary.
#[inline]
- pub fn new_immutable_temp(ty: Ty<'tcx>, span: Span) -> Self {
- Self::new_local(ty, Mutability::Not, false, span)
+ pub fn block_tail(mut self, info: BlockTailInfo) -> Self {
+ assert!(self.is_block_tail.is_none());
+ self.is_block_tail = Some(info);
+ self
}
/// Create a new `LocalDecl` for a internal temporary.
visibility_scope: OUTERMOST_SOURCE_SCOPE,
internal,
is_user_variable: None,
+ is_block_tail: None,
}
}
},
visibility_scope: OUTERMOST_SOURCE_SCOPE,
internal: false,
+ is_block_tail: None,
name: None, // FIXME maybe we do want some name here?
is_user_variable: None,
}
destination: Option<(Place<'tcx>, BasicBlock)>,
/// Cleanups to be done if the call unwinds.
cleanup: Option<BasicBlock>,
+ /// Whether this is from a call in HIR, rather than from an overloaded
+ /// operator. True for overloaded function call.
+ from_hir_call: bool,
},
/// Jump to the target if the condition has the expected value,
};
fmt_const_val(&mut s, &c).unwrap();
s.into()
- }).chain(iter::once(String::from("otherwise").into()))
+ }).chain(iter::once("otherwise".into()))
.collect()
}
Call {
destination: Some(_),
cleanup: Some(_),
..
- } => vec!["return".into_cow(), "unwind".into_cow()],
+ } => vec!["return".into(), "unwind".into()],
Call {
destination: Some(_),
cleanup: None,
..
- } => vec!["return".into_cow()],
+ } => vec!["return".into()],
Call {
destination: None,
cleanup: Some(_),
..
- } => vec!["unwind".into_cow()],
+ } => vec!["unwind".into()],
Call {
destination: None,
cleanup: None,
..
} => vec![],
- Yield { drop: Some(_), .. } => vec!["resume".into_cow(), "drop".into_cow()],
- Yield { drop: None, .. } => vec!["resume".into_cow()],
+ Yield { drop: Some(_), .. } => vec!["resume".into(), "drop".into()],
+ Yield { drop: None, .. } => vec!["resume".into()],
DropAndReplace { unwind: None, .. } | Drop { unwind: None, .. } => {
- vec!["return".into_cow()]
+ vec!["return".into()]
}
DropAndReplace {
unwind: Some(_), ..
}
| Drop {
unwind: Some(_), ..
- } => vec!["return".into_cow(), "unwind".into_cow()],
+ } => vec!["return".into(), "unwind".into()],
Assert { cleanup: None, .. } => vec!["".into()],
- Assert { .. } => vec!["success".into_cow(), "unwind".into_cow()],
+ Assert { .. } => vec!["success".into(), "unwind".into()],
FalseEdges {
ref imaginary_targets,
..
*/
CloneTypeFoldableAndLiftImpls! {
+ BlockTailInfo,
Mutability,
SourceInfo,
UpvarDecl,
user_ty,
name,
source_info,
+ is_block_tail,
visibility_scope,
}
}
ref args,
ref destination,
cleanup,
+ from_hir_call,
} => {
let dest = destination
.as_ref()
args: args.fold_with(folder),
destination: dest,
cleanup,
+ from_hir_call,
}
}
Assert {
String::new()
};
- let crate_disambiguator = format!("{}", tcx.crate_disambiguator(cnum));
+ let crate_disambiguator = tcx.crate_disambiguator(cnum).to_string();
// Using a shortened disambiguator of about 40 bits
format!("{}.{}{}",
tcx.crate_name(cnum),
assert!(index < adt_def.variants.len());
assert_eq!(adt_def, adt_def1);
PlaceTy::Downcast { adt_def,
- substs,
- variant_index: index }
+ substs,
+ variant_index: index }
}
_ => {
bug!("cannot downcast non-ADT type: `{:?}`", self)
}
},
_ => None,
- }\f
+ }
_ => None,
}
}
impl<'tcx> BinOp {
pub fn ty<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
- lhs_ty: Ty<'tcx>,
- rhs_ty: Ty<'tcx>)
- -> Ty<'tcx> {
+ lhs_ty: Ty<'tcx>,
+ rhs_ty: Ty<'tcx>)
+ -> Ty<'tcx> {
// FIXME: handle SIMD correctly
match self {
&BinOp::Add | &BinOp::Sub | &BinOp::Mul | &BinOp::Div | &BinOp::Rem |
TerminatorKind::Call { ref $($mutability)* func,
ref $($mutability)* args,
ref $($mutability)* destination,
- cleanup } => {
+ cleanup,
+ from_hir_call: _, } => {
self.visit_operand(func, source_location);
for arg in args {
self.visit_operand(arg, source_location);
ref $($mutability)* visibility_scope,
internal: _,
is_user_variable: _,
+ is_block_tail: _,
} = *local_decl;
self.visit_ty(ty, TyContext::LocalDecl {
{
debug!("overlap(a_def_id={:?}, b_def_id={:?})", a_def_id, b_def_id);
- // For the purposes of this check, we don't bring any skolemized
+ // For the purposes of this check, we don't bring any placeholder
// types into scope; instead, we replace the generic types with
// fresh type variables, and hence we do our evaluations in an
// empty environment.
ty::Error => true,
+ ty::UnnormalizedProjection(..) |
ty::Closure(..) |
ty::Generator(..) |
ty::GeneratorWitness(..) |
use ty::SubtypePredicate;
use util::nodemap::{FxHashMap, FxHashSet};
-use syntax_pos::{DUMMY_SP, Span};
+use syntax_pos::{DUMMY_SP, Span, ExpnInfo, ExpnFormat};
impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
pub fn report_fulfillment_errors(&self,
}).collect();
for (index, error) in errors.iter().enumerate() {
- error_map.entry(error.obligation.cause.span).or_default().push(
+ // We want to ignore desugarings here: spans are equivalent even
+ // if one is the result of a desugaring and the other is not.
+ let mut span = error.obligation.cause.span;
+ if let Some(ExpnInfo {
+ format: ExpnFormat::CompilerDesugaring(_),
+ def_site: Some(def_span),
+ ..
+ }) = span.ctxt().outer().expn_info() {
+ span = def_span;
+ }
+
+ error_map.entry(span).or_default().push(
ErrorDescriptor {
predicate: error.obligation.predicate.clone(),
index: Some(index)
- });
+ }
+ );
self.reported_trait_errors.borrow_mut()
- .entry(error.obligation.cause.span).or_default()
+ .entry(span).or_default()
.push(error.obligation.predicate.clone());
}
- // We do this in 2 passes because we want to display errors in order, tho
+ // We do this in 2 passes because we want to display errors in order, though
// maybe it *is* better to sort errors by span or something.
let mut is_suppressed = vec![false; errors.len()];
for (_, error_set) in error_map.iter() {
ty::Generator(..) => Some(18),
ty::Foreign(..) => Some(19),
ty::GeneratorWitness(..) => Some(20),
- ty::Infer(..) | ty::Error => None
+ ty::Infer(..) | ty::Error => None,
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
}
}
let infcx = selcx.infcx();
infcx.commit_if_ok(|snapshot| {
- let (skol_predicate, skol_map) =
- infcx.skolemize_late_bound_regions(&obligation.predicate);
+ let (placeholder_predicate, placeholder_map) =
+ infcx.replace_late_bound_regions_with_placeholders(&obligation.predicate);
- let skol_obligation = obligation.with(skol_predicate);
+ let skol_obligation = obligation.with(placeholder_predicate);
let r = match project_and_unify_type(selcx, &skol_obligation) {
Ok(result) => {
let span = obligation.cause.span;
- match infcx.leak_check(false, span, &skol_map, snapshot) {
- Ok(()) => Ok(infcx.plug_leaks(skol_map, snapshot, result)),
+ match infcx.leak_check(false, span, &placeholder_map, snapshot) {
+ Ok(()) => Ok(infcx.plug_leaks(placeholder_map, snapshot, result)),
Err(e) => {
debug!("poly_project_and_unify_type: leak check encountered error {:?}", e);
Err(MismatchedProjectionTypes { err: e })
// # Cache
-/// The projection cache. Unlike the standard caches, this can
-/// include infcx-dependent type variables - therefore, we have to roll
-/// the cache back each time we roll a snapshot back, to avoid assumptions
-/// on yet-unresolved inference variables. Types with skolemized regions
-/// also have to be removed when the respective snapshot ends.
+/// The projection cache. Unlike the standard caches, this can include
+/// infcx-dependent type variables - therefore, we have to roll the
+/// cache back each time we roll a snapshot back, to avoid assumptions
+/// on yet-unresolved inference variables. Types with placeholder
+/// regions also have to be removed when the respective snapshot ends.
///
/// Because of that, projection cache entries can be "stranded" and left
/// inaccessible when type variables inside the key are resolved. We make no
self.map.rollback_to(&snapshot.snapshot);
}
- pub fn rollback_skolemized(&mut self, snapshot: &ProjectionCacheSnapshot) {
+ pub fn rollback_placeholder(&mut self, snapshot: &ProjectionCacheSnapshot) {
self.map.partial_rollback(&snapshot.snapshot, &|k| k.ty.has_re_skol());
}
| ty::Opaque(..)
| ty::Infer(_)
| ty::Generator(..) => false,
+
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
}
}
//!
//! [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#selection
-use self::SelectionCandidate::*;
use self::EvaluationResult::*;
+use self::SelectionCandidate::*;
use super::coherence::{self, Conflict};
-use super::DerivedObligationCause;
-use super::{IntercrateMode, TraitQueryMode};
use super::project;
use super::project::{normalize_with_depth, Normalized, ProjectionCacheKey};
-use super::{PredicateObligation, TraitObligation, ObligationCause};
-use super::{ObligationCauseCode, BuiltinDerivedObligation, ImplDerivedObligation};
-use super::{SelectionError, Unimplemented, OutputTypeParameterMismatch, Overflow};
-use super::{ObjectCastObligation, Obligation};
-use super::TraitNotObjectSafe;
+use super::util;
+use super::DerivedObligationCause;
use super::Selection;
use super::SelectionResult;
-use super::{VtableBuiltin, VtableImpl, VtableParam, VtableClosure, VtableGenerator,
- VtableFnPointer, VtableObject, VtableAutoImpl};
-use super::{VtableImplData, VtableObjectData, VtableBuiltinData, VtableGeneratorData,
- VtableClosureData, VtableAutoImplData, VtableFnPointerData};
-use super::util;
-
-use dep_graph::{DepNodeIndex, DepKind};
+use super::TraitNotObjectSafe;
+use super::{BuiltinDerivedObligation, ImplDerivedObligation, ObligationCauseCode};
+use super::{IntercrateMode, TraitQueryMode};
+use super::{ObjectCastObligation, Obligation};
+use super::{ObligationCause, PredicateObligation, TraitObligation};
+use super::{OutputTypeParameterMismatch, Overflow, SelectionError, Unimplemented};
+use super::{
+ VtableAutoImpl, VtableBuiltin, VtableClosure, VtableFnPointer, VtableGenerator, VtableImpl,
+ VtableObject, VtableParam,
+};
+use super::{
+ VtableAutoImplData, VtableBuiltinData, VtableClosureData, VtableFnPointerData,
+ VtableGeneratorData, VtableImplData, VtableObjectData,
+};
+
+use dep_graph::{DepKind, DepNodeIndex};
use hir::def_id::DefId;
use infer;
use infer::{InferCtxt, InferOk, TypeFreshener};
-use ty::subst::{Subst, Substs};
-use ty::{self, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
+use middle::lang_items;
+use mir::interpret::GlobalId;
use ty::fast_reject;
use ty::relate::TypeRelation;
-use middle::lang_items;
-use mir::interpret::{GlobalId};
+use ty::subst::{Subst, Substs};
+use ty::{self, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable};
+use hir;
use rustc_data_structures::bit_set::GrowableBitSet;
use rustc_data_structures::sync::Lock;
-use std::iter;
+use rustc_target::spec::abi::Abi;
use std::cmp;
use std::fmt;
+use std::iter;
use std::mem;
use std::rc::Rc;
-use rustc_target::spec::abi::Abi;
-use hir;
use util::nodemap::{FxHashMap, FxHashSet};
-pub struct SelectionContext<'cx, 'gcx: 'cx+'tcx, 'tcx: 'cx> {
+pub struct SelectionContext<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> {
infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
- /// Freshener used specifically for skolemizing entries on the
- /// obligation stack. This ensures that all entries on the stack
- /// at one time will have the same set of skolemized entries,
- /// which is important for checking for trait bounds that
- /// recursively require themselves.
+ /// Freshener used specifically for entries on the obligation
+ /// stack. This ensures that all entries on the stack at one time
+ /// will have the same set of placeholder entries, which is
+ /// important for checking for trait bounds that recursively
+ /// require themselves.
freshener: TypeFreshener<'cx, 'gcx, 'tcx>,
/// If true, indicates that the evaluation should be conservative
impl IntercrateAmbiguityCause {
/// Emits notes when the overlap is caused by complex intercrate ambiguities.
/// See #23980 for details.
- pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(&self,
- err: &mut ::errors::DiagnosticBuilder<'_>) {
+ pub fn add_intercrate_ambiguity_hint<'a, 'tcx>(
+ &self,
+ err: &mut ::errors::DiagnosticBuilder<'_>,
+ ) {
err.note(&self.intercrate_ambiguity_hint());
}
pub fn intercrate_ambiguity_hint(&self) -> String {
match self {
- &IntercrateAmbiguityCause::DownstreamCrate { ref trait_desc, ref self_desc } => {
+ &IntercrateAmbiguityCause::DownstreamCrate {
+ ref trait_desc,
+ ref self_desc,
+ } => {
let self_desc = if let &Some(ref ty) = self_desc {
format!(" for type `{}`", ty)
- } else { String::new() };
- format!("downstream crates may implement trait `{}`{}", trait_desc, self_desc)
+ } else {
+ String::new()
+ };
+ format!(
+ "downstream crates may implement trait `{}`{}",
+ trait_desc, self_desc
+ )
}
- &IntercrateAmbiguityCause::UpstreamCrateUpdate { ref trait_desc, ref self_desc } => {
+ &IntercrateAmbiguityCause::UpstreamCrateUpdate {
+ ref trait_desc,
+ ref self_desc,
+ } => {
let self_desc = if let &Some(ref ty) = self_desc {
format!(" for type `{}`", ty)
- } else { String::new() };
- format!("upstream crates may add new impl of trait `{}`{} \
- in future versions",
- trait_desc, self_desc)
+ } else {
+ String::new()
+ };
+ format!(
+ "upstream crates may add new impl of trait `{}`{} \
+ in future versions",
+ trait_desc, self_desc
+ )
}
}
}
struct TraitObligationStack<'prev, 'tcx: 'prev> {
obligation: &'prev TraitObligation<'tcx>,
- /// Trait ref from `obligation` but skolemized with the
+ /// Trait ref from `obligation` but "freshened" with the
/// selection-context's freshener. Used to check for recursion.
fresh_trait_ref: ty::PolyTraitRef<'tcx>,
#[derive(Clone)]
pub struct SelectionCache<'tcx> {
- hashmap: Lock<FxHashMap<ty::TraitRef<'tcx>,
- WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>>,
+ hashmap: Lock<
+ FxHashMap<ty::TraitRef<'tcx>, WithDepNode<SelectionResult<'tcx, SelectionCandidate<'tcx>>>>,
+ >,
}
/// The selection process begins by considering all impls, where
/// required for associated types to work in default impls, as the bounds
/// are visible both as projection bounds and as where-clauses from the
/// parameter environment.
-#[derive(PartialEq,Eq,Debug,Clone)]
+#[derive(PartialEq, Eq, Debug, Clone)]
enum SelectionCandidate<'tcx> {
/// If has_nested is false, there are no *further* obligations
- BuiltinCandidate { has_nested: bool },
+ BuiltinCandidate {
+ has_nested: bool,
+ },
ParamCandidate(ty::PolyTraitRef<'tcx>),
ImplCandidate(DefId),
AutoImplCandidate(DefId),
type Lifted = SelectionCandidate<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
Some(match *self {
- BuiltinCandidate { has_nested } => {
- BuiltinCandidate {
- has_nested,
- }
- }
+ BuiltinCandidate { has_nested } => BuiltinCandidate { has_nested },
ImplCandidate(def_id) => ImplCandidate(def_id),
AutoImplCandidate(def_id) => AutoImplCandidate(def_id),
ProjectionCandidate => ProjectionCandidate,
ambiguous: bool,
}
-#[derive(PartialEq,Eq,Debug,Clone)]
+#[derive(PartialEq, Eq, Debug, Clone)]
struct EvaluatedCandidate<'tcx> {
candidate: SelectionCandidate<'tcx>,
evaluation: EvaluationResult,
/// candidate (a where-clause or user-defined impl).
None,
/// It is unknown whether there is an impl.
- Ambiguous
+ Ambiguous,
}
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
impl EvaluationResult {
pub fn may_apply(self) -> bool {
match self {
- EvaluatedToOk |
- EvaluatedToAmbig |
- EvaluatedToUnknown => true,
+ EvaluatedToOk | EvaluatedToAmbig | EvaluatedToUnknown => true,
- EvaluatedToErr |
- EvaluatedToRecur => false
+ EvaluatedToErr | EvaluatedToRecur => false,
}
}
fn is_stack_dependent(self) -> bool {
match self {
- EvaluatedToUnknown |
- EvaluatedToRecur => true,
+ EvaluatedToUnknown | EvaluatedToRecur => true,
- EvaluatedToOk |
- EvaluatedToAmbig |
- EvaluatedToErr => false,
+ EvaluatedToOk | EvaluatedToAmbig | EvaluatedToErr => false,
}
}
}
/// Indicates that trait evaluation caused overflow.
pub struct OverflowError;
-impl_stable_hash_for!(struct OverflowError { });
+impl_stable_hash_for!(struct OverflowError {});
impl<'tcx> From<OverflowError> for SelectionError<'tcx> {
fn from(OverflowError: OverflowError) -> SelectionError<'tcx> {
#[derive(Clone)]
pub struct EvaluationCache<'tcx> {
- hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>
+ hashmap: Lock<FxHashMap<ty::PolyTraitRef<'tcx>, WithDepNode<EvaluationResult>>>,
}
impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> {
}
}
- pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
- mode: IntercrateMode) -> SelectionContext<'cx, 'gcx, 'tcx> {
+ pub fn intercrate(
+ infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
+ mode: IntercrateMode,
+ ) -> SelectionContext<'cx, 'gcx, 'tcx> {
debug!("intercrate({:?})", mode);
SelectionContext {
infcx,
}
}
- pub fn with_negative(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
- allow_negative_impls: bool) -> SelectionContext<'cx, 'gcx, 'tcx> {
+ pub fn with_negative(
+ infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
+ allow_negative_impls: bool,
+ ) -> SelectionContext<'cx, 'gcx, 'tcx> {
debug!("with_negative({:?})", allow_negative_impls);
SelectionContext {
infcx,
}
}
- pub fn with_query_mode(infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
- query_mode: TraitQueryMode) -> SelectionContext<'cx, 'gcx, 'tcx> {
+ pub fn with_query_mode(
+ infcx: &'cx InferCtxt<'cx, 'gcx, 'tcx>,
+ query_mode: TraitQueryMode,
+ ) -> SelectionContext<'cx, 'gcx, 'tcx> {
debug!("with_query_mode({:?})", query_mode);
SelectionContext {
infcx,
/// Wraps the inference context's in_snapshot s.t. snapshot handling is only from the selection
/// context's self.
fn in_snapshot<R, F>(&mut self, f: F) -> R
- where F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R
+ where
+ F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R,
{
self.infcx.in_snapshot(|snapshot| f(self, snapshot))
}
/// Wraps a probe s.t. obligations collected during it are ignored and old obligations are
/// retained.
fn probe<R, F>(&mut self, f: F) -> R
- where F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R
+ where
+ F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> R,
{
self.infcx.probe(|snapshot| f(self, snapshot))
}
/// Wraps a commit_if_ok s.t. obligations collected during it are not returned in selection if
/// the transaction fails and s.t. old obligations are retained.
- fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E> where
- F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> Result<T, E>
+ fn commit_if_ok<T, E, F>(&mut self, f: F) -> Result<T, E>
+ where
+ F: FnOnce(&mut Self, &infer::CombinedSnapshot<'cx, 'tcx>) -> Result<T, E>,
{
self.infcx.commit_if_ok(|snapshot| f(self, snapshot))
}
-
///////////////////////////////////////////////////////////////////////////
// Selection
//
/// Attempts to satisfy the obligation. If successful, this will affect the surrounding
/// type environment by performing unification.
- pub fn select(&mut self, obligation: &TraitObligation<'tcx>)
- -> SelectionResult<'tcx, Selection<'tcx>> {
+ pub fn select(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ ) -> SelectionResult<'tcx, Selection<'tcx>> {
debug!("select({:?})", obligation);
debug_assert!(!obligation.predicate.has_escaping_regions());
// earlier.
assert!(self.query_mode == TraitQueryMode::Canonical);
return Err(SelectionError::Overflow);
- },
- Err(e) => { return Err(e); },
- Ok(None) => { return Ok(None); },
- Ok(Some(candidate)) => candidate
+ }
+ Err(e) => {
+ return Err(e);
+ }
+ Ok(None) => {
+ return Ok(None);
+ }
+ Ok(Some(candidate)) => candidate,
};
match self.confirm_candidate(obligation, candidate) {
Err(SelectionError::Overflow) => {
assert!(self.query_mode == TraitQueryMode::Canonical);
Err(SelectionError::Overflow)
- },
+ }
Err(e) => Err(e),
- Ok(candidate) => Ok(Some(candidate))
+ Ok(candidate) => Ok(Some(candidate)),
}
}
// we can be sure it does not.
/// Evaluates whether the obligation `obligation` can be satisfied (by any means).
- pub fn predicate_may_hold_fatal(&mut self,
- obligation: &PredicateObligation<'tcx>)
- -> bool
- {
- debug!("predicate_may_hold_fatal({:?})",
- obligation);
+ pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool {
+ debug!("predicate_may_hold_fatal({:?})", obligation);
// This fatal query is a stopgap that should only be used in standard mode,
// where we do not expect overflow to be propagated.
/// Evaluates whether the obligation `obligation` can be satisfied and returns
/// an `EvaluationResult`.
- pub fn evaluate_obligation_recursively(&mut self,
- obligation: &PredicateObligation<'tcx>)
- -> Result<EvaluationResult, OverflowError>
- {
- self.probe(|this, _|
+ pub fn evaluate_obligation_recursively(
+ &mut self,
+ obligation: &PredicateObligation<'tcx>,
+ ) -> Result<EvaluationResult, OverflowError> {
+ self.probe(|this, _| {
this.evaluate_predicate_recursively(TraitObligationStackList::empty(), obligation)
- )
+ })
}
/// Evaluates the predicates in `predicates` recursively. Note that
/// this applies projections in the predicates, and therefore
/// is run within an inference probe.
- fn evaluate_predicates_recursively<'a,'o,I>(&mut self,
- stack: TraitObligationStackList<'o, 'tcx>,
- predicates: I)
- -> Result<EvaluationResult, OverflowError>
- where I : IntoIterator<Item=&'a PredicateObligation<'tcx>>, 'tcx:'a
+ fn evaluate_predicates_recursively<'a, 'o, I>(
+ &mut self,
+ stack: TraitObligationStackList<'o, 'tcx>,
+ predicates: I,
+ ) -> Result<EvaluationResult, OverflowError>
+ where
+ I: IntoIterator<Item = &'a PredicateObligation<'tcx>>,
+ 'tcx: 'a,
{
let mut result = EvaluatedToOk;
for obligation in predicates {
let eval = self.evaluate_predicate_recursively(stack, obligation)?;
- debug!("evaluate_predicate_recursively({:?}) = {:?}",
- obligation, eval);
+ debug!(
+ "evaluate_predicate_recursively({:?}) = {:?}",
+ obligation, eval
+ );
if let EvaluatedToErr = eval {
// fast-path - EvaluatedToErr is the top of the lattice,
// so we don't need to look on the other predicates.
Ok(result)
}
- fn evaluate_predicate_recursively<'o>(&mut self,
- previous_stack: TraitObligationStackList<'o, 'tcx>,
- obligation: &PredicateObligation<'tcx>)
- -> Result<EvaluationResult, OverflowError>
- {
- debug!("evaluate_predicate_recursively({:?})",
- obligation);
+ fn evaluate_predicate_recursively<'o>(
+ &mut self,
+ previous_stack: TraitObligationStackList<'o, 'tcx>,
+ obligation: &PredicateObligation<'tcx>,
+ ) -> Result<EvaluationResult, OverflowError> {
+ debug!("evaluate_predicate_recursively({:?})", obligation);
match obligation.predicate {
ty::Predicate::Trait(ref t) => {
ty::Predicate::Subtype(ref p) => {
// does this code ever run?
- match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) {
+ match self.infcx
+ .subtype_predicate(&obligation.cause, obligation.param_env, p)
+ {
Some(Ok(InferOk { obligations, .. })) => {
self.evaluate_predicates_recursively(previous_stack, &obligations)
- },
+ }
Some(Err(_)) => Ok(EvaluatedToErr),
None => Ok(EvaluatedToAmbig),
}
}
- ty::Predicate::WellFormed(ty) => {
- match ty::wf::obligations(self.infcx,
- obligation.param_env,
- obligation.cause.body_id,
- ty, obligation.cause.span) {
- Some(obligations) =>
- self.evaluate_predicates_recursively(previous_stack, obligations.iter()),
- None =>
- Ok(EvaluatedToAmbig),
+ ty::Predicate::WellFormed(ty) => match ty::wf::obligations(
+ self.infcx,
+ obligation.param_env,
+ obligation.cause.body_id,
+ ty,
+ obligation.cause.span,
+ ) {
+ Some(obligations) => {
+ self.evaluate_predicates_recursively(previous_stack, obligations.iter())
}
- }
+ None => Ok(EvaluatedToAmbig),
+ },
ty::Predicate::TypeOutlives(ref binder) => {
assert!(!binder.has_escaping_regions());
let project_obligation = obligation.with(data.clone());
match project::poly_project_and_unify_type(self, &project_obligation) {
Ok(Some(subobligations)) => {
- let result = self.evaluate_predicates_recursively(previous_stack,
- subobligations.iter());
+ let result = self.evaluate_predicates_recursively(
+ previous_stack,
+ subobligations.iter(),
+ );
if let Some(key) =
ProjectionCacheKey::from_poly_projection_predicate(self, data)
{
self.infcx.projection_cache.borrow_mut().complete(key);
}
result
- },
+ }
Ok(None) => Ok(EvaluatedToAmbig),
- Err(_) => Ok(EvaluatedToErr)
+ Err(_) => Ok(EvaluatedToErr),
}
}
} else {
Ok(EvaluatedToErr)
}
- },
- None => Ok(EvaluatedToAmbig)
+ }
+ None => Ok(EvaluatedToAmbig),
}
}
let tcx = self.tcx();
match tcx.lift_to_global(&(obligation.param_env, substs)) {
Some((param_env, substs)) => {
- let instance = ty::Instance::resolve(
- tcx.global_tcx(),
- param_env,
- def_id,
- substs,
- );
+ let instance =
+ ty::Instance::resolve(tcx.global_tcx(), param_env, def_id, substs);
if let Some(instance) = instance {
let cid = GlobalId {
instance,
- promoted: None
+ promoted: None,
};
match self.tcx().const_eval(param_env.and(cid)) {
Ok(_) => Ok(EvaluatedToOk),
- Err(_) => Ok(EvaluatedToErr)
+ Err(_) => Ok(EvaluatedToErr),
}
} else {
Ok(EvaluatedToErr)
}
}
- fn evaluate_trait_predicate_recursively<'o>(&mut self,
- previous_stack: TraitObligationStackList<'o, 'tcx>,
- mut obligation: TraitObligation<'tcx>)
- -> Result<EvaluationResult, OverflowError>
- {
+ fn evaluate_trait_predicate_recursively<'o>(
+ &mut self,
+ previous_stack: TraitObligationStackList<'o, 'tcx>,
+ mut obligation: TraitObligation<'tcx>,
+ ) -> Result<EvaluationResult, OverflowError> {
debug!("evaluate_trait_predicate_recursively({:?})", obligation);
if self.intercrate.is_none() && obligation.is_global()
- && obligation.param_env.caller_bounds.iter().all(|bound| bound.needs_subst()) {
+ && obligation
+ .param_env
+ .caller_bounds
+ .iter()
+ .all(|bound| bound.needs_subst())
+ {
// If a param env has no global bounds, global obligations do not
// depend on its particular value in order to work, so we can clear
// out the param env and get better caching.
- debug!("evaluate_trait_predicate_recursively({:?}) - in global", obligation);
+ debug!(
+ "evaluate_trait_predicate_recursively({:?}) - in global",
+ obligation
+ );
obligation.param_env = obligation.param_env.without_caller_bounds();
}
let stack = self.push_stack(previous_stack, &obligation);
let fresh_trait_ref = stack.fresh_trait_ref;
if let Some(result) = self.check_evaluation_cache(obligation.param_env, fresh_trait_ref) {
- debug!("CACHE HIT: EVAL({:?})={:?}",
- fresh_trait_ref,
- result);
+ debug!("CACHE HIT: EVAL({:?})={:?}", fresh_trait_ref, result);
return Ok(result);
}
let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack));
let result = result?;
- debug!("CACHE MISS: EVAL({:?})={:?}",
- fresh_trait_ref,
- result);
+ debug!("CACHE MISS: EVAL({:?})={:?}", fresh_trait_ref, result);
self.insert_evaluation_cache(obligation.param_env, fresh_trait_ref, dep_node, result);
Ok(result)
}
- fn evaluate_stack<'o>(&mut self,
- stack: &TraitObligationStack<'o, 'tcx>)
- -> Result<EvaluationResult, OverflowError>
- {
+ fn evaluate_stack<'o>(
+ &mut self,
+ stack: &TraitObligationStack<'o, 'tcx>,
+ ) -> Result<EvaluationResult, OverflowError> {
// In intercrate mode, whenever any of the types are unbound,
// there can always be an impl. Even if there are no impls in
// this crate, perhaps the type would be unified with
// This suffices to allow chains like `FnMut` implemented in
// terms of `Fn` etc, but we could probably make this more
// precise still.
- let unbound_input_types =
- stack.fresh_trait_ref.skip_binder().input_types().any(|ty| ty.is_fresh());
+ let unbound_input_types = stack
+ .fresh_trait_ref
+ .skip_binder()
+ .input_types()
+ .any(|ty| ty.is_fresh());
// this check was an imperfect workaround for a bug n the old
// intercrate mode, it should be removed when that goes away.
- if unbound_input_types &&
- self.intercrate == Some(IntercrateMode::Issue43355)
- {
- debug!("evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
- stack.fresh_trait_ref);
+ if unbound_input_types && self.intercrate == Some(IntercrateMode::Issue43355) {
+ debug!(
+ "evaluate_stack({:?}) --> unbound argument, intercrate --> ambiguous",
+ stack.fresh_trait_ref
+ );
// Heuristics: show the diagnostics when there are no candidates in crate.
if self.intercrate_ambiguity_causes.is_some() {
debug!("evaluate_stack: intercrate_ambiguity_causes is some");
},
};
debug!("evaluate_stack: pushing cause = {:?}", cause);
- self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
+ self.intercrate_ambiguity_causes
+ .as_mut()
+ .unwrap()
+ .push(cause);
}
}
}
return Ok(EvaluatedToAmbig);
}
- if unbound_input_types &&
- stack.iter().skip(1).any(
- |prev| stack.obligation.param_env == prev.obligation.param_env &&
- self.match_fresh_trait_refs(&stack.fresh_trait_ref,
- &prev.fresh_trait_ref))
- {
- debug!("evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
- stack.fresh_trait_ref);
+ if unbound_input_types && stack.iter().skip(1).any(|prev| {
+ stack.obligation.param_env == prev.obligation.param_env
+ && self.match_fresh_trait_refs(&stack.fresh_trait_ref, &prev.fresh_trait_ref)
+ }) {
+ debug!(
+ "evaluate_stack({:?}) --> unbound argument, recursive --> giving up",
+ stack.fresh_trait_ref
+ );
return Ok(EvaluatedToUnknown);
}
// `Send`.
//
// Note that we do this comparison using the `fresh_trait_ref`
- // fields. Because these have all been skolemized using
+ // fields. Because these have all been freshened using
// `self.freshener`, we can be sure that (a) this will not
// affect the inferencer state and (b) that if we see two
- // skolemized types with the same index, they refer to the
- // same unbound type variable.
- if let Some(rec_index) =
- stack.iter()
+ // fresh regions with the same index, they refer to the same
+ // unbound type variable.
+ if let Some(rec_index) = stack.iter()
.skip(1) // skip top-most frame
.position(|prev| stack.obligation.param_env == prev.obligation.param_env &&
stack.fresh_trait_ref == prev.fresh_trait_ref)
{
- debug!("evaluate_stack({:?}) --> recursive",
- stack.fresh_trait_ref);
+ debug!("evaluate_stack({:?}) --> recursive", stack.fresh_trait_ref);
let cycle = stack.iter().skip(1).take(rec_index + 1);
let cycle = cycle.map(|stack| ty::Predicate::Trait(stack.obligation.predicate));
if self.coinductive_match(cycle) {
- debug!("evaluate_stack({:?}) --> recursive, coinductive",
- stack.fresh_trait_ref);
+ debug!(
+ "evaluate_stack({:?}) --> recursive, coinductive",
+ stack.fresh_trait_ref
+ );
return Ok(EvaluatedToOk);
} else {
- debug!("evaluate_stack({:?}) --> recursive, inductive",
- stack.fresh_trait_ref);
+ debug!(
+ "evaluate_stack({:?}) --> recursive, inductive",
+ stack.fresh_trait_ref
+ );
return Ok(EvaluatedToRecur);
}
}
Ok(Some(c)) => self.evaluate_candidate(stack, &c),
Ok(None) => Ok(EvaluatedToAmbig),
Err(Overflow) => Err(OverflowError),
- Err(..) => Ok(EvaluatedToErr)
+ Err(..) => Ok(EvaluatedToErr),
}
}
/// - all the predicates at positions `X..` between `X` an the top are
/// also defaulted traits.
pub fn coinductive_match<I>(&mut self, cycle: I) -> bool
- where I: Iterator<Item=ty::Predicate<'tcx>>
+ where
+ I: Iterator<Item = ty::Predicate<'tcx>>,
{
let mut cycle = cycle;
cycle.all(|predicate| self.coinductive_predicate(predicate))
fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool {
let result = match predicate {
- ty::Predicate::Trait(ref data) => {
- self.tcx().trait_is_auto(data.def_id())
- },
- _ => false
+ ty::Predicate::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()),
+ _ => false,
};
debug!("coinductive_predicate({:?}) = {:?}", predicate, result);
result
/// Further evaluate `candidate` to decide whether all type parameters match and whether nested
/// obligations are met. Returns true if `candidate` remains viable after this further
/// scrutiny.
- fn evaluate_candidate<'o>(&mut self,
- stack: &TraitObligationStack<'o, 'tcx>,
- candidate: &SelectionCandidate<'tcx>)
- -> Result<EvaluationResult, OverflowError>
- {
- debug!("evaluate_candidate: depth={} candidate={:?}",
- stack.obligation.recursion_depth, candidate);
+ fn evaluate_candidate<'o>(
+ &mut self,
+ stack: &TraitObligationStack<'o, 'tcx>,
+ candidate: &SelectionCandidate<'tcx>,
+ ) -> Result<EvaluationResult, OverflowError> {
+ debug!(
+ "evaluate_candidate: depth={} candidate={:?}",
+ stack.obligation.recursion_depth, candidate
+ );
let result = self.probe(|this, _| {
let candidate = (*candidate).clone();
match this.confirm_candidate(stack.obligation, candidate) {
- Ok(selection) => {
- this.evaluate_predicates_recursively(
- stack.list(),
- selection.nested_obligations().iter())
- }
- Err(..) => Ok(EvaluatedToErr)
+ Ok(selection) => this.evaluate_predicates_recursively(
+ stack.list(),
+ selection.nested_obligations().iter(),
+ ),
+ Err(..) => Ok(EvaluatedToErr),
}
})?;
- debug!("evaluate_candidate: depth={} result={:?}",
- stack.obligation.recursion_depth, result);
+ debug!(
+ "evaluate_candidate: depth={} result={:?}",
+ stack.obligation.recursion_depth, result
+ );
Ok(result)
}
- fn check_evaluation_cache(&self,
- param_env: ty::ParamEnv<'tcx>,
- trait_ref: ty::PolyTraitRef<'tcx>)
- -> Option<EvaluationResult>
- {
+ fn check_evaluation_cache(
+ &self,
+ param_env: ty::ParamEnv<'tcx>,
+ trait_ref: ty::PolyTraitRef<'tcx>,
+ ) -> Option<EvaluationResult> {
let tcx = self.tcx();
if self.can_use_global_caches(param_env) {
let cache = tcx.evaluation_cache.hashmap.borrow();
return Some(cached.get(tcx));
}
}
- self.infcx.evaluation_cache.hashmap
- .borrow()
- .get(&trait_ref)
- .map(|v| v.get(tcx))
+ self.infcx
+ .evaluation_cache
+ .hashmap
+ .borrow()
+ .get(&trait_ref)
+ .map(|v| v.get(tcx))
}
- fn insert_evaluation_cache(&mut self,
- param_env: ty::ParamEnv<'tcx>,
- trait_ref: ty::PolyTraitRef<'tcx>,
- dep_node: DepNodeIndex,
- result: EvaluationResult)
- {
+ fn insert_evaluation_cache(
+ &mut self,
+ param_env: ty::ParamEnv<'tcx>,
+ trait_ref: ty::PolyTraitRef<'tcx>,
+ dep_node: DepNodeIndex,
+ result: EvaluationResult,
+ ) {
// Avoid caching results that depend on more than just the trait-ref
// - the stack can create recursion.
if result.is_stack_dependent() {
if let Some(trait_ref) = self.tcx().lift_to_global(&trait_ref) {
debug!(
"insert_evaluation_cache(trait_ref={:?}, candidate={:?}) global",
- trait_ref,
- result,
+ trait_ref, result,
);
// This may overwrite the cache with the same value
// FIXME: Due to #50507 this overwrites the different values
// This should be changed to use HashMapExt::insert_same
// when that is fixed
- self.tcx().evaluation_cache
- .hashmap.borrow_mut()
- .insert(trait_ref, WithDepNode::new(dep_node, result));
+ self.tcx()
+ .evaluation_cache
+ .hashmap
+ .borrow_mut()
+ .insert(trait_ref, WithDepNode::new(dep_node, result));
return;
}
}
debug!(
"insert_evaluation_cache(trait_ref={:?}, candidate={:?})",
- trait_ref,
- result,
+ trait_ref, result,
);
- self.infcx.evaluation_cache.hashmap
- .borrow_mut()
- .insert(trait_ref, WithDepNode::new(dep_node, result));
+ self.infcx
+ .evaluation_cache
+ .hashmap
+ .borrow_mut()
+ .insert(trait_ref, WithDepNode::new(dep_node, result));
}
///////////////////////////////////////////////////////////////////////////
// [rustc guide]:
// https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#candidate-assembly
- fn candidate_from_obligation<'o>(&mut self,
- stack: &TraitObligationStack<'o, 'tcx>)
- -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
- {
+ fn candidate_from_obligation<'o>(
+ &mut self,
+ stack: &TraitObligationStack<'o, 'tcx>,
+ ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
// Watch out for overflow. This intentionally bypasses (and does
// not update) the cache.
let recursion_limit = *self.infcx.tcx.sess.recursion_limit.get();
match self.query_mode {
TraitQueryMode::Standard => {
self.infcx().report_overflow_error(&stack.obligation, true);
- },
+ }
TraitQueryMode::Canonical => {
return Err(Overflow);
- },
+ }
}
}
- // Check the cache. Note that we skolemize the trait-ref
- // separately rather than using `stack.fresh_trait_ref` -- this
- // is because we want the unbound variables to be replaced
- // with fresh skolemized types starting from index 0.
- let cache_fresh_trait_pred =
- self.infcx.freshen(stack.obligation.predicate.clone());
- debug!("candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
- cache_fresh_trait_pred,
- stack);
+ // Check the cache. Note that we freshen the trait-ref
+ // separately rather than using `stack.fresh_trait_ref` --
+ // this is because we want the unbound variables to be
+ // replaced with fresh types starting from index 0.
+ let cache_fresh_trait_pred = self.infcx.freshen(stack.obligation.predicate.clone());
+ debug!(
+ "candidate_from_obligation(cache_fresh_trait_pred={:?}, obligation={:?})",
+ cache_fresh_trait_pred, stack
+ );
debug_assert!(!stack.obligation.predicate.has_escaping_regions());
- if let Some(c) = self.check_candidate_cache(stack.obligation.param_env,
- &cache_fresh_trait_pred) {
- debug!("CACHE HIT: SELECT({:?})={:?}",
- cache_fresh_trait_pred,
- c);
+ if let Some(c) =
+ self.check_candidate_cache(stack.obligation.param_env, &cache_fresh_trait_pred)
+ {
+ debug!("CACHE HIT: SELECT({:?})={:?}", cache_fresh_trait_pred, c);
return c;
}
// If no match, compute result and insert into cache.
- let (candidate, dep_node) = self.in_task(|this|
- this.candidate_from_obligation_no_cache(stack)
- );
+ let (candidate, dep_node) =
+ self.in_task(|this| this.candidate_from_obligation_no_cache(stack));
- debug!("CACHE MISS: SELECT({:?})={:?}",
- cache_fresh_trait_pred, candidate);
- self.insert_candidate_cache(stack.obligation.param_env,
- cache_fresh_trait_pred,
- dep_node,
- candidate.clone());
+ debug!(
+ "CACHE MISS: SELECT({:?})={:?}",
+ cache_fresh_trait_pred, candidate
+ );
+ self.insert_candidate_cache(
+ stack.obligation.param_env,
+ cache_fresh_trait_pred,
+ dep_node,
+ candidate.clone(),
+ );
candidate
}
fn in_task<OP, R>(&mut self, op: OP) -> (R, DepNodeIndex)
- where OP: FnOnce(&mut Self) -> R
+ where
+ OP: FnOnce(&mut Self) -> R,
{
- let (result, dep_node) = self.tcx().dep_graph.with_anon_task(DepKind::TraitSelect, ||
- op(self)
- );
+ let (result, dep_node) = self.tcx()
+ .dep_graph
+ .with_anon_task(DepKind::TraitSelect, || op(self));
self.tcx().dep_graph.read_index(dep_node);
(result, dep_node)
}
// Treat negative impls as unimplemented
- fn filter_negative_impls(&self, candidate: SelectionCandidate<'tcx>)
- -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
+ fn filter_negative_impls(
+ &self,
+ candidate: SelectionCandidate<'tcx>,
+ ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
if let ImplCandidate(def_id) = candidate {
- if !self.allow_negative_impls &&
- self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative {
- return Err(Unimplemented)
+ if !self.allow_negative_impls
+ && self.tcx().impl_polarity(def_id) == hir::ImplPolarity::Negative
+ {
+ return Err(Unimplemented);
}
}
Ok(Some(candidate))
}
- fn candidate_from_obligation_no_cache<'o>(&mut self,
- stack: &TraitObligationStack<'o, 'tcx>)
- -> SelectionResult<'tcx, SelectionCandidate<'tcx>>
- {
+ fn candidate_from_obligation_no_cache<'o>(
+ &mut self,
+ stack: &TraitObligationStack<'o, 'tcx>,
+ ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> {
if stack.obligation.predicate.references_error() {
// If we encounter a `Error`, we generally prefer the
// most "optimistic" result in response -- that is, the
if let Ok(candidate_set) = self.assemble_candidates(stack) {
let mut no_candidates_apply = true;
{
- let evaluated_candidates = candidate_set.vec.iter().map(|c|
- self.evaluate_candidate(stack, &c));
+ let evaluated_candidates = candidate_set
+ .vec
+ .iter()
+ .map(|c| self.evaluate_candidate(stack, &c));
for ec in evaluated_candidates {
match ec {
Ok(c) => {
if c.may_apply() {
no_candidates_apply = false;
- break
+ break;
}
- },
- Err(e) => return Err(e.into())
+ }
+ Err(e) => return Err(e.into()),
}
}
}
self_desc,
}
} else {
- IntercrateAmbiguityCause::DownstreamCrate { trait_desc, self_desc }
+ IntercrateAmbiguityCause::DownstreamCrate {
+ trait_desc,
+ self_desc,
+ }
};
debug!("evaluate_stack: pushing cause = {:?}", cause);
- self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause);
+ self.intercrate_ambiguity_causes
+ .as_mut()
+ .unwrap()
+ .push(cause);
}
}
}
let mut candidates = candidate_set.vec;
- debug!("assembled {} candidates for {:?}: {:?}",
- candidates.len(),
- stack,
- candidates);
+ debug!(
+ "assembled {} candidates for {:?}: {:?}",
+ candidates.len(),
+ stack,
+ candidates
+ );
// At this point, we know that each of the entries in the
// candidate set is *individually* applicable. Now we have to
let mut candidates: Vec<EvaluatedCandidate<'_>> =
candidates?.into_iter().filter_map(|c| c).collect();
- debug!("winnowed to {} candidates for {:?}: {:?}",
- candidates.len(),
- stack,
- candidates);
+ debug!(
+ "winnowed to {} candidates for {:?}: {:?}",
+ candidates.len(),
+ stack,
+ candidates
+ );
// If there are STILL multiple candidate, we can further
// reduce the list by dropping duplicates -- including
if candidates.len() > 1 {
let mut i = 0;
while i < candidates.len() {
- let is_dup =
- (0..candidates.len())
- .filter(|&j| i != j)
- .any(|j| self.candidate_should_be_dropped_in_favor_of(&candidates[i],
- &candidates[j]));
+ let is_dup = (0..candidates.len()).filter(|&j| i != j).any(|j| {
+ self.candidate_should_be_dropped_in_favor_of(&candidates[i], &candidates[j])
+ });
if is_dup {
- debug!("Dropping candidate #{}/{}: {:?}",
- i, candidates.len(), candidates[i]);
+ debug!(
+ "Dropping candidate #{}/{}: {:?}",
+ i,
+ candidates.len(),
+ candidates[i]
+ );
candidates.swap_remove(i);
} else {
- debug!("Retaining candidate #{}/{}: {:?}",
- i, candidates.len(), candidates[i]);
+ debug!(
+ "Retaining candidate #{}/{}: {:?}",
+ i,
+ candidates.len(),
+ candidates[i]
+ );
i += 1;
// If there are *STILL* multiple candidates, give up
self.filter_negative_impls(candidates.pop().unwrap().candidate)
}
- fn is_knowable<'o>(&mut self,
- stack: &TraitObligationStack<'o, 'tcx>)
- -> Option<Conflict>
- {
+ fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option<Conflict> {
debug!("is_knowable(intercrate={:?})", self.intercrate);
if !self.intercrate.is_some() {
}
let obligation = &stack.obligation;
- let predicate = self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
+ let predicate = self.infcx()
+ .resolve_type_vars_if_possible(&obligation.predicate);
// ok to skip binder because of the nature of the
// trait-ref-is-knowable check, which does not care about
let trait_ref = predicate.skip_binder().trait_ref;
let result = coherence::trait_ref_is_knowable(self.tcx(), trait_ref);
- if let (Some(Conflict::Downstream { used_to_be_broken: true }),
- Some(IntercrateMode::Issue43355)) = (result, self.intercrate) {
+ if let (
+ Some(Conflict::Downstream {
+ used_to_be_broken: true,
+ }),
+ Some(IntercrateMode::Issue43355),
+ ) = (result, self.intercrate)
+ {
debug!("is_knowable: IGNORING conflict to be bug-compatible with #43355");
None
} else {
true
}
- fn check_candidate_cache(&mut self,
- param_env: ty::ParamEnv<'tcx>,
- cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>)
- -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>>
- {
+ fn check_candidate_cache(
+ &mut self,
+ param_env: ty::ParamEnv<'tcx>,
+ cache_fresh_trait_pred: &ty::PolyTraitPredicate<'tcx>,
+ ) -> Option<SelectionResult<'tcx, SelectionCandidate<'tcx>>> {
let tcx = self.tcx();
let trait_ref = &cache_fresh_trait_pred.skip_binder().trait_ref;
if self.can_use_global_caches(param_env) {
return Some(cached.get(tcx));
}
}
- self.infcx.selection_cache.hashmap
- .borrow()
- .get(trait_ref)
- .map(|v| v.get(tcx))
+ self.infcx
+ .selection_cache
+ .hashmap
+ .borrow()
+ .get(trait_ref)
+ .map(|v| v.get(tcx))
}
- fn insert_candidate_cache(&mut self,
- param_env: ty::ParamEnv<'tcx>,
- cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
- dep_node: DepNodeIndex,
- candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>)
- {
+ fn insert_candidate_cache(
+ &mut self,
+ param_env: ty::ParamEnv<'tcx>,
+ cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>,
+ dep_node: DepNodeIndex,
+ candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>,
+ ) {
let tcx = self.tcx();
let trait_ref = cache_fresh_trait_pred.skip_binder().trait_ref;
if self.can_use_global_caches(param_env) {
if let Some(candidate) = tcx.lift_to_global(&candidate) {
debug!(
"insert_candidate_cache(trait_ref={:?}, candidate={:?}) global",
- trait_ref,
- candidate,
+ trait_ref, candidate,
);
// This may overwrite the cache with the same value
tcx.selection_cache
- .hashmap.borrow_mut()
- .insert(trait_ref, WithDepNode::new(dep_node, candidate));
+ .hashmap
+ .borrow_mut()
+ .insert(trait_ref, WithDepNode::new(dep_node, candidate));
return;
}
}
debug!(
"insert_candidate_cache(trait_ref={:?}, candidate={:?}) local",
- trait_ref,
- candidate,
+ trait_ref, candidate,
);
- self.infcx.selection_cache.hashmap
- .borrow_mut()
- .insert(trait_ref, WithDepNode::new(dep_node, candidate));
+ self.infcx
+ .selection_cache
+ .hashmap
+ .borrow_mut()
+ .insert(trait_ref, WithDepNode::new(dep_node, candidate));
}
- fn assemble_candidates<'o>(&mut self,
- stack: &TraitObligationStack<'o, 'tcx>)
- -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>>
- {
- let obligation = stack.obligation;
+ fn assemble_candidates<'o>(
+ &mut self,
+ stack: &TraitObligationStack<'o, 'tcx>,
+ ) -> Result<SelectionCandidateSet<'tcx>, SelectionError<'tcx>> {
+ let TraitObligationStack { obligation, .. } = *stack;
let ref obligation = Obligation {
param_env: obligation.param_env,
cause: obligation.cause.clone(),
recursion_depth: obligation.recursion_depth,
- predicate: self.infcx().resolve_type_vars_if_possible(&obligation.predicate)
+ predicate: self.infcx()
+ .resolve_type_vars_if_possible(&obligation.predicate),
};
if obligation.predicate.skip_binder().self_ty().is_ty_var() {
// Take the fast path out - this also improves
// performance by preventing assemble_candidates_from_impls from
// matching every impl for this trait.
- return Ok(SelectionCandidateSet { vec: vec![], ambiguous: true });
+ return Ok(SelectionCandidateSet {
+ vec: vec![],
+ ambiguous: true,
+ });
}
let mut candidates = SelectionCandidateSet {
vec: Vec::new(),
- ambiguous: false
+ ambiguous: false,
};
// Other bounds. Consider both in-scope bounds from fn decl
let lang_items = self.tcx().lang_items();
if lang_items.copy_trait() == Some(def_id) {
- debug!("obligation self ty is {:?}",
- obligation.predicate.skip_binder().self_ty());
+ debug!(
+ "obligation self ty is {:?}",
+ obligation.predicate.skip_binder().self_ty()
+ );
// User-defined copy impls are permitted, but only for
// structs and enums.
// Sized is never implementable by end-users, it is
// always automatically computed.
let sized_conditions = self.sized_conditions(obligation);
- self.assemble_builtin_bound_candidates(sized_conditions,
- &mut candidates)?;
+ self.assemble_builtin_bound_candidates(sized_conditions, &mut candidates)?;
} else if lang_items.unsize_trait() == Some(def_id) {
self.assemble_candidates_for_unsizing(obligation, &mut candidates);
} else {
Ok(candidates)
}
- fn assemble_candidates_from_projected_tys(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- {
+ fn assemble_candidates_from_projected_tys(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) {
debug!("assemble_candidates_for_projected_tys({:?})", obligation);
- // before we go into the whole skolemization thing, just
+ // before we go into the whole placeholder thing, just
// quickly check if the self-type is a projection at all.
match obligation.predicate.skip_binder().trait_ref.self_ty().sty {
ty::Projection(_) | ty::Opaque(..) => {}
ty::Infer(ty::TyVar(_)) => {
- span_bug!(obligation.cause.span,
- "Self=_ should have been handled by assemble_candidates");
+ span_bug!(
+ obligation.cause.span,
+ "Self=_ should have been handled by assemble_candidates"
+ );
}
- _ => return
+ _ => return,
}
- let result = self.probe(|this, snapshot|
- this.match_projection_obligation_against_definition_bounds(obligation,
- snapshot)
- );
+ let result = self.probe(|this, snapshot| {
+ this.match_projection_obligation_against_definition_bounds(obligation, snapshot)
+ });
if result {
candidates.vec.push(ProjectionCandidate);
fn match_projection_obligation_against_definition_bounds(
&mut self,
obligation: &TraitObligation<'tcx>,
- snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
- -> bool
- {
- let poly_trait_predicate =
- self.infcx().resolve_type_vars_if_possible(&obligation.predicate);
- let (skol_trait_predicate, skol_map) =
- self.infcx().skolemize_late_bound_regions(&poly_trait_predicate);
- debug!("match_projection_obligation_against_definition_bounds: \
- skol_trait_predicate={:?} skol_map={:?}",
- skol_trait_predicate,
- skol_map);
+ snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
+ ) -> bool {
+ let poly_trait_predicate = self.infcx()
+ .resolve_type_vars_if_possible(&obligation.predicate);
+ let (skol_trait_predicate, placeholder_map) = self.infcx()
+ .replace_late_bound_regions_with_placeholders(&poly_trait_predicate);
+ debug!(
+ "match_projection_obligation_against_definition_bounds: \
+ skol_trait_predicate={:?} placeholder_map={:?}",
+ skol_trait_predicate, placeholder_map
+ );
let (def_id, substs) = match skol_trait_predicate.trait_ref.self_ty().sty {
- ty::Projection(ref data) =>
- (data.trait_ref(self.tcx()).def_id, data.substs),
+ ty::Projection(ref data) => (data.trait_ref(self.tcx()).def_id, data.substs),
ty::Opaque(def_id, substs) => (def_id, substs),
_ => {
span_bug!(
obligation.cause.span,
"match_projection_obligation_against_definition_bounds() called \
but self-ty is not a projection: {:?}",
- skol_trait_predicate.trait_ref.self_ty());
+ skol_trait_predicate.trait_ref.self_ty()
+ );
}
};
- debug!("match_projection_obligation_against_definition_bounds: \
- def_id={:?}, substs={:?}",
- def_id, substs);
+ debug!(
+ "match_projection_obligation_against_definition_bounds: \
+ def_id={:?}, substs={:?}",
+ def_id, substs
+ );
let predicates_of = self.tcx().predicates_of(def_id);
let bounds = predicates_of.instantiate(self.tcx(), substs);
- debug!("match_projection_obligation_against_definition_bounds: \
- bounds={:?}",
- bounds);
+ debug!(
+ "match_projection_obligation_against_definition_bounds: \
+ bounds={:?}",
+ bounds
+ );
- let matching_bound =
- util::elaborate_predicates(self.tcx(), bounds.predicates)
+ let matching_bound = util::elaborate_predicates(self.tcx(), bounds.predicates)
.filter_to_traits()
- .find(
- |bound| self.probe(
- |this, _| this.match_projection(obligation,
- bound.clone(),
- skol_trait_predicate.trait_ref.clone(),
- &skol_map,
- snapshot)));
-
- debug!("match_projection_obligation_against_definition_bounds: \
- matching_bound={:?}",
- matching_bound);
+ .find(|bound| {
+ self.probe(|this, _| {
+ this.match_projection(
+ obligation,
+ bound.clone(),
+ skol_trait_predicate.trait_ref.clone(),
+ &placeholder_map,
+ snapshot,
+ )
+ })
+ });
+
+ debug!(
+ "match_projection_obligation_against_definition_bounds: \
+ matching_bound={:?}",
+ matching_bound
+ );
match matching_bound {
None => false,
Some(bound) => {
// Repeat the successful match, if any, this time outside of a probe.
- let result = self.match_projection(obligation,
- bound,
- skol_trait_predicate.trait_ref.clone(),
- &skol_map,
- snapshot);
+ let result = self.match_projection(
+ obligation,
+ bound,
+ skol_trait_predicate.trait_ref.clone(),
+ &placeholder_map,
+ snapshot,
+ );
- self.infcx.pop_skolemized(skol_map, snapshot);
+ self.infcx.pop_placeholders(placeholder_map, snapshot);
assert!(result);
true
}
}
- fn match_projection(&mut self,
- obligation: &TraitObligation<'tcx>,
- trait_bound: ty::PolyTraitRef<'tcx>,
- skol_trait_ref: ty::TraitRef<'tcx>,
- skol_map: &infer::SkolemizationMap<'tcx>,
- snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
- -> bool
- {
+ fn match_projection(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ trait_bound: ty::PolyTraitRef<'tcx>,
+ skol_trait_ref: ty::TraitRef<'tcx>,
+ placeholder_map: &infer::PlaceholderMap<'tcx>,
+ snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
+ ) -> bool {
debug_assert!(!skol_trait_ref.has_escaping_regions());
- if self.infcx.at(&obligation.cause, obligation.param_env)
- .sup(ty::Binder::dummy(skol_trait_ref), trait_bound).is_err() {
+ if self.infcx
+ .at(&obligation.cause, obligation.param_env)
+ .sup(ty::Binder::dummy(skol_trait_ref), trait_bound)
+ .is_err()
+ {
return false;
}
- self.infcx.leak_check(false, obligation.cause.span, skol_map, snapshot).is_ok()
+ self.infcx
+ .leak_check(false, obligation.cause.span, placeholder_map, snapshot)
+ .is_ok()
}
/// Given an obligation like `<SomeTrait for T>`, search the obligations that the caller
/// supplied to find out whether it is listed among them.
///
/// Never affects inference environment.
- fn assemble_candidates_from_caller_bounds<'o>(&mut self,
- stack: &TraitObligationStack<'o, 'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- -> Result<(),SelectionError<'tcx>>
- {
- debug!("assemble_candidates_from_caller_bounds({:?})",
- stack.obligation);
+ fn assemble_candidates_from_caller_bounds<'o>(
+ &mut self,
+ stack: &TraitObligationStack<'o, 'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) -> Result<(), SelectionError<'tcx>> {
+ debug!(
+ "assemble_candidates_from_caller_bounds({:?})",
+ stack.obligation
+ );
- let all_bounds =
- stack.obligation.param_env.caller_bounds
- .iter()
- .filter_map(|o| o.to_opt_poly_trait_ref());
+ let all_bounds = stack
+ .obligation
+ .param_env
+ .caller_bounds
+ .iter()
+ .filter_map(|o| o.to_opt_poly_trait_ref());
// micro-optimization: filter out predicates relating to different
// traits.
Ok(())
}
- fn evaluate_where_clause<'o>(&mut self,
- stack: &TraitObligationStack<'o, 'tcx>,
- where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
- -> Result<EvaluationResult, OverflowError>
- {
- self.probe(move |this, _|
+ fn evaluate_where_clause<'o>(
+ &mut self,
+ stack: &TraitObligationStack<'o, 'tcx>,
+ where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
+ ) -> Result<EvaluationResult, OverflowError> {
+ self.probe(move |this, _| {
match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) {
Ok(obligations) => {
this.evaluate_predicates_recursively(stack.list(), obligations.iter())
}
- Err(()) => Ok(EvaluatedToErr)
+ Err(()) => Ok(EvaluatedToErr),
}
- )
+ })
}
- fn assemble_generator_candidates(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- -> Result<(),SelectionError<'tcx>>
- {
+ fn assemble_generator_candidates(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) -> Result<(), SelectionError<'tcx>> {
if self.tcx().lang_items().gen_trait() != Some(obligation.predicate.def_id()) {
return Ok(());
}
let self_ty = *obligation.self_ty().skip_binder();
match self_ty.sty {
ty::Generator(..) => {
- debug!("assemble_generator_candidates: self_ty={:?} obligation={:?}",
- self_ty,
- obligation);
+ debug!(
+ "assemble_generator_candidates: self_ty={:?} obligation={:?}",
+ self_ty, obligation
+ );
candidates.vec.push(GeneratorCandidate);
}
/// Note: the type parameters on a closure candidate are modeled as *output* type
/// parameters and hence do not affect whether this trait is a match or not. They will be
/// unified during the confirmation step.
- fn assemble_closure_candidates(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- -> Result<(),SelectionError<'tcx>>
- {
- let kind = match self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()) {
+ fn assemble_closure_candidates(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) -> Result<(), SelectionError<'tcx>> {
+ let kind = match self.tcx()
+ .lang_items()
+ .fn_trait_kind(obligation.predicate.def_id())
+ {
Some(k) => k,
- None => { return Ok(()); }
+ None => {
+ return Ok(());
+ }
};
// ok to skip binder because the substs on closure types never
// type/region parameters
match obligation.self_ty().skip_binder().sty {
ty::Closure(closure_def_id, closure_substs) => {
- debug!("assemble_unboxed_candidates: kind={:?} obligation={:?}",
- kind, obligation);
+ debug!(
+ "assemble_unboxed_candidates: kind={:?} obligation={:?}",
+ kind, obligation
+ );
match self.infcx.closure_kind(closure_def_id, closure_substs) {
Some(closure_kind) => {
- debug!("assemble_unboxed_candidates: closure_kind = {:?}", closure_kind);
+ debug!(
+ "assemble_unboxed_candidates: closure_kind = {:?}",
+ closure_kind
+ );
if closure_kind.extends(kind) {
candidates.vec.push(ClosureCandidate);
}
}
/// Implement one of the `Fn()` family for a fn pointer.
- fn assemble_fn_pointer_candidates(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- -> Result<(),SelectionError<'tcx>>
- {
+ fn assemble_fn_pointer_candidates(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) -> Result<(), SelectionError<'tcx>> {
// We provide impl of all fn traits for fn pointers.
- if self.tcx().lang_items().fn_trait_kind(obligation.predicate.def_id()).is_none() {
+ if self.tcx()
+ .lang_items()
+ .fn_trait_kind(obligation.predicate.def_id())
+ .is_none()
+ {
return Ok(());
}
abi: Abi::Rust,
variadic: false,
..
- } = self_ty.fn_sig(self.tcx()).skip_binder() {
+ } = self_ty.fn_sig(self.tcx()).skip_binder()
+ {
candidates.vec.push(FnPointerCandidate);
}
}
}
/// Search for impls that might apply to `obligation`.
- fn assemble_candidates_from_impls(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- -> Result<(), SelectionError<'tcx>>
- {
- debug!("assemble_candidates_from_impls(obligation={:?})", obligation);
+ fn assemble_candidates_from_impls(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) -> Result<(), SelectionError<'tcx>> {
+ debug!(
+ "assemble_candidates_from_impls(obligation={:?})",
+ obligation
+ );
self.tcx().for_each_relevant_impl(
obligation.predicate.def_id(),
obligation.predicate.skip_binder().trait_ref.self_ty(),
|impl_def_id| {
- self.probe(|this, snapshot| /* [1] */
- if let Ok(skol_map) = this.match_impl(impl_def_id, obligation, snapshot) {
+ self.probe(|this, snapshot| {
+ if let Ok(placeholder_map) = this.match_impl(impl_def_id, obligation, snapshot)
+ {
candidates.vec.push(ImplCandidate(impl_def_id));
- // NB: we can safely drop the skol map
- // since we are in a probe [1]
- mem::drop(skol_map);
+ // NB: we can safely drop the placeholder map
+ // since we are in a probe.
+ mem::drop(placeholder_map);
}
- );
- }
+ });
+ },
);
Ok(())
}
- fn assemble_candidates_from_auto_impls(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- -> Result<(), SelectionError<'tcx>>
- {
+ fn assemble_candidates_from_auto_impls(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) -> Result<(), SelectionError<'tcx>> {
// OK to skip binder here because the tests we do below do not involve bound regions
let self_ty = *obligation.self_ty().skip_binder();
debug!("assemble_candidates_from_auto_impls(self_ty={:?})", self_ty);
// still be provided by a manual implementation for
// this trait and type.
}
- ty::Param(..) |
- ty::Projection(..) => {
+ ty::Param(..) | ty::Projection(..) => {
// In these cases, we don't know what the actual
// type is. Therefore, we cannot break it down
// into its constituent types. So we don't
// the auto impl might apply, we don't know
candidates.ambiguous = true;
}
- _ => {
- candidates.vec.push(AutoImplCandidate(def_id.clone()))
- }
+ _ => candidates.vec.push(AutoImplCandidate(def_id.clone())),
}
}
}
/// Search for impls that might apply to `obligation`.
- fn assemble_candidates_from_object_ty(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- {
- debug!("assemble_candidates_from_object_ty(self_ty={:?})",
- obligation.self_ty().skip_binder());
+ fn assemble_candidates_from_object_ty(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) {
+ debug!(
+ "assemble_candidates_from_object_ty(self_ty={:?})",
+ obligation.self_ty().skip_binder()
+ );
// Object-safety candidates are only applicable to object-safe
// traits. Including this check is useful because it helps
let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty());
let poly_trait_ref = match self_ty.sty {
ty::Dynamic(ref data, ..) => {
- if data.auto_traits().any(|did| did == obligation.predicate.def_id()) {
- debug!("assemble_candidates_from_object_ty: matched builtin bound, \
- pushing candidate");
+ if data.auto_traits()
+ .any(|did| did == obligation.predicate.def_id())
+ {
+ debug!(
+ "assemble_candidates_from_object_ty: matched builtin bound, \
+ pushing candidate"
+ );
candidates.vec.push(BuiltinObjectCandidate);
return;
}
candidates.ambiguous = true; // could wind up being an object type
return;
}
- _ => return
+ _ => return,
};
- debug!("assemble_candidates_from_object_ty: poly_trait_ref={:?}",
- poly_trait_ref);
+ debug!(
+ "assemble_candidates_from_object_ty: poly_trait_ref={:?}",
+ poly_trait_ref
+ );
// Count only those upcast versions that match the trait-ref
// we are looking for. Specifically, do not only check for the
// correct trait, but also the correct type parameters.
// For example, we may be trying to upcast `Foo` to `Bar<i32>`,
// but `Foo` is declared as `trait Foo : Bar<u32>`.
- let upcast_trait_refs =
- util::supertraits(this.tcx(), poly_trait_ref)
- .filter(|upcast_trait_ref|
+ let upcast_trait_refs = util::supertraits(this.tcx(), poly_trait_ref)
+ .filter(|upcast_trait_ref| {
this.probe(|this, _| {
let upcast_trait_ref = upcast_trait_ref.clone();
- this.match_poly_trait_ref(obligation, upcast_trait_ref).is_ok()
+ this.match_poly_trait_ref(obligation, upcast_trait_ref)
+ .is_ok()
})
- )
+ })
.count();
if upcast_trait_refs > 1 {
}
/// Search for unsizing that might apply to `obligation`.
- fn assemble_candidates_for_unsizing(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>) {
+ fn assemble_candidates_for_unsizing(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) {
// We currently never consider higher-ranked obligations e.g.
// `for<'a> &'a T: Unsize<Trait+'a>` to be implemented. This is not
// because they are a priori invalid, and we could potentially add support
return;
}
};
- let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
+ let target = obligation
+ .predicate
+ .skip_binder()
+ .trait_ref
+ .substs
+ .type_at(1);
- debug!("assemble_candidates_for_unsizing(source={:?}, target={:?})",
- source, target);
+ debug!(
+ "assemble_candidates_for_unsizing(source={:?}, target={:?})",
+ source, target
+ );
let may_apply = match (&source.sty, &target.sty) {
// Trait+Kx+'a -> Trait+Ky+'b (upcasts).
// We always upcast when we can because of reason
// #2 (region bounds).
match (data_a.principal(), data_b.principal()) {
- (Some(a), Some(b)) => a.def_id() == b.def_id() &&
- data_b.auto_traits()
+ (Some(a), Some(b)) => {
+ a.def_id() == b.def_id()
+ && data_b.auto_traits()
// All of a's auto traits need to be in b's auto traits.
- .all(|b| data_a.auto_traits().any(|a| a == b)),
- _ => false
+ .all(|b| data_a.auto_traits().any(|a| a == b))
+ }
+ _ => false,
}
}
// Ambiguous handling is below T -> Trait, because inference
// variables can still implement Unsize<Trait> and nested
// obligations will have the final say (likely deferred).
- (&ty::Infer(ty::TyVar(_)), _) |
- (_, &ty::Infer(ty::TyVar(_))) => {
+ (&ty::Infer(ty::TyVar(_)), _) | (_, &ty::Infer(ty::TyVar(_))) => {
debug!("assemble_candidates_for_unsizing: ambiguous");
candidates.ambiguous = true;
false
}
// (.., T) -> (.., U).
- (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
- tys_a.len() == tys_b.len()
- }
+ (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => tys_a.len() == tys_b.len(),
- _ => false
+ _ => false,
};
if may_apply {
//
// Winnowing is the process of attempting to resolve ambiguity by
// probing further. During the winnowing process, we unify all
- // type variables (ignoring skolemization) and then we also
- // attempt to evaluate recursive bounds to see if they are
- // satisfied.
+ // type variables and then we also attempt to evaluate recursive
+ // bounds to see if they are satisfied.
/// Returns true if `victim` should be dropped in favor of
/// `other`. Generally speaking we will drop duplicate
fn candidate_should_be_dropped_in_favor_of<'o>(
&mut self,
victim: &EvaluatedCandidate<'tcx>,
- other: &EvaluatedCandidate<'tcx>)
- -> bool
- {
+ other: &EvaluatedCandidate<'tcx>,
+ ) -> bool {
if victim.candidate == other.candidate {
return true;
}
// Check if a bound would previously have been removed when normalizing
// the param_env so that it can be given the lowest priority. See
// #50825 for the motivation for this.
- let is_global = |cand: &ty::PolyTraitRef<'_>| {
- cand.is_global() && !cand.has_late_bound_regions()
- };
+ let is_global =
+ |cand: &ty::PolyTraitRef<'_>| cand.is_global() && !cand.has_late_bound_regions();
match other.candidate {
// Prefer BuiltinCandidate { has_nested: false } to anything else.
BuiltinCandidate { has_nested: false } => true,
ParamCandidate(ref cand) => match victim.candidate {
AutoImplCandidate(..) => {
- bug!("default implementations shouldn't be recorded \
- when there are other valid candidates");
+ bug!(
+ "default implementations shouldn't be recorded \
+ when there are other valid candidates"
+ );
}
// Prefer BuiltinCandidate { has_nested: false } to anything else.
// This is a fix for #53123 and prevents winnowing from accidentally extending the
// lifetime of a variable.
BuiltinCandidate { has_nested: false } => false,
- ImplCandidate(..) |
- ClosureCandidate |
- GeneratorCandidate |
- FnPointerCandidate |
- BuiltinObjectCandidate |
- BuiltinUnsizeCandidate |
- BuiltinCandidate { .. } => {
+ ImplCandidate(..)
+ | ClosureCandidate
+ | GeneratorCandidate
+ | FnPointerCandidate
+ | BuiltinObjectCandidate
+ | BuiltinUnsizeCandidate
+ | BuiltinCandidate { .. } => {
// Global bounds from the where clause should be ignored
// here (see issue #50825). Otherwise, we have a where
// clause so don't go around looking for impls.
!is_global(cand)
}
- ObjectCandidate |
- ProjectionCandidate => {
+ ObjectCandidate | ProjectionCandidate => {
// Arbitrarily give param candidates priority
// over projection and object candidates.
!is_global(cand)
- },
+ }
ParamCandidate(..) => false,
},
- ObjectCandidate |
- ProjectionCandidate => match victim.candidate {
+ ObjectCandidate | ProjectionCandidate => match victim.candidate {
AutoImplCandidate(..) => {
- bug!("default implementations shouldn't be recorded \
- when there are other valid candidates");
+ bug!(
+ "default implementations shouldn't be recorded \
+ when there are other valid candidates"
+ );
}
// Prefer BuiltinCandidate { has_nested: false } to anything else.
// This is a fix for #53123 and prevents winnowing from accidentally extending the
// lifetime of a variable.
BuiltinCandidate { has_nested: false } => false,
- ImplCandidate(..) |
- ClosureCandidate |
- GeneratorCandidate |
- FnPointerCandidate |
- BuiltinObjectCandidate |
- BuiltinUnsizeCandidate |
- BuiltinCandidate { .. } => {
- true
- }
- ObjectCandidate |
- ProjectionCandidate => {
+ ImplCandidate(..)
+ | ClosureCandidate
+ | GeneratorCandidate
+ | FnPointerCandidate
+ | BuiltinObjectCandidate
+ | BuiltinUnsizeCandidate
+ | BuiltinCandidate { .. } => true,
+ ObjectCandidate | ProjectionCandidate => {
// Arbitrarily give param candidates priority
// over projection and object candidates.
true
- },
+ }
ParamCandidate(ref cand) => is_global(cand),
},
ImplCandidate(other_def) => {
match victim.candidate {
ImplCandidate(victim_def) => {
let tcx = self.tcx().global_tcx();
- return tcx.specializes((other_def, victim_def)) ||
- tcx.impls_are_allowed_to_overlap(other_def, victim_def);
+ return tcx.specializes((other_def, victim_def))
+ || tcx.impls_are_allowed_to_overlap(other_def, victim_def);
}
ParamCandidate(ref cand) => {
// Prefer the impl to a global where clause candidate.
return is_global(cand);
}
- _ => ()
+ _ => (),
}
}
false
- },
- ClosureCandidate |
- GeneratorCandidate |
- FnPointerCandidate |
- BuiltinObjectCandidate |
- BuiltinUnsizeCandidate |
- BuiltinCandidate { has_nested: true } => {
+ }
+ ClosureCandidate
+ | GeneratorCandidate
+ | FnPointerCandidate
+ | BuiltinObjectCandidate
+ | BuiltinUnsizeCandidate
+ | BuiltinCandidate { has_nested: true } => {
match victim.candidate {
ParamCandidate(ref cand) => {
// Prefer these to a global where-clause bound
_ => false,
}
}
- _ => false
+ _ => false,
}
}
// These cover the traits that are built-in to the language
// itself: `Copy`, `Clone` and `Sized`.
- fn assemble_builtin_bound_candidates<'o>(&mut self,
- conditions: BuiltinImplConditions<'tcx>,
- candidates: &mut SelectionCandidateSet<'tcx>)
- -> Result<(), SelectionError<'tcx>>
- {
+ fn assemble_builtin_bound_candidates<'o>(
+ &mut self,
+ conditions: BuiltinImplConditions<'tcx>,
+ candidates: &mut SelectionCandidateSet<'tcx>,
+ ) -> Result<(), SelectionError<'tcx>> {
match conditions {
BuiltinImplConditions::Where(nested) => {
debug!("builtin_bound: nested={:?}", nested);
candidates.vec.push(BuiltinCandidate {
- has_nested: nested.skip_binder().len() > 0
+ has_nested: nested.skip_binder().len() > 0,
});
}
BuiltinImplConditions::None => {}
Ok(())
}
- fn sized_conditions(&mut self,
- obligation: &TraitObligation<'tcx>)
- -> BuiltinImplConditions<'tcx>
- {
+ fn sized_conditions(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ ) -> BuiltinImplConditions<'tcx> {
use self::BuiltinImplConditions::{Ambiguous, None, Where};
// NOTE: binder moved to (*)
- let self_ty = self.infcx.shallow_resolve(
- obligation.predicate.skip_binder().self_ty());
+ let self_ty = self.infcx
+ .shallow_resolve(obligation.predicate.skip_binder().self_ty());
match self_ty.sty {
- ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
- ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
- ty::FnDef(..) | ty::FnPtr(_) | ty::RawPtr(..) |
- ty::Char | ty::Ref(..) | ty::Generator(..) |
- ty::GeneratorWitness(..) | ty::Array(..) | ty::Closure(..) |
- ty::Never | ty::Error => {
+ ty::Infer(ty::IntVar(_))
+ | ty::Infer(ty::FloatVar(_))
+ | ty::Uint(_)
+ | ty::Int(_)
+ | ty::Bool
+ | ty::Float(_)
+ | ty::FnDef(..)
+ | ty::FnPtr(_)
+ | ty::RawPtr(..)
+ | ty::Char
+ | ty::Ref(..)
+ | ty::Generator(..)
+ | ty::GeneratorWitness(..)
+ | ty::Array(..)
+ | ty::Closure(..)
+ | ty::Never
+ | ty::Error => {
// safe for everything
Where(ty::Binder::dummy(Vec::new()))
}
ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None,
- ty::Tuple(tys) => {
- Where(ty::Binder::bind(tys.last().into_iter().cloned().collect()))
- }
+ ty::Tuple(tys) => Where(ty::Binder::bind(tys.last().into_iter().cloned().collect())),
ty::Adt(def, substs) => {
let sized_crit = def.sized_constraint(self.tcx());
// (*) binder moved here
Where(ty::Binder::bind(
- sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect()
+ sized_crit
+ .iter()
+ .map(|ty| ty.subst(self.tcx(), substs))
+ .collect(),
))
}
ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None,
ty::Infer(ty::TyVar(_)) => Ambiguous,
- ty::Infer(ty::CanonicalTy(_)) |
- ty::Infer(ty::FreshTy(_)) |
- ty::Infer(ty::FreshIntTy(_)) |
- ty::Infer(ty::FreshFloatTy(_)) => {
- bug!("asked to assemble builtin bounds of unexpected type: {:?}",
- self_ty);
+ ty::UnnormalizedProjection(..)
+ | ty::Infer(ty::CanonicalTy(_))
+ | ty::Infer(ty::FreshTy(_))
+ | ty::Infer(ty::FreshIntTy(_))
+ | ty::Infer(ty::FreshFloatTy(_)) => {
+ bug!(
+ "asked to assemble builtin bounds of unexpected type: {:?}",
+ self_ty
+ );
}
}
}
- fn copy_clone_conditions(&mut self,
- obligation: &TraitObligation<'tcx>)
- -> BuiltinImplConditions<'tcx>
- {
+ fn copy_clone_conditions(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ ) -> BuiltinImplConditions<'tcx> {
// NOTE: binder moved to (*)
- let self_ty = self.infcx.shallow_resolve(
- obligation.predicate.skip_binder().self_ty());
+ let self_ty = self.infcx
+ .shallow_resolve(obligation.predicate.skip_binder().self_ty());
use self::BuiltinImplConditions::{Ambiguous, None, Where};
match self_ty.sty {
- ty::Infer(ty::IntVar(_)) | ty::Infer(ty::FloatVar(_)) |
- ty::FnDef(..) | ty::FnPtr(_) | ty::Error => {
- Where(ty::Binder::dummy(Vec::new()))
- }
-
- ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) |
- ty::Char | ty::RawPtr(..) | ty::Never |
- ty::Ref(_, _, hir::MutImmutable) => {
+ ty::Infer(ty::IntVar(_))
+ | ty::Infer(ty::FloatVar(_))
+ | ty::FnDef(..)
+ | ty::FnPtr(_)
+ | ty::Error => Where(ty::Binder::dummy(Vec::new())),
+
+ ty::Uint(_)
+ | ty::Int(_)
+ | ty::Bool
+ | ty::Float(_)
+ | ty::Char
+ | ty::RawPtr(..)
+ | ty::Never
+ | ty::Ref(_, _, hir::MutImmutable) => {
// Implementations provided in libcore
None
}
- ty::Dynamic(..) | ty::Str | ty::Slice(..) |
- ty::Generator(..) | ty::GeneratorWitness(..) | ty::Foreign(..) |
- ty::Ref(_, _, hir::MutMutable) => {
- None
- }
+ ty::Dynamic(..)
+ | ty::Str
+ | ty::Slice(..)
+ | ty::Generator(..)
+ | ty::GeneratorWitness(..)
+ | ty::Foreign(..)
+ | ty::Ref(_, _, hir::MutMutable) => None,
ty::Array(element_ty, _) => {
// (*) binder moved here
let is_copy_trait = Some(trait_id) == self.tcx().lang_items().copy_trait();
let is_clone_trait = Some(trait_id) == self.tcx().lang_items().clone_trait();
if is_copy_trait || is_clone_trait {
- Where(ty::Binder::bind(substs.upvar_tys(def_id, self.tcx()).collect()))
+ Where(ty::Binder::bind(
+ substs.upvar_tys(def_id, self.tcx()).collect(),
+ ))
} else {
None
}
Ambiguous
}
- ty::Infer(ty::CanonicalTy(_)) |
- ty::Infer(ty::FreshTy(_)) |
- ty::Infer(ty::FreshIntTy(_)) |
- ty::Infer(ty::FreshFloatTy(_)) => {
- bug!("asked to assemble builtin bounds of unexpected type: {:?}",
- self_ty);
+ ty::UnnormalizedProjection(..)
+ | ty::Infer(ty::CanonicalTy(_))
+ | ty::Infer(ty::FreshTy(_))
+ | ty::Infer(ty::FreshIntTy(_))
+ | ty::Infer(ty::FreshFloatTy(_)) => {
+ bug!(
+ "asked to assemble builtin bounds of unexpected type: {:?}",
+ self_ty
+ );
}
}
}
/// ```
fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Vec<Ty<'tcx>> {
match t.sty {
- ty::Uint(_) |
- ty::Int(_) |
- ty::Bool |
- ty::Float(_) |
- ty::FnDef(..) |
- ty::FnPtr(_) |
- ty::Str |
- ty::Error |
- ty::Infer(ty::IntVar(_)) |
- ty::Infer(ty::FloatVar(_)) |
- ty::Never |
- ty::Char => {
- Vec::new()
- }
-
- ty::Dynamic(..) |
- ty::Param(..) |
- ty::Foreign(..) |
- ty::Projection(..) |
- ty::Infer(ty::CanonicalTy(_)) |
- ty::Infer(ty::TyVar(_)) |
- ty::Infer(ty::FreshTy(_)) |
- ty::Infer(ty::FreshIntTy(_)) |
- ty::Infer(ty::FreshFloatTy(_)) => {
- bug!("asked to assemble constituent types of unexpected type: {:?}",
- t);
- }
-
- ty::RawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
- ty::Ref(_, element_ty, _) => {
- vec![element_ty]
- },
+ ty::Uint(_)
+ | ty::Int(_)
+ | ty::Bool
+ | ty::Float(_)
+ | ty::FnDef(..)
+ | ty::FnPtr(_)
+ | ty::Str
+ | ty::Error
+ | ty::Infer(ty::IntVar(_))
+ | ty::Infer(ty::FloatVar(_))
+ | ty::Never
+ | ty::Char => Vec::new(),
+
+ ty::UnnormalizedProjection(..)
+ | ty::Dynamic(..)
+ | ty::Param(..)
+ | ty::Foreign(..)
+ | ty::Projection(..)
+ | ty::Infer(ty::CanonicalTy(_))
+ | ty::Infer(ty::TyVar(_))
+ | ty::Infer(ty::FreshTy(_))
+ | ty::Infer(ty::FreshIntTy(_))
+ | ty::Infer(ty::FreshFloatTy(_)) => {
+ bug!(
+ "asked to assemble constituent types of unexpected type: {:?}",
+ t
+ );
+ }
- ty::Array(element_ty, _) | ty::Slice(element_ty) => {
+ ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => {
vec![element_ty]
}
+ ty::Array(element_ty, _) | ty::Slice(element_ty) => vec![element_ty],
+
ty::Tuple(ref tys) => {
// (T1, ..., Tn) -- meets any bound that all of T1...Tn meet
tys.to_vec()
}
- ty::Closure(def_id, ref substs) => {
- substs.upvar_tys(def_id, self.tcx()).collect()
- }
+ ty::Closure(def_id, ref substs) => substs.upvar_tys(def_id, self.tcx()).collect(),
ty::Generator(def_id, ref substs, _) => {
let witness = substs.witness(def_id, self.tcx());
- substs.upvar_tys(def_id, self.tcx()).chain(iter::once(witness)).collect()
+ substs
+ .upvar_tys(def_id, self.tcx())
+ .chain(iter::once(witness))
+ .collect()
}
ty::GeneratorWitness(types) => {
}
// for `PhantomData<T>`, we pass `T`
- ty::Adt(def, substs) if def.is_phantom_data() => {
- substs.types().collect()
- }
+ ty::Adt(def, substs) if def.is_phantom_data() => substs.types().collect(),
- ty::Adt(def, substs) => {
- def.all_fields()
- .map(|f| f.ty(self.tcx(), substs))
- .collect()
- }
+ ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect(),
ty::Opaque(def_id, substs) => {
// We can resolve the `impl Trait` to its concrete type,
}
}
- fn collect_predicates_for_types(&mut self,
- param_env: ty::ParamEnv<'tcx>,
- cause: ObligationCause<'tcx>,
- recursion_depth: usize,
- trait_def_id: DefId,
- types: ty::Binder<Vec<Ty<'tcx>>>)
- -> Vec<PredicateObligation<'tcx>>
- {
+ fn collect_predicates_for_types(
+ &mut self,
+ param_env: ty::ParamEnv<'tcx>,
+ cause: ObligationCause<'tcx>,
+ recursion_depth: usize,
+ trait_def_id: DefId,
+ types: ty::Binder<Vec<Ty<'tcx>>>,
+ ) -> Vec<PredicateObligation<'tcx>> {
// Because the types were potentially derived from
// higher-ranked obligations they may reference late-bound
// regions. For example, `for<'a> Foo<&'a int> : Copy` would
//
// The strategy is to:
//
- // 1. Instantiate those regions to skolemized regions (e.g.,
+ // 1. Instantiate those regions to placeholder regions (e.g.,
// `for<'a> &'a int` becomes `&0 int`.
// 2. Produce something like `&'0 int : Copy`
// 3. Re-bind the regions back to `for<'a> &'a int : Copy`
- types.skip_binder().into_iter().flat_map(|ty| { // binder moved -\
- let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
-
- self.in_snapshot(|this, snapshot| {
- let (skol_ty, skol_map) =
- this.infcx().skolemize_late_bound_regions(&ty);
- let Normalized { value: normalized_ty, mut obligations } =
- project::normalize_with_depth(this,
- param_env,
- cause.clone(),
- recursion_depth,
- &skol_ty);
- let skol_obligation =
- this.tcx().predicate_for_trait_def(param_env,
- cause.clone(),
- trait_def_id,
- recursion_depth,
- normalized_ty,
- &[]);
- obligations.push(skol_obligation);
- this.infcx().plug_leaks(skol_map, snapshot, obligations)
+ types
+ .skip_binder()
+ .into_iter()
+ .flat_map(|ty| {
+ // binder moved -\
+ let ty: ty::Binder<Ty<'tcx>> = ty::Binder::bind(ty); // <----/
+
+ self.in_snapshot(|this, snapshot| {
+ let (skol_ty, placeholder_map) = this.infcx()
+ .replace_late_bound_regions_with_placeholders(&ty);
+ let Normalized {
+ value: normalized_ty,
+ mut obligations,
+ } = project::normalize_with_depth(
+ this,
+ param_env,
+ cause.clone(),
+ recursion_depth,
+ &skol_ty,
+ );
+ let skol_obligation = this.tcx().predicate_for_trait_def(
+ param_env,
+ cause.clone(),
+ trait_def_id,
+ recursion_depth,
+ normalized_ty,
+ &[],
+ );
+ obligations.push(skol_obligation);
+ this.infcx()
+ .plug_leaks(placeholder_map, snapshot, obligations)
+ })
})
- }).collect()
+ .collect()
}
///////////////////////////////////////////////////////////////////////////
// [rustc guide]:
// https://rust-lang-nursery.github.io/rustc-guide/traits/resolution.html#confirmation
- fn confirm_candidate(&mut self,
- obligation: &TraitObligation<'tcx>,
- candidate: SelectionCandidate<'tcx>)
- -> Result<Selection<'tcx>, SelectionError<'tcx>>
- {
- debug!("confirm_candidate({:?}, {:?})",
- obligation,
- candidate);
+ fn confirm_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ candidate: SelectionCandidate<'tcx>,
+ ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
+ debug!("confirm_candidate({:?}, {:?})", obligation, candidate);
match candidate {
BuiltinCandidate { has_nested } => {
Ok(VtableAutoImpl(data))
}
- ImplCandidate(impl_def_id) => {
- Ok(VtableImpl(self.confirm_impl_candidate(obligation, impl_def_id)))
- }
+ ImplCandidate(impl_def_id) => Ok(VtableImpl(self.confirm_impl_candidate(
+ obligation,
+ impl_def_id,
+ ))),
ClosureCandidate => {
let vtable_closure = self.confirm_closure_candidate(obligation)?;
}
FnPointerCandidate => {
- let data =
- self.confirm_fn_pointer_candidate(obligation)?;
+ let data = self.confirm_fn_pointer_candidate(obligation)?;
Ok(VtableFnPointer(data))
}
}
}
- fn confirm_projection_candidate(&mut self,
- obligation: &TraitObligation<'tcx>)
- {
+ fn confirm_projection_candidate(&mut self, obligation: &TraitObligation<'tcx>) {
self.in_snapshot(|this, snapshot| {
let result =
- this.match_projection_obligation_against_definition_bounds(obligation,
- snapshot);
+ this.match_projection_obligation_against_definition_bounds(obligation, snapshot);
assert!(result);
})
}
- fn confirm_param_candidate(&mut self,
- obligation: &TraitObligation<'tcx>,
- param: ty::PolyTraitRef<'tcx>)
- -> Vec<PredicateObligation<'tcx>>
- {
- debug!("confirm_param_candidate({:?},{:?})",
- obligation,
- param);
+ fn confirm_param_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ param: ty::PolyTraitRef<'tcx>,
+ ) -> Vec<PredicateObligation<'tcx>> {
+ debug!("confirm_param_candidate({:?},{:?})", obligation, param);
// During evaluation, we already checked that this
// where-clause trait-ref could be unified with the obligation
match self.match_where_clause_trait_ref(obligation, param.clone()) {
Ok(obligations) => obligations,
Err(()) => {
- bug!("Where clause `{:?}` was applicable to `{:?}` but now is not",
- param,
- obligation);
+ bug!(
+ "Where clause `{:?}` was applicable to `{:?}` but now is not",
+ param,
+ obligation
+ );
}
}
}
- fn confirm_builtin_candidate(&mut self,
- obligation: &TraitObligation<'tcx>,
- has_nested: bool)
- -> VtableBuiltinData<PredicateObligation<'tcx>>
- {
- debug!("confirm_builtin_candidate({:?}, {:?})",
- obligation, has_nested);
+ fn confirm_builtin_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ has_nested: bool,
+ ) -> VtableBuiltinData<PredicateObligation<'tcx>> {
+ debug!(
+ "confirm_builtin_candidate({:?}, {:?})",
+ obligation, has_nested
+ );
let lang_items = self.tcx().lang_items();
let obligations = if has_nested {
let trait_def = obligation.predicate.def_id();
- let conditions =
- if Some(trait_def) == lang_items.sized_trait() {
- self.sized_conditions(obligation)
- } else if Some(trait_def) == lang_items.copy_trait() {
- self.copy_clone_conditions(obligation)
- } else if Some(trait_def) == lang_items.clone_trait() {
- self.copy_clone_conditions(obligation)
- } else {
- bug!("unexpected builtin trait {:?}", trait_def)
+ let conditions = if Some(trait_def) == lang_items.sized_trait() {
+ self.sized_conditions(obligation)
+ } else if Some(trait_def) == lang_items.copy_trait() {
+ self.copy_clone_conditions(obligation)
+ } else if Some(trait_def) == lang_items.clone_trait() {
+ self.copy_clone_conditions(obligation)
+ } else {
+ bug!("unexpected builtin trait {:?}", trait_def)
};
let nested = match conditions {
BuiltinImplConditions::Where(nested) => nested,
- _ => bug!("obligation {:?} had matched a builtin impl but now doesn't",
- obligation)
+ _ => bug!(
+ "obligation {:?} had matched a builtin impl but now doesn't",
+ obligation
+ ),
};
let cause = obligation.derived_cause(BuiltinDerivedObligation);
- self.collect_predicates_for_types(obligation.param_env,
- cause,
- obligation.recursion_depth+1,
- trait_def,
- nested)
+ self.collect_predicates_for_types(
+ obligation.param_env,
+ cause,
+ obligation.recursion_depth + 1,
+ trait_def,
+ nested,
+ )
} else {
vec![]
};
- debug!("confirm_builtin_candidate: obligations={:?}",
- obligations);
+ debug!("confirm_builtin_candidate: obligations={:?}", obligations);
- VtableBuiltinData { nested: obligations }
+ VtableBuiltinData {
+ nested: obligations,
+ }
}
/// This handles the case where a `auto trait Foo` impl is being used.
///
/// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
/// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
- fn confirm_auto_impl_candidate(&mut self,
- obligation: &TraitObligation<'tcx>,
- trait_def_id: DefId)
- -> VtableAutoImplData<PredicateObligation<'tcx>>
- {
- debug!("confirm_auto_impl_candidate({:?}, {:?})",
- obligation,
- trait_def_id);
+ fn confirm_auto_impl_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ trait_def_id: DefId,
+ ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
+ debug!(
+ "confirm_auto_impl_candidate({:?}, {:?})",
+ obligation, trait_def_id
+ );
let types = obligation.predicate.map_bound(|inner| {
let self_ty = self.infcx.shallow_resolve(inner.self_ty());
}
/// See `confirm_auto_impl_candidate`
- fn vtable_auto_impl(&mut self,
- obligation: &TraitObligation<'tcx>,
- trait_def_id: DefId,
- nested: ty::Binder<Vec<Ty<'tcx>>>)
- -> VtableAutoImplData<PredicateObligation<'tcx>>
- {
+ fn vtable_auto_impl(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ trait_def_id: DefId,
+ nested: ty::Binder<Vec<Ty<'tcx>>>,
+ ) -> VtableAutoImplData<PredicateObligation<'tcx>> {
debug!("vtable_auto_impl: nested={:?}", nested);
let cause = obligation.derived_cause(BuiltinDerivedObligation);
cause,
obligation.recursion_depth + 1,
trait_def_id,
- nested);
+ nested,
+ );
let trait_obligations: Vec<PredicateObligation<'_>> = self.in_snapshot(|this, snapshot| {
let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
- let (trait_ref, skol_map) =
- this.infcx().skolemize_late_bound_regions(&poly_trait_ref);
+ let (trait_ref, placeholder_map) = this.infcx()
+ .replace_late_bound_regions_with_placeholders(&poly_trait_ref);
let cause = obligation.derived_cause(ImplDerivedObligation);
- this.impl_or_trait_obligations(cause,
- obligation.recursion_depth + 1,
- obligation.param_env,
- trait_def_id,
- &trait_ref.substs,
- skol_map,
- snapshot)
+ this.impl_or_trait_obligations(
+ cause,
+ obligation.recursion_depth + 1,
+ obligation.param_env,
+ trait_def_id,
+ &trait_ref.substs,
+ placeholder_map,
+ snapshot,
+ )
});
// Adds the predicates from the trait. Note that this contains a `Self: Trait`
VtableAutoImplData {
trait_def_id,
- nested: obligations
+ nested: obligations,
}
}
- fn confirm_impl_candidate(&mut self,
- obligation: &TraitObligation<'tcx>,
- impl_def_id: DefId)
- -> VtableImplData<'tcx, PredicateObligation<'tcx>>
- {
- debug!("confirm_impl_candidate({:?},{:?})",
- obligation,
- impl_def_id);
+ fn confirm_impl_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ impl_def_id: DefId,
+ ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
+ debug!("confirm_impl_candidate({:?},{:?})", obligation, impl_def_id);
// First, create the substitutions by matching the impl again,
// this time not in a probe.
self.in_snapshot(|this, snapshot| {
- let (substs, skol_map) =
- this.rematch_impl(impl_def_id, obligation,
- snapshot);
+ let (substs, placeholder_map) = this.rematch_impl(impl_def_id, obligation, snapshot);
debug!("confirm_impl_candidate substs={:?}", substs);
let cause = obligation.derived_cause(ImplDerivedObligation);
- this.vtable_impl(impl_def_id,
- substs,
- cause,
- obligation.recursion_depth + 1,
- obligation.param_env,
- skol_map,
- snapshot)
+ this.vtable_impl(
+ impl_def_id,
+ substs,
+ cause,
+ obligation.recursion_depth + 1,
+ obligation.param_env,
+ placeholder_map,
+ snapshot,
+ )
})
}
- fn vtable_impl(&mut self,
- impl_def_id: DefId,
- mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
- cause: ObligationCause<'tcx>,
- recursion_depth: usize,
- param_env: ty::ParamEnv<'tcx>,
- skol_map: infer::SkolemizationMap<'tcx>,
- snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
- -> VtableImplData<'tcx, PredicateObligation<'tcx>>
- {
- debug!("vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, skol_map={:?})",
- impl_def_id,
- substs,
- recursion_depth,
- skol_map);
-
- let mut impl_obligations =
- self.impl_or_trait_obligations(cause,
- recursion_depth,
- param_env,
- impl_def_id,
- &substs.value,
- skol_map,
- snapshot);
-
- debug!("vtable_impl: impl_def_id={:?} impl_obligations={:?}",
- impl_def_id,
- impl_obligations);
+ fn vtable_impl(
+ &mut self,
+ impl_def_id: DefId,
+ mut substs: Normalized<'tcx, &'tcx Substs<'tcx>>,
+ cause: ObligationCause<'tcx>,
+ recursion_depth: usize,
+ param_env: ty::ParamEnv<'tcx>,
+ placeholder_map: infer::PlaceholderMap<'tcx>,
+ snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
+ ) -> VtableImplData<'tcx, PredicateObligation<'tcx>> {
+ debug!(
+ "vtable_impl(impl_def_id={:?}, substs={:?}, recursion_depth={}, placeholder_map={:?})",
+ impl_def_id, substs, recursion_depth, placeholder_map
+ );
+
+ let mut impl_obligations = self.impl_or_trait_obligations(
+ cause,
+ recursion_depth,
+ param_env,
+ impl_def_id,
+ &substs.value,
+ placeholder_map,
+ snapshot,
+ );
+
+ debug!(
+ "vtable_impl: impl_def_id={:?} impl_obligations={:?}",
+ impl_def_id, impl_obligations
+ );
// Because of RFC447, the impl-trait-ref and obligations
// are sufficient to determine the impl substs, without
// e.g. `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
impl_obligations.append(&mut substs.obligations);
- VtableImplData { impl_def_id,
- substs: substs.value,
- nested: impl_obligations }
+ VtableImplData {
+ impl_def_id,
+ substs: substs.value,
+ nested: impl_obligations,
+ }
}
- fn confirm_object_candidate(&mut self,
- obligation: &TraitObligation<'tcx>)
- -> VtableObjectData<'tcx, PredicateObligation<'tcx>>
- {
- debug!("confirm_object_candidate({:?})",
- obligation);
+ fn confirm_object_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ ) -> VtableObjectData<'tcx, PredicateObligation<'tcx>> {
+ debug!("confirm_object_candidate({:?})", obligation);
// FIXME skipping binder here seems wrong -- we should
// probably flatten the binder from the obligation and the
// binder from the object. Have to try to make a broken test
// case that results. -nmatsakis
- let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
+ let self_ty = self.infcx
+ .shallow_resolve(*obligation.self_ty().skip_binder());
let poly_trait_ref = match self_ty.sty {
ty::Dynamic(ref data, ..) => {
data.principal().unwrap().with_self_ty(self.tcx(), self_ty)
}
- _ => span_bug!(obligation.cause.span,
- "object candidate with non-object")
+ _ => span_bug!(obligation.cause.span, "object candidate with non-object"),
};
let mut upcast_trait_ref = None;
// where we can unify because otherwise select would have
// reported an ambiguity. (When we do find a match, also
// record it for later.)
- let nonmatching =
- util::supertraits(tcx, poly_trait_ref)
- .take_while(|&t|
- match self.commit_if_ok(|this, _|
- this.match_poly_trait_ref(obligation, t))
- {
- Ok(obligations) => {
- upcast_trait_ref = Some(t);
- nested.extend(obligations);
- false
- }
- Err(_) => { true }
+ let nonmatching = util::supertraits(tcx, poly_trait_ref).take_while(
+ |&t| match self.commit_if_ok(|this, _| this.match_poly_trait_ref(obligation, t)) {
+ Ok(obligations) => {
+ upcast_trait_ref = Some(t);
+ nested.extend(obligations);
+ false
}
- );
+ Err(_) => true,
+ },
+ );
// Additionally, for each of the nonmatching predicates that
// we pass over, we sum up the set of number of vtable
}
}
- fn confirm_fn_pointer_candidate(&mut self, obligation: &TraitObligation<'tcx>)
- -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>>
- {
- debug!("confirm_fn_pointer_candidate({:?})",
- obligation);
+ fn confirm_fn_pointer_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ ) -> Result<VtableFnPointerData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
+ debug!("confirm_fn_pointer_candidate({:?})", obligation);
// ok to skip binder; it is reintroduced below
- let self_ty = self.infcx.shallow_resolve(*obligation.self_ty().skip_binder());
+ let self_ty = self.infcx
+ .shallow_resolve(*obligation.self_ty().skip_binder());
let sig = self_ty.fn_sig(self.tcx());
- let trait_ref =
- self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
- self_ty,
- sig,
- util::TupleArgumentsFlag::Yes)
+ let trait_ref = self.tcx()
+ .closure_trait_ref_and_return_type(
+ obligation.predicate.def_id(),
+ self_ty,
+ sig,
+ util::TupleArgumentsFlag::Yes,
+ )
.map_bound(|(trait_ref, _)| trait_ref);
- let Normalized { value: trait_ref, obligations } =
- project::normalize_with_depth(self,
- obligation.param_env,
- obligation.cause.clone(),
- obligation.recursion_depth + 1,
- &trait_ref);
+ let Normalized {
+ value: trait_ref,
+ obligations,
+ } = project::normalize_with_depth(
+ self,
+ obligation.param_env,
+ obligation.cause.clone(),
+ obligation.recursion_depth + 1,
+ &trait_ref,
+ );
- self.confirm_poly_trait_refs(obligation.cause.clone(),
- obligation.param_env,
- obligation.predicate.to_poly_trait_ref(),
- trait_ref)?;
- Ok(VtableFnPointerData { fn_ty: self_ty, nested: obligations })
+ self.confirm_poly_trait_refs(
+ obligation.cause.clone(),
+ obligation.param_env,
+ obligation.predicate.to_poly_trait_ref(),
+ trait_ref,
+ )?;
+ Ok(VtableFnPointerData {
+ fn_ty: self_ty,
+ nested: obligations,
+ })
}
- fn confirm_generator_candidate(&mut self,
- obligation: &TraitObligation<'tcx>)
- -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>,
- SelectionError<'tcx>>
- {
+ fn confirm_generator_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ ) -> Result<VtableGeneratorData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
// ok to skip binder because the substs on generator types never
// touch bound regions, they just capture the in-scope
// type/region parameters
- let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
+ let self_ty = self.infcx
+ .shallow_resolve(obligation.self_ty().skip_binder());
let (generator_def_id, substs) = match self_ty.sty {
ty::Generator(id, substs, _) => (id, substs),
- _ => bug!("closure candidate for non-closure {:?}", obligation)
+ _ => bug!("closure candidate for non-closure {:?}", obligation),
};
- debug!("confirm_generator_candidate({:?},{:?},{:?})",
- obligation,
- generator_def_id,
- substs);
+ debug!(
+ "confirm_generator_candidate({:?},{:?},{:?})",
+ obligation, generator_def_id, substs
+ );
- let trait_ref =
- self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
+ let trait_ref = self.generator_trait_ref_unnormalized(obligation, generator_def_id, substs);
let Normalized {
value: trait_ref,
- mut obligations
- } = normalize_with_depth(self,
- obligation.param_env,
- obligation.cause.clone(),
- obligation.recursion_depth+1,
- &trait_ref);
-
- debug!("confirm_generator_candidate(generator_def_id={:?}, \
- trait_ref={:?}, obligations={:?})",
- generator_def_id,
- trait_ref,
- obligations);
-
- obligations.extend(
- self.confirm_poly_trait_refs(obligation.cause.clone(),
- obligation.param_env,
- obligation.predicate.to_poly_trait_ref(),
- trait_ref)?);
+ mut obligations,
+ } = normalize_with_depth(
+ self,
+ obligation.param_env,
+ obligation.cause.clone(),
+ obligation.recursion_depth + 1,
+ &trait_ref,
+ );
+
+ debug!(
+ "confirm_generator_candidate(generator_def_id={:?}, \
+ trait_ref={:?}, obligations={:?})",
+ generator_def_id, trait_ref, obligations
+ );
+
+ obligations.extend(self.confirm_poly_trait_refs(
+ obligation.cause.clone(),
+ obligation.param_env,
+ obligation.predicate.to_poly_trait_ref(),
+ trait_ref,
+ )?);
Ok(VtableGeneratorData {
generator_def_id: generator_def_id,
substs: substs.clone(),
- nested: obligations
+ nested: obligations,
})
}
- fn confirm_closure_candidate(&mut self,
- obligation: &TraitObligation<'tcx>)
- -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>,
- SelectionError<'tcx>>
- {
+ fn confirm_closure_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ ) -> Result<VtableClosureData<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
debug!("confirm_closure_candidate({:?})", obligation);
let kind = self.tcx()
- .lang_items()
- .fn_trait_kind(obligation.predicate.def_id())
- .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}",
- obligation));
+ .lang_items()
+ .fn_trait_kind(obligation.predicate.def_id())
+ .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation));
// ok to skip binder because the substs on closure types never
// touch bound regions, they just capture the in-scope
// type/region parameters
- let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
+ let self_ty = self.infcx
+ .shallow_resolve(obligation.self_ty().skip_binder());
let (closure_def_id, substs) = match self_ty.sty {
ty::Closure(id, substs) => (id, substs),
- _ => bug!("closure candidate for non-closure {:?}", obligation)
+ _ => bug!("closure candidate for non-closure {:?}", obligation),
};
- let trait_ref =
- self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
+ let trait_ref = self.closure_trait_ref_unnormalized(obligation, closure_def_id, substs);
let Normalized {
value: trait_ref,
- mut obligations
- } = normalize_with_depth(self,
- obligation.param_env,
- obligation.cause.clone(),
- obligation.recursion_depth+1,
- &trait_ref);
-
- debug!("confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
- closure_def_id,
- trait_ref,
- obligations);
-
- obligations.extend(
- self.confirm_poly_trait_refs(obligation.cause.clone(),
- obligation.param_env,
- obligation.predicate.to_poly_trait_ref(),
- trait_ref)?);
+ mut obligations,
+ } = normalize_with_depth(
+ self,
+ obligation.param_env,
+ obligation.cause.clone(),
+ obligation.recursion_depth + 1,
+ &trait_ref,
+ );
+
+ debug!(
+ "confirm_closure_candidate(closure_def_id={:?}, trait_ref={:?}, obligations={:?})",
+ closure_def_id, trait_ref, obligations
+ );
+
+ obligations.extend(self.confirm_poly_trait_refs(
+ obligation.cause.clone(),
+ obligation.param_env,
+ obligation.predicate.to_poly_trait_ref(),
+ trait_ref,
+ )?);
obligations.push(Obligation::new(
obligation.cause.clone(),
obligation.param_env,
- ty::Predicate::ClosureKind(closure_def_id, substs, kind)));
+ ty::Predicate::ClosureKind(closure_def_id, substs, kind),
+ ));
Ok(VtableClosureData {
closure_def_id,
substs: substs.clone(),
- nested: obligations
+ nested: obligations,
})
}
/// because these output type parameters should not affect the
/// selection of the impl. Therefore, if there is a mismatch, we
/// report an error to the user.
- fn confirm_poly_trait_refs(&mut self,
- obligation_cause: ObligationCause<'tcx>,
- obligation_param_env: ty::ParamEnv<'tcx>,
- obligation_trait_ref: ty::PolyTraitRef<'tcx>,
- expected_trait_ref: ty::PolyTraitRef<'tcx>)
- -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>>
- {
+ fn confirm_poly_trait_refs(
+ &mut self,
+ obligation_cause: ObligationCause<'tcx>,
+ obligation_param_env: ty::ParamEnv<'tcx>,
+ obligation_trait_ref: ty::PolyTraitRef<'tcx>,
+ expected_trait_ref: ty::PolyTraitRef<'tcx>,
+ ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
let obligation_trait_ref = obligation_trait_ref.clone();
self.infcx
.at(&obligation_cause, obligation_param_env)
.map_err(|e| OutputTypeParameterMismatch(expected_trait_ref, obligation_trait_ref, e))
}
- fn confirm_builtin_unsize_candidate(&mut self,
- obligation: &TraitObligation<'tcx>,)
- -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>>
- {
+ fn confirm_builtin_unsize_candidate(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ ) -> Result<VtableBuiltinData<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
let tcx = self.tcx();
// assemble_candidates_for_unsizing should ensure there are no late bound
// regions here. See the comment there for more details.
- let source = self.infcx.shallow_resolve(
- obligation.self_ty().no_late_bound_regions().unwrap());
- let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1);
+ let source = self.infcx
+ .shallow_resolve(obligation.self_ty().no_late_bound_regions().unwrap());
+ let target = obligation
+ .predicate
+ .skip_binder()
+ .trait_ref
+ .substs
+ .type_at(1);
let target = self.infcx.shallow_resolve(target);
- debug!("confirm_builtin_unsize_candidate(source={:?}, target={:?})",
- source, target);
+ debug!(
+ "confirm_builtin_unsize_candidate(source={:?}, target={:?})",
+ source, target
+ );
let mut nested = vec![];
match (&source.sty, &target.sty) {
// See assemble_candidates_for_unsizing for more info.
let existential_predicates = data_a.map_bound(|data_a| {
let principal = data_a.principal();
- let iter = principal.into_iter().map(ty::ExistentialPredicate::Trait)
- .chain(data_a.projection_bounds()
- .map(|x| ty::ExistentialPredicate::Projection(x)))
- .chain(data_b.auto_traits().map(ty::ExistentialPredicate::AutoTrait));
+ let iter = principal
+ .into_iter()
+ .map(ty::ExistentialPredicate::Trait)
+ .chain(
+ data_a
+ .projection_bounds()
+ .map(|x| ty::ExistentialPredicate::Projection(x)),
+ )
+ .chain(
+ data_b
+ .auto_traits()
+ .map(ty::ExistentialPredicate::AutoTrait),
+ );
tcx.mk_existential_predicates(iter)
});
let new_trait = tcx.mk_dynamic(existential_predicates, r_b);
- let InferOk { obligations, .. } =
- self.infcx.at(&obligation.cause, obligation.param_env)
- .eq(target, new_trait)
- .map_err(|_| Unimplemented)?;
+ let InferOk { obligations, .. } = self.infcx
+ .at(&obligation.cause, obligation.param_env)
+ .eq(target, new_trait)
+ .map_err(|_| Unimplemented)?;
nested.extend(obligations);
// Register one obligation for 'a: 'b.
- let cause = ObligationCause::new(obligation.cause.span,
- obligation.cause.body_id,
- ObjectCastObligation(target));
+ let cause = ObligationCause::new(
+ obligation.cause.span,
+ obligation.cause.body_id,
+ ObjectCastObligation(target),
+ );
let outlives = ty::OutlivesPredicate(r_a, r_b);
- nested.push(Obligation::with_depth(cause,
- obligation.recursion_depth + 1,
- obligation.param_env,
- ty::Binder::bind(outlives).to_predicate()));
+ nested.push(Obligation::with_depth(
+ cause,
+ obligation.recursion_depth + 1,
+ obligation.param_env,
+ ty::Binder::bind(outlives).to_predicate(),
+ ));
}
// T -> Trait.
(_, &ty::Dynamic(ref data, r)) => {
- let mut object_dids =
- data.auto_traits().chain(data.principal().map(|p| p.def_id()));
+ let mut object_dids = data.auto_traits()
+ .chain(data.principal().map(|p| p.def_id()));
if let Some(did) = object_dids.find(|did| !tcx.is_object_safe(*did)) {
- return Err(TraitNotObjectSafe(did))
+ return Err(TraitNotObjectSafe(did));
}
- let cause = ObligationCause::new(obligation.cause.span,
- obligation.cause.body_id,
- ObjectCastObligation(target));
+ let cause = ObligationCause::new(
+ obligation.cause.span,
+ obligation.cause.body_id,
+ ObjectCastObligation(target),
+ );
let predicate_to_obligation = |predicate| {
- Obligation::with_depth(cause.clone(),
- obligation.recursion_depth + 1,
- obligation.param_env,
- predicate)
+ Obligation::with_depth(
+ cause.clone(),
+ obligation.recursion_depth + 1,
+ obligation.param_env,
+ predicate,
+ )
};
// Create obligations:
// words, if the object type is Foo+Send, this would create an obligation for the
// Send check.)
// - Projection predicates
- nested.extend(data.iter().map(|d|
- predicate_to_obligation(d.with_self_ty(tcx, source))
- ));
+ nested.extend(
+ data.iter()
+ .map(|d| predicate_to_obligation(d.with_self_ty(tcx, source))),
+ );
// We can only make objects from sized types.
let tr = ty::TraitRef {
// being cast to `Foo+'a` outlives `'a`:
let outlives = ty::OutlivesPredicate(source, r);
nested.push(predicate_to_obligation(
- ty::Binder::dummy(outlives).to_predicate()));
+ ty::Binder::dummy(outlives).to_predicate(),
+ ));
}
// [T; n] -> [T].
(&ty::Array(a, _), &ty::Slice(b)) => {
- let InferOk { obligations, .. } =
- self.infcx.at(&obligation.cause, obligation.param_env)
- .eq(b, a)
- .map_err(|_| Unimplemented)?;
+ let InferOk { obligations, .. } = self.infcx
+ .at(&obligation.cause, obligation.param_env)
+ .eq(b, a)
+ .map_err(|_| Unimplemented)?;
nested.extend(obligations);
}
// Struct<T> -> Struct<U>.
(&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => {
- let fields = def
- .all_fields()
+ let fields = def.all_fields()
.map(|f| tcx.type_of(f.did))
.collect::<Vec<_>>();
// Check that the source struct with the target's
// unsized parameters is equal to the target.
- let params = substs_a.iter().enumerate().map(|(i, &k)|
+ let params = substs_a.iter().enumerate().map(|(i, &k)| {
if ty_params.contains(i) {
substs_b.type_at(i).into()
} else {
k
}
- );
+ });
let new_struct = tcx.mk_adt(def, tcx.mk_substs(params));
- let InferOk { obligations, .. } =
- self.infcx.at(&obligation.cause, obligation.param_env)
- .eq(target, new_struct)
- .map_err(|_| Unimplemented)?;
+ let InferOk { obligations, .. } = self.infcx
+ .at(&obligation.cause, obligation.param_env)
+ .eq(target, new_struct)
+ .map_err(|_| Unimplemented)?;
nested.extend(obligations);
// Construct the nested Field<T>: Unsize<Field<U>> predicate.
obligation.predicate.def_id(),
obligation.recursion_depth + 1,
inner_source,
- &[inner_target.into()]));
+ &[inner_target.into()],
+ ));
}
// (.., T) -> (.., U).
// Check that the source tuple with the target's
// last element is equal to the target.
let new_tuple = tcx.mk_tup(a_mid.iter().cloned().chain(iter::once(b_last)));
- let InferOk { obligations, .. } =
- self.infcx.at(&obligation.cause, obligation.param_env)
- .eq(target, new_tuple)
- .map_err(|_| Unimplemented)?;
+ let InferOk { obligations, .. } = self.infcx
+ .at(&obligation.cause, obligation.param_env)
+ .eq(target, new_tuple)
+ .map_err(|_| Unimplemented)?;
nested.extend(obligations);
// Construct the nested T: Unsize<U> predicate.
obligation.predicate.def_id(),
obligation.recursion_depth + 1,
a_last,
- &[b_last.into()]));
+ &[b_last.into()],
+ ));
}
- _ => bug!()
+ _ => bug!(),
};
Ok(VtableBuiltinData { nested: nested })
// run inside of a `probe()` so that their side-effects are
// contained.
- fn rematch_impl(&mut self,
- impl_def_id: DefId,
- obligation: &TraitObligation<'tcx>,
- snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
- -> (Normalized<'tcx, &'tcx Substs<'tcx>>,
- infer::SkolemizationMap<'tcx>)
- {
+ fn rematch_impl(
+ &mut self,
+ impl_def_id: DefId,
+ obligation: &TraitObligation<'tcx>,
+ snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
+ ) -> (
+ Normalized<'tcx, &'tcx Substs<'tcx>>,
+ infer::PlaceholderMap<'tcx>,
+ ) {
match self.match_impl(impl_def_id, obligation, snapshot) {
- Ok((substs, skol_map)) => (substs, skol_map),
+ Ok((substs, placeholder_map)) => (substs, placeholder_map),
Err(()) => {
- bug!("Impl {:?} was matchable against {:?} but now is not",
- impl_def_id,
- obligation);
+ bug!(
+ "Impl {:?} was matchable against {:?} but now is not",
+ impl_def_id,
+ obligation
+ );
}
}
}
- fn match_impl(&mut self,
- impl_def_id: DefId,
- obligation: &TraitObligation<'tcx>,
- snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
- -> Result<(Normalized<'tcx, &'tcx Substs<'tcx>>,
- infer::SkolemizationMap<'tcx>), ()>
- {
+ fn match_impl(
+ &mut self,
+ impl_def_id: DefId,
+ obligation: &TraitObligation<'tcx>,
+ snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
+ ) -> Result<
+ (
+ Normalized<'tcx, &'tcx Substs<'tcx>>,
+ infer::PlaceholderMap<'tcx>,
+ ),
+ (),
+ > {
let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap();
// Before we create the substitutions and everything, first
return Err(());
}
- let (skol_obligation, skol_map) = self.infcx().skolemize_late_bound_regions(
- &obligation.predicate);
+ let (skol_obligation, placeholder_map) = self.infcx()
+ .replace_late_bound_regions_with_placeholders(&obligation.predicate);
let skol_obligation_trait_ref = skol_obligation.trait_ref;
- let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span,
- impl_def_id);
-
- let impl_trait_ref = impl_trait_ref.subst(self.tcx(),
- impl_substs);
-
- let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } =
- project::normalize_with_depth(self,
- obligation.param_env,
- obligation.cause.clone(),
- obligation.recursion_depth + 1,
- &impl_trait_ref);
-
- debug!("match_impl(impl_def_id={:?}, obligation={:?}, \
- impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
- impl_def_id,
- obligation,
- impl_trait_ref,
- skol_obligation_trait_ref);
-
- let InferOk { obligations, .. } =
- self.infcx.at(&obligation.cause, obligation.param_env)
- .eq(skol_obligation_trait_ref, impl_trait_ref)
- .map_err(|e|
- debug!("match_impl: failed eq_trait_refs due to `{}`", e)
- )?;
+ let impl_substs = self.infcx
+ .fresh_substs_for_item(obligation.cause.span, impl_def_id);
+
+ let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs);
+
+ let Normalized {
+ value: impl_trait_ref,
+ obligations: mut nested_obligations,
+ } = project::normalize_with_depth(
+ self,
+ obligation.param_env,
+ obligation.cause.clone(),
+ obligation.recursion_depth + 1,
+ &impl_trait_ref,
+ );
+
+ debug!(
+ "match_impl(impl_def_id={:?}, obligation={:?}, \
+ impl_trait_ref={:?}, skol_obligation_trait_ref={:?})",
+ impl_def_id, obligation, impl_trait_ref, skol_obligation_trait_ref
+ );
+
+ let InferOk { obligations, .. } = self.infcx
+ .at(&obligation.cause, obligation.param_env)
+ .eq(skol_obligation_trait_ref, impl_trait_ref)
+ .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?;
nested_obligations.extend(obligations);
- if let Err(e) = self.infcx.leak_check(false,
- obligation.cause.span,
- &skol_map,
- snapshot) {
+ if let Err(e) =
+ self.infcx
+ .leak_check(false, obligation.cause.span, &placeholder_map, snapshot)
+ {
debug!("match_impl: failed leak check due to `{}`", e);
return Err(());
}
debug!("match_impl: success impl_substs={:?}", impl_substs);
- Ok((Normalized {
- value: impl_substs,
- obligations: nested_obligations
- }, skol_map))
+ Ok((
+ Normalized {
+ value: impl_substs,
+ obligations: nested_obligations,
+ },
+ placeholder_map,
+ ))
}
- fn fast_reject_trait_refs(&mut self,
- obligation: &TraitObligation<'_>,
- impl_trait_ref: &ty::TraitRef<'_>)
- -> bool
- {
+ fn fast_reject_trait_refs(
+ &mut self,
+ obligation: &TraitObligation<'_>,
+ impl_trait_ref: &ty::TraitRef<'_>,
+ ) -> bool {
// We can avoid creating type variables and doing the full
// substitution if we find that any of the input types, when
// simplified, do not match.
- obligation.predicate.skip_binder().input_types()
+ obligation
+ .predicate
+ .skip_binder()
+ .input_types()
.zip(impl_trait_ref.input_types())
.any(|(obligation_ty, impl_ty)| {
let simplified_obligation_ty =
fast_reject::simplify_type(self.tcx(), obligation_ty, true);
- let simplified_impl_ty =
- fast_reject::simplify_type(self.tcx(), impl_ty, false);
+ let simplified_impl_ty = fast_reject::simplify_type(self.tcx(), impl_ty, false);
- simplified_obligation_ty.is_some() &&
- simplified_impl_ty.is_some() &&
- simplified_obligation_ty != simplified_impl_ty
+ simplified_obligation_ty.is_some()
+ && simplified_impl_ty.is_some()
+ && simplified_obligation_ty != simplified_impl_ty
})
}
/// result from the normalization. Normalization is necessary
/// because where-clauses are stored in the parameter environment
/// unnormalized.
- fn match_where_clause_trait_ref(&mut self,
- obligation: &TraitObligation<'tcx>,
- where_clause_trait_ref: ty::PolyTraitRef<'tcx>)
- -> Result<Vec<PredicateObligation<'tcx>>, ()>
- {
+ fn match_where_clause_trait_ref(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ where_clause_trait_ref: ty::PolyTraitRef<'tcx>,
+ ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
self.match_poly_trait_ref(obligation, where_clause_trait_ref)
}
/// Returns `Ok` if `poly_trait_ref` being true implies that the
/// obligation is satisfied.
- fn match_poly_trait_ref(&mut self,
- obligation: &TraitObligation<'tcx>,
- poly_trait_ref: ty::PolyTraitRef<'tcx>)
- -> Result<Vec<PredicateObligation<'tcx>>, ()>
- {
- debug!("match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
- obligation,
- poly_trait_ref);
+ fn match_poly_trait_ref(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ poly_trait_ref: ty::PolyTraitRef<'tcx>,
+ ) -> Result<Vec<PredicateObligation<'tcx>>, ()> {
+ debug!(
+ "match_poly_trait_ref: obligation={:?} poly_trait_ref={:?}",
+ obligation, poly_trait_ref
+ );
- self.infcx.at(&obligation.cause, obligation.param_env)
- .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
- .map(|InferOk { obligations, .. }| obligations)
- .map_err(|_| ())
+ self.infcx
+ .at(&obligation.cause, obligation.param_env)
+ .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref)
+ .map(|InferOk { obligations, .. }| obligations)
+ .map_err(|_| ())
}
///////////////////////////////////////////////////////////////////////////
// Miscellany
- fn match_fresh_trait_refs(&self,
- previous: &ty::PolyTraitRef<'tcx>,
- current: &ty::PolyTraitRef<'tcx>)
- -> bool
- {
+ fn match_fresh_trait_refs(
+ &self,
+ previous: &ty::PolyTraitRef<'tcx>,
+ current: &ty::PolyTraitRef<'tcx>,
+ ) -> bool {
let mut matcher = ty::_match::Match::new(self.tcx());
matcher.relate(previous, current).is_ok()
}
- fn push_stack<'o,'s:'o>(&mut self,
- previous_stack: TraitObligationStackList<'s, 'tcx>,
- obligation: &'o TraitObligation<'tcx>)
- -> TraitObligationStack<'o, 'tcx>
- {
- let fresh_trait_ref =
- obligation.predicate.to_poly_trait_ref().fold_with(&mut self.freshener);
+ fn push_stack<'o, 's: 'o>(
+ &mut self,
+ previous_stack: TraitObligationStackList<'s, 'tcx>,
+ obligation: &'o TraitObligation<'tcx>,
+ ) -> TraitObligationStack<'o, 'tcx> {
+ let fresh_trait_ref = obligation
+ .predicate
+ .to_poly_trait_ref()
+ .fold_with(&mut self.freshener);
TraitObligationStack {
obligation,
}
}
- fn closure_trait_ref_unnormalized(&mut self,
- obligation: &TraitObligation<'tcx>,
- closure_def_id: DefId,
- substs: ty::ClosureSubsts<'tcx>)
- -> ty::PolyTraitRef<'tcx>
- {
+ fn closure_trait_ref_unnormalized(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ closure_def_id: DefId,
+ substs: ty::ClosureSubsts<'tcx>,
+ ) -> ty::PolyTraitRef<'tcx> {
let closure_type = self.infcx.closure_sig(closure_def_id, substs);
// (1) Feels icky to skip the binder here, but OTOH we know
// in fact unparameterized (or at least does not reference any
// regions bound in the obligation). Still probably some
// refactoring could make this nicer.
- self.tcx().closure_trait_ref_and_return_type(obligation.predicate.def_id(),
- obligation.predicate
- .skip_binder()
- .self_ty(), // (1)
- closure_type,
- util::TupleArgumentsFlag::No)
+ self.tcx()
+ .closure_trait_ref_and_return_type(
+ obligation.predicate.def_id(),
+ obligation.predicate.skip_binder().self_ty(), // (1)
+ closure_type,
+ util::TupleArgumentsFlag::No,
+ )
.map_bound(|(trait_ref, _)| trait_ref)
}
- fn generator_trait_ref_unnormalized(&mut self,
- obligation: &TraitObligation<'tcx>,
- closure_def_id: DefId,
- substs: ty::GeneratorSubsts<'tcx>)
- -> ty::PolyTraitRef<'tcx>
- {
+ fn generator_trait_ref_unnormalized(
+ &mut self,
+ obligation: &TraitObligation<'tcx>,
+ closure_def_id: DefId,
+ substs: ty::GeneratorSubsts<'tcx>,
+ ) -> ty::PolyTraitRef<'tcx> {
let gen_sig = substs.poly_sig(closure_def_id, self.tcx());
// (1) Feels icky to skip the binder here, but OTOH we know
// regions bound in the obligation). Still probably some
// refactoring could make this nicer.
- self.tcx().generator_trait_ref_and_outputs(obligation.predicate.def_id(),
- obligation.predicate
- .skip_binder()
- .self_ty(), // (1)
- gen_sig)
+ self.tcx()
+ .generator_trait_ref_and_outputs(
+ obligation.predicate.def_id(),
+ obligation.predicate.skip_binder().self_ty(), // (1)
+ gen_sig,
+ )
.map_bound(|(trait_ref, ..)| trait_ref)
}
/// impl or trait. The obligations are substituted and fully
/// normalized. This is used when confirming an impl or default
/// impl.
- fn impl_or_trait_obligations(&mut self,
- cause: ObligationCause<'tcx>,
- recursion_depth: usize,
- param_env: ty::ParamEnv<'tcx>,
- def_id: DefId, // of impl or trait
- substs: &Substs<'tcx>, // for impl or trait
- skol_map: infer::SkolemizationMap<'tcx>,
- snapshot: &infer::CombinedSnapshot<'cx, 'tcx>)
- -> Vec<PredicateObligation<'tcx>>
- {
+ fn impl_or_trait_obligations(
+ &mut self,
+ cause: ObligationCause<'tcx>,
+ recursion_depth: usize,
+ param_env: ty::ParamEnv<'tcx>,
+ def_id: DefId, // of impl or trait
+ substs: &Substs<'tcx>, // for impl or trait
+ placeholder_map: infer::PlaceholderMap<'tcx>,
+ snapshot: &infer::CombinedSnapshot<'cx, 'tcx>,
+ ) -> Vec<PredicateObligation<'tcx>> {
debug!("impl_or_trait_obligations(def_id={:?})", def_id);
let tcx = self.tcx();
// that order.
let predicates = tcx.predicates_of(def_id);
assert_eq!(predicates.parent, None);
- let mut predicates: Vec<_> = predicates.predicates.iter().flat_map(|(predicate, _)| {
- let predicate = normalize_with_depth(self, param_env, cause.clone(), recursion_depth,
- &predicate.subst(tcx, substs));
- predicate.obligations.into_iter().chain(
- Some(Obligation {
+ let mut predicates: Vec<_> = predicates
+ .predicates
+ .iter()
+ .flat_map(|(predicate, _)| {
+ let predicate = normalize_with_depth(
+ self,
+ param_env,
+ cause.clone(),
+ recursion_depth,
+ &predicate.subst(tcx, substs),
+ );
+ predicate.obligations.into_iter().chain(Some(Obligation {
cause: cause.clone(),
recursion_depth,
param_env,
- predicate: predicate.value
+ predicate: predicate.value,
}))
- }).collect();
+ })
+ .collect();
// We are performing deduplication here to avoid exponential blowups
// (#38528) from happening, but the real cause of the duplication is
let mut seen = FxHashSet();
predicates.retain(|i| seen.insert(i.clone()));
}
- self.infcx().plug_leaks(skol_map, snapshot, predicates)
+ self.infcx()
+ .plug_leaks(placeholder_map, snapshot, predicates)
}
}
impl<'tcx> TraitObligation<'tcx> {
#[allow(unused_comparisons)]
- pub fn derived_cause(&self,
- variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>)
- -> ObligationCause<'tcx>
- {
+ pub fn derived_cause(
+ &self,
+ variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>,
+ ) -> ObligationCause<'tcx> {
/*!
* Creates a cause for obligations that are derived from
* `obligation` by a recursive search (e.g., for a builtin
if obligation.recursion_depth >= 0 {
let derived_cause = DerivedObligationCause {
parent_trait_ref: obligation.predicate.to_poly_trait_ref(),
- parent_code: Rc::new(obligation.cause.code.clone())
+ parent_code: Rc::new(obligation.cause.code.clone()),
};
let derived_code = variant(derived_cause);
- ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code)
+ ObligationCause::new(
+ obligation.cause.span,
+ obligation.cause.body_id,
+ derived_code,
+ )
} else {
obligation.cause.clone()
}
impl<'tcx> SelectionCache<'tcx> {
pub fn new() -> SelectionCache<'tcx> {
SelectionCache {
- hashmap: Lock::new(FxHashMap())
+ hashmap: Lock::new(FxHashMap()),
}
}
impl<'tcx> EvaluationCache<'tcx> {
pub fn new() -> EvaluationCache<'tcx> {
EvaluationCache {
- hashmap: Lock::new(FxHashMap())
+ hashmap: Lock::new(FxHashMap()),
}
}
}
}
-impl<'o,'tcx> TraitObligationStack<'o,'tcx> {
- fn list(&'o self) -> TraitObligationStackList<'o,'tcx> {
+impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> {
+ fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> {
TraitObligationStackList::with(self)
}
- fn iter(&'o self) -> TraitObligationStackList<'o,'tcx> {
+ fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> {
self.list()
}
}
#[derive(Copy, Clone)]
-struct TraitObligationStackList<'o,'tcx:'o> {
- head: Option<&'o TraitObligationStack<'o,'tcx>>
+struct TraitObligationStackList<'o, 'tcx: 'o> {
+ head: Option<&'o TraitObligationStack<'o, 'tcx>>,
}
-impl<'o,'tcx> TraitObligationStackList<'o,'tcx> {
- fn empty() -> TraitObligationStackList<'o,'tcx> {
+impl<'o, 'tcx> TraitObligationStackList<'o, 'tcx> {
+ fn empty() -> TraitObligationStackList<'o, 'tcx> {
TraitObligationStackList { head: None }
}
- fn with(r: &'o TraitObligationStack<'o,'tcx>) -> TraitObligationStackList<'o,'tcx> {
+ fn with(r: &'o TraitObligationStack<'o, 'tcx>) -> TraitObligationStackList<'o, 'tcx> {
TraitObligationStackList { head: Some(r) }
}
}
-impl<'o,'tcx> Iterator for TraitObligationStackList<'o,'tcx>{
- type Item = &'o TraitObligationStack<'o,'tcx>;
+impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> {
+ type Item = &'o TraitObligationStack<'o, 'tcx>;
- fn next(&mut self) -> Option<&'o TraitObligationStack<'o,'tcx>> {
+ fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> {
match self.head {
Some(o) => {
*self = o.previous;
Some(o)
}
- None => None
+ None => None,
}
}
}
-impl<'o,'tcx> fmt::Debug for TraitObligationStack<'o,'tcx> {
+impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TraitObligationStack({:?})", self.obligation)
}
#[derive(Clone, Eq, PartialEq)]
pub struct WithDepNode<T> {
dep_node: DepNodeIndex,
- cached_value: T
+ cached_value: T,
}
impl<T: Clone> WithDepNode<T> {
pub fn new(dep_node: DepNodeIndex, cached_value: T) -> Self {
- WithDepNode { dep_node, cached_value }
+ WithDepNode {
+ dep_node,
+ cached_value,
+ }
}
pub fn get(&self, tcx: TyCtxt<'_, '_, '_>) -> T {
return false;
}
- // create a parameter environment corresponding to a (skolemized) instantiation of impl1
+ // create a parameter environment corresponding to a (placeholder) instantiation of impl1
let penv = tcx.param_env(impl1_def_id);
let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id).unwrap();
Ok(ty::GenericPredicates {
parent: Decodable::decode(decoder)?,
predicates: (0..decoder.read_usize()?).map(|_| {
- // Handle shorthands first, if we have an usize > 0x80.
- let predicate = if decoder.positioned_at_shorthand() {
- let pos = decoder.read_usize()?;
- assert!(pos >= SHORTHAND_OFFSET);
- let shorthand = pos - SHORTHAND_OFFSET;
-
- decoder.with_position(shorthand, ty::Predicate::decode)
- } else {
- ty::Predicate::decode(decoder)
- }?;
- Ok((predicate, Decodable::decode(decoder)?))
- })
- .collect::<Result<Vec<_>, _>>()?,
+ // Handle shorthands first, if we have an usize > 0x80.
+ let predicate = if decoder.positioned_at_shorthand() {
+ let pos = decoder.read_usize()?;
+ assert!(pos >= SHORTHAND_OFFSET);
+ let shorthand = pos - SHORTHAND_OFFSET;
+
+ decoder.with_position(shorthand, ty::Predicate::decode)
+ } else {
+ ty::Predicate::decode(decoder)
+ }?;
+ Ok((predicate, Decodable::decode(decoder)?))
+ })
+ .collect::<Result<Vec<_>, _>>()?,
})
}
#[inline]
pub fn decode_allocation<'a, 'tcx, D>(decoder: &mut D)
- -> Result<&'tcx Allocation, D::Error>
+ -> Result<&'tcx Allocation, D::Error>
where D: TyDecoder<'a, 'tcx>,
'tcx: 'a,
{
// types/regions in the global interner
if local as *const _ as usize == global as *const _ as usize {
bug!("Attempted to intern `{:?}` which contains \
- inference types/regions in the global type context",
- &ty_struct);
+ inference types/regions in the global type context",
+ &ty_struct);
}
// Don't be &mut TyS.
bug!("node {} with HirId::owner {:?} cannot be placed in \
TypeckTables with local_id_root {:?}",
- tcx.hir.node_to_string(node_id),
- DefId::local(hir_id.owner),
- local_id_root)
+ tcx.hir.node_to_string(node_id),
+ DefId::local(hir_id.owner),
+ local_id_root)
});
}
} else {
}
pub fn node_id_to_type(&self, id: hir::HirId) -> Ty<'tcx> {
- match self.node_id_to_type_opt(id) {
- Some(ty) => ty,
- None => {
- bug!("node_id_to_type: no type for node `{}`",
- tls::with(|tcx| {
- let id = tcx.hir.hir_to_node_id(id);
- tcx.hir.node_to_string(id)
- }))
- }
- }
+ self.node_id_to_type_opt(id).unwrap_or_else(||
+ bug!("node_id_to_type: no type for node `{}`",
+ tls::with(|tcx| {
+ let id = tcx.hir.hir_to_node_id(id);
+ tcx.hir.node_to_string(id)
+ }))
+ )
}
pub fn node_id_to_type_opt(&self, id: hir::HirId) -> Option<Ty<'tcx>> {
}
pub fn pat_adjustments_mut(&mut self)
- -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
+ -> LocalTableInContextMut<'_, Vec<Ty<'tcx>>> {
LocalTableInContextMut {
local_id_root: self.local_id_root,
data: &mut self.pat_adjustments,
let hir_id = hir.node_to_hir_id(k);
let map = trait_map.entry(hir_id.owner).or_default();
Lrc::get_mut(map).unwrap()
- .insert(hir_id.local_id,
- Lrc::new(StableVec::new(v)));
+ .insert(hir_id.local_id,
+ Lrc::new(StableVec::new(v)));
}
let gcx = &GlobalCtxt {
};
$(let mut $variant = total;)*
-
for &Interned(t) in tcx.interners.type_.borrow().iter() {
let variant = match t.sty {
ty::Bool | ty::Char | ty::Int(..) | ty::Uint(..) |
}
println!("Ty interner total ty region both");
$(println!(" {:18}: {uses:6} {usespc:4.1}%, \
-{ty:4.1}% {region:5.1}% {both:4.1}%",
+ {ty:4.1}% {region:5.1}% {both:4.1}%",
stringify!($variant),
uses = $variant.total,
usespc = $variant.total as f64 * 100.0 / total.total as f64,
both = $variant.both_infer as f64 * 100.0 / total.total as f64);
)*
println!(" total {uses:6} \
-{ty:4.1}% {region:5.1}% {both:4.1}%",
+ {ty:4.1}% {region:5.1}% {both:4.1}%",
uses = total.total,
ty = total.ty_infer as f64 * 100.0 / total.total as f64,
region = total.region_infer as f64 * 100.0 / total.total as f64,
self,
Adt, Array, Slice, RawPtr, Ref, FnDef, FnPtr,
Generator, GeneratorWitness, Dynamic, Closure, Tuple,
- Param, Infer, Projection, Opaque, Foreign);
+ Param, Infer, UnnormalizedProjection, Projection, Opaque, Foreign);
println!("Substs interner: #{}", self.interners.substs.borrow().len());
println!("Region interner: #{}", self.interners.region.borrow().len());
}
pub fn mk_closure(self, closure_id: DefId, closure_substs: ClosureSubsts<'tcx>)
- -> Ty<'tcx> {
+ -> Ty<'tcx> {
self.mk_ty(Closure(closure_id, closure_substs))
}
}
pub fn mk_ty_param(self,
- index: u32,
- name: InternedString) -> Ty<'tcx> {
+ index: u32,
+ name: InternedString) -> Ty<'tcx> {
self.mk_ty(Param(ParamTy { idx: index, name: name }))
}
use hir::def_id::DefId;
use ty::{self, BoundRegion, Region, Ty, TyCtxt};
+use std::borrow::Cow;
use std::fmt;
use rustc_target::spec::abi;
use syntax::ast;
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::TypeError::*;
fn report_maybe_different(f: &mut fmt::Formatter<'_>,
- expected: String, found: String) -> fmt::Result {
+ expected: &str, found: &str) -> fmt::Result {
// A naive approach to making sure that we're not reporting silly errors such as:
// (expected closure, found closure).
if expected == found {
br)
}
Sorts(values) => ty::tls::with(|tcx| {
- report_maybe_different(f, values.expected.sort_string(tcx),
- values.found.sort_string(tcx))
+ report_maybe_different(f, &values.expected.sort_string(tcx),
+ &values.found.sort_string(tcx))
}),
Traits(values) => ty::tls::with(|tcx| {
report_maybe_different(f,
- format!("trait `{}`",
- tcx.item_path_str(values.expected)),
- format!("trait `{}`",
- tcx.item_path_str(values.found)))
+ &format!("trait `{}`",
+ tcx.item_path_str(values.expected)),
+ &format!("trait `{}`",
+ tcx.item_path_str(values.found)))
}),
IntMismatch(ref values) => {
write!(f, "expected `{:?}`, found `{:?}`",
values.found)
},
ExistentialMismatch(ref values) => {
- report_maybe_different(f, format!("trait `{}`", values.expected),
- format!("trait `{}`", values.found))
+ report_maybe_different(f, &format!("trait `{}`", values.expected),
+ &format!("trait `{}`", values.found))
}
OldStyleLUB(ref err) => {
write!(f, "{}", err)
}
impl<'a, 'gcx, 'lcx, 'tcx> ty::TyS<'tcx> {
- pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> String {
+ pub fn sort_string(&self, tcx: TyCtxt<'a, 'gcx, 'lcx>) -> Cow<'static, str> {
match self.sty {
ty::Bool | ty::Char | ty::Int(_) |
- ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string(),
- ty::Tuple(ref tys) if tys.is_empty() => self.to_string(),
+ ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => self.to_string().into(),
+ ty::Tuple(ref tys) if tys.is_empty() => self.to_string().into(),
- ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)),
- ty::Foreign(def_id) => format!("extern type `{}`", tcx.item_path_str(def_id)),
+ ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.item_path_str(def.did)).into(),
+ ty::Foreign(def_id) => format!("extern type `{}`", tcx.item_path_str(def_id)).into(),
ty::Array(_, n) => {
match n.assert_usize(tcx) {
- Some(n) => format!("array of {} elements", n),
- None => "array".to_string(),
+ Some(n) => format!("array of {} elements", n).into(),
+ None => "array".into(),
}
}
- ty::Slice(_) => "slice".to_string(),
- ty::RawPtr(_) => "*-ptr".to_string(),
+ ty::Slice(_) => "slice".into(),
+ ty::RawPtr(_) => "*-ptr".into(),
ty::Ref(region, ty, mutbl) => {
let tymut = ty::TypeAndMut { ty, mutbl };
let tymut_string = tymut.to_string();
format!("{}reference", match mutbl {
hir::Mutability::MutMutable => "mutable ",
_ => ""
- })
+ }).into()
} else {
- format!("&{}", tymut_string)
+ format!("&{}", tymut_string).into()
}
}
- ty::FnDef(..) => "fn item".to_string(),
- ty::FnPtr(_) => "fn pointer".to_string(),
+ ty::FnDef(..) => "fn item".into(),
+ ty::FnPtr(_) => "fn pointer".into(),
ty::Dynamic(ref inner, ..) => {
- inner.principal().map_or_else(|| "trait".to_string(),
- |p| format!("trait {}", tcx.item_path_str(p.def_id())))
+ inner.principal().map_or_else(|| "trait".into(),
+ |p| format!("trait {}", tcx.item_path_str(p.def_id())).into())
}
- ty::Closure(..) => "closure".to_string(),
- ty::Generator(..) => "generator".to_string(),
- ty::GeneratorWitness(..) => "generator witness".to_string(),
- ty::Tuple(..) => "tuple".to_string(),
- ty::Infer(ty::TyVar(_)) => "inferred type".to_string(),
- ty::Infer(ty::IntVar(_)) => "integral variable".to_string(),
- ty::Infer(ty::FloatVar(_)) => "floating-point variable".to_string(),
+ ty::Closure(..) => "closure".into(),
+ ty::Generator(..) => "generator".into(),
+ ty::GeneratorWitness(..) => "generator witness".into(),
+ ty::Tuple(..) => "tuple".into(),
+ ty::Infer(ty::TyVar(_)) => "inferred type".into(),
+ ty::Infer(ty::IntVar(_)) => "integral variable".into(),
+ ty::Infer(ty::FloatVar(_)) => "floating-point variable".into(),
ty::Infer(ty::CanonicalTy(_)) |
- ty::Infer(ty::FreshTy(_)) => "skolemized type".to_string(),
- ty::Infer(ty::FreshIntTy(_)) => "skolemized integral type".to_string(),
- ty::Infer(ty::FreshFloatTy(_)) => "skolemized floating-point type".to_string(),
- ty::Projection(_) => "associated type".to_string(),
+ ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
+ ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
+ ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
+ ty::Projection(_) => "associated type".into(),
+ ty::UnnormalizedProjection(_) => "non-normalized associated type".into(),
ty::Param(ref p) => {
if p.is_self() {
- "Self".to_string()
+ "Self".into()
} else {
- "type parameter".to_string()
+ "type parameter".into()
}
}
- ty::Opaque(..) => "opaque type".to_string(),
- ty::Error => "type error".to_string(),
+ ty::Opaque(..) => "opaque type".into(),
+ ty::Error => "type error".into(),
}
}
}
db.note("no two closures, even if identical, have the same type");
db.help("consider boxing your closure and/or using it as a trait object");
}
- match (&values.found.sty, &values.expected.sty) { // Issue #53280
- (ty::Infer(ty::IntVar(_)), ty::Float(_)) => {
- if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
- if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
- db.span_suggestion_with_applicability(
- sp,
- "use a float literal",
- format!("{}.0", snippet),
- Applicability::MachineApplicable
- );
- }
+ if let (ty::Infer(ty::IntVar(_)), ty::Float(_)) =
+ (&values.found.sty, &values.expected.sty) // Issue #53280
+ {
+ if let Ok(snippet) = self.sess.source_map().span_to_snippet(sp) {
+ if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
+ db.span_suggestion_with_applicability(
+ sp,
+ "use a float literal",
+ format!("{}.0", snippet),
+ Applicability::MachineApplicable
+ );
}
- },
- _ => {}
+ }
}
},
OldStyleLUB(err) => {
ty::FnPtr(ref f) => {
Some(FunctionSimplifiedType(f.skip_binder().inputs().len()))
}
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
ty::Projection(_) | ty::Param(_) => {
if can_simplify_params {
// In normalized types, projections don't unify with
let outer_exclusive_binder = computation.outer_exclusive_binder;
if outer_exclusive_binder > ty::INNERMOST {
self.add_exclusive_binder(outer_exclusive_binder.shifted_out(1));
- } else {
- // otherwise, this binder captures nothing
- }
+ } // otherwise, this binder captures nothing
}
fn add_sty(&mut self, st: &ty::TyKind<'_>) {
self.add_projection_ty(data);
}
+ &ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
+
&ty::Opaque(_, substs) => {
self.add_flags(TypeFlags::HAS_PROJECTION);
self.add_substs(substs);
/// we already use the term "free region". It refers to the regions that we use to represent bound
/// regions on a fn definition while we are typechecking its body.
///
-/// To clarify, conceptually there is no particular difference between an "escaping" region and a
-/// "free" region. However, there is a big difference in practice. Basically, when "entering" a
-/// binding level, one is generally required to do some sort of processing to a bound region, such
-/// as replacing it with a fresh/skolemized region, or making an entry in the environment to
-/// represent the scope to which it is attached, etc. An escaping region represents a bound region
-/// for which this processing has not yet been done.
+/// To clarify, conceptually there is no particular difference between
+/// an "escaping" region and a "free" region. However, there is a big
+/// difference in practice. Basically, when "entering" a binding
+/// level, one is generally required to do some sort of processing to
+/// a bound region, such as replacing it with a fresh/placeholder
+/// region, or making an entry in the environment to represent the
+/// scope to which it is attached, etc. An escaping region represents
+/// a bound region for which this processing has not yet been done.
struct HasEscapingRegionsVisitor {
/// Anything bound by `outer_index` or "above" is escaping
outer_index: ty::DebruijnIndex,
}
fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
- match *r {
- ty::ReLateBound(debruijn, br) if debruijn == self.current_index => {
+ if let ty::ReLateBound(debruijn, br) = *r {
+ if debruijn == self.current_index {
self.regions.insert(br);
}
- _ => { }
}
false
}
tcx: TyCtxt<'a, 'gcx, 'tcx>,
id: DefId) -> bool
{
- for root_id in self.root_ids.iter() {
- if tcx.is_descendant_of(id, *root_id) {
- return true;
- }
- }
- false
+ self.root_ids.iter().any(|root_id| tcx.is_descendant_of(id, *root_id))
}
/// Calculate the intersection of a collection of forests.
}
ret.root_ids.extend(old_ret.drain());
- for id in next_forest.root_ids {
- if ret.contains(tcx, id) {
- next_ret.push(id);
- }
- }
+ next_ret.extend(next_forest.root_ids.into_iter().filter(|&id| ret.contains(tcx, id)));
mem::swap(&mut next_ret, &mut ret.root_ids);
next_ret.drain();
let mut ret = DefIdForest::empty();
let mut next_ret = SmallVec::new();
for next_forest in iter {
- for id in ret.root_ids.drain() {
- if !next_forest.contains(tcx, id) {
- next_ret.push(id);
- }
- }
+ next_ret.extend(ret.root_ids.drain().filter(|&id| !next_forest.contains(tcx, id)));
for id in next_forest.root_ids {
if !next_ret.contains(&id) {
}
pub fn resolve_closure(
- tcx: TyCtxt<'a, 'tcx, 'tcx>,
- def_id: DefId,
- substs: ty::ClosureSubsts<'tcx>,
- requested_kind: ty::ClosureKind)
- -> Instance<'tcx>
+ tcx: TyCtxt<'a, 'tcx, 'tcx>,
+ def_id: DefId,
+ substs: ty::ClosureSubsts<'tcx>,
+ requested_kind: ty::ClosureKind)
+ -> Instance<'tcx>
{
let actual_kind = substs.closure_kind(def_id, tcx);
) -> Option<Instance<'tcx>> {
let def_id = trait_item.def_id;
debug!("resolve_associated_item(trait_item={:?}, \
- trait_id={:?}, \
- rcvr_substs={:?})",
+ trait_id={:?}, \
+ rcvr_substs={:?})",
def_id, trait_id, rcvr_substs);
let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
traits::VtableClosure(closure_data) => {
let trait_closure_kind = tcx.lang_items().fn_trait_kind(trait_id).unwrap();
Some(Instance::resolve_closure(tcx, closure_data.closure_def_id, closure_data.substs,
- trait_closure_kind))
+ trait_closure_kind))
}
traits::VtableFnPointer(ref data) => {
Some(Instance {
}
fn needs_fn_once_adapter_shim<'a, 'tcx>(actual_closure_kind: ty::ClosureKind,
- trait_closure_kind: ty::ClosureKind)
+ trait_closure_kind: ty::ClosureKind)
-> Result<bool, ()>
{
match (actual_closure_kind, trait_closure_kind) {
}
fn fn_once_adapter_instance<'a, 'tcx>(
- tcx: TyCtxt<'a, 'tcx, 'tcx>,
- closure_did: DefId,
- substs: ty::ClosureSubsts<'tcx>,
- ) -> Instance<'tcx> {
+ tcx: TyCtxt<'a, 'tcx, 'tcx>,
+ closure_did: DefId,
+ substs: ty::ClosureSubsts<'tcx>)
+ -> Instance<'tcx>
+{
debug!("fn_once_adapter_shim({:?}, {:?})",
- closure_did,
- substs);
+ closure_did,
+ substs);
let fn_once = tcx.lang_items().fn_once_trait().unwrap();
let call_once = tcx.associated_items(fn_once)
.find(|it| it.kind == ty::AssociatedKind::Method)
let data = cur_def_key.disambiguated_data.data;
let symbol = data.get_opt_name().map(|n| n.as_str()).unwrap_or_else(|| {
- if let DefPathData::CrateRoot = data { // reexported `extern crate` (#43189)
+ if let DefPathData::CrateRoot = data { // reexported `extern crate` (#43189)
self.original_crate_name(cur_def.krate).as_str()
} else {
Symbol::intern("<unnamed>").as_str()
if let Some(trait_ref) = impl_trait_ref {
// Trait impls.
- buffer.push(&format!("<{} as {}>",
- self_ty,
- trait_ref));
+ buffer.push(&format!("<{} as {}>", self_ty, trait_ref));
return;
}
ty::Str |
ty::FnPtr(_) |
ty::Projection(_) |
+ ty::UnnormalizedProjection(..) |
ty::Param(_) |
ty::Opaque(..) |
ty::Infer(_) |
fn to_ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, signed: bool) -> Ty<'tcx>;
fn from_attr<C: HasDataLayout>(cx: C, ity: attr::IntType) -> Integer;
fn repr_discr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
- ty: Ty<'tcx>,
- repr: &ReprOptions,
- min: i128,
- max: i128)
- -> (Integer, bool);
+ ty: Ty<'tcx>,
+ repr: &ReprOptions,
+ min: i128,
+ max: i128)
+ -> (Integer, bool);
}
impl IntegerExt for Integer {
/// N.B.: u128 values above i128::MAX will be treated as signed, but
/// that shouldn't affect anything, other than maybe debuginfo.
fn repr_discr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
- ty: Ty<'tcx>,
- repr: &ReprOptions,
- min: i128,
- max: i128)
- -> (Integer, bool) {
+ ty: Ty<'tcx>,
+ repr: &ReprOptions,
+ min: i128,
+ max: i128)
+ -> (Integer, bool) {
// Theoretically, negative values could be larger in unsigned representation
// than the unsigned representation of the signed minimum. However, if there
// are any negative values, the only valid unsigned representation is u128
let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
if discr < fit {
bug!("Integer::repr_discr: `#[repr]` hint too small for \
- discriminant range of enum `{}", ty)
+ discriminant range of enum `{}", ty)
}
return (discr, ity.is_signed());
}
// WARNING: the ARM EABI has two variants; the one corresponding
// to `at_least == I32` appears to be used on Linux and NetBSD,
// but some systems may use the variant corresponding to no
- // lower bound. However, we don't run on those yet...?
+ // lower bound. However, we don't run on those yet...?
"arm" => min_from_extern = Some(I32),
_ => min_from_extern = Some(I32),
}
/// A univariant, but with a prefix of an arbitrary size & alignment (e.g. enum tag).
Prefixed(Size, Align),
}
+
let univariant_uninterned = |fields: &[TyLayout<'_>], repr: &ReprOptions, kind| {
let packed = repr.packed();
if packed && repr.align > 0 {
let field = fields[i as usize];
if !sized {
bug!("univariant: field #{} of `{}` comes after unsized field",
- offsets.len(), ty);
+ offsets.len(), ty);
}
if field.is_unsized() {
};
univariant(&tys.iter().map(|ty| self.layout_of(ty)).collect::<Result<Vec<_>, _>>()?,
- &ReprOptions::default(), kind)?
+ &ReprOptions::default(), kind)?
}
// SIMD vector types.
Abi::Scalar(ref scalar) => scalar.clone(),
_ => {
tcx.sess.fatal(&format!("monomorphising SIMD type `{}` with \
- a non-machine element type `{}`",
+ a non-machine element type `{}`",
ty, element.ty));
}
};
// Only one variant is present.
(present_second.is_none() &&
// Representation optimizations are allowed.
- !def.repr.inhibit_enum_layout_opt());
+ !def.repr.inhibit_enum_layout_opt());
if is_struct {
// Struct, or univariant enum equivalent to a struct.
// (Typechecking will reject discriminant-sizing attrs.)
let param_env = tcx.param_env(def.did);
let last_field = def.variants[v].fields.last().unwrap();
let always_sized = tcx.type_of(last_field.did)
- .is_sized(tcx.at(DUMMY_SP), param_env);
+ .is_sized(tcx.at(DUMMY_SP), param_env);
if !always_sized { StructKind::MaybeUnsized }
else { StructKind::AlwaysSized }
};
}
tcx.layout_raw(param_env.and(normalized))?
}
- ty::GeneratorWitness(..) | ty::Infer(_) => {
+ ty::UnnormalizedProjection(..) | ty::GeneratorWitness(..) | ty::Infer(_) => {
bug!("LayoutDetails::compute: unexpected type `{}`", ty)
}
ty::Param(_) | ty::Error => {
let fields: Vec<_> =
variant_def.fields.iter().map(|f| f.ident.name).collect();
build_variant_info(Some(variant_def.name),
- &fields,
- layout.for_variant(self, i))
+ &fields,
+ layout.for_variant(self, i))
})
.collect();
record(adt_kind.into(), adt_packed, match layout.variants {
}
}
- ty::Projection(_) | ty::Opaque(..) | ty::Param(_) |
- ty::Infer(_) | ty::Error => {
+ ty::Projection(_) | ty::UnnormalizedProjection(..) |
+ ty::Opaque(..) | ty::Param(_) | ty::Infer(_) | ty::Error => {
bug!("TyLayout::field_type: unexpected type `{}`", this.ty)
}
})
impl GenericParamDef {
pub fn to_early_bound_region_data(&self) -> ty::EarlyBoundRegion {
- match self.kind {
- GenericParamDefKind::Lifetime => {
- ty::EarlyBoundRegion {
- def_id: self.def_id,
- index: self.index,
- name: self.name,
- }
+ if let GenericParamDefKind::Lifetime = self.kind {
+ ty::EarlyBoundRegion {
+ def_id: self.def_id,
+ index: self.index,
+ name: self.name,
}
- _ => bug!("cannot convert a non-lifetime parameter def to an early bound region")
+ } else {
+ bug!("cannot convert a non-lifetime parameter def to an early bound region")
}
}
pub fn to_bound_region(&self) -> ty::BoundRegion {
- match self.kind {
- GenericParamDefKind::Lifetime => {
- self.to_early_bound_region_data().to_bound_region()
- }
- _ => bug!("cannot convert a non-lifetime parameter def to an early bound region")
+ if let GenericParamDefKind::Lifetime = self.kind {
+ self.to_early_bound_region_data().to_bound_region()
+ } else {
+ bug!("cannot convert a non-lifetime parameter def to an early bound region")
}
}
}
}
} else {
tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
- .region_param(param, tcx)
+ .region_param(param, tcx)
}
}
}
} else {
tcx.generics_of(self.parent.expect("parent_count>0 but no parent?"))
- .type_param(param, tcx)
+ .type_param(param, tcx)
}
}
}
}
};
- // The only reason to collect into a vector here is that I was
+ // FIXME: The only reason to collect into a vector here is that I was
// too lazy to make the full (somewhat complicated) iterator
// type that would be needed here. But I wanted this fn to
// return an iterator conceptually, rather than a `Vec`, so as
/// region `'a` is in a subuniverse U2 of U1, because we can name it
/// inside the fn type but not outside.
///
-/// Universes are related to **skolemization** -- which is a way of
-/// doing type- and trait-checking around these "forall" binders (also
-/// called **universal quantification**). The idea is that when, in
-/// the body of `bar`, we refer to `T` as a type, we aren't referring
-/// to any type in particular, but rather a kind of "fresh" type that
-/// is distinct from all other types we have actually declared. This
-/// is called a **skolemized** type, and we use universes to talk
-/// about this. In other words, a type name in universe 0 always
-/// corresponds to some "ground" type that the user declared, but a
-/// type name in a non-zero universe is a skolemized type -- an
-/// idealized representative of "types in general" that we use for
-/// checking generic functions.
+/// Universes are used to do type- and trait-checking around these
+/// "forall" binders (also called **universal quantification**). The
+/// idea is that when, in the body of `bar`, we refer to `T` as a
+/// type, we aren't referring to any type in particular, but rather a
+/// kind of "fresh" type that is distinct from all other types we have
+/// actually declared. This is called a **placeholder** type, and we
+/// use universes to talk about this. In other words, a type name in
+/// universe 0 always corresponds to some "ground" type that the user
+/// declared, but a type name in a non-zero universe is a placeholder
+/// type -- an idealized representative of "types in general" that we
+/// use for checking generic functions.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
pub struct UniverseIndex(u32);
}
}
+/// The "placeholder index" fully defines a placeholder region.
+/// Placeholder regions are identified by both a **universe** as well
+/// as a "bound-region" within that universe. The `bound_region` is
+/// basically a name -- distinct bound regions within the same
+/// universe are just two regions with an unknown relationship to one
+/// another.
+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, PartialOrd, Ord)]
+pub struct Placeholder {
+ pub universe: UniverseIndex,
+ pub name: BoundRegion,
+}
+
/// When type checking, we use the `ParamEnv` to track
/// details about the set of where-clauses that are in scope at this
/// particular point.
const IS_FUNDAMENTAL = 1 << 2;
const IS_UNION = 1 << 3;
const IS_BOX = 1 << 4;
+ /// Indicates whether the type is an `Arc`.
+ const IS_ARC = 1 << 5;
+ /// Indicates whether the type is an `Rc`.
+ const IS_RC = 1 << 6;
/// Indicates whether the variant list of this ADT is `#[non_exhaustive]`.
/// (i.e., this flag is never set unless this ADT is an enum).
- const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 5;
+ const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 7;
}
}
if Some(did) == tcx.lang_items().owned_box() {
flags = flags | AdtFlags::IS_BOX;
}
+ if Some(did) == tcx.lang_items().arc() {
+ flags = flags | AdtFlags::IS_ARC;
+ }
+ if Some(did) == tcx.lang_items().rc() {
+ flags = flags | AdtFlags::IS_RC;
+ }
if kind == AdtKind::Enum && tcx.has_attr(did, "non_exhaustive") {
debug!("found non-exhaustive variant list for {:?}", did);
flags = flags | AdtFlags::IS_VARIANT_LIST_NON_EXHAUSTIVE;
self.flags.intersects(AdtFlags::IS_PHANTOM_DATA)
}
+ /// Returns `true` if this is `Arc<T>`.
+ pub fn is_arc(&self) -> bool {
+ self.flags.intersects(AdtFlags::IS_ARC)
+ }
+
+ /// Returns `true` if this is `Rc<T>`.
+ pub fn is_rc(&self) -> bool {
+ self.flags.intersects(AdtFlags::IS_RC)
+ }
+
/// Returns true if this is Box<T>.
#[inline]
pub fn is_box(&self) -> bool {
if !expr_did.is_local() {
span_bug!(tcx.def_span(expr_did),
"variant discriminant evaluation succeeded \
- in its crate but failed locally");
+ in its crate but failed locally");
}
None
}
debug!("sized_constraint_for_ty({:?}) intermediate = {:?}",
ty, adt_tys);
adt_tys.iter()
- .map(|ty| ty.subst(tcx, substs))
- .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
- .collect()
+ .map(|ty| ty.subst(tcx, substs))
+ .flat_map(|ty| self.sized_constraint_for_ty(tcx, ty))
+ .collect()
}
Projection(..) | Opaque(..) => {
vec![ty]
}
+ UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
+
Param(..) => {
// perf hack: if there is a `T: Sized` bound, then
// we know that `T` is Sized and do not need to check
}
}
-fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
- -> AssociatedItem
-{
+fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> AssociatedItem {
let id = tcx.hir.as_local_node_id(def_id).unwrap();
let parent_id = tcx.hir.get_parent(id);
let parent_def_id = tcx.hir.local_def_id(parent_id);
/// See `ParamEnv` struct def'n for details.
fn param_env<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId)
- -> ParamEnv<'tcx> {
-
+ -> ParamEnv<'tcx>
+{
// The param_env of an impl Trait type is its defining function's param_env
if let Some(parent) = is_impl_trait_defn(tcx, def_id) {
return param_env(tcx, parent);
// projection).
match ty.sty {
ty::Closure(def_id, ref substs) => {
-
for upvar_ty in substs.upvar_tys(def_id, *self) {
self.compute_components(upvar_ty, out);
}
}
}
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
+
// We assume that inference variables are fully resolved.
// So, if we encounter an inference variable, just record
// the unresolved variable as a component.
}
fn push_region_constraints<'tcx>(out: &mut Vec<Component<'tcx>>, regions: Vec<ty::Region<'tcx>>) {
- for r in regions {
- if !r.is_late_bound() {
- out.push(Component::Region(r));
- }
- }
+ out.extend(regions.iter().filter(|&r| !r.is_late_bound()).map(|r| Component::Region(r)));
}
use ty::query::QueryCache;
use util::profiling::ProfileCategory;
+use std::borrow::Cow;
use std::hash::Hash;
use std::fmt::Debug;
use syntax_pos::symbol::InternedString;
}
pub(super) trait QueryDescription<'tcx>: QueryAccessors<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, key: Self::Key) -> String;
+ fn describe(tcx: TyCtxt<'_, '_, '_>, key: Self::Key) -> Cow<'static, str>;
#[inline]
fn cache_on_disk(_: Self::Key) -> bool {
}
impl<'tcx, M: QueryAccessors<'tcx, Key=DefId>> QueryDescription<'tcx> for M {
- default fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
+ default fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
if !tcx.sess.verbose() {
- format!("processing `{}`", tcx.item_path_str(def_id))
+ format!("processing `{}`", tcx.item_path_str(def_id)).into()
} else {
let name = unsafe { ::std::intrinsics::type_name::<M>() };
- format!("processing `{}` applied to `{:?}`", name, def_id)
+ format!("processing `{}` applied to `{:?}`", name, def_id).into()
}
}
}
fn describe(
_tcx: TyCtxt<'_, '_, '_>,
goal: CanonicalProjectionGoal<'tcx>,
- ) -> String {
- format!("normalizing `{:?}`", goal)
+ ) -> Cow<'static, str> {
+ format!("normalizing `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::implied_outlives_bounds<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTyGoal<'tcx>) -> String {
- format!("computing implied outlives bounds for `{:?}`", goal)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTyGoal<'tcx>) -> Cow<'static, str> {
+ format!("computing implied outlives bounds for `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::dropck_outlives<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTyGoal<'tcx>) -> String {
- format!("computing dropck types for `{:?}`", goal)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTyGoal<'tcx>) -> Cow<'static, str> {
+ format!("computing dropck types for `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::normalize_ty_after_erasing_regions<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
- format!("normalizing `{:?}`", goal)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: ParamEnvAnd<'tcx, Ty<'tcx>>) -> Cow<'static, str> {
+ format!("normalizing `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::evaluate_obligation<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalPredicateGoal<'tcx>) -> String {
- format!("evaluating trait selection obligation `{}`", goal.value.value)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalPredicateGoal<'tcx>) -> Cow<'static, str> {
+ format!("evaluating trait selection obligation `{}`", goal.value.value).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::type_op_eq<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTypeOpEqGoal<'tcx>) -> String {
- format!("evaluating `type_op_eq` `{:?}`", goal)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTypeOpEqGoal<'tcx>) -> Cow<'static, str> {
+ format!("evaluating `type_op_eq` `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::type_op_subtype<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTypeOpSubtypeGoal<'tcx>) -> String {
- format!("evaluating `type_op_subtype` `{:?}`", goal)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTypeOpSubtypeGoal<'tcx>)
+ -> Cow<'static, str> {
+ format!("evaluating `type_op_subtype` `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::type_op_prove_predicate<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTypeOpProvePredicateGoal<'tcx>) -> String {
- format!("evaluating `type_op_prove_predicate` `{:?}`", goal)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, goal: CanonicalTypeOpProvePredicateGoal<'tcx>)
+ -> Cow<'static, str> {
+ format!("evaluating `type_op_prove_predicate` `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::type_op_normalize_ty<'tcx> {
fn describe(_tcx: TyCtxt<'_, '_, '_>,
- goal: CanonicalTypeOpNormalizeGoal<'tcx, Ty<'tcx>>) -> String {
- format!("normalizing `{:?}`", goal)
+ goal: CanonicalTypeOpNormalizeGoal<'tcx, Ty<'tcx>>) -> Cow<'static, str> {
+ format!("normalizing `{:?}`", goal).into()
}
}
fn describe(
_tcx: TyCtxt<'_, '_, '_>,
goal: CanonicalTypeOpNormalizeGoal<'tcx, ty::Predicate<'tcx>>,
- ) -> String {
- format!("normalizing `{:?}`", goal)
+ ) -> Cow<'static, str> {
+ format!("normalizing `{:?}`", goal).into()
}
}
fn describe(
_tcx: TyCtxt<'_, '_, '_>,
goal: CanonicalTypeOpNormalizeGoal<'tcx, ty::PolyFnSig<'tcx>>,
- ) -> String {
- format!("normalizing `{:?}`", goal)
+ ) -> Cow<'static, str> {
+ format!("normalizing `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::type_op_normalize_fn_sig<'tcx> {
fn describe(_tcx: TyCtxt<'_, '_, '_>,
- goal: CanonicalTypeOpNormalizeGoal<'tcx, ty::FnSig<'tcx>>) -> String {
- format!("normalizing `{:?}`", goal)
+ goal: CanonicalTypeOpNormalizeGoal<'tcx, ty::FnSig<'tcx>>) -> Cow<'static, str> {
+ format!("normalizing `{:?}`", goal).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_copy_raw<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
- format!("computing whether `{}` is `Copy`", env.value)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
+ -> Cow<'static, str> {
+ format!("computing whether `{}` is `Copy`", env.value).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_sized_raw<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
- format!("computing whether `{}` is `Sized`", env.value)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
+ -> Cow<'static, str> {
+ format!("computing whether `{}` is `Sized`", env.value).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_freeze_raw<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
- format!("computing whether `{}` is freeze", env.value)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
+ -> Cow<'static, str> {
+ format!("computing whether `{}` is freeze", env.value).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::needs_drop_raw<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
- format!("computing whether `{}` needs drop", env.value)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
+ -> Cow<'static, str> {
+ format!("computing whether `{}` needs drop", env.value).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::layout_raw<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> String {
- format!("computing layout of `{}`", env.value)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>)
+ -> Cow<'static, str> {
+ format!("computing layout of `{}`", env.value).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::super_predicates_of<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
format!("computing the supertraits of `{}`",
- tcx.item_path_str(def_id))
+ tcx.item_path_str(def_id)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::erase_regions_ty<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, ty: Ty<'tcx>) -> String {
- format!("erasing regions from `{:?}`", ty)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, ty: Ty<'tcx>) -> Cow<'static, str> {
+ format!("erasing regions from `{:?}`", ty).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::type_param_predicates<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, (_, def_id): (DefId, DefId)) -> String {
+ fn describe(tcx: TyCtxt<'_, '_, '_>, (_, def_id): (DefId, DefId)) -> Cow<'static, str> {
let id = tcx.hir.as_local_node_id(def_id).unwrap();
format!("computing the bounds for type parameter `{}`",
- tcx.hir.ty_param_name(id))
+ tcx.hir.ty_param_name(id)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::coherent_trait<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
format!("coherence checking all impls of trait `{}`",
- tcx.item_path_str(def_id))
+ tcx.item_path_str(def_id)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::upstream_monomorphizations<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, k: CrateNum) -> String {
- format!("collecting available upstream monomorphizations `{:?}`", k)
+ fn describe(_: TyCtxt<'_, '_, '_>, k: CrateNum) -> Cow<'static, str> {
+ format!("collecting available upstream monomorphizations `{:?}`", k).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::crate_inherent_impls<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, k: CrateNum) -> String {
- format!("all inherent impls defined in crate `{:?}`", k)
+ fn describe(_: TyCtxt<'_, '_, '_>, k: CrateNum) -> Cow<'static, str> {
+ format!("all inherent impls defined in crate `{:?}`", k).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::crate_inherent_impls_overlap_check<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "check for overlap between inherent impls defined in this crate".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "check for overlap between inherent impls defined in this crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::crate_variances<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "computing the variances for items in this crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "computing the variances for items in this crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::inferred_outlives_crate<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "computing the inferred outlives predicates for items in this crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "computing the inferred outlives predicates for items in this crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::mir_shims<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def: ty::InstanceDef<'tcx>) -> String {
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def: ty::InstanceDef<'tcx>) -> Cow<'static, str> {
format!("generating MIR shim for `{}`",
- tcx.item_path_str(def.def_id()))
+ tcx.item_path_str(def.def_id())).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::privacy_access_levels<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "privacy access levels".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "privacy access levels".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::typeck_item_bodies<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "type-checking all item bodies".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "type-checking all item bodies".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::reachable_set<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "reachability".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "reachability".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::const_eval<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>) -> String {
- format!("const-evaluating `{}`", tcx.item_path_str(key.value.instance.def.def_id()))
+ fn describe(tcx: TyCtxt<'_, '_, '_>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>)
+ -> Cow<'static, str>
+ {
+ format!("const-evaluating `{}`", tcx.item_path_str(key.value.instance.def.def_id())).into()
}
#[inline]
}
impl<'tcx> QueryDescription<'tcx> for queries::mir_keys<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "getting a list of all mir_keys".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "getting a list of all mir_keys".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::symbol_name<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, instance: ty::Instance<'tcx>) -> String {
- format!("computing the symbol for `{}`", instance)
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, instance: ty::Instance<'tcx>) -> Cow<'static, str> {
+ format!("computing the symbol for `{}`", instance).into()
}
#[inline]
}
impl<'tcx> QueryDescription<'tcx> for queries::describe_def<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("describe_def")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::def_span<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("def_span")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::lookup_stability<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("stability")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::lookup_deprecation_entry<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("deprecation")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::item_attrs<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("item_attrs")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_reachable_non_generic<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("is_reachable_non_generic")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::fn_arg_names<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("fn_arg_names")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::impl_parent<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("impl_parent")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::trait_of_item<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
bug!("trait_of_item")
}
}
impl<'tcx> QueryDescription<'tcx> for queries::const_is_rvalue_promotable_to_static<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
format!("const checking if rvalue is promotable to static `{}`",
- tcx.item_path_str(def_id))
+ tcx.item_path_str(def_id)).into()
}
#[inline]
#[inline]
fn try_load_from_disk<'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
- id: SerializedDepNodeIndex)
- -> Option<Self::Value> {
+ id: SerializedDepNodeIndex)
+ -> Option<Self::Value> {
tcx.queries.on_disk_cache.try_load_query_result(tcx, id)
}
}
impl<'tcx> QueryDescription<'tcx> for queries::rvalue_promotable_map<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
format!("checking which parts of `{}` are promotable to static",
- tcx.item_path_str(def_id))
+ tcx.item_path_str(def_id)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_mir_available<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
format!("checking if item is mir available: `{}`",
- tcx.item_path_str(def_id))
+ tcx.item_path_str(def_id)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::codegen_fulfill_obligation<'tcx> {
fn describe(tcx: TyCtxt<'_, '_, '_>,
- key: (ty::ParamEnv<'tcx>, ty::PolyTraitRef<'tcx>)) -> String {
+ key: (ty::ParamEnv<'tcx>, ty::PolyTraitRef<'tcx>)) -> Cow<'static, str> {
format!("checking if `{}` fulfills its obligations", tcx.item_path_str(key.1.def_id()))
+ .into()
}
#[inline]
}
impl<'tcx> QueryDescription<'tcx> for queries::trait_impls_of<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
- format!("trait impls of `{}`", tcx.item_path_str(def_id))
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
+ format!("trait impls of `{}`", tcx.item_path_str(def_id)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_object_safe<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
- format!("determine object safety of trait `{}`", tcx.item_path_str(def_id))
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
+ format!("determine object safety of trait `{}`", tcx.item_path_str(def_id)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_const_fn_raw<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> String {
- format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id))
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Cow<'static, str> {
+ format!("checking if item is const fn: `{}`", tcx.item_path_str(def_id)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::dylib_dependency_formats<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "dylib dependency formats of crate".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "dylib dependency formats of crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_panic_runtime<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "checking if the crate is_panic_runtime".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "checking if the crate is_panic_runtime".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_compiler_builtins<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "checking if the crate is_compiler_builtins".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "checking if the crate is_compiler_builtins".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::has_global_allocator<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "checking if the crate has_global_allocator".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "checking if the crate has_global_allocator".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::has_panic_handler<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "checking if the crate has_panic_handler".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "checking if the crate has_panic_handler".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::extern_crate<'tcx> {
- fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> String {
- "getting crate's ExternCrateData".to_string()
+ fn describe(_: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
+ "getting crate's ExternCrateData".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::lint_levels<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "computing the lint levels for items in this crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "computing the lint levels for items in this crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::specializes<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: (DefId, DefId)) -> String {
- "computing whether impls specialize one another".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: (DefId, DefId)) -> Cow<'static, str> {
+ "computing whether impls specialize one another".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::in_scope_traits_map<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefIndex) -> String {
- "traits in scope at a block".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefIndex) -> Cow<'static, str> {
+ "traits in scope at a block".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_no_builtins<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "test whether a crate has #![no_builtins]".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "test whether a crate has #![no_builtins]".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::panic_strategy<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "query a crate's configured panic strategy".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "query a crate's configured panic strategy".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_profiler_runtime<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "query a crate is #![profiler_runtime]".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "query a crate is #![profiler_runtime]".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_sanitizer_runtime<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "query a crate is #![sanitizer_runtime]".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "query a crate is #![sanitizer_runtime]".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::reachable_non_generics<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the exported symbols of a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the exported symbols of a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::native_libraries<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the native libraries of a linked crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the native libraries of a linked crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::foreign_modules<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the foreign modules of a linked crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the foreign modules of a linked crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::plugin_registrar_fn<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the plugin registrar for a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the plugin registrar for a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::derive_registrar_fn<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the derive registrar for a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the derive registrar for a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::crate_disambiguator<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the disambiguator a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the disambiguator a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::crate_hash<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the hash a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the hash a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::original_crate_name<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the original name a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the original name a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::extra_filename<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the extra filename for a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the extra filename for a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::implementations_of_trait<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: (CrateNum, DefId)) -> String {
- "looking up implementations of a trait in a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: (CrateNum, DefId)) -> Cow<'static, str> {
+ "looking up implementations of a trait in a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::all_trait_implementations<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up all (?) trait implementations".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up all (?) trait implementations".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::link_args<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up link arguments for a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up link arguments for a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::resolve_lifetimes<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "resolving lifetimes".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "resolving lifetimes".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::named_region_map<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefIndex) -> String {
- "looking up a named region".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefIndex) -> Cow<'static, str> {
+ "looking up a named region".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::is_late_bound_map<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefIndex) -> String {
- "testing if a region is late bound".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefIndex) -> Cow<'static, str> {
+ "testing if a region is late bound".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::object_lifetime_defaults_map<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefIndex) -> String {
- "looking up lifetime defaults for a region".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefIndex) -> Cow<'static, str> {
+ "looking up lifetime defaults for a region".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::dep_kind<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "fetching what a dependency looks like".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "fetching what a dependency looks like".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::crate_name<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "fetching what a crate is named".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "fetching what a crate is named".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::get_lib_features<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- format!("calculating the lib features map")
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "calculating the lib features map".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::defined_lib_features<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- format!("calculating the lib features defined in a crate")
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "calculating the lib features defined in a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::get_lang_items<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "calculating the lang items map".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "calculating the lang items map".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::defined_lang_items<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "calculating the lang items defined in a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "calculating the lang items defined in a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::missing_lang_items<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "calculating the missing lang items in a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "calculating the missing lang items in a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::visible_parent_map<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "calculating the visible parent map".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "calculating the visible parent map".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::missing_extern_crate_item<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "seeing if we're missing an `extern crate` item for this crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "seeing if we're missing an `extern crate` item for this crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::used_crate_source<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking at the source for a crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking at the source for a crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::postorder_cnums<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "generating a postorder list of CrateNums".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "generating a postorder list of CrateNums".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::maybe_unused_extern_crates<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up all possibly unused extern crates".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up all possibly unused extern crates".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::stability_index<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "calculating the stability index for the local crate".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "calculating the stability index for the local crate".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::all_traits<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "fetching all foreign and local traits".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "fetching all foreign and local traits".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::all_crate_nums<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "fetching all foreign CrateNum instances".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "fetching all foreign CrateNum instances".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::exported_symbols<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "exported_symbols".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "exported_symbols".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::collect_and_partition_mono_items<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "collect_and_partition_mono_items".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "collect_and_partition_mono_items".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::codegen_unit<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: InternedString) -> String {
- "codegen_unit".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: InternedString) -> Cow<'static, str> {
+ "codegen_unit".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::output_filenames<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "output_filenames".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "output_filenames".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::vtable_methods<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, key: ty::PolyTraitRef<'tcx> ) -> String {
- format!("finding all methods for trait {}", tcx.item_path_str(key.def_id()))
+ fn describe(tcx: TyCtxt<'_, '_, '_>, key: ty::PolyTraitRef<'tcx> ) -> Cow<'static, str> {
+ format!("finding all methods for trait {}", tcx.item_path_str(key.def_id())).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::features_query<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up enabled feature gates".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up enabled feature gates".into()
}
}
}
impl<'tcx> QueryDescription<'tcx> for queries::substitute_normalize_and_test_predicates<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, key: (DefId, &'tcx Substs<'tcx>)) -> String {
- format!("testing substituted normalized predicates:`{}`", tcx.item_path_str(key.0))
+ fn describe(tcx: TyCtxt<'_, '_, '_>, key: (DefId, &'tcx Substs<'tcx>)) -> Cow<'static, str> {
+ format!("testing substituted normalized predicates:`{}`", tcx.item_path_str(key.0)).into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::target_features_whitelist<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "looking up the whitelist of target features".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "looking up the whitelist of target features".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::instance_def_size_estimate<'tcx> {
- fn describe(tcx: TyCtxt<'_, '_, '_>, def: ty::InstanceDef<'tcx>) -> String {
- format!("estimating size for `{}`", tcx.item_path_str(def.def_id()))
+ fn describe(tcx: TyCtxt<'_, '_, '_>, def: ty::InstanceDef<'tcx>) -> Cow<'static, str> {
+ format!("estimating size for `{}`", tcx.item_path_str(def.def_id())).into()
}
}
}
impl<'tcx> QueryDescription<'tcx> for queries::program_clauses_for<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefId) -> String {
- "generating chalk-style clauses".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: DefId) -> Cow<'static, str> {
+ "generating chalk-style clauses".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::program_clauses_for_env<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: ty::ParamEnv<'tcx>) -> String {
- "generating chalk-style clauses for param env".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: ty::ParamEnv<'tcx>) -> Cow<'static, str> {
+ "generating chalk-style clauses for param env".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::wasm_import_module_map<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "wasm import module map".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "wasm import module map".into()
}
}
impl<'tcx> QueryDescription<'tcx> for queries::dllimport_foreign_items<'tcx> {
- fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> String {
- "wasm import module map".to_string()
+ fn describe(_tcx: TyCtxt<'_, '_, '_>, _: CrateNum) -> Cow<'static, str> {
+ "wasm import module map".into()
}
}
let mut cycle = Vec::new();
while let Some(job) = current_job {
- cycle.insert(0, job.info.clone());
+ cycle.push(job.info.clone());
if ptr::eq(&*job, self) {
+ cycle.reverse();
+
// This is the end of the cycle
// The span entry we included was for the usage
// of the cycle itself, and not part of the cycle
query: Lrc<QueryJob<'tcx>>,
visited: &mut FxHashSet<*const QueryJob<'tcx>>
) -> bool {
- // We already visited this or we're deliberately ignoring it
- if visited.contains(&query.as_ptr()) {
- return false;
- }
-
// This query is connected to the root (it has no query parent), return true
if query.parent.is_none() {
return true;
}
+ // We already visited this or we're deliberately ignoring it
+ if visited.contains(&query.as_ptr()) {
+ return false;
+ }
+
visited.insert(query.as_ptr());
let mut connected = false;
// Reverse the stack so earlier entries require later entries
stack.reverse();
- // Extract the spans and queries into separate arrays
- let mut spans: Vec<_> = stack.iter().map(|e| e.0).collect();
- let queries = stack.into_iter().map(|e| e.1);
+ // The stack is a vector of pairs of spans and queries
+ let (mut spans, queries): (Vec<_>, Vec<_>) = stack.into_iter().unzip();
// Shift the spans so that queries are matched with the span for their waitee
- let last = spans.pop().unwrap();
- spans.insert(0, last);
+ spans.rotate_right(1);
// Zip them back together
let mut stack: Vec<_> = spans.into_iter().zip(queries).collect();
// Find the queries in the cycle which are
// connected to queries outside the cycle
- let entry_points: Vec<Lrc<QueryJob<'tcx>>> = stack.iter().filter_map(|query| {
+ let entry_points = stack.iter().filter_map(|query| {
// Mark all the other queries in the cycle as already visited
let mut visited = FxHashSet::from_iter(stack.iter().filter_map(|q| {
if q.1.as_ptr() != query.1.as_ptr() {
} else {
None
}
- }).collect();
+ });
// Deterministically pick an entry point
// FIXME: Sort this instead
let mut hcx = tcx.create_stable_hashing_context();
- let entry_point = entry_points.iter().min_by_key(|q| {
+ let entry_point = entry_points.min_by_key(|q| {
let mut stable_hasher = StableHasher::<u64>::new();
q.info.query.hash_stable(&mut hcx, &mut stable_hasher);
stable_hasher.finish()
}).unwrap().as_ptr();
- // Shift the stack until our entry point is first
- while stack[0].1.as_ptr() != entry_point {
- let last = stack.pop().unwrap();
- stack.insert(0, last);
+ // Shift the stack so that our entry point is first
+ let entry_point_pos = stack.iter().position(|(_, query)| query.as_ptr() == entry_point);
+ if let Some(pos) = entry_point_pos {
+ stack.rotate_right(pos);
}
// Create the cycle error
use rustc_data_structures::sync::Lrc;
use rustc_target::spec::PanicStrategy;
+use std::borrow::Cow;
use std::ops::Deref;
use std::sync::Arc;
use syntax_pos::{Span, DUMMY_SP};
})?;
// Encode diagnostics
- let diagnostics_index = {
- let mut diagnostics_index = EncodedDiagnosticsIndex::new();
-
- for (dep_node_index, diagnostics) in self.current_diagnostics
- .borrow()
- .iter() {
- let pos = AbsoluteBytePos::new(encoder.position());
- // Let's make sure we get the expected type here:
- let diagnostics: &EncodedDiagnostics = diagnostics;
- let dep_node_index =
- SerializedDepNodeIndex::new(dep_node_index.index());
- encoder.encode_tagged(dep_node_index, diagnostics)?;
- diagnostics_index.push((dep_node_index, pos));
- }
-
- diagnostics_index
- };
+ let diagnostics_index: EncodedDiagnosticsIndex = self.current_diagnostics.borrow()
+ .iter()
+ .map(|(dep_node_index, diagnostics)|
+ {
+ let pos = AbsoluteBytePos::new(encoder.position());
+ // Let's make sure we get the expected type here:
+ let diagnostics: &EncodedDiagnostics = diagnostics;
+ let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
+ encoder.encode_tagged(dep_node_index, diagnostics)?;
+
+ Ok((dep_node_index, pos))
+ })
+ .collect::<Result<_, _>>()?;
let interpret_alloc_index = {
let mut interpret_alloc_index = Vec::new();
// otherwise, abort
break;
}
+ interpret_alloc_index.reserve(new_n);
for idx in n..new_n {
let id = encoder.interpret_allocs_inverse[idx];
let pos = encoder.position() as u32;
tcx.dep_graph.with_ignore(|| {
let current_cnums = tcx.all_crate_nums(LOCAL_CRATE).iter().map(|&cnum| {
let crate_name = tcx.original_crate_name(cnum)
- .as_str()
.to_string();
let crate_disambiguator = tcx.crate_disambiguator(cnum);
((crate_name, crate_disambiguator), cnum)
}).collect::<FxHashMap<_,_>>();
let map_size = prev_cnums.iter()
- .map(|&(cnum, ..)| cnum)
- .max()
- .unwrap_or(0) + 1;
+ .map(|&(cnum, ..)| cnum)
+ .max()
+ .unwrap_or(0) + 1;
let mut map = IndexVec::new();
map.resize(map_size as usize, None);
}
}
-
//- DECODING -------------------------------------------------------------------
/// A decoder that can read the incr. comp. cache. It is similar to the one
file_index_to_file.borrow_mut().entry(index).or_insert_with(|| {
let stable_id = file_index_to_stable_id[&index];
source_map.source_file_by_stable_id(stable_id)
- .expect("Failed to lookup SourceFile in new context.")
+ .expect("Failed to lookup SourceFile in new context.")
}).clone()
}
}
struct CacheEncoder<'enc, 'a, 'tcx, E>
where E: 'enc + ty_codec::TyEncoder,
- 'tcx: 'a,
+ 'tcx: 'a,
{
tcx: TyCtxt<'a, 'tcx, 'tcx>,
encoder: &'enc mut E,
let (file_lo, line_lo, col_lo) = match self.source_map
.byte_pos_to_line_and_col(span_data.lo) {
Some(pos) => pos,
- None => {
- return TAG_INVALID_SPAN.encode(self);
- }
+ None => return TAG_INVALID_SPAN.encode(self)
};
if !file_lo.contains(span_data.hi) {
let prev_dep_node_index =
self.dep_graph.prev_dep_node_index_of(dep_node);
let result = Q::try_load_from_disk(self.global_tcx(),
- prev_dep_node_index);
+ prev_dep_node_index);
// We always expect to find a cached result for things that
// can be forced from DepNode.
debug_assert!(!dep_node.kind.can_reconstruct_query_key() ||
- result.is_some(),
- "Missing on-disk cache entry for {:?}",
- dep_node);
+ result.is_some(),
+ "Missing on-disk cache entry for {:?}",
+ dep_node);
result
} else {
// Some things are never cached on disk.
assert!(Some(self.dep_graph.fingerprint_of(dep_node_index)) ==
self.dep_graph.prev_fingerprint_of(dep_node),
"Fingerprint for green query instance not loaded \
- from cache: {:?}", dep_node);
+ from cache: {:?}", dep_node);
debug!("BEGIN verify_ich({:?})", dep_node);
let mut hcx = self.create_stable_hashing_context();
// (see for example #48923)
assert!(!self.dep_graph.dep_node_exists(&dep_node),
"Forcing query with already existing DepNode.\n\
- - query-key: {:?}\n\
- - dep-node: {:?}",
+ - query-key: {:?}\n\
+ - dep-node: {:?}",
key, dep_node);
profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
// We use try_lock here since we are only called from the
// deadlock handler, and this shouldn't be locked
- $(for v in self.$name.try_lock().unwrap().active.values() {
- match *v {
- QueryResult::Started(ref job) => jobs.push(job.clone()),
- _ => (),
- }
- })*
-
- return jobs;
+ $(
+ jobs.extend(
+ self.$name.try_lock().unwrap().active.values().filter_map(|v|
+ if let QueryResult::Started(ref job) = *v {
+ Some(job.clone())
+ } else {
+ None
+ }
+ )
+ );
+ )*
+
+ jobs
}
}
}
}
- pub fn describe(&self, tcx: TyCtxt<'_, '_, '_>) -> String {
+ pub fn describe(&self, tcx: TyCtxt<'_, '_, '_>) -> Cow<'static, str> {
let (r, name) = match *self {
$(Query::$name(key) => {
(queries::$name::describe(tcx, key), stringify!($name))
})*
};
if tcx.sess.verbose() {
- format!("{} [{}]", r, name)
+ format!("{} [{}]", r, name).into()
} else {
r
}
}
// The def_span query is used to calculate default_span,
// so exit to avoid infinite recursion
- match *self {
- Query::def_span(..) => return span,
- _ => ()
+ if let Query::def_span(..) = *self {
+ return span
}
match *self {
$(Query::$name(key) => key.default_span(tcx),)*
)
);
- match tcx.force_query::<::ty::query::queries::$query<'_>>(
+ if let Err(e) = tcx.force_query::<::ty::query::queries::$query<'_>>(
$key, DUMMY_SP, *dep_node
) {
- Ok(_) => {},
- Err(e) => {
- tcx.report_cycle(e).emit();
- }
+ tcx.report_cycle(e).emit();
}
}
}
if a.len() != b.len() {
Err(TypeError::ProjectionBoundsLength(expected_found(relation, &a.len(), &b.len())))
} else {
- a.iter().zip(b)
- .map(|(a, b)| relation.relate(a, b))
- .collect()
+ a.iter()
+ .zip(b)
+ .map(|(a, b)| relation.relate(a, b))
+ .collect()
}
}
}
-> RelateResult<'tcx, GeneratorWitness<'tcx>>
where R: TypeRelation<'a, 'gcx, 'tcx>, 'gcx: 'a+'tcx, 'tcx: 'a
{
- assert!(a.0.len() == b.0.len());
+ assert_eq!(a.0.len(), b.0.len());
let tcx = relation.tcx();
let types = tcx.mk_type_list(a.0.iter().zip(b.0).map(|(a, b)| relation.relate(a, b)))?;
Ok(GeneratorWitness(types))
ConstValue::Unevaluated(def_id, substs) => {
// FIXME(eddyb) get the right param_env.
let param_env = ty::ParamEnv::empty();
- match tcx.lift_to_global(&substs) {
- Some(substs) => {
- let instance = ty::Instance::resolve(
- tcx.global_tcx(),
- param_env,
- def_id,
- substs,
- );
- if let Some(instance) = instance {
- let cid = GlobalId {
- instance,
- promoted: None
- };
- if let Some(s) = tcx.const_eval(param_env.and(cid))
- .ok()
- .map(|c| c.unwrap_usize(tcx)) {
- return Ok(s)
- }
+ if let Some(substs) = tcx.lift_to_global(&substs) {
+ let instance = ty::Instance::resolve(
+ tcx.global_tcx(),
+ param_env,
+ def_id,
+ substs,
+ );
+ if let Some(instance) = instance {
+ let cid = GlobalId {
+ instance,
+ promoted: None
+ };
+ if let Some(s) = tcx.const_eval(param_env.and(cid))
+ .ok()
+ .map(|c| c.unwrap_usize(tcx)) {
+ return Ok(s)
}
- },
- None => {}
+ }
}
tcx.sess.delay_span_bug(tcx.def_span(def_id),
"array length could not be evaluated");
type Lifted = ty::GenSig<'tcx>;
fn lift_to_tcx<'b, 'gcx>(&self, tcx: TyCtxt<'b, 'gcx, 'tcx>) -> Option<Self::Lifted> {
tcx.lift(&(self.yield_ty, self.return_ty))
- .map(|(yield_ty, return_ty)| {
- ty::GenSig {
- yield_ty,
- return_ty,
- }
- })
+ .map(|(yield_ty, return_ty)| {
+ ty::GenSig {
+ yield_ty,
+ return_ty,
+ }
+ })
}
}
CyclicTy(t) => return tcx.lift(&t).map(|t| CyclicTy(t)),
ProjectionMismatched(x) => ProjectionMismatched(x),
ProjectionBoundsLength(x) => ProjectionBoundsLength(x),
-
Sorts(ref x) => return tcx.lift(x).map(Sorts),
OldStyleLUB(ref x) => return tcx.lift(x).map(OldStyleLUB),
ExistentialMismatch(ref x) => return tcx.lift(x).map(ExistentialMismatch)
use ty::InstanceDef::*;
self.substs.visit_with(visitor) ||
match self.def {
- Item(did) => did.visit_with(visitor),
- Intrinsic(did) => did.visit_with(visitor),
- FnPtrShim(did, ty) => {
- did.visit_with(visitor) ||
- ty.visit_with(visitor)
+ Item(did) | Intrinsic(did) | Virtual(did, _) => {
+ did.visit_with(visitor)
},
- Virtual(did, _) => did.visit_with(visitor),
- ClosureOnceShim { call_once } => call_once.visit_with(visitor),
- DropGlue(did, ty) => {
- did.visit_with(visitor) ||
- ty.visit_with(visitor)
+ FnPtrShim(did, ty) | CloneShim(did, ty) => {
+ did.visit_with(visitor) || ty.visit_with(visitor)
},
- CloneShim(did, ty) => {
- did.visit_with(visitor) ||
- ty.visit_with(visitor)
+ DropGlue(did, ty) => {
+ did.visit_with(visitor) || ty.visit_with(visitor)
},
+ ClosureOnceShim { call_once } => call_once.visit_with(visitor),
}
}
}
ty::GeneratorWitness(types) => ty::GeneratorWitness(types.fold_with(folder)),
ty::Closure(did, substs) => ty::Closure(did, substs.fold_with(folder)),
ty::Projection(ref data) => ty::Projection(data.fold_with(folder)),
+ ty::UnnormalizedProjection(ref data) => {
+ ty::UnnormalizedProjection(data.fold_with(folder))
+ }
ty::Opaque(did, substs) => ty::Opaque(did, substs.fold_with(folder)),
ty::Bool | ty::Char | ty::Str | ty::Int(_) |
ty::Uint(_) | ty::Float(_) | ty::Error | ty::Infer(_) |
}
ty::GeneratorWitness(ref types) => types.visit_with(visitor),
ty::Closure(_did, ref substs) => substs.visit_with(visitor),
- ty::Projection(ref data) => data.visit_with(visitor),
+ ty::Projection(ref data) | ty::UnnormalizedProjection(ref data) => {
+ data.visit_with(visitor)
+ }
ty::Opaque(_, ref substs) => substs.visit_with(visitor),
ty::Bool | ty::Char | ty::Str | ty::Int(_) |
ty::Uint(_) | ty::Float(_) | ty::Error | ty::Infer(_) |
Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability),
/// The anonymous type of a function declaration/definition. Each
- /// function has a unique type.
+ /// function has a unique type, which is output (for a function
+ /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
+ ///
+ /// For example the type of `bar` here:
+ ///
+ /// ```rust
+ /// fn foo() -> i32 { 1 }
+ /// let bar = foo; // bar: fn() -> i32 {foo}
+ /// ```
FnDef(DefId, &'tcx Substs<'tcx>),
/// A pointer to a function. Written as `fn() -> i32`.
+ ///
+ /// For example the type of `bar` here:
+ ///
+ /// ```rust
+ /// fn foo() -> i32 { 1 }
+ /// let bar: fn() -> i32 = foo;
+ /// ```
FnPtr(PolyFnSig<'tcx>),
/// A trait, defined with `trait`.
/// `<T as Trait<..>>::N`.
Projection(ProjectionTy<'tcx>),
+ /// A placeholder type used when we do not have enough information
+ /// to normalize the projection of an associated type to an
+ /// existing concrete type. Currently only used with chalk-engine.
+ UnnormalizedProjection(ProjectionTy<'tcx>),
+
/// Opaque (`impl Trait`) type found in a return type.
/// The `DefId` comes either from
/// * the `impl Trait` ast::Ty node,
/// Object types don't have a self-type specified. Therefore, when
/// we convert the principal trait-ref into a normal trait-ref,
/// you must give *some* self-type. A common choice is `mk_err()`
- /// or some skolemized type.
+ /// or some placeholder type.
pub fn with_self_ty(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, self_ty: Ty<'tcx>)
-> ty::TraitRef<'tcx> {
// otherwise the escaping regions would be captured by the binder
/// Object types don't have a self-type specified. Therefore, when
/// we convert the principal trait-ref into a normal trait-ref,
/// you must give *some* self-type. A common choice is `mk_err()`
- /// or some skolemized type.
+ /// or some placeholder type.
pub fn with_self_ty(&self, tcx: TyCtxt<'_, '_, 'tcx>,
self_ty: Ty<'tcx>)
-> ty::PolyTraitRef<'tcx> {
/// Binder is a binder for higher-ranked lifetimes. It is part of the
/// compiler's representation for things like `for<'a> Fn(&'a isize)`
/// (which would be represented by the type `PolyTraitRef ==
-/// Binder<TraitRef>`). Note that when we skolemize, instantiate,
+/// Binder<TraitRef>`). Note that when we instantiate,
/// erase, or otherwise "discharge" these bound regions, we change the
/// type from `Binder<T>` to just `T` (see
/// e.g. `liberate_late_bound_regions`).
// FIXME(#50125): Ignoring `Self` with `idx != 0` might lead to weird behavior elsewhere,
// but this should only be possible when using `-Z continue-parse-after-error` like
// `compile-fail/issue-36638.rs`.
- if self.name == keywords::SelfType.name().as_str() && self.idx == 0 {
- true
- } else {
- false
- }
+ self.name == keywords::SelfType.name().as_str() && self.idx == 0
}
}
///
/// Unlike Param-s, bound regions are not supposed to exist "in the wild"
/// outside their binder, e.g. in types passed to type inference, and
-/// should first be substituted (by skolemized regions, free regions,
+/// should first be substituted (by placeholder regions, free regions,
/// or region variables).
///
-/// ## Skolemized and Free Regions
+/// ## Placeholder and Free Regions
///
/// One often wants to work with bound regions without knowing their precise
/// identity. For example, when checking a function, the lifetime of a borrow
/// it must be ensured that bounds on the region can't be accidentally
/// assumed without being checked.
///
-/// The process of doing that is called "skolemization". The bound regions
-/// are replaced by skolemized markers, which don't satisfy any relation
-/// not explicitly provided.
+/// To do this, we replace the bound regions with placeholder markers,
+/// which don't satisfy any relation not explicitly provided.
///
-/// There are 2 kinds of skolemized regions in rustc: `ReFree` and
-/// `ReSkolemized`. When checking an item's body, `ReFree` is supposed
+/// There are 2 kinds of placeholder regions in rustc: `ReFree` and
+/// `RePlaceholder`. When checking an item's body, `ReFree` is supposed
/// to be used. These also support explicit bounds: both the internally-stored
/// *scope*, which the region is assumed to outlive, as well as other
/// relations stored in the `FreeRegionMap`. Note that these relations
///
/// When working with higher-ranked types, some region relations aren't
/// yet known, so you can't just call `resolve_regions_and_report_errors`.
-/// `ReSkolemized` is designed for this purpose. In these contexts,
+/// `RePlaceholder` is designed for this purpose. In these contexts,
/// there's also the risk that some inference variable laying around will
-/// get unified with your skolemized region: if you want to check whether
+/// get unified with your placeholder region: if you want to check whether
/// `for<'a> Foo<'_>: 'a`, and you substitute your bound region `'a`
-/// with a skolemized region `'%a`, the variable `'_` would just be
-/// instantiated to the skolemized region `'%a`, which is wrong because
+/// with a placeholder region `'%a`, the variable `'_` would just be
+/// instantiated to the placeholder region `'%a`, which is wrong because
/// the inference variable is supposed to satisfy the relation
-/// *for every value of the skolemized region*. To ensure that doesn't
+/// *for every value of the placeholder region*. To ensure that doesn't
/// happen, you can use `leak_check`. This is more clearly explained
/// by the [rustc guide].
///
/// A region variable. Should not exist after typeck.
ReVar(RegionVid),
- /// A skolemized region - basically the higher-ranked version of ReFree.
+ /// A placeholder region - basically the higher-ranked version of ReFree.
/// Should not exist after typeck.
- ReSkolemized(ty::UniverseIndex, BoundRegion),
+ RePlaceholder(ty::Placeholder),
/// Empty lifetime is for data that is never accessed.
/// Bottom in the region lattice. We treat ReEmpty somewhat
RegionKind::ReScope(..) => false,
RegionKind::ReStatic => true,
RegionKind::ReVar(..) => false,
- RegionKind::ReSkolemized(_, br) => br.is_named(),
+ RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(),
RegionKind::ReEmpty => false,
RegionKind::ReErased => false,
RegionKind::ReClosureBound(..) => false,
flags = flags | TypeFlags::HAS_FREE_REGIONS;
flags = flags | TypeFlags::HAS_RE_INFER;
}
- ty::ReSkolemized(..) => {
+ ty::RePlaceholder(..) => {
flags = flags | TypeFlags::HAS_FREE_REGIONS;
flags = flags | TypeFlags::HAS_RE_SKOL;
}
}
}
+ /// Returns `true` if this type is an `Arc<T>`.
+ pub fn is_arc(&self) -> bool {
+ match self.sty {
+ Adt(def, _) => def.is_arc(),
+ _ => false,
+ }
+ }
+
+ /// Returns `true` if this type is an `Rc<T>`.
+ pub fn is_rc(&self) -> bool {
+ match self.sty {
+ Adt(def, _) => def.is_rc(),
+ _ => false,
+ }
+ }
+
pub fn is_box(&self) -> bool {
match self.sty {
Adt(def, _) => def.is_box(),
Generator(_, GeneratorSubsts { ref substs }, _) => {
substs.regions().collect()
}
- Projection(ref data) => {
+ Projection(ref data) | UnnormalizedProjection(ref data) => {
data.substs.regions().collect()
}
FnDef(..) |
ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
+
ty::Infer(ty::TyVar(_)) => false,
ty::Infer(ty::CanonicalTy(_)) |
tcx: TyCtxt<'_, '_, '_>,
ty: ParamEnvAnd<'tcx, Ty<'tcx>>,
) -> u128 {
- match self.assert_bits(tcx, ty) {
- Some(val) => val,
- None => bug!("expected bits of {}, got {:#?}", ty.value, self),
- }
+ self.assert_bits(tcx, ty).unwrap_or_else(||
+ bug!("expected bits of {}, got {:#?}", ty.value, self))
}
#[inline]
pub fn unwrap_usize(&self, tcx: TyCtxt<'_, '_, '_>) -> u64 {
- match self.assert_usize(tcx) {
- Some(val) => val,
- None => bug!("expected constant usize, got {:#?}", self),
- }
+ self.assert_usize(tcx).unwrap_or_else(||
+ bug!("expected constant usize, got {:#?}", self))
}
}
where F: FnMut(&ty::GenericParamDef, &[Kind<'tcx>]) -> Kind<'tcx>
{
Substs::for_item(tcx, def_id, |param, substs| {
- match self.get(param.index as usize) {
- Some(&kind) => kind,
- None => mk_kind(param, substs),
- }
+ self.get(param.index as usize)
+ .cloned()
+ .unwrap_or_else(|| mk_kind(param, substs))
})
}
mk_kind: &mut F)
where F: FnMut(&ty::GenericParamDef, &[Kind<'tcx>]) -> Kind<'tcx>
{
+ substs.reserve(defs.params.len());
for param in &defs.params {
let kind = mk_kind(param, substs);
assert_eq!(param.index as usize, substs.len());
pub trait Subst<'tcx> : Sized {
fn subst<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>,
- substs: &[Kind<'tcx>]) -> Self {
+ substs: &[Kind<'tcx>]) -> Self {
self.subst_spanned(tcx, substs, None)
}
span_bug!(
span,
"Type parameter `{:?}` ({:?}/{}) out of range \
- when substituting (root type={:?}) substs={:?}",
+ when substituting (root type={:?}) substs={:?}",
p,
source_ty,
p.idx,
}
}
} else {
- for v in impls.non_blanket_impls.values() {
- for &impl_def_id in v {
- f(impl_def_id);
- }
+ for &impl_def_id in impls.non_blanket_impls.values().flatten() {
+ f(impl_def_id);
}
}
}
fast_reject::simplify_type(tcx, impl_self_ty, false)
{
impls.non_blanket_impls
- .entry(simplified_self_ty)
- .or_default()
- .push(impl_def_id);
+ .entry(simplified_self_ty)
+ .or_default()
+ .push(impl_def_id);
} else {
impls.blanket_impls.push(impl_def_id);
}
impl IntTypeExt for attr::IntType {
fn to_ty<'a, 'gcx, 'tcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Ty<'tcx> {
match *self {
- SignedInt(ast::IntTy::I8) => tcx.types.i8,
- SignedInt(ast::IntTy::I16) => tcx.types.i16,
- SignedInt(ast::IntTy::I32) => tcx.types.i32,
- SignedInt(ast::IntTy::I64) => tcx.types.i64,
+ SignedInt(ast::IntTy::I8) => tcx.types.i8,
+ SignedInt(ast::IntTy::I16) => tcx.types.i16,
+ SignedInt(ast::IntTy::I32) => tcx.types.i32,
+ SignedInt(ast::IntTy::I64) => tcx.types.i64,
SignedInt(ast::IntTy::I128) => tcx.types.i128,
- SignedInt(ast::IntTy::Isize) => tcx.types.isize,
+ SignedInt(ast::IntTy::Isize) => tcx.types.isize,
UnsignedInt(ast::UintTy::U8) => tcx.types.u8,
UnsignedInt(ast::UintTy::U16) => tcx.types.u16,
UnsignedInt(ast::UintTy::U32) => tcx.types.u32,
UnsignedInt(ast::UintTy::U64) => tcx.types.u64,
- UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
+ UnsignedInt(ast::UintTy::U128) => tcx.types.u128,
UnsignedInt(ast::UintTy::Usize) => tcx.types.usize,
}
}
let mut infringing = Vec::new();
for variant in &adt.variants {
for field in &variant.fields {
- let span = tcx.def_span(field.did);
let ty = field.ty(tcx, substs);
if ty.references_error() {
continue;
}
+ let span = tcx.def_span(field.did);
let cause = ObligationCause { span, ..ObligationCause::dummy() };
let ctx = traits::FulfillmentContext::new();
match traits::fully_normalize(&infcx, ctx, cause, self, &ty) {
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
- match ty.sty {
- ty::Adt(def, substs) => {
- for field in def.all_fields() {
- let field_ty = field.ty(self, substs);
- if let Error = field_ty.sty {
- return true;
- }
+ if let ty::Adt(def, substs) = ty.sty {
+ for field in def.all_fields() {
+ let field_ty = field.ty(self, substs);
+ if let Error = field_ty.sty {
+ return true;
}
}
- _ => (),
}
false
}
let ty = self.type_of(adt_did);
self.for_each_relevant_impl(drop_trait, ty, |impl_did| {
if let Some(item) = self.associated_items(impl_did).next() {
- if let Ok(()) = validate(self, impl_did) {
+ if validate(self, impl_did).is_ok() {
dtor_did = Some(item.def_id);
}
}
false
}
}
- }).map(|(&item_param, _)| item_param).collect();
+ })
+ .map(|(&item_param, _)| item_param)
+ .collect();
debug!("destructor_constraint({:?}) = {:?}", def.did, result);
result
}
pub fn is_representable(&'tcx self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
sp: Span)
- -> Representability {
-
+ -> Representability
+ {
// Iterate until something non-representable is found
fn fold_repr<It: Iterator<Item=Representability>>(iter: It) -> Representability {
iter.fold(Representability::Representable, |r1, r2| {
let (param_env, ty) = query.into_parts();
let needs_drop = |ty: Ty<'tcx>| -> bool {
- match tcx.try_needs_drop_raw(DUMMY_SP, param_env.and(ty)) {
- Ok(v) => v,
- Err(mut bug) => {
- // Cycles should be reported as an error by `check_representable`.
- //
- // Consider the type as not needing drop in the meanwhile to
- // avoid further errors.
- //
- // In case we forgot to emit a bug elsewhere, delay our
- // diagnostic to get emitted as a compiler bug.
- bug.delay_as_bug();
- false
- }
- }
+ tcx.try_needs_drop_raw(DUMMY_SP, param_env.and(ty)).unwrap_or_else(|mut bug| {
+ // Cycles should be reported as an error by `check_representable`.
+ //
+ // Consider the type as not needing drop in the meanwhile to
+ // avoid further errors.
+ //
+ // In case we forgot to emit a bug elsewhere, delay our
+ // diagnostic to get emitted as a compiler bug.
+ bug.delay_as_bug();
+ false
+ })
};
assert!(!ty.needs_infer());
ty::Dynamic(..) | ty::Projection(..) | ty::Param(_) |
ty::Opaque(..) | ty::Infer(_) | ty::Error => true,
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
+
// Structural recursion.
ty::Array(ty, _) | ty::Slice(ty) => needs_drop(ty),
debug!("next(): stack={:?}", self.stack);
match self.stack.pop() {
None => {
- return None;
+ None
}
Some(ty) => {
self.last_subtree = self.stack.len();
ty::Ref(_, ty, _) => {
stack.push(ty);
}
- ty::Projection(ref data) => {
+ ty::Projection(ref data) | ty::UnnormalizedProjection(ref data) => {
stack.extend(data.substs.types().rev());
}
ty::Dynamic(ref obj, ..) => {
let predicate = ty::Predicate::ConstEvaluatable(def_id, substs);
let cause = self.cause(traits::MiscObligation);
self.out.push(traits::Obligation::new(cause,
- self.param_env,
- predicate));
+ self.param_env,
+ predicate));
}
}
self.compute_projection(data);
}
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
+
ty::Adt(def, substs) => {
// WfNominalType
let obligations = self.nominal_obligations(def.did, substs);
let explicit_bound = region;
+ self.out.reserve(implicit_bounds.len());
for implicit_bound in implicit_bounds {
let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound));
let outlives = ty::Binder::dummy(
{
// Since we don't actually *know* the self type for an object,
// this "open(err)" serves as a kind of dummy standin -- basically
- // a skolemized type.
+ // a placeholder type.
let open_ty = tcx.mk_infer(ty::FreshTy(0));
let predicates = existential_predicates.iter().filter_map(|predicate| {
use ty::{Error, Str, Array, Slice, Float, FnDef, FnPtr};
use ty::{Param, RawPtr, Ref, Never, Tuple};
use ty::{Closure, Generator, GeneratorWitness, Foreign, Projection, Opaque};
-use ty::{Dynamic, Int, Uint, Infer};
+use ty::{UnnormalizedProjection, Dynamic, Int, Uint, Infer};
use ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, GenericParamCount, GenericParamDefKind};
use util::nodemap::FxHashSet;
}
ty::ReLateBound(_, br) |
ty::ReFree(ty::FreeRegion { bound_region: br, .. }) |
- ty::ReSkolemized(_, br) => {
+ ty::RePlaceholder(ty::Placeholder { name: br, .. }) => {
write!(f, "{}", br)
}
ty::ReScope(scope) if cx.identify_regions => {
write!(f, "'?{}", c.index())
}
- ty::ReSkolemized(universe, ref bound_region) => {
- write!(f, "ReSkolemized({:?}, {:?})", universe, bound_region)
+ ty::RePlaceholder(placeholder) => {
+ write!(f, "RePlaceholder({:?})", placeholder)
}
ty::ReEmpty => write!(f, "ReEmpty"),
}
Foreign(def_id) => parameterized(f, subst::Substs::empty(), def_id, &[]),
Projection(ref data) => data.print(f, cx),
+ UnnormalizedProjection(ref data) => {
+ write!(f, "Unnormalized(")?;
+ data.print(f, cx)?;
+ write!(f, ")")
+ }
Opaque(def_id, substs) => {
if cx.is_verbose {
return write!(f, "Opaque({:?}, {:?})", def_id, substs);
// These cannot exist in borrowck
RegionKind::ReVar(..) |
RegionKind::ReCanonical(..) |
- RegionKind::ReSkolemized(..) |
+ RegionKind::RePlaceholder(..) |
RegionKind::ReClosureBound(..) |
RegionKind::ReErased => span_bug!(borrow_span,
"unexpected region in borrowck {:?}",
ty::ReClosureBound(..) |
ty::ReLateBound(..) |
ty::ReVar(..) |
- ty::ReSkolemized(..) |
+ ty::RePlaceholder(..) |
ty::ReErased => {
span_bug!(
cmt.span,
use rustc_mir::util::suggest_ref_mut;
use rustc::util::nodemap::FxHashSet;
+use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::fmt;
use std::rc::Rc;
match err.code {
err_mutbl => {
- let descr = match err.cmt.note {
+ let descr: Cow<'static, str> = match err.cmt.note {
mc::NoteClosureEnv(_) | mc::NoteUpvarRef(_) => {
- self.cmt_to_string(&err.cmt)
+ self.cmt_to_cow_str(&err.cmt)
}
_ => match opt_loan_path_is_field(&err.cmt) {
(None, true) => {
format!("{} of {} binding",
- self.cmt_to_string(&err.cmt),
- err.cmt.mutbl.to_user_str())
+ self.cmt_to_cow_str(&err.cmt),
+ err.cmt.mutbl.to_user_str()).into()
}
(None, false) => {
format!("{} {}",
err.cmt.mutbl.to_user_str(),
- self.cmt_to_string(&err.cmt))
+ self.cmt_to_cow_str(&err.cmt)).into()
}
(Some(lp), true) => {
format!("{} `{}` of {} binding",
- self.cmt_to_string(&err.cmt),
+ self.cmt_to_cow_str(&err.cmt),
self.loan_path_to_string(&lp),
- err.cmt.mutbl.to_user_str())
+ err.cmt.mutbl.to_user_str()).into()
}
(Some(lp), false) => {
format!("{} {} `{}`",
err.cmt.mutbl.to_user_str(),
- self.cmt_to_string(&err.cmt),
- self.loan_path_to_string(&lp))
+ self.cmt_to_cow_str(&err.cmt),
+ self.loan_path_to_string(&lp)).into()
}
}
};
err_borrowed_pointer_too_short(loan_scope, ptr_scope) => {
let descr = self.cmt_to_path_or_string(err.cmt);
let mut db = self.lifetime_too_short_for_reborrow(error_span, &descr, Origin::Ast);
- let descr = match opt_loan_path(&err.cmt) {
+ let descr: Cow<'static, str> = match opt_loan_path(&err.cmt) {
Some(lp) => {
- format!("`{}`", self.loan_path_to_string(&lp))
+ format!("`{}`", self.loan_path_to_string(&lp)).into()
}
- None => self.cmt_to_string(&err.cmt),
+ None => self.cmt_to_cow_str(&err.cmt)
};
self.tcx.note_and_explain_region(
&self.region_scope_tree,
result
}
- pub fn cmt_to_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
+ pub fn cmt_to_cow_str(&self, cmt: &mc::cmt_<'tcx>) -> Cow<'static, str> {
cmt.descriptive_string(self.tcx)
}
pub fn cmt_to_path_or_string(&self, cmt: &mc::cmt_<'tcx>) -> String {
match opt_loan_path(cmt) {
Some(lp) => format!("`{}`", self.loan_path_to_string(&lp)),
- None => self.cmt_to_string(cmt),
+ None => self.cmt_to_cow_str(cmt).into_owned(),
}
}
}
}
let (hir_id, span) = ids[0];
- let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
+ if span.compiler_desugaring_kind().is_some() {
+ // If the `mut` arises as part of a desugaring, we should ignore it.
+ continue;
+ }
// Ok, every name wasn't used mutably, so issue a warning that this
// didn't need to be mutable.
+ let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
tcx.struct_span_lint_hir(UNUSED_MUT,
hir_id,
span,
Box::new(WasmLd {
cmd,
sess,
+ info: self
}) as Box<dyn Linker>
}
}
pub struct WasmLd<'a> {
cmd: Command,
sess: &'a Session,
+ info: &'a LinkerInfo,
}
impl<'a> Linker for WasmLd<'a> {
fn build_dylib(&mut self, _out_filename: &Path) {
}
- fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType) {
+ fn export_symbols(&mut self, _tmpdir: &Path, crate_type: CrateType) {
+ for sym in self.info.exports[&crate_type].iter() {
+ self.cmd.arg("--export").arg(&sym);
+ }
}
fn subsystem(&mut self, _subsystem: &str) {
}
ty::Error |
ty::Infer(_) |
+ ty::UnnormalizedProjection(..) |
ty::Projection(..) |
ty::Opaque(..) |
ty::GeneratorWitness(..) |
bug!("undesugared DropAndReplace in codegen: {:?}", terminator);
}
- mir::TerminatorKind::Call { ref func, ref args, ref destination, cleanup } => {
+ mir::TerminatorKind::Call {
+ ref func,
+ ref args,
+ ref destination,
+ cleanup,
+ from_hir_call: _
+ } => {
// Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
let callee = self.codegen_operand(&bx, func);
}
}
-declare_lint! {
- PRIVATE_NO_MANGLE_FNS,
- Warn,
- "functions marked #[no_mangle] should be exported"
-}
-
-declare_lint! {
- PRIVATE_NO_MANGLE_STATICS,
- Warn,
- "statics marked #[no_mangle] should be exported"
-}
-
declare_lint! {
NO_MANGLE_CONST_ITEMS,
Deny,
impl LintPass for InvalidNoMangleItems {
fn get_lints(&self) -> LintArray {
- lint_array!(PRIVATE_NO_MANGLE_FNS,
- PRIVATE_NO_MANGLE_STATICS,
- NO_MANGLE_CONST_ITEMS,
+ lint_array!(NO_MANGLE_CONST_ITEMS,
NO_MANGLE_GENERIC_ITEMS)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
- let suggest_export = |vis: &hir::Visibility, err: &mut DiagnosticBuilder| {
- let suggestion = match vis.node {
- hir::VisibilityKind::Inherited => {
- // inherited visibility is empty span at item start; need an extra space
- Some("pub ".to_owned())
- },
- hir::VisibilityKind::Restricted { .. } |
- hir::VisibilityKind::Crate(_) => {
- Some("pub".to_owned())
- },
- hir::VisibilityKind::Public => {
- err.help("try exporting the item with a `pub use` statement");
- None
- }
- };
- if let Some(replacement) = suggestion {
- err.span_suggestion_with_applicability(
- vis.span,
- "try making it public",
- replacement,
- Applicability::MachineApplicable
- );
- }
- };
-
match it.node {
hir::ItemKind::Fn(.., ref generics, _) => {
if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
- if attr::contains_name(&it.attrs, "linkage") {
- return;
- }
- if !cx.access_levels.is_reachable(it.id) {
- let msg = "function is marked #[no_mangle], but not exported";
- let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg);
- suggest_export(&it.vis, &mut err);
- err.emit();
- }
for param in &generics.params {
match param.kind {
GenericParamKind::Lifetime { .. } => {}
}
}
}
- hir::ItemKind::Static(..) => {
- if attr::contains_name(&it.attrs, "no_mangle") &&
- !cx.access_levels.is_reachable(it.id) {
- let msg = "static is marked #[no_mangle], but not exported";
- let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg);
- suggest_export(&it.vis, &mut err);
- err.emit();
- }
- }
hir::ItemKind::Const(..) => {
if attr::contains_name(&it.attrs, "no_mangle") {
// Const items do not refer to a particular location in memory, and therefore
UNUSED_DOC_COMMENTS,
UNCONDITIONAL_RECURSION,
PLUGIN_AS_LIBRARY,
- PRIVATE_NO_MANGLE_FNS,
- PRIVATE_NO_MANGLE_STATICS,
NO_MANGLE_CONST_ITEMS,
NO_MANGLE_GENERIC_ITEMS,
MUTABLE_TRANSMUTES,
"converted into hard error, see https://github.com/rust-lang/rust/issues/48950");
store.register_removed("resolve_trait_on_defaulted_unit",
"converted into hard error, see https://github.com/rust-lang/rust/issues/48950");
+ store.register_removed("private_no_mangle_fns",
+ "no longer an warning, #[no_mangle] functions always exported");
+ store.register_removed("private_no_mangle_statics",
+ "no longer an warning, #[no_mangle] statics always exported");
}
ty::Closure(..) |
ty::Generator(..) |
ty::GeneratorWitness(..) |
+ ty::UnnormalizedProjection(..) |
ty::Projection(..) |
ty::Opaque(..) |
ty::FnDef(..) => bug!("Unexpected type in foreign function"),
ty::Adt(def, _) => {
if def.variants.is_empty() {
return;
- } else {
- check_must_use(cx, def.did, s.span, "")
}
+ check_must_use(cx, def.did, s.span, "")
},
_ => false,
};
AssignOp(.., ref value) => (value, "assigned value", false),
// either function/method call, or something this lint doesn't care about
ref call_or_other => {
- let args_to_check;
- let call_kind;
- match *call_or_other {
- Call(_, ref args) => {
- call_kind = "function";
- args_to_check = &args[..];
- },
- MethodCall(_, ref args) => {
- call_kind = "method";
- // first "argument" is self (which sometimes needs parens)
- args_to_check = &args[1..];
- }
+ let (args_to_check, call_kind) = match *call_or_other {
+ Call(_, ref args) => (&args[..], "function"),
+ // first "argument" is self (which sometimes needs parens)
+ MethodCall(_, ref args) => (&args[1..], "method"),
// actual catch-all arm
_ => { return; }
- }
+ };
// Don't lint if this is a nested macro expansion: otherwise, the lint could
// trigger in situations that macro authors shouldn't have to care about, e.g.,
// when a parenthesized token tree matched in one macro expansion is matched as
}
fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
- let (value, msg) = match s.node {
- ast::StmtKind::Local(ref local) => {
- match local.init {
- Some(ref value) => (value, "assigned value"),
- None => return,
- }
+ if let ast::StmtKind::Local(ref local) = s.node {
+ if let Some(ref value) = local.init {
+ self.check_unused_parens_core(cx, &value, "assigned value", false);
}
- _ => return,
- };
- self.check_unused_parens_core(cx, &value, msg, false);
+ }
}
}
let orig_ident = items[0].0.prefix.segments.last().unwrap().ident;
if orig_ident.name == keywords::SelfValue.name() {
return;
- } else {
- node_ident = rename.unwrap_or(orig_ident);
}
+ node_ident = rename.unwrap_or(orig_ident);
}
ast::UseTreeKind::Glob => {
node_ident = ast::Ident::from_str("*");
use rustc::hir::def_id::DefId;
use rustc::middle::region::ScopeTree;
use rustc::mir::{
- self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, FakeReadCause, Field, Local,
- LocalDecl, LocalKind, Location, Operand, Place, PlaceProjection, ProjectionElem, Rvalue,
- Statement, StatementKind, TerminatorKind, VarBindingForm,
+ self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, Field, Local,
+ LocalDecl, LocalKind, Location, Operand, Place, PlaceProjection, ProjectionElem,
+ Rvalue, Statement, StatementKind, TerminatorKind, VarBindingForm,
};
use rustc::ty;
use rustc::util::ppaux::with_highlight_region_for_bound_region;
move_spans.var_span_label(&mut err, "move occurs due to use in closure");
self.explain_why_borrow_contains_point(context, borrow, None)
- .emit(self.infcx.tcx, &mut err);
+ .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
err.buffer(&mut self.errors_buffer);
}
});
self.explain_why_borrow_contains_point(context, borrow, None)
- .emit(self.infcx.tcx, &mut err);
+ .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
err.buffer(&mut self.errors_buffer);
}
let desc_place = self.describe_place(place).unwrap_or("_".to_owned());
let tcx = self.infcx.tcx;
+ let first_borrow_desc;
+
// FIXME: supply non-"" `opt_via` when appropriate
let mut err = match (
gen_borrow_kind,
"immutable",
"mutable",
) {
- (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt)
- | (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
+ (BorrowKind::Shared, lft, _, BorrowKind::Mut { .. }, _, rgt) => {
+ first_borrow_desc = "mutable ";
+ tcx.cannot_reborrow_already_borrowed(
+ span,
+ &desc_place,
+ "",
+ lft,
+ issued_span,
+ "it",
+ rgt,
+ "",
+ None,
+ Origin::Mir,
+ )
+ }
+ (BorrowKind::Mut { .. }, _, lft, BorrowKind::Shared, rgt, _) => {
+ first_borrow_desc = "immutable ";
tcx.cannot_reborrow_already_borrowed(
span,
&desc_place,
}
(BorrowKind::Mut { .. }, _, _, BorrowKind::Mut { .. }, _, _) => {
+ first_borrow_desc = "first ";
tcx.cannot_mutably_borrow_multiply(
span,
&desc_place,
}
(BorrowKind::Unique, _, _, BorrowKind::Unique, _, _) => {
+ first_borrow_desc = "first ";
tcx.cannot_uniquely_borrow_by_two_closures(
span,
&desc_place,
return;
}
- (BorrowKind::Unique, _, _, _, _, _) => tcx.cannot_uniquely_borrow_by_one_closure(
- span,
- &desc_place,
- "",
- issued_span,
- "it",
- "",
- None,
- Origin::Mir,
- ),
+ (BorrowKind::Unique, _, _, _, _, _) => {
+ first_borrow_desc = "first ";
+ tcx.cannot_uniquely_borrow_by_one_closure(
+ span,
+ &desc_place,
+ "",
+ issued_span,
+ "it",
+ "",
+ None,
+ Origin::Mir,
+ )
+ },
(BorrowKind::Shared, lft, _, BorrowKind::Unique, _, _) => {
+ first_borrow_desc = "first ";
tcx.cannot_reborrow_already_uniquely_borrowed(
span,
&desc_place,
}
(BorrowKind::Mut { .. }, _, lft, BorrowKind::Unique, _, _) => {
+ first_borrow_desc = "first ";
tcx.cannot_reborrow_already_uniquely_borrowed(
span,
&desc_place,
}
self.explain_why_borrow_contains_point(context, issued_borrow, None)
- .emit(self.infcx.tcx, &mut err);
+ .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, first_borrow_desc);
err.buffer(&mut self.errors_buffer);
}
if let BorrowExplanation::MustBeValidFor(..) = explanation {
} else {
- explanation.emit(self.infcx.tcx, &mut err);
+ explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
}
} else {
err.span_label(borrow_span, "borrowed value does not live long enough");
borrow_spans.args_span_label(&mut err, "value captured here");
- explanation.emit(self.infcx.tcx, &mut err);
+ explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
}
err
_ => {}
}
- explanation.emit(self.infcx.tcx, &mut err);
+ explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
err.buffer(&mut self.errors_buffer);
}
match explanation {
BorrowExplanation::UsedLater(..)
| BorrowExplanation::UsedLaterInLoop(..)
- | BorrowExplanation::UsedLaterWhenDropped(..) => {
+ | BorrowExplanation::UsedLaterWhenDropped { .. } => {
// Only give this note and suggestion if it could be relevant.
err.note("consider using a `let` binding to create a longer lived value");
}
_ => {}
}
- explanation.emit(self.infcx.tcx, &mut err);
+ explanation.add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
borrow_spans.args_span_label(&mut err, "value captured here");
loan_spans.var_span_label(&mut err, "borrow occurs due to use in closure");
self.explain_why_borrow_contains_point(context, loan, None)
- .emit(self.infcx.tcx, &mut err);
+ .add_explanation_to_diagnostic(self.infcx.tcx, self.mir, &mut err, "");
err.buffer(&mut self.errors_buffer);
}
}
}
- /// Returns the `FakeReadCause` at this location if it is a `FakeRead` statement.
- pub(super) fn retrieve_fake_read_cause_for_location(
- &self,
- location: &Location,
- ) -> Option<FakeReadCause> {
- let stmt = self.mir.basic_blocks()[location.block]
- .statements
- .get(location.statement_index)?;
- if let StatementKind::FakeRead(cause, _) = stmt.kind {
- Some(cause)
- } else {
- None
- }
- }
-
fn classify_drop_access_kind(&self, place: &Place<'tcx>) -> StorageDeadOrDrop<'tcx> {
let tcx = self.infcx.tcx;
match place {
// lifetimes without names with the value `'0`.
match ty.sty {
ty::TyKind::Ref(ty::RegionKind::ReLateBound(_, br), _, _)
- | ty::TyKind::Ref(ty::RegionKind::ReSkolemized(_, br), _, _) => {
- with_highlight_region_for_bound_region(*br, counter, || format!("{}", ty))
- }
+ | ty::TyKind::Ref(
+ ty::RegionKind::RePlaceholder(ty::Placeholder { name: br, .. }),
+ _,
+ _,
+ ) => with_highlight_region_for_bound_region(*br, counter, || format!("{}", ty)),
_ => format!("{}", ty),
}
}
fn get_region_name_for_ty(&self, ty: ty::Ty<'tcx>, counter: usize) -> String {
match ty.sty {
ty::TyKind::Ref(region, _, _) => match region {
- ty::RegionKind::ReLateBound(_, br) | ty::RegionKind::ReSkolemized(_, br) => {
+ ty::RegionKind::ReLateBound(_, br)
+ | ty::RegionKind::RePlaceholder(ty::Placeholder { name: br, .. }) => {
with_highlight_region_for_bound_region(*br, counter, || format!("{}", region))
}
_ => format!("{}", region),
}
let span = local_decl.source_info.span;
- let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
+ if span.compiler_desugaring_kind().is_some() {
+ // If the `mut` arises as part of a desugaring, we should ignore it.
+ continue;
+ }
let mut err = tcx.struct_span_lint_node(
UNUSED_MUT,
span,
"variable does not need to be mutable",
);
+ let mut_span = tcx.sess.source_map().span_until_non_whitespace(span);
err.span_suggestion_short_with_applicability(
mut_span,
"remove this `mut`",
ref args,
ref destination,
cleanup: _,
+ from_hir_call: _,
} => {
self.consume_operand(ContextKind::CallOperator.new(loc), (func, span), flow_state);
for arg in args {
// except according to those terms.
use core::unicode::property::Pattern_White_Space;
+use std::fmt::{self, Display};
+
use rustc::mir::*;
use rustc::ty;
use rustc_errors::{DiagnosticBuilder,Applicability};
use borrow_check::MirBorrowckCtxt;
use borrow_check::prefixes::PrefixSet;
-use dataflow::move_paths::{IllegalMoveOrigin, IllegalMoveOriginKind};
-use dataflow::move_paths::{LookupResult, MoveError, MovePathIndex};
+use dataflow::move_paths::{
+ IllegalMoveOrigin, IllegalMoveOriginKind, InitLocation,
+ LookupResult, MoveError, MovePathIndex,
+};
use util::borrowck_errors::{BorrowckErrors, Origin};
// Often when desugaring a pattern match we may have many individual moves in
},
}
+enum BorrowedContentSource {
+ Arc,
+ Rc,
+ Other,
+}
+
+impl Display for BorrowedContentSource {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ match *self {
+ BorrowedContentSource::Arc => write!(f, "an `Arc`"),
+ BorrowedContentSource::Rc => write!(f, "an `Rc`"),
+ BorrowedContentSource::Other => write!(f, "borrowed content"),
+ }
+ }
+}
+
impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) {
let grouped_errors = self.group_move_errors(move_errors);
diag
}
- _ => self.infcx.tcx.cannot_move_out_of(
- span, "borrowed content", origin
- ),
+ _ => {
+ let source = self.borrowed_content_source(place);
+ self.infcx.tcx.cannot_move_out_of(
+ span, &format!("{}", source), origin
+ )
+ },
}
}
IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => {
);
}
}
+
+ fn borrowed_content_source(&self, place: &Place<'tcx>) -> BorrowedContentSource {
+ // Look up the provided place and work out the move path index for it,
+ // we'll use this to work back through where this value came from and check whether it
+ // was originally part of an `Rc` or `Arc`.
+ let initial_mpi = match self.move_data.rev_lookup.find(place) {
+ LookupResult::Exact(mpi) | LookupResult::Parent(Some(mpi)) => mpi,
+ _ => return BorrowedContentSource::Other,
+ };
+
+ let mut queue = vec![initial_mpi];
+ let mut visited = Vec::new();
+ debug!("borrowed_content_source: queue={:?}", queue);
+ while let Some(mpi) = queue.pop() {
+ debug!(
+ "borrowed_content_source: mpi={:?} queue={:?} visited={:?}",
+ mpi, queue, visited
+ );
+
+ // Don't visit the same path twice.
+ if visited.contains(&mpi) {
+ continue;
+ }
+ visited.push(mpi);
+
+ for i in &self.move_data.init_path_map[mpi] {
+ let init = &self.move_data.inits[*i];
+ debug!("borrowed_content_source: init={:?}", init);
+ // We're only interested in statements that initialized a value, not the
+ // initializations from arguments.
+ let loc = match init.location {
+ InitLocation::Statement(stmt) => stmt,
+ _ => continue,
+ };
+
+ let bbd = &self.mir[loc.block];
+ let is_terminator = bbd.statements.len() == loc.statement_index;
+ debug!("borrowed_content_source: loc={:?} is_terminator={:?}", loc, is_terminator);
+ if !is_terminator {
+ let stmt = &bbd.statements[loc.statement_index];
+ debug!("borrowed_content_source: stmt={:?}", stmt);
+ // We're only interested in assignments (in particular, where the
+ // assignment came from - was it an `Rc` or `Arc`?).
+ if let StatementKind::Assign(_, box Rvalue::Ref(_, _, source)) = &stmt.kind {
+ let ty = source.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
+ let ty = match ty.sty {
+ ty::TyKind::Ref(_, ty, _) => ty,
+ _ => ty,
+ };
+ debug!("borrowed_content_source: ty={:?}", ty);
+
+ if ty.is_arc() {
+ return BorrowedContentSource::Arc;
+ } else if ty.is_rc() {
+ return BorrowedContentSource::Rc;
+ } else {
+ queue.push(init.path);
+ }
+ }
+ } else if let Some(Terminator {
+ kind: TerminatorKind::Call { args, .. },
+ ..
+ }) = &bbd.terminator {
+ for arg in args {
+ let source = match arg {
+ Operand::Copy(place) | Operand::Move(place) => place,
+ _ => continue,
+ };
+
+ let ty = source.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx);
+ let ty = match ty.sty {
+ ty::TyKind::Ref(_, ty, _) => ty,
+ _ => ty,
+ };
+ debug!("borrowed_content_source: ty={:?}", ty);
+
+ if ty.is_arc() {
+ return BorrowedContentSource::Arc;
+ } else if ty.is_rc() {
+ return BorrowedContentSource::Rc;
+ } else {
+ queue.push(init.path);
+ }
+ }
+ }
+ }
+ }
+
+ BorrowedContentSource::Other
+ }
}
// except according to those terms.
use borrow_check::borrow_set::BorrowData;
+use borrow_check::error_reporting::UseSpans;
use borrow_check::nll::region_infer::Cause;
use borrow_check::{Context, MirBorrowckCtxt, WriteKind};
-use rustc::ty::{Region, TyCtxt};
-use rustc::mir::{FakeReadCause, Location, Place, TerminatorKind};
+use rustc::ty::{self, Region, TyCtxt};
+use rustc::mir::{FakeReadCause, Local, Location, Mir, Operand};
+use rustc::mir::{Place, StatementKind, TerminatorKind};
use rustc_errors::DiagnosticBuilder;
use syntax_pos::Span;
-use syntax_pos::symbol::Symbol;
mod find_use;
pub(in borrow_check) enum BorrowExplanation<'tcx> {
- UsedLater(bool, Option<FakeReadCause>, Span),
- UsedLaterInLoop(bool, Span),
- UsedLaterWhenDropped(Span, Symbol, bool),
+ UsedLater(LaterUseKind, Span),
+ UsedLaterInLoop(LaterUseKind, Span),
+ UsedLaterWhenDropped {
+ drop_loc: Location,
+ dropped_local: Local,
+ should_note_order: bool,
+ },
MustBeValidFor(Region<'tcx>),
Unexplained,
}
+#[derive(Clone, Copy)]
+pub(in borrow_check) enum LaterUseKind {
+ ClosureCapture,
+ Call,
+ FakeLetRead,
+ Other,
+}
+
impl<'tcx> BorrowExplanation<'tcx> {
- pub(in borrow_check) fn emit<'cx, 'gcx>(
+ pub(in borrow_check) fn add_explanation_to_diagnostic<'cx, 'gcx>(
&self,
tcx: TyCtxt<'cx, 'gcx, 'tcx>,
- err: &mut DiagnosticBuilder<'_>
+ mir: &Mir<'tcx>,
+ err: &mut DiagnosticBuilder<'_>,
+ borrow_desc: &str,
) {
match *self {
- BorrowExplanation::UsedLater(is_in_closure, fake_read_cause, var_or_use_span) => {
- let message = if is_in_closure {
- "borrow later captured here by closure"
- } else if let Some(FakeReadCause::ForLet) = fake_read_cause {
- "borrow later stored here"
- } else {
- "borrow later used here"
+ BorrowExplanation::UsedLater(later_use_kind, var_or_use_span) => {
+ let message = match later_use_kind {
+ LaterUseKind::ClosureCapture => "borrow later captured here by closure",
+ LaterUseKind::Call => "borrow later used by call",
+ LaterUseKind::FakeLetRead => "borrow later stored here",
+ LaterUseKind::Other => "borrow later used here",
};
- err.span_label(var_or_use_span, message);
+ err.span_label(var_or_use_span, format!("{}{}", borrow_desc, message));
},
- BorrowExplanation::UsedLaterInLoop(is_in_closure, var_or_use_span) => {
- let message = if is_in_closure {
- "borrow captured here by closure, in later iteration of loop"
- } else {
- "borrow used here, in later iteration of loop"
+ BorrowExplanation::UsedLaterInLoop(later_use_kind, var_or_use_span) => {
+ let message = match later_use_kind {
+ LaterUseKind::ClosureCapture => {
+ "borrow captured here by closure, in later iteration of loop"
+ },
+ LaterUseKind::Call => "borrow used by call, in later iteration of loop",
+ LaterUseKind::FakeLetRead => "borrow later stored here",
+ LaterUseKind::Other => "borrow used here, in later iteration of loop",
};
- err.span_label(var_or_use_span, message);
+ err.span_label(var_or_use_span, format!("{}{}", borrow_desc, message));
},
- BorrowExplanation::UsedLaterWhenDropped(span, local_name, should_note_order) => {
- err.span_label(
- span,
- format!("borrow later used here, when `{}` is dropped", local_name),
- );
+ BorrowExplanation::UsedLaterWhenDropped { drop_loc, dropped_local,
+ should_note_order } =>
+ {
+ let local_decl = &mir.local_decls[dropped_local];
+ let (dtor_desc, type_desc) = match local_decl.ty.sty {
+ // If type is an ADT that implements Drop, then
+ // simplify output by reporting just the ADT name.
+ ty::Adt(adt, _substs) if adt.has_dtor(tcx) && !adt.is_box() =>
+ ("`Drop` code", format!("type `{}`", tcx.item_path_str(adt.did))),
+
+ // Otherwise, just report the whole type (and use
+ // the intentionally fuzzy phrase "destructor")
+ ty::Closure(..) =>
+ ("destructor", format!("closure")),
+ ty::Generator(..) =>
+ ("destructor", format!("generator")),
+
+ _ => ("destructor", format!("type `{}`", local_decl.ty)),
+ };
+
+ match local_decl.name {
+ Some(local_name) => {
+ let message =
+ format!("{B}borrow might be used here, when `{LOC}` is dropped \
+ and runs the {DTOR} for {TYPE}",
+ B=borrow_desc, LOC=local_name, TYPE=type_desc, DTOR=dtor_desc);
+ err.span_label(mir.source_info(drop_loc).span, message);
+
+ if should_note_order {
+ err.note(
+ "values in a scope are dropped \
+ in the opposite order they are defined",
+ );
+ }
+ }
+ None => {
+ err.span_label(local_decl.source_info.span,
+ format!("a temporary with access to the {B}borrow \
+ is created here ...",
+ B=borrow_desc));
+ let message =
+ format!("... and the {B}borrow might be used here, \
+ when that temporary is dropped \
+ and runs the {DTOR} for {TYPE}",
+ B=borrow_desc, TYPE=type_desc, DTOR=dtor_desc);
+ err.span_label(mir.source_info(drop_loc).span, message);
+
+ if let Some(info) = &local_decl.is_block_tail {
+ // FIXME: use span_suggestion instead, highlighting the
+ // whole block tail expression.
+ let msg = if info.tail_result_is_ignored {
+ "The temporary is part of an expression at the end of a block. \
+ Consider adding semicolon after the expression so its temporaries \
+ are dropped sooner, before the local variables declared by the \
+ block are dropped."
+ } else {
+ "The temporary is part of an expression at the end of a block. \
+ Consider forcing this temporary to be dropped sooner, before \
+ the block's local variables are dropped. \
+ For example, you could save the expression's value in a new \
+ local variable `x` and then make `x` be the expression \
+ at the end of the block."
+ };
- if should_note_order {
- err.note(
- "values in a scope are dropped \
- in the opposite order they are defined",
- );
+ err.note(msg);
+ }
+ }
}
- },
+ }
+
BorrowExplanation::MustBeValidFor(region) => {
tcx.note_and_explain_free_region(
err,
- "borrowed value must be valid for ",
+ &format!("{}{}", borrow_desc, "borrowed value must be valid for "),
region,
"...",
);
}
impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
- /// Adds annotations to `err` explaining *why* the borrow contains the
+ /// Returns structured explanation for *why* the borrow contains the
/// point from `context`. This is key for the "3-point errors"
/// [described in the NLL RFC][d].
///
/// - `kind_place`: if Some, this describes the statement that triggered the error.
/// - first half is the kind of write, if any, being performed
/// - second half is the place being accessed
- /// - `err`: where the error annotations are going to be added
///
/// [d]: https://rust-lang.github.io/rfcs/2094-nll.html#leveraging-intuition-framing-errors-in-terms-of-points
pub(in borrow_check) fn explain_why_borrow_contains_point(
kind_place: Option<(WriteKind, &Place<'tcx>)>,
) -> BorrowExplanation<'tcx> {
debug!(
- "find_why_borrow_contains_point(context={:?}, borrow={:?})",
- context, borrow,
+ "explain_why_borrow_contains_point(context={:?}, borrow={:?}, kind_place={:?})",
+ context, borrow, kind_place
);
let regioncx = &self.nonlexical_regioncx;
.or_else(|| self.borrow_spans(span, location));
if self.is_borrow_location_in_loop(context.loc) {
- BorrowExplanation::UsedLaterInLoop(spans.for_closure(), spans.var_or_use())
+ let later_use = self.later_use_kind(spans, location);
+ BorrowExplanation::UsedLaterInLoop(later_use.0, later_use.1)
} else {
// Check if the location represents a `FakeRead`, and adapt the error
// message to the `FakeReadCause` it is from: in particular,
// the ones inserted in optimized `let var = <expr>` patterns.
- BorrowExplanation::UsedLater(
- spans.for_closure(),
- self.retrieve_fake_read_cause_for_location(&location),
- spans.var_or_use()
- )
+ let later_use = self.later_use_kind(spans, location);
+ BorrowExplanation::UsedLater(later_use.0, later_use.1)
}
}
- Some(Cause::DropVar(local, location)) => match &mir.local_decls[local].name {
- Some(local_name) => {
- let mut should_note_order = false;
- if let Some((WriteKind::StorageDeadOrDrop, place)) = kind_place {
- if let Place::Local(borrowed_local) = place {
- let dropped_local_scope = mir.local_decls[local].visibility_scope;
- let borrowed_local_scope =
- mir.local_decls[*borrowed_local].visibility_scope;
-
- if mir.is_sub_scope(borrowed_local_scope, dropped_local_scope)
- && local != *borrowed_local
- {
- should_note_order = true;
- }
- }
- }
+ Some(Cause::DropVar(local, location)) => {
+ let mut should_note_order = false;
+ if mir.local_decls[local].name.is_some() {
+ if let Some((WriteKind::StorageDeadOrDrop, place)) = kind_place {
+ if let Place::Local(borrowed_local) = place {
+ let dropped_local_scope = mir.local_decls[local].visibility_scope;
+ let borrowed_local_scope =
+ mir.local_decls[*borrowed_local].visibility_scope;
- BorrowExplanation::UsedLaterWhenDropped(
- mir.source_info(location).span,
- *local_name,
- should_note_order
- )
- },
+ if mir.is_sub_scope(borrowed_local_scope, dropped_local_scope)
+ && local != *borrowed_local
+ {
+ should_note_order = true;
+ }
+ }
+ }
+ }
- None => BorrowExplanation::Unexplained,
- },
+ BorrowExplanation::UsedLaterWhenDropped {
+ drop_loc: location,
+ dropped_local: local,
+ should_note_order,
+ }
+ }
None => if let Some(region) = regioncx.to_error_region(region_sub) {
BorrowExplanation::MustBeValidFor(region)
false
}
+
+ fn later_use_kind(&self, use_spans: UseSpans, location: Location) -> (LaterUseKind, Span) {
+ use self::LaterUseKind::*;
+
+ let block = &self.mir.basic_blocks()[location.block];
+ match use_spans {
+ UseSpans::ClosureUse { var_span, .. } => (LaterUseKind::ClosureCapture, var_span),
+ UseSpans::OtherUse(span) => {
+ (if let Some(stmt) = block.statements.get(location.statement_index) {
+ match stmt.kind {
+ StatementKind::FakeRead(FakeReadCause::ForLet, _) => FakeLetRead,
+ _ => Other,
+ }
+ } else {
+ assert_eq!(location.statement_index, block.statements.len());
+ match block.terminator().kind {
+ TerminatorKind::Call { ref func, from_hir_call: true, .. } => {
+ // Just point to the function, to reduce the chance
+ // of overlapping spans.
+ let function_span = match func {
+ Operand::Constant(c) => c.span,
+ Operand::Copy(Place::Local(l)) | Operand::Move(Place::Local(l)) => {
+ let local_decl = &self.mir.local_decls[*l];
+ if local_decl.name.is_none() {
+ local_decl.source_info.span
+ } else {
+ span
+ }
+ },
+ _ => span,
+ };
+ return (Call, function_span);
+ },
+ _ => Other,
+ }
+ }, span)
+ }
+ }
+ }
}
ref args,
ref destination,
cleanup: _,
+ from_hir_call: _,
} => {
self.consume_operand(ContextKind::CallOperator.new(location), func);
for arg in args {
// Run the MIR type-checker.
let MirTypeckResults {
constraints,
+ placeholder_indices,
universal_region_relations,
} = type_check::type_check(
infcx,
elements,
);
+ let placeholder_indices = Rc::new(placeholder_indices);
+
if let Some(all_facts) = &mut all_facts {
all_facts
.universal_region
let mut regioncx = RegionInferenceContext::new(
var_origins,
universal_regions,
+ placeholder_indices,
universal_region_relations,
mir,
outlives_constraints,
ty::ReLateBound(..)
| ty::ReScope(..)
| ty::ReVar(..)
- | ty::ReSkolemized(..)
+ | ty::RePlaceholder(..)
| ty::ReEmpty
| ty::ReErased
| ty::ReClosureBound(..)
use super::universal_regions::UniversalRegions;
use borrow_check::nll::constraints::graph::NormalConstraintGraph;
use borrow_check::nll::constraints::{ConstraintSccIndex, ConstraintSet, OutlivesConstraint};
-use borrow_check::nll::region_infer::values::{RegionElement, ToElementIndex};
+use borrow_check::nll::region_infer::values::{PlaceholderIndices, RegionElement, ToElementIndex};
use borrow_check::nll::type_check::free_region_relations::UniversalRegionRelations;
use borrow_check::nll::type_check::Locations;
use rustc::hir::def_id::DefId;
pub(crate) fn new(
var_infos: VarInfos,
universal_regions: Rc<UniversalRegions<'tcx>>,
+ placeholder_indices: Rc<PlaceholderIndices>,
universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
_mir: &Mir<'tcx>,
outlives_constraints: ConstraintSet,
.map(|info| RegionDefinition::new(info.universe, info.origin))
.collect();
- // Compute the max universe used anywhere amongst the regions.
- let max_universe = definitions
- .iter()
- .map(|d| d.universe)
- .max()
- .unwrap_or(ty::UniverseIndex::ROOT);
-
let constraints = Rc::new(outlives_constraints); // freeze constraints
let constraint_graph = Rc::new(constraints.graph(definitions.len()));
let fr_static = universal_regions.fr_static;
let constraint_sccs = Rc::new(constraints.compute_sccs(&constraint_graph, fr_static));
- let mut scc_values = RegionValues::new(elements, universal_regions.len(), max_universe);
+ let mut scc_values =
+ RegionValues::new(elements, universal_regions.len(), &placeholder_indices);
for region in liveness_constraints.rows() {
let scc = constraint_sccs.scc(region);
self.scc_values.add_element(scc, variable);
}
- NLLRegionVariableOrigin::BoundRegion(ui) => {
- // Each placeholder region X outlives its
- // associated universe but nothing else. Every
- // placeholder region is always in a universe that
- // contains `ui` -- but when placeholder regions
- // are placed into an SCC, that SCC may include
- // things from other universes that do not include
- // `ui`.
+ NLLRegionVariableOrigin::Placeholder(placeholder) => {
+ // Each placeholder region is only visible from
+ // its universe `ui` and its superuniverses. So we
+ // can't just add it into `scc` unless the
+ // universe of the scc can name this region.
let scc_universe = self.scc_universes[scc];
- if ui.is_subset_of(scc_universe) {
- self.scc_values.add_element(scc, ui);
+ if placeholder.universe.is_subset_of(scc_universe) {
+ self.scc_values.add_element(scc, placeholder);
} else {
self.add_incompatible_universe(scc);
}
// B's value, and check whether all of them are nameable
// from universe_a
self.scc_values
- .subuniverses_contained_in(scc_b)
- .all(|u| u.is_subset_of(universe_a))
+ .placeholders_contained_in(scc_b)
+ .all(|p| p.universe.is_subset_of(universe_a))
}
/// Extend `scc` so that it can outlive some placeholder region
);
}
- NLLRegionVariableOrigin::BoundRegion(universe) => {
- self.check_bound_universal_region(infcx, mir, mir_def_id, fr, universe);
+ NLLRegionVariableOrigin::Placeholder(placeholder) => {
+ self.check_bound_universal_region(infcx, mir, mir_def_id, fr, placeholder);
}
NLLRegionVariableOrigin::Existential => {
assert!(self.scc_universes[longer_fr_scc] == ty::UniverseIndex::ROOT);
debug_assert!(
self.scc_values
- .subuniverses_contained_in(longer_fr_scc)
+ .placeholders_contained_in(longer_fr_scc)
.next()
.is_none()
);
mir: &Mir<'tcx>,
_mir_def_id: DefId,
longer_fr: RegionVid,
- universe: ty::UniverseIndex,
+ placeholder: ty::Placeholder,
) {
- debug!("check_bound_universal_region(fr={:?})", longer_fr);
+ debug!(
+ "check_bound_universal_region(fr={:?}, placeholder={:?})",
+ longer_fr, placeholder,
+ );
let longer_fr_scc = self.constraint_sccs.scc(longer_fr);
.find(|element| match element {
RegionElement::Location(_) => true,
RegionElement::RootUniversalRegion(_) => true,
- RegionElement::SubUniversalRegion(ui) => *ui != universe,
+ RegionElement::PlaceholderRegion(placeholder1) => placeholder != *placeholder1,
})
} {
Some(v) => v,
let error_region = match error_element {
RegionElement::Location(l) => self.find_sub_region_live_at(longer_fr, l),
RegionElement::RootUniversalRegion(r) => r,
- RegionElement::SubUniversalRegion(error_ui) => self.definitions
+ RegionElement::PlaceholderRegion(error_placeholder) => self.definitions
.iter_enumerated()
.filter_map(|(r, definition)| match definition.origin {
- NLLRegionVariableOrigin::BoundRegion(ui) if error_ui == ui => Some(r),
+ NLLRegionVariableOrigin::Placeholder(p) if p == error_placeholder => Some(r),
_ => None,
})
.next()
use rustc::mir::{BasicBlock, Location, Mir};
use rustc::ty::{self, RegionVid};
use rustc_data_structures::bit_set::{HybridBitSet, SparseBitMatrix};
+use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::indexed_vec::Idx;
use rustc_data_structures::indexed_vec::IndexVec;
use std::fmt::Debug;
impl RegionValueElements {
crate fn new(mir: &Mir<'_>) -> Self {
let mut num_points = 0;
- let statements_before_block: IndexVec<BasicBlock, usize> = mir
- .basic_blocks()
+ let statements_before_block: IndexVec<BasicBlock, usize> = mir.basic_blocks()
.iter()
.map(|block_data| {
let v = num_points;
let mut basic_blocks = IndexVec::with_capacity(num_points);
for (bb, bb_data) in mir.basic_blocks().iter_enumerated() {
- basic_blocks.extend((0 .. bb_data.statements.len() + 1).map(|_| bb));
+ basic_blocks.extend((0..bb_data.statements.len() + 1).map(|_| bb));
}
Self {
let block = self.basic_blocks[index];
let start_index = self.statements_before_block[block];
let statement_index = index.index() - start_index;
- Location { block, statement_index }
+ Location {
+ block,
+ statement_index,
+ }
}
/// Sometimes we get point-indices back from bitsets that may be
index: PointIndex,
stack: &mut Vec<PointIndex>,
) {
- let Location { block, statement_index } = self.to_location(index);
+ let Location {
+ block,
+ statement_index,
+ } = self.to_location(index);
if statement_index == 0 {
// If this is a basic block head, then the predecessors are
// the the terminators of other basic blocks
stack.extend(
- mir
- .predecessors_for(block)
+ mir.predecessors_for(block)
.iter()
.map(|&pred_bb| mir.terminator_loc(pred_bb))
.map(|pred_loc| self.point_from_location(pred_loc)),
pub struct PointIndex { DEBUG_FORMAT = "PointIndex({})" }
}
-/// A single integer representing a (non-zero) `UniverseIndex`.
-/// Computed just by subtracting one from `UniverseIndex`; this is
-/// because the `0` value for `UniverseIndex` represents the root
-/// universe, and we don't need/want a bit for that one.
+/// A single integer representing a `ty::Placeholder`.
newtype_index! {
pub struct PlaceholderIndex { DEBUG_FORMAT = "PlaceholderIndex({})" }
}
/// A subuniverse from a subuniverse (e.g., instantiated from a
/// `for<'a> fn(&'a u32)` type).
- SubUniversalRegion(ty::UniverseIndex),
+ PlaceholderRegion(ty::Placeholder),
}
/// When we initially compute liveness, we use a bit matrix storing
/// Adds all the elements in the given bit array into the given
/// region. Returns true if any of them are newly added.
crate fn add_elements(&mut self, row: N, locations: &HybridBitSet<PointIndex>) -> bool {
- debug!("LivenessValues::add_elements(row={:?}, locations={:?})", row, locations);
+ debug!(
+ "LivenessValues::add_elements(row={:?}, locations={:?})",
+ row, locations
+ );
self.points.union_into_row(row, locations)
}
}
}
+/// Maps from `ty::Placeholder` values that are used in the rest of
+/// rustc to the internal `PlaceholderIndex` values that are used in
+/// NLL.
+#[derive(Default)]
+crate struct PlaceholderIndices {
+ to_index: FxHashMap<ty::Placeholder, PlaceholderIndex>,
+ from_index: IndexVec<PlaceholderIndex, ty::Placeholder>,
+}
+
+impl PlaceholderIndices {
+ crate fn insert(&mut self, placeholder: ty::Placeholder) -> PlaceholderIndex {
+ let PlaceholderIndices {
+ to_index,
+ from_index,
+ } = self;
+ *to_index
+ .entry(placeholder)
+ .or_insert_with(|| from_index.push(placeholder))
+ }
+
+ crate fn lookup_index(&self, placeholder: ty::Placeholder) -> PlaceholderIndex {
+ self.to_index[&placeholder]
+ }
+
+ crate fn lookup_placeholder(&self, placeholder: PlaceholderIndex) -> ty::Placeholder {
+ self.from_index[placeholder]
+ }
+
+ crate fn len(&self) -> usize {
+ self.from_index.len()
+ }
+}
+
+impl ::std::iter::FromIterator<ty::Placeholder> for PlaceholderIndices {
+ fn from_iter<I>(iter: I) -> Self
+ where
+ I: IntoIterator<Item = ty::Placeholder>,
+ {
+ let mut result = Self::default();
+ iter.into_iter().for_each(|p| {
+ result.insert(p);
+ });
+ result
+ }
+}
+
/// Stores the full values for a set of regions (in contrast to
/// `LivenessValues`, which only stores those points in the where a
/// region is live). The full value for a region may contain points in
#[derive(Clone)]
crate struct RegionValues<N: Idx> {
elements: Rc<RegionValueElements>,
+ placeholder_indices: Rc<PlaceholderIndices>,
points: SparseBitMatrix<N, PointIndex>,
free_regions: SparseBitMatrix<N, RegionVid>,
crate fn new(
elements: &Rc<RegionValueElements>,
num_universal_regions: usize,
- max_universe: ty::UniverseIndex,
+ placeholder_indices: &Rc<PlaceholderIndices>,
) -> Self {
- let num_placeholders = max_universe.as_usize();
+ let num_placeholders = placeholder_indices.len();
Self {
elements: elements.clone(),
points: SparseBitMatrix::new(elements.num_points),
+ placeholder_indices: placeholder_indices.clone(),
free_regions: SparseBitMatrix::new(num_universal_regions),
placeholders: SparseBitMatrix::new(num_placeholders),
}
/// Returns the locations contained within a given region `r`.
crate fn locations_outlived_by<'a>(&'a self, r: N) -> impl Iterator<Item = Location> + 'a {
- self.points
- .row(r)
- .into_iter()
- .flat_map(move |set| {
- set.iter()
- .take_while(move |&p| self.elements.point_in_range(p))
- .map(move |p| self.elements.to_location(p))
- })
+ self.points.row(r).into_iter().flat_map(move |set| {
+ set.iter()
+ .take_while(move |&p| self.elements.point_in_range(p))
+ .map(move |p| self.elements.to_location(p))
+ })
}
/// Returns just the universal regions that are contained in a given region's value.
}
/// Returns all the elements contained in a given region's value.
- crate fn subuniverses_contained_in<'a>(
+ crate fn placeholders_contained_in<'a>(
&'a self,
r: N,
- ) -> impl Iterator<Item = ty::UniverseIndex> + 'a {
+ ) -> impl Iterator<Item = ty::Placeholder> + 'a {
self.placeholders
.row(r)
.into_iter()
.flat_map(|set| set.iter())
- .map(|p| ty::UniverseIndex::from_u32((p.index() + 1) as u32))
+ .map(move |p| self.placeholder_indices.lookup_placeholder(p))
}
/// Returns all the elements contained in a given region's value.
crate fn elements_contained_in<'a>(&'a self, r: N) -> impl Iterator<Item = RegionElement> + 'a {
let points_iter = self.locations_outlived_by(r).map(RegionElement::Location);
- let free_regions_iter = self
- .universal_regions_outlived_by(r)
+ let free_regions_iter = self.universal_regions_outlived_by(r)
.map(RegionElement::RootUniversalRegion);
- let subuniverses_iter = self
- .subuniverses_contained_in(r)
- .map(RegionElement::SubUniversalRegion);
+ let placeholder_universes_iter = self.placeholders_contained_in(r)
+ .map(RegionElement::PlaceholderRegion);
points_iter
.chain(free_regions_iter)
- .chain(subuniverses_iter)
+ .chain(placeholder_universes_iter)
}
/// Returns a "pretty" string value of the region. Meant for debugging.
}
}
-impl ToElementIndex for ty::UniverseIndex {
+impl ToElementIndex for ty::Placeholder {
fn add_to_row<N: Idx>(self, values: &mut RegionValues<N>, row: N) -> bool {
- let index = PlaceholderIndex::new(self.as_usize() - 1);
+ let index = values.placeholder_indices.lookup_index(self);
values.placeholders.insert(row, index)
}
fn contained_in_row<N: Idx>(self, values: &RegionValues<N>, row: N) -> bool {
- let index = PlaceholderIndex::new(self.as_usize() - 1);
+ let index = values.placeholder_indices.lookup_index(self);
values.placeholders.contains(row, index)
}
}
result.push_str(&format!("{:?}", fr));
}
- RegionElement::SubUniversalRegion(ur) => {
+ RegionElement::PlaceholderRegion(placeholder) => {
if let Some((location1, location2)) = open_location {
push_sep(&mut result);
push_location_range(&mut result, location1, location2);
}
push_sep(&mut result);
- result.push_str(&format!("{:?}", ur));
+ result.push_str(&format!("{:?}", placeholder));
}
}
}
use borrow_check::location::LocationTable;
use borrow_check::nll::constraints::{ConstraintCategory, ConstraintSet, OutlivesConstraint};
use borrow_check::nll::facts::AllFacts;
-use borrow_check::nll::region_infer::values::{LivenessValues, RegionValueElements};
+use borrow_check::nll::region_infer::values::LivenessValues;
+use borrow_check::nll::region_infer::values::PlaceholderIndices;
+use borrow_check::nll::region_infer::values::RegionValueElements;
use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
use borrow_check::nll::renumber;
use borrow_check::nll::type_check::free_region_relations::{
use rustc::ty::fold::TypeFoldable;
use rustc::ty::subst::Subst;
use rustc::ty::{self, CanonicalTy, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
-use std::{fmt, iter};
use std::rc::Rc;
+use std::{fmt, iter};
use syntax_pos::{Span, DUMMY_SP};
use transform::{MirPass, MirSource};
-use rustc_data_structures::fx::FxHashSet;
use either::Either;
+use rustc_data_structures::fx::FxHashSet;
macro_rules! span_mirbug {
($context:expr, $elem:expr, $($message:tt)*) => ({
outlives_constraints: ConstraintSet::default(),
type_tests: Vec::default(),
};
+ let mut placeholder_indices = PlaceholderIndices::default();
let CreateResult {
universal_region_relations,
borrow_set,
all_facts,
constraints: &mut constraints,
+ placeholder_indices: &mut placeholder_indices,
};
type_check_internal(
cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
- cx.borrowck_context.as_mut().map(|bcx| translate_outlives_facts(bcx));
+ cx.borrowck_context
+ .as_mut()
+ .map(|bcx| translate_outlives_facts(bcx));
},
);
MirTypeckResults {
constraints,
+ placeholder_indices,
universal_region_relations,
}
}
fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
if let Some(facts) = cx.all_facts {
let location_table = cx.location_table;
- facts.outlives.extend(
- cx.constraints.outlives_constraints.iter().flat_map(|constraint: &OutlivesConstraint| {
- if let Some(from_location) = constraint.locations.from_location() {
- Either::Left(iter::once((
- constraint.sup,
- constraint.sub,
- location_table.mid_index(from_location),
- )))
- } else {
- Either::Right(location_table.all_points().map(move |location| {
- (constraint.sup, constraint.sub, location)
- }))
- }
- })
- );
+ facts
+ .outlives
+ .extend(cx.constraints.outlives_constraints.iter().flat_map(
+ |constraint: &OutlivesConstraint| {
+ if let Some(from_location) = constraint.locations.from_location() {
+ Either::Left(iter::once((
+ constraint.sup,
+ constraint.sub,
+ location_table.mid_index(from_location),
+ )))
+ } else {
+ Either::Right(
+ location_table
+ .all_points()
+ .map(move |location| (constraint.sup, constraint.sub, location)),
+ )
+ }
+ },
+ ));
}
}
all_facts: &'a mut Option<AllFacts>,
borrow_set: &'a BorrowSet<'tcx>,
constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
+ placeholder_indices: &'a mut PlaceholderIndices,
}
crate struct MirTypeckResults<'tcx> {
crate constraints: MirTypeckRegionConstraints<'tcx>,
+ crate placeholder_indices: PlaceholderIndices,
crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
}
/// delegate.
fn push_outlives(&mut self, sup: ty::Region<'tcx>, sub: ty::Region<'tcx>);
- /// Creates a new region variable representing an instantiated
- /// higher-ranked region; this will be either existential or
- /// universal depending on the context. So e.g. if you have
- /// `for<'a> fn(..) <: for<'b> fn(..)`, then we will first
- /// instantiate `'b` with a universally quantitifed region and
- /// then `'a` with an existentially quantified region (the order
- /// is important so that the existential region `'a` can see the
- /// universal one).
- fn next_region_var(
- &mut self,
- universally_quantified: UniversallyQuantified,
- ) -> ty::Region<'tcx>;
+ /// Creates a new universe index. Used when instantiating placeholders.
+ fn next_subuniverse(&mut self) -> ty::UniverseIndex;
+
+ /// Creates a new region variable representing a higher-ranked
+ /// region that is instantiated existentially. This creates an
+ /// inference variable, typically.
+ ///
+ /// So e.g. if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
+ /// we will invoke this method to instantiate `'a` with an
+ /// inference variable (though `'b` would be instantiated first,
+ /// as a placeholder).
+ fn next_existential_region_var(&mut self) -> ty::Region<'tcx>;
+
+ /// Creates a new region variable representing a
+ /// higher-ranked region that is instantiated universally.
+ /// This creates a new region placeholder, typically.
+ ///
+ /// So e.g. if you have `for<'a> fn(..) <: for<'b> fn(..)`, then
+ /// we will invoke this method to instantiate `'b` with a
+ /// placeholder region.
+ fn next_placeholder_region(&mut self, placeholder: ty::Placeholder) -> ty::Region<'tcx>;
/// Creates a new existential region in the given universe. This
/// is used when handling subtyping and type variables -- if we
}
impl TypeRelatingDelegate<'tcx> for NllTypeRelatingDelegate<'_, '_, '_, 'tcx> {
- fn next_region_var(
- &mut self,
- universally_quantified: UniversallyQuantified,
- ) -> ty::Region<'tcx> {
- let origin = if universally_quantified.0 {
- NLLRegionVariableOrigin::BoundRegion(self.infcx.create_subuniverse())
- } else {
- NLLRegionVariableOrigin::Existential
- };
+ fn next_subuniverse(&mut self) -> ty::UniverseIndex {
+ self.infcx.create_subuniverse()
+ }
+
+ fn next_existential_region_var(&mut self) -> ty::Region<'tcx> {
+ let origin = NLLRegionVariableOrigin::Existential;
+ self.infcx.next_nll_region_var(origin)
+ }
+
+ fn next_placeholder_region(&mut self, placeholder: ty::Placeholder) -> ty::Region<'tcx> {
+ let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
+ if let Some(borrowck_context) = &mut self.borrowck_context {
+ borrowck_context.placeholder_indices.insert(placeholder);
+ }
self.infcx.next_nll_region_var(origin)
}
universally_quantified: UniversallyQuantified,
) -> BoundRegionScope<'tcx> {
let mut scope = BoundRegionScope::default();
+
+ // Create a callback that creates (via the delegate) either an
+ // existential or placeholder region as needed.
+ let mut next_region = {
+ let delegate = &mut self.delegate;
+ let mut lazy_universe = None;
+ move |br: ty::BoundRegion| {
+ if universally_quantified.0 {
+ // The first time this closure is called, create a
+ // new universe for the placeholders we will make
+ // from here out.
+ let universe = lazy_universe.unwrap_or_else(|| {
+ let universe = delegate.next_subuniverse();
+ lazy_universe = Some(universe);
+ universe
+ });
+
+ let placeholder = ty::Placeholder { universe, name: br };
+ delegate.next_placeholder_region(placeholder)
+ } else {
+ delegate.next_existential_region_var()
+ }
+ }
+ };
+
value.skip_binder().visit_with(&mut ScopeInstantiator {
- delegate: &mut self.delegate,
+ next_region: &mut next_region,
target_index: ty::INNERMOST,
- universally_quantified,
bound_region_scope: &mut scope,
});
+
scope
}
/// binder depth, and finds late-bound regions targeting the
/// `for<..`>. For each of those, it creates an entry in
/// `bound_region_scope`.
-struct ScopeInstantiator<'me, 'tcx: 'me, D>
-where
- D: TypeRelatingDelegate<'tcx> + 'me,
-{
- delegate: &'me mut D,
+struct ScopeInstantiator<'me, 'tcx: 'me> {
+ next_region: &'me mut dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx>,
// The debruijn index of the scope we are instantiating.
target_index: ty::DebruijnIndex,
- universally_quantified: UniversallyQuantified,
bound_region_scope: &'me mut BoundRegionScope<'tcx>,
}
-impl<'me, 'tcx, D> TypeVisitor<'tcx> for ScopeInstantiator<'me, 'tcx, D>
-where
- D: TypeRelatingDelegate<'tcx>,
-{
+impl<'me, 'tcx> TypeVisitor<'tcx> for ScopeInstantiator<'me, 'tcx> {
fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
self.target_index.shift_in(1);
t.super_visit_with(self);
fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
let ScopeInstantiator {
- universally_quantified,
bound_region_scope,
- delegate,
+ next_region,
..
} = self;
bound_region_scope
.map
.entry(*br)
- .or_insert_with(|| delegate.next_region_var(*universally_quantified));
+ .or_insert_with(|| next_region(*br));
}
_ => {}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-use build::{BlockAnd, BlockAndExtension, Builder};
+use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
use build::ForGuard::OutsideGuard;
use build::matches::ArmHasGuard;
use hair::*;
let Stmt { kind, opt_destruction_scope } = this.hir.mirror(stmt);
match kind {
StmtKind::Expr { scope, expr } => {
+ this.block_context.push(BlockFrame::Statement { ignores_expr_result: true });
unpack!(block = this.in_opt_scope(
opt_destruction_scope.map(|de|(de, source_info)), block, |this| {
let si = (scope, source_info);
initializer,
lint_level
} => {
+ let ignores_expr_result = if let PatternKind::Wild = *pattern.kind {
+ true
+ } else {
+ false
+ };
+ this.block_context.push(BlockFrame::Statement { ignores_expr_result });
+
// Enter the remainder scope, i.e. the bindings' destruction scope.
this.push_scope((remainder_scope, source_info));
let_scope_stack.push(remainder_scope);
}
}
}
+
+ let popped = this.block_context.pop();
+ assert!(popped.map_or(false, |bf|bf.is_statement()));
}
+
// Then, the block may have an optional trailing expression which is a “return” value
- // of the block.
+ // of the block, which is stored into `destination`.
+ let tcx = this.hir.tcx();
+ let destination_ty = destination.ty(&this.local_decls, tcx).to_ty(tcx);
if let Some(expr) = expr {
+ let tail_result_is_ignored = destination_ty.is_unit() ||
+ match this.block_context.last() {
+ // no context: conservatively assume result is read
+ None => false,
+
+ // sub-expression: block result feeds into some computation
+ Some(BlockFrame::SubExpr) => false,
+
+ // otherwise: use accumualated is_ignored state.
+ Some(BlockFrame::TailExpr { tail_result_is_ignored: ignored }) |
+ Some(BlockFrame::Statement { ignores_expr_result: ignored }) => *ignored,
+ };
+ this.block_context.push(BlockFrame::TailExpr { tail_result_is_ignored });
+
unpack!(block = this.into(destination, block, expr));
+ let popped = this.block_context.pop();
+
+ assert!(popped.map_or(false, |bf|bf.is_tail_expr()));
} else {
// If a block has no trailing expression, then it is given an implicit return type.
// This return type is usually `()`, unless the block is diverging, in which case the
// return type is `!`. For the unit type, we need to actually return the unit, but in
// the case of `!`, no return value is required, as the block will never return.
- let tcx = this.hir.tcx();
- let ty = destination.ty(&this.local_decls, tcx).to_ty(tcx);
- if ty.is_unit() {
+ if destination_ty.is_unit() {
// We only want to assign an implicit `()` as the return value of the block if the
// block does not diverge. (Otherwise, we may try to assign a unit to a `!`-type.)
this.cfg.push_assign_unit(block, source_info, destination);
//! See docs in build/expr/mod.rs
-use build::{BlockAnd, BlockAndExtension, Builder};
+use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
use hair::*;
use rustc::middle::region;
use rustc::mir::*;
}
let expr_ty = expr.ty;
- let temp = if mutability == Mutability::Not {
- this.local_decls
- .push(LocalDecl::new_immutable_temp(expr_ty, expr_span))
- } else {
- this.local_decls
- .push(LocalDecl::new_temp(expr_ty, expr_span))
- };
+ let temp = {
+ let mut local_decl = LocalDecl::new_temp(expr_ty, expr_span);
+ if mutability == Mutability::Not {
+ local_decl = local_decl.immutable();
+ }
+
+ debug!("creating temp {:?} with block_context: {:?}", local_decl, this.block_context);
+ // Find out whether this temp is being created within the
+ // tail expression of a block whose result is ignored.
+ for bf in this.block_context.iter().rev() {
+ match bf {
+ BlockFrame::SubExpr => continue,
+ BlockFrame::Statement { .. } => break,
+ &BlockFrame::TailExpr { tail_result_is_ignored } => {
+ local_decl = local_decl.block_tail(BlockTailInfo {
+ tail_result_is_ignored
+ });
+ break;
+ }
+ }
+ }
+ this.local_decls.push(local_decl)
+ };
if !expr_ty.is_never() {
this.cfg.push(
block,
//! See docs in build/expr/mod.rs
use build::expr::category::{Category, RvalueFunc};
-use build::{BlockAnd, BlockAndExtension, Builder};
+use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
use hair::*;
use rustc::mir::*;
use rustc::ty;
let expr_span = expr.span;
let source_info = this.source_info(expr_span);
- match expr.kind {
+ let expr_is_block_or_scope = match expr.kind {
+ ExprKind::Block { .. } => true,
+ ExprKind::Scope { .. } => true,
+ _ => false,
+ };
+
+ if !expr_is_block_or_scope {
+ this.block_context.push(BlockFrame::SubExpr);
+ }
+
+ let block_and = match expr.kind {
ExprKind::Scope {
region_scope,
lint_level,
);
exit_block.unit()
}
- ExprKind::Call { ty, fun, args } => {
+ ExprKind::Call { ty, fun, args, from_hir_call } => {
// FIXME(canndrew): This is_never should probably be an is_uninhabited
let diverges = expr.ty.is_never();
let intrinsic = match ty.sty {
visibility_scope: source_info.scope,
internal: true,
is_user_variable: None,
+ is_block_tail: None,
});
let ptr_temp = Place::Local(ptr_temp);
let block = unpack!(this.into(&ptr_temp, block, ptr));
} else {
Some((destination.clone(), success))
},
+ from_hir_call,
},
);
success.unit()
.push_assign(block, source_info, destination, rvalue);
block.unit()
}
+ };
+
+ if !expr_is_block_or_scope {
+ let popped = this.block_context.pop();
+ assert!(popped.is_some());
}
+
+ block_and
}
}
// except according to those terms.
use build::scope::BreakableScope;
-use build::{BlockAnd, BlockAndExtension, Builder};
+use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
use hair::*;
use rustc::mir::*;
let source_info = this.source_info(expr.span);
// Handle a number of expressions that don't need a destination at all. This
// avoids needing a mountain of temporary `()` variables.
+ let expr2 = expr.clone();
match expr.kind {
ExprKind::Scope {
region_scope,
// is better for borrowck interaction with overloaded
// operators like x[j] = x[i].
+ debug!("stmt_expr Assign block_context.push(SubExpr) : {:?}", expr2);
+ this.block_context.push(BlockFrame::SubExpr);
+
// Generate better code for things that don't need to be
// dropped.
if this.hir.needs_drop(lhs.ty) {
let rhs = unpack!(block = this.as_local_operand(block, rhs));
let lhs = unpack!(block = this.as_place(block, lhs));
unpack!(block = this.build_drop_and_replace(block, lhs_span, lhs, rhs));
- block.unit()
} else {
let rhs = unpack!(block = this.as_local_rvalue(block, rhs));
let lhs = unpack!(block = this.as_place(block, lhs));
this.cfg.push_assign(block, source_info, &lhs, rhs);
- block.unit()
}
+
+ this.block_context.pop();
+ block.unit()
}
ExprKind::AssignOp { op, lhs, rhs } => {
// FIXME(#28160) there is an interesting semantics
let lhs = this.hir.mirror(lhs);
let lhs_ty = lhs.ty;
+ debug!("stmt_expr AssignOp block_context.push(SubExpr) : {:?}", expr2);
+ this.block_context.push(BlockFrame::SubExpr);
+
// As above, RTL.
let rhs = unpack!(block = this.as_local_operand(block, rhs));
let lhs = unpack!(block = this.as_place(block, lhs));
);
this.cfg.push_assign(block, source_info, &lhs, result);
+ this.block_context.pop();
block.unit()
}
ExprKind::Continue { label } => {
(break_block, region_scope, break_destination.clone())
};
if let Some(value) = value {
- unpack!(block = this.into(&destination, block, value))
+ debug!("stmt_expr Break val block_context.push(SubExpr) : {:?}", expr2);
+ this.block_context.push(BlockFrame::SubExpr);
+ unpack!(block = this.into(&destination, block, value));
+ this.block_context.pop();
} else {
this.cfg.push_assign_unit(block, source_info, &destination)
}
}
ExprKind::Return { value } => {
block = match value {
- Some(value) => unpack!(this.into(&Place::Local(RETURN_PLACE), block, value)),
+ Some(value) => {
+ debug!("stmt_expr Return val block_context.push(SubExpr) : {:?}", expr2);
+ this.block_context.push(BlockFrame::SubExpr);
+ let result = unpack!(this.into(&Place::Local(RETURN_PLACE), block, value));
+ this.block_context.pop();
+ result
+ }
None => {
this.cfg
.push_assign_unit(block, source_info, &Place::Local(RETURN_PLACE));
outputs,
inputs,
} => {
+ debug!("stmt_expr InlineAsm block_context.push(SubExpr) : {:?}", expr2);
+ this.block_context.push(BlockFrame::SubExpr);
let outputs = outputs
.into_iter()
.map(|output| unpack!(block = this.as_place(block, output)))
},
},
);
+ this.block_context.pop();
block.unit()
}
_ => {
source_info,
visibility_scope,
internal: false,
+ is_block_tail: None,
is_user_variable: Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
binding_mode,
// hypothetically, `visit_bindings` could try to unzip
visibility_scope,
// FIXME: should these secretly injected ref_for_guard's be marked as `internal`?
internal: false,
+ is_block_tail: None,
is_user_variable: Some(ClearCrossCrate::Set(BindingForm::RefForGuard)),
});
LocalsForNode::ForGuard {
args: vec![val, expect],
destination: Some((eq_result.clone(), eq_block)),
cleanup: Some(cleanup),
+ from_hir_call: false,
});
// check the result
tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
}
+#[derive(Debug, PartialEq, Eq)]
+pub enum BlockFrame {
+ /// Evaluation is currently within a statement.
+ ///
+ /// Examples include:
+ /// 1. `EXPR;`
+ /// 2. `let _ = EXPR;`
+ /// 3. `let x = EXPR;`
+ Statement {
+ /// If true, then statement discards result from evaluating
+ /// the expression (such as examples 1 and 2 above).
+ ignores_expr_result: bool
+ },
+
+ /// Evaluation is currently within the tail expression of a block.
+ ///
+ /// Example: `{ STMT_1; STMT_2; EXPR }`
+ TailExpr {
+ /// If true, then the surrounding context of the block ignores
+ /// the result of evaluating the block's tail expression.
+ ///
+ /// Example: `let _ = { STMT_1; EXPR };`
+ tail_result_is_ignored: bool
+ },
+
+ /// Generic mark meaning that the block occurred as a subexpression
+ /// where the result might be used.
+ ///
+ /// Examples: `foo(EXPR)`, `match EXPR { ... }`
+ SubExpr,
+}
+
+impl BlockFrame {
+ fn is_tail_expr(&self) -> bool {
+ match *self {
+ BlockFrame::TailExpr { .. } => true,
+
+ BlockFrame::Statement { .. } |
+ BlockFrame::SubExpr => false,
+ }
+ }
+ fn is_statement(&self) -> bool {
+ match *self {
+ BlockFrame::Statement { .. } => true,
+
+ BlockFrame::TailExpr { .. } |
+ BlockFrame::SubExpr => false,
+ }
+ }
+ }
+
struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
hir: Cx<'a, 'gcx, 'tcx>,
cfg: CFG<'tcx>,
/// see the `scope` module for more details
scopes: Vec<scope::Scope<'tcx>>,
+ /// the block-context: each time we build the code within an hair::Block,
+ /// we push a frame here tracking whether we are building a statement or
+ /// if we are pushing the tail expression of the block. This is used to
+ /// embed information in generated temps about whether they were created
+ /// for a block tail expression or not.
+ ///
+ /// It would be great if we could fold this into `self.scopes`
+ /// somehow; but right now I think that is very tightly tied to
+ /// the code generation in ways that we cannot (or should not)
+ /// start just throwing new entries onto that vector in order to
+ /// distinguish the context of EXPR1 from the context of EXPR2 in
+ /// `{ STMTS; EXPR1 } + EXPR2`
+ block_context: Vec<BlockFrame>,
+
/// The current unsafe block in scope, even if it is hidden by
/// a PushUnsafeBlock
unpushed_unsafe: Safety,
fn_span: span,
arg_count,
scopes: vec![],
+ block_context: vec![],
source_scopes: IndexVec::new(),
source_scope: OUTERMOST_SOURCE_SCOPE,
source_scope_local_data: IndexVec::new(),
name,
internal: false,
is_user_variable: None,
+ is_block_tail: None,
});
}
self.propagate_bits_into_entry_set_for(in_out, *target, dirty_list);
}
}
- mir::TerminatorKind::Call { cleanup, ref destination, func: _, args: _ } => {
+ mir::TerminatorKind::Call { cleanup, ref destination, .. } => {
if let Some(unwind) = cleanup {
if !self.dead_unwinds.contains(bb) {
self.propagate_bits_into_entry_set_for(in_out, unwind, dirty_list);
self.gather_operand(value);
self.gather_init(location, InitKind::Deep);
}
- TerminatorKind::Call { ref func, ref args, ref destination, cleanup: _ } => {
+ TerminatorKind::Call {
+ ref func,
+ ref args,
+ ref destination,
+ cleanup: _,
+ from_hir_call: _,
+ } => {
self.gather_operand(func);
for arg in args {
self.gather_operand(arg);
use rustc::hir;
use rustc::hir::def_id::LocalDefId;
use rustc::mir::{BorrowKind};
+use syntax_pos::Span;
impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr {
type Output = Expr<'tcx>;
let kind = match expr.node {
// Here comes the interesting stuff:
- hir::ExprKind::MethodCall(.., ref args) => {
+ hir::ExprKind::MethodCall(_, method_span, ref args) => {
// Rewrite a.b(c) into UFCS form like Trait::b(a, c)
- let expr = method_callee(cx, expr, None);
+ let expr = method_callee(cx, expr, method_span,None);
let args = args.iter()
.map(|e| e.to_ref())
.collect();
ty: expr.ty,
fun: expr.to_ref(),
args,
+ from_hir_call: true,
}
}
// rewrite f(u, v) into FnOnce::call_once(f, (u, v))
- let method = method_callee(cx, expr, None);
+ let method = method_callee(cx, expr, fun.span,None);
let arg_tys = args.iter().map(|e| cx.tables().expr_ty_adjusted(e));
let tupled_args = Expr {
ty: method.ty,
fun: method.to_ref(),
args: vec![fun.to_ref(), tupled_args.to_ref()],
+ from_hir_call: true,
}
} else {
let adt_data = if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) =
ty: cx.tables().node_id_to_type(fun.hir_id),
fun: fun.to_ref(),
args: args.to_ref(),
+ from_hir_call: true,
}
}
}
fn method_callee<'a, 'gcx, 'tcx>(
cx: &mut Cx<'a, 'gcx, 'tcx>,
expr: &hir::Expr,
+ span: Span,
overloaded_callee: Option<(DefId, &'tcx Substs<'tcx>)>,
) -> Expr<'tcx> {
let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
Expr {
temp_lifetime,
ty,
- span: expr.span,
+ span,
kind: ExprKind::Literal {
literal: ty::Const::zero_sized(cx.tcx(), ty),
user_ty,
expr: &'tcx hir::Expr,
args: Vec<ExprRef<'tcx>>)
-> ExprKind<'tcx> {
- let fun = method_callee(cx, expr, None);
+ let fun = method_callee(cx, expr, expr.span, None);
ExprKind::Call {
ty: fun.ty,
fun: fun.to_ref(),
args,
+ from_hir_call: false,
}
}
// construct the complete expression `foo()` for the overloaded call,
// which will yield the &T type
let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
- let fun = method_callee(cx, expr, overloaded_callee);
+ let fun = method_callee(cx, expr, expr.span, overloaded_callee);
let ref_expr = Expr {
temp_lifetime,
ty: ref_ty,
ty: fun.ty,
fun: fun.to_ref(),
args,
+ from_hir_call: false,
},
};
ty: Ty<'tcx>,
fun: ExprRef<'tcx>,
args: Vec<ExprRef<'tcx>>,
+ // Whether this is from a call in HIR, rather than from an overloaded
+ // operator. True for overloaded function call.
+ from_hir_call: bool,
},
Deref {
arg: ExprRef<'tcx>,
/// Undefined bytes
impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
- // FIXME(solson): This is a very naive, slow version.
+ // FIXME: Add a fast version for the common, nonoverlapping case
fn copy_undef_mask(
&mut self,
src: Pointer,
}
ty::Error |
ty::Infer(_) |
+ ty::UnnormalizedProjection(..) |
ty::Projection(..) |
ty::Param(_) |
ty::GeneratorWitness(_) |
fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
LocalDecl {
- mutability, ty,
+ mutability,
+ ty,
user_ty: None,
name: None,
source_info,
visibility_scope: source_info.scope,
internal: false,
is_user_variable: None,
+ is_block_tail: None,
}
}
args: vec![Operand::Move(ref_loc)],
destination: Some((dest, next)),
cleanup: Some(cleanup),
+ from_hir_call: true,
}, false);
}
Some(BasicBlock::new(3))
} else {
None
- }
+ },
+ from_hir_call: true,
}, false);
if let Adjustment::RefMut = rcvr_adjustment {
source_info,
visibility_scope: source_info.scope,
internal: false,
+ is_block_tail: None,
is_user_variable: None,
};
let new_ret_local = Local::new(mir.local_decls.len());
source_info,
visibility_scope: source_info.scope,
internal: false,
+ is_block_tail: None,
is_user_variable: None,
};
source_info,
visibility_scope: source_info.scope,
internal: false,
+ is_block_tail: None,
is_user_variable: None,
};
args: vec![lhs, rhs],
destination: Some((place, bb)),
cleanup: None,
+ from_hir_call: false,
},
});
}
};
match terminator.kind {
- TerminatorKind::Call { mut func, mut args, .. } => {
+ TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
self.visit_operand(&mut func, loc);
for arg in &mut args {
self.visit_operand(arg, loc);
func,
args,
cleanup: None,
- destination: Some((Place::Local(new_temp), new_target))
+ destination: Some((Place::Local(new_temp), new_target)),
+ from_hir_call,
},
..terminator
};
TerminatorKind::Call {
func,
args,
+ from_hir_call: _,
destination: _,
cleanup: _,
} => {
args: vec![Operand::Move(Place::Local(ref_place))],
destination: Some((unit_temp, succ)),
cleanup: unwind.into_option(),
+ from_hir_call: true,
},
- source_info: self.source_info
+ source_info: self.source_info,
}),
is_cleanup: unwind.is_cleanup(),
};
func: Operand::function_handle(tcx, free_func, substs, self.source_info.span),
args: args,
destination: Some((unit_temp, target)),
- cleanup: None
+ cleanup: None,
+ from_hir_call: false,
}; // FIXME(#43234)
let free_block = self.new_block(unwind, call);
test = false
[dependencies]
+bitflags = "1.0"
log = "0.4"
syntax = { path = "../libsyntax" }
rustc = { path = "../librustc" }
#![feature(rustc_diagnostic_macros)]
#![feature(slice_sort_by_cached_key)]
+#[macro_use]
+extern crate bitflags;
#[macro_use]
extern crate log;
#[macro_use]
normal_ancestor_id: DefId,
resolutions: RefCell<FxHashMap<(Ident, Namespace), &'a RefCell<NameResolution<'a>>>>,
- legacy_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>, Option<Def>)>>,
+ legacy_macro_resolutions: RefCell<Vec<(Ident, MacroKind, ParentScope<'a>,
+ Option<&'a NameBinding<'a>>)>>,
macro_resolutions: RefCell<Vec<(Box<[Ident]>, Span)>>,
builtin_attrs: RefCell<Vec<(Ident, ParentScope<'a>)>>,
}
}
- fn get_macro<'b: 'a>(&self, resolver: &mut Resolver<'a, 'b>) -> Lrc<SyntaxExtension> {
- resolver.get_macro(self.def_ignoring_ambiguity())
- }
-
// We sometimes need to treat variants as `pub` for backwards compatibility
fn pseudo_vis(&self) -> ty::Visibility {
if self.is_variant() && self.def().def_id().is_local() {
self.resolve_ident_in_module(module, ident, ns, record_used, path_span)
} else if opt_ns == Some(MacroNS) {
assert!(ns == TypeNS);
- self.resolve_lexical_macro_path_segment(ident, ns, None, parent_scope, record_used,
- record_used, path_span).map(|(b, _)| b)
+ self.early_resolve_ident_in_lexical_scope(ident, ns, None, parent_scope,
+ record_used, record_used, path_span)
} else {
let record_used_id =
if record_used { crate_lint.node_id().or(Some(CRATE_NODE_ID)) } else { None };
use {AmbiguityError, CrateLint, Resolver, ResolutionError, is_known_tool, resolve_error};
use {Module, ModuleKind, NameBinding, NameBindingKind, PathResult, ToNameBinding};
use ModuleOrUniformRoot;
-use Namespace::{self, TypeNS, MacroNS};
+use Namespace::{self, *};
use build_reduced_graph::{BuildReducedGraphVisitor, IsMacroExport};
use resolve_imports::ImportResolver;
use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX, DefIndex,
use syntax::ast::{self, Name, Ident};
use syntax::attr;
use syntax::errors::DiagnosticBuilder;
-use syntax::ext::base::{self, Determinacy, MultiModifier, MultiDecorator};
+use syntax::ext::base::{self, Determinacy};
use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver};
-use syntax::ext::expand::{AstFragment, Invocation, InvocationKind, TogetherWith};
+use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
use syntax::ext::hygiene::{self, Mark};
use syntax::ext::tt::macro_rules;
use syntax::feature_gate::{self, feature_err, emit_feature_err, is_builtin_attr_name, GateIssue};
use std::mem;
use rustc_data_structures::sync::Lrc;
-#[derive(Clone, Copy)]
-crate struct FromPrelude(bool);
-
#[derive(Clone)]
pub struct InvocationData<'a> {
def_index: DefIndex,
// Resolves attribute and derive legacy macros from `#![plugin(..)]`.
fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>, allow_derive: bool)
-> Option<ast::Attribute> {
- for i in 0..attrs.len() {
- let name = attrs[i].name();
-
- if self.session.plugin_attributes.borrow().iter()
- .any(|&(ref attr_nm, _)| name == &**attr_nm) {
- attr::mark_known(&attrs[i]);
- }
-
- match self.builtin_macros.get(&name).cloned() {
- Some(binding) => match *binding.get_macro(self) {
- MultiModifier(..) | MultiDecorator(..) | SyntaxExtension::AttrProcMacro(..) => {
- return Some(attrs.remove(i))
- }
- _ => {}
- },
- None => {}
- }
+ if !allow_derive {
+ return None;
}
- if !allow_derive { return None }
-
// Check for legacy derives
for i in 0..attrs.len() {
let name = attrs[i].name();
fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
-> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
- let (path, kind, derives_in_scope, together_with) = match invoc.kind {
+ let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
InvocationKind::Attr { attr: None, .. } =>
return Ok(None),
- InvocationKind::Attr { attr: Some(ref attr), ref traits, together_with, .. } =>
- (&attr.path, MacroKind::Attr, traits.clone(), together_with),
+ InvocationKind::Attr { attr: Some(ref attr), ref traits, after_derive, .. } =>
+ (&attr.path, MacroKind::Attr, traits.clone(), after_derive),
InvocationKind::Bang { ref mac, .. } =>
- (&mac.node.path, MacroKind::Bang, Vec::new(), TogetherWith::None),
+ (&mac.node.path, MacroKind::Bang, Vec::new(), false),
InvocationKind::Derive { ref path, .. } =>
- (path, MacroKind::Derive, Vec::new(), TogetherWith::None),
+ (path, MacroKind::Derive, Vec::new(), false),
};
let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
let (def, ext) = self.resolve_macro_to_def(path, kind, &parent_scope, force)?;
if let Def::Macro(def_id, _) = def {
- match together_with {
- TogetherWith::Derive =>
- self.session.span_err(invoc.span(),
- "macro attributes must be placed before `#[derive]`"),
- TogetherWith::TestBench if !self.session.features_untracked().plugin =>
- self.session.span_err(invoc.span(),
- "macro attributes cannot be used together with `#[test]` or `#[bench]`"),
- _ => {}
+ if after_derive {
+ self.session.span_err(invoc.span(),
+ "macro attributes must be placed before `#[derive]`");
}
self.macro_defs.insert(invoc.expansion_data.mark, def_id);
let normal_module_def_id =
Err(Determinacy::Determined)
},
};
+
parent_scope.module.macro_resolutions.borrow_mut()
.push((path.into_boxed_slice(), span));
- return def;
- }
- let result = if let Some(legacy_binding) = self.resolve_legacy_scope(path[0], Some(kind),
- parent_scope, false) {
- Ok(legacy_binding.def())
+ def
} else {
- match self.resolve_lexical_macro_path_segment(path[0], MacroNS, Some(kind),
- parent_scope, false, force, span) {
- Ok((binding, _)) => Ok(binding.def_ignoring_ambiguity()),
+ let binding = self.early_resolve_ident_in_lexical_scope(
+ path[0], MacroNS, Some(kind), parent_scope, false, force, span
+ );
+ match binding {
+ Ok(..) => {}
+ Err(Determinacy::Determined) => self.found_unresolved_macro = true,
Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
- Err(Determinacy::Determined) => {
- self.found_unresolved_macro = true;
- Err(Determinacy::Determined)
- }
}
- };
- parent_scope.module.legacy_macro_resolutions.borrow_mut()
- .push((path[0], kind, parent_scope.clone(), result.ok()));
+ parent_scope.module.legacy_macro_resolutions.borrow_mut()
+ .push((path[0], kind, parent_scope.clone(), binding.ok()));
- result
+ binding.map(|binding| binding.def_ignoring_ambiguity())
+ }
}
- // Resolve the initial segment of a non-global macro path
- // (e.g. `foo` in `foo::bar!(); or `foo!();`).
+ // Resolve an identifier in lexical scope.
// This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
// expansion and import resolution (perhaps they can be merged in the future).
- crate fn resolve_lexical_macro_path_segment(
+ // The function is used for resolving initial segments of macro paths (e.g. `foo` in
+ // `foo::bar!(); or `foo!();`) and can be used for "uniform path" imports in the future.
+ crate fn early_resolve_ident_in_lexical_scope(
&mut self,
mut ident: Ident,
ns: Namespace,
record_used: bool,
force: bool,
path_span: Span,
- ) -> Result<(&'a NameBinding<'a>, FromPrelude), Determinacy> {
+ ) -> Result<&'a NameBinding<'a>, Determinacy> {
// General principles:
// 1. Not controlled (user-defined) names should have higher priority than controlled names
// built into the language or standard library. This way we can add new names into the
// language or standard library without breaking user code.
- // 2. "Closed set" below means new names can appear after the current resolution attempt.
+ // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
// Places to search (in order of decreasing priority):
// (Type NS)
// 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
// 4. Tool modules (closed, controlled right now, but not in the future).
// 5. Standard library prelude (de-facto closed, controlled).
// 6. Language prelude (closed, controlled).
+ // (Value NS)
+ // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
+ // (open set, not controlled).
+ // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
+ // (open, not controlled).
+ // 3. Standard library prelude (de-facto closed, controlled).
// (Macro NS)
- // 0. Derive helpers (open, not controlled). All ambiguities with other names
+ // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
// are currently reported as errors. They should be higher in priority than preludes
// and probably even names in modules according to the "general principles" above. They
// also should be subject to restricted shadowing because are effectively produced by
// derives (you need to resolve the derive first to add helpers into scope), but they
// should be available before the derive is expanded for compatibility.
// It's mess in general, so we are being conservative for now.
- // 1. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
- // (open, not controlled).
- // 2. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
- // 2a. User-defined prelude from macro-use
+ // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
+ // priority than prelude macros, but create ambiguities with macros in modules.
+ // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
+ // (open, not controlled). Have higher priority than prelude macros, but create
+ // ambiguities with `macro_rules`.
+ // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
+ // 4a. User-defined prelude from macro-use
// (open, the open part is from macro expansions, not controlled).
- // 2b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
- // 3. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
- // 4. Language prelude: builtin attributes (closed, controlled).
+ // 4b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
+ // 5. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
+ // 6. Language prelude: builtin attributes (closed, controlled).
+ // 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
+ // but introduced by legacy plugins using `register_attribute`. Priority is somewhere
+ // in prelude, not sure where exactly (creates ambiguities with any other prelude names).
+
+ enum WhereToResolve<'a> {
+ DeriveHelpers,
+ MacroRules(LegacyScope<'a>),
+ Module(Module<'a>),
+ MacroUsePrelude,
+ BuiltinMacros,
+ BuiltinAttrs,
+ LegacyPluginHelpers,
+ ExternPrelude,
+ ToolPrelude,
+ StdLibPrelude,
+ BuiltinTypes,
+ }
+
+ bitflags! {
+ struct Flags: u8 {
+ const DERIVE_HELPERS = 1 << 0;
+ const MACRO_RULES = 1 << 1;
+ const MODULE = 1 << 2;
+ const PRELUDE = 1 << 3;
+ }
+ }
- assert!(ns == TypeNS || ns == MacroNS);
assert!(force || !record_used); // `record_used` implies `force`
ident = ident.modern();
// }
// So we have to save the innermost solution and continue searching in outer scopes
// to detect potential ambiguities.
- let mut innermost_result: Option<(&NameBinding, FromPrelude)> = None;
-
- enum WhereToResolve<'a> {
- Module(Module<'a>),
- MacroUsePrelude,
- BuiltinMacros,
- BuiltinAttrs,
- DeriveHelpers,
- ExternPrelude,
- ToolPrelude,
- StdLibPrelude,
- BuiltinTypes,
- }
+ let mut innermost_result: Option<(&NameBinding, Flags, /* conflicts with */ Flags)> = None;
// Go through all the scopes and try to resolve the name.
let mut where_to_resolve = WhereToResolve::DeriveHelpers;
let mut use_prelude = !parent_scope.module.no_implicit_prelude;
loop {
let result = match where_to_resolve {
+ WhereToResolve::DeriveHelpers => {
+ let mut result = Err(Determinacy::Determined);
+ for derive in &parent_scope.derives {
+ let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
+ if let Ok((_, ext)) = self.resolve_macro_to_def(derive, MacroKind::Derive,
+ &parent_scope, force) {
+ if let SyntaxExtension::ProcMacroDerive(_, helper_attrs, _) = &*ext {
+ if helper_attrs.contains(&ident.name) {
+ let binding =
+ (Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
+ ty::Visibility::Public, derive.span, Mark::root())
+ .to_name_binding(self.arenas);
+ result = Ok((binding, Flags::DERIVE_HELPERS, Flags::all()));
+ break;
+ }
+ }
+ }
+ }
+ result
+ }
+ WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
+ LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
+ Ok((legacy_binding.binding, Flags::MACRO_RULES, Flags::empty())),
+ _ => Err(Determinacy::Determined),
+ }
WhereToResolve::Module(module) => {
let orig_current_module = mem::replace(&mut self.current_module, module);
let binding = self.resolve_ident_in_module_unadjusted(
path_span,
);
self.current_module = orig_current_module;
- binding.map(|binding| (binding, FromPrelude(false)))
+ binding.map(|binding| (binding, Flags::MODULE, Flags::empty()))
}
WhereToResolve::MacroUsePrelude => {
match self.macro_use_prelude.get(&ident.name).cloned() {
- Some(binding) => Ok((binding, FromPrelude(true))),
+ Some(binding) => Ok((binding, Flags::PRELUDE, Flags::empty())),
None => Err(Determinacy::Determined),
}
}
WhereToResolve::BuiltinMacros => {
match self.builtin_macros.get(&ident.name).cloned() {
- Some(binding) => Ok((binding, FromPrelude(true))),
+ Some(binding) => Ok((binding, Flags::PRELUDE, Flags::empty())),
None => Err(Determinacy::Determined),
}
}
let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
ty::Visibility::Public, ident.span, Mark::root())
.to_name_binding(self.arenas);
- Ok((binding, FromPrelude(true)))
+ Ok((binding, Flags::PRELUDE, Flags::empty()))
} else {
Err(Determinacy::Determined)
}
}
- WhereToResolve::DeriveHelpers => {
- let mut result = Err(Determinacy::Determined);
- for derive in &parent_scope.derives {
- let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
- if let Ok((_, ext)) = self.resolve_macro_to_def(derive, MacroKind::Derive,
- &parent_scope, force) {
- if let SyntaxExtension::ProcMacroDerive(_, helper_attrs, _) = &*ext {
- if helper_attrs.contains(&ident.name) {
- let binding =
- (Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
- ty::Visibility::Public, derive.span, Mark::root())
- .to_name_binding(self.arenas);
- result = Ok((binding, FromPrelude(false)));
- break;
- }
- }
- }
+ WhereToResolve::LegacyPluginHelpers => {
+ if self.session.plugin_attributes.borrow().iter()
+ .any(|(name, _)| ident.name == &**name) {
+ let binding = (Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper),
+ ty::Visibility::Public, ident.span, Mark::root())
+ .to_name_binding(self.arenas);
+ Ok((binding, Flags::PRELUDE, Flags::PRELUDE))
+ } else {
+ Err(Determinacy::Determined)
}
- result
}
WhereToResolve::ExternPrelude => {
if use_prelude && self.session.extern_prelude.contains(&ident.name) {
let binding = (crate_root, ty::Visibility::Public,
ident.span, Mark::root()).to_name_binding(self.arenas);
- Ok((binding, FromPrelude(true)))
+ Ok((binding, Flags::PRELUDE, Flags::empty()))
} else {
Err(Determinacy::Determined)
}
if use_prelude && is_known_tool(ident.name) {
let binding = (Def::ToolMod, ty::Visibility::Public,
ident.span, Mark::root()).to_name_binding(self.arenas);
- Ok((binding, FromPrelude(true)))
+ Ok((binding, Flags::PRELUDE, Flags::empty()))
} else {
Err(Determinacy::Determined)
}
false,
path_span,
) {
- result = Ok((binding, FromPrelude(true)));
+ result = Ok((binding, Flags::PRELUDE, Flags::empty()));
}
}
}
result
}
WhereToResolve::BuiltinTypes => {
- if let Some(prim_ty) =
- self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
- let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
- ident.span, Mark::root()).to_name_binding(self.arenas);
- Ok((binding, FromPrelude(true)))
- } else {
- Err(Determinacy::Determined)
+ match self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
+ Some(prim_ty) => {
+ let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
+ ident.span, Mark::root()).to_name_binding(self.arenas);
+ Ok((binding, Flags::PRELUDE, Flags::empty()))
+ }
+ None => Err(Determinacy::Determined)
}
}
};
macro_rules! continue_search { () => {
where_to_resolve = match where_to_resolve {
+ WhereToResolve::DeriveHelpers =>
+ WhereToResolve::MacroRules(parent_scope.legacy),
+ WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
+ LegacyScope::Binding(binding) =>
+ WhereToResolve::MacroRules(binding.parent_legacy_scope),
+ LegacyScope::Invocation(invocation) =>
+ WhereToResolve::MacroRules(invocation.output_legacy_scope.get()),
+ LegacyScope::Empty => WhereToResolve::Module(parent_scope.module),
+ LegacyScope::Uninitialized => unreachable!(),
+ }
WhereToResolve::Module(module) => {
match self.hygienic_lexical_parent(module, &mut ident.span) {
Some(parent_module) => WhereToResolve::Module(parent_module),
None => {
use_prelude = !module.no_implicit_prelude;
- if ns == MacroNS {
- WhereToResolve::MacroUsePrelude
- } else {
- WhereToResolve::ExternPrelude
+ match ns {
+ TypeNS => WhereToResolve::ExternPrelude,
+ ValueNS => WhereToResolve::StdLibPrelude,
+ MacroNS => WhereToResolve::MacroUsePrelude,
}
}
}
}
WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
- WhereToResolve::BuiltinAttrs => break, // nowhere else to search
- WhereToResolve::DeriveHelpers => WhereToResolve::Module(parent_scope.module),
+ WhereToResolve::BuiltinAttrs => WhereToResolve::LegacyPluginHelpers,
+ WhereToResolve::LegacyPluginHelpers => break, // nowhere else to search
WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
- WhereToResolve::StdLibPrelude => WhereToResolve::BuiltinTypes,
+ WhereToResolve::StdLibPrelude => match ns {
+ TypeNS => WhereToResolve::BuiltinTypes,
+ ValueNS => break, // nowhere else to search
+ MacroNS => unreachable!(),
+ }
WhereToResolve::BuiltinTypes => break, // nowhere else to search
};
}}
match result {
- Ok(result) => {
- if sub_namespace_mismatch(kind, result.0.macro_kind()) {
+ Ok((binding, flags, ambig_flags)) => {
+ if sub_namespace_mismatch(kind, binding.macro_kind()) {
continue_search!();
}
if !record_used {
- return Ok(result);
+ return Ok(binding);
}
- if let Some(innermost_result) = innermost_result {
+ if let Some((innermost_binding, innermost_flags, innermost_ambig_flags))
+ = innermost_result {
// Found another solution, if the first one was "weak", report an error.
- let (def, innermost_def) = (result.0.def(), innermost_result.0.def());
- if def != innermost_def &&
- (innermost_result.0.is_glob_import() ||
- innermost_result.0.may_appear_after(parent_scope.expansion, result.0) ||
- innermost_def == Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper) ||
- def == Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper)) {
+ if binding.def() != innermost_binding.def() &&
+ (innermost_binding.is_glob_import() ||
+ innermost_binding.may_appear_after(parent_scope.expansion, binding) ||
+ innermost_flags.intersects(ambig_flags) ||
+ flags.intersects(innermost_ambig_flags) ||
+ (innermost_flags.contains(Flags::MACRO_RULES) &&
+ flags.contains(Flags::MODULE) &&
+ !self.disambiguate_legacy_vs_modern(innermost_binding, binding))) {
self.ambiguity_errors.push(AmbiguityError {
ident,
- b1: innermost_result.0,
- b2: result.0,
+ b1: innermost_binding,
+ b2: binding,
});
- return Ok(innermost_result);
+ return Ok(innermost_binding);
}
} else {
// Found the first solution.
- innermost_result = Some(result);
+ innermost_result = Some((binding, flags, ambig_flags));
}
continue_search!();
}
// The first found solution was the only one, return it.
- if let Some(innermost_result) = innermost_result {
- return Ok(innermost_result);
+ if let Some((binding, ..)) = innermost_result {
+ return Ok(binding);
}
let determinacy = Determinacy::determined(force);
let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
ty::Visibility::Public, ident.span, Mark::root())
.to_name_binding(self.arenas);
- Ok((binding, FromPrelude(true)))
+ Ok(binding)
} else {
Err(determinacy)
}
}
- fn resolve_legacy_scope(
- &mut self,
- ident: Ident,
- kind: Option<MacroKind>,
- parent_scope: &ParentScope<'a>,
- record_used: bool,
- ) -> Option<&'a NameBinding<'a>> {
- if sub_namespace_mismatch(kind, Some(MacroKind::Bang)) {
- return None;
- }
-
- let ident = ident.modern();
-
- // This is *the* result, resolution from the scope closest to the resolved identifier.
- // However, sometimes this result is "weak" because it comes from a macro expansion,
- // and in this case it cannot shadow names from outer scopes, e.g.
- // macro_rules! m { ... } // solution in outer scope
- // {
- // define_m!(); // generates another `macro_rules! m` - innermost solution
- // // weak, cannot shadow the outer `m`, need to report ambiguity error
- // m!();
- // }
- // So we have to save the innermost solution and continue searching in outer scopes
- // to detect potential ambiguities.
- let mut innermost_result: Option<&NameBinding> = None;
-
- // Go through all the scopes and try to resolve the name.
- let mut where_to_resolve = parent_scope.legacy;
- loop {
- let result = match where_to_resolve {
- LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
- Some(legacy_binding.binding),
- _ => None,
- };
-
- macro_rules! continue_search { () => {
- where_to_resolve = match where_to_resolve {
- LegacyScope::Empty => break, // nowhere else to search
- LegacyScope::Binding(binding) => binding.parent_legacy_scope,
- LegacyScope::Invocation(invocation) => invocation.output_legacy_scope.get(),
- LegacyScope::Uninitialized => unreachable!(),
- };
-
- continue;
- }}
-
- match result {
- Some(result) => {
- if !record_used {
- return Some(result);
- }
-
- if let Some(innermost_result) = innermost_result {
- // Found another solution, if the first one was "weak", report an error.
- if result.def() != innermost_result.def() &&
- innermost_result.may_appear_after(parent_scope.expansion, result) {
- self.ambiguity_errors.push(AmbiguityError {
- ident,
- b1: innermost_result,
- b2: result,
- });
- return Some(innermost_result);
- }
- } else {
- // Found the first solution.
- innermost_result = Some(result);
- }
-
- continue_search!();
- }
- None => {
- continue_search!();
- }
- }
- }
-
- // The first found solution was the only one (or there was no solution at all), return it.
- innermost_result
- }
-
pub fn finalize_current_module_macro_resolutions(&mut self) {
let module = self.current_module;
for &(ref path, span) in module.macro_resolutions.borrow().iter() {
let legacy_macro_resolutions =
mem::replace(&mut *module.legacy_macro_resolutions.borrow_mut(), Vec::new());
- for (ident, kind, parent_scope, def) in legacy_macro_resolutions {
- let span = ident.span;
- let legacy_resolution = self.resolve_legacy_scope(
- ident, Some(kind), &parent_scope, true
+ for (ident, kind, parent_scope, initial_binding) in legacy_macro_resolutions {
+ let binding = self.early_resolve_ident_in_lexical_scope(
+ ident, MacroNS, Some(kind), &parent_scope, true, true, ident.span
);
- let resolution = self.resolve_lexical_macro_path_segment(
- ident, MacroNS, Some(kind), &parent_scope, true, true, span
- );
-
- let check_consistency = |this: &Self, new_def: Def| {
- if let Some(def) = def {
- if this.ambiguity_errors.is_empty() && new_def != def && new_def != Def::Err {
- // Make sure compilation does not succeed if preferred macro resolution
- // has changed after the macro had been expanded. In theory all such
- // situations should be reported as ambiguity errors, so this is span-bug.
- span_bug!(span, "inconsistent resolution for a macro");
+ match binding {
+ Ok(binding) => {
+ let def = binding.def_ignoring_ambiguity();
+ if let Some(initial_binding) = initial_binding {
+ self.record_use(ident, MacroNS, initial_binding);
+ let initial_def = initial_binding.def_ignoring_ambiguity();
+ if self.ambiguity_errors.is_empty() &&
+ def != initial_def && def != Def::Err {
+ // Make sure compilation does not succeed if preferred macro resolution
+ // has changed after the macro had been expanded. In theory all such
+ // situations should be reported as ambiguity errors, so this is a bug.
+ span_bug!(ident.span, "inconsistent resolution for a macro");
+ }
+ } else {
+ // It's possible that the macro was unresolved (indeterminate) and silently
+ // expanded into a dummy fragment for recovery during expansion.
+ // Now, post-expansion, the resolution may succeed, but we can't change the
+ // past and need to report an error.
+ let msg = format!("cannot determine resolution for the {} `{}`",
+ kind.descr(), ident);
+ let msg_note = "import resolution is stuck, try simplifying macro imports";
+ self.session.struct_span_err(ident.span, &msg).note(msg_note).emit();
}
- } else {
- // It's possible that the macro was unresolved (indeterminate) and silently
- // expanded into a dummy fragment for recovery during expansion.
- // Now, post-expansion, the resolution may succeed, but we can't change the
- // past and need to report an error.
- let msg =
- format!("cannot determine resolution for the {} `{}`", kind.descr(), ident);
- let msg_note = "import resolution is stuck, try simplifying macro imports";
- this.session.struct_span_err(span, &msg).note(msg_note).emit();
}
- };
-
- match (legacy_resolution, resolution) {
- (None, Err(_)) => {
- assert!(def.is_none());
+ Err(..) => {
+ assert!(initial_binding.is_none());
let bang = if kind == MacroKind::Bang { "!" } else { "" };
let msg =
format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
- let mut err = self.session.struct_span_err(span, &msg);
- self.suggest_macro_name(&ident.as_str(), kind, &mut err, span);
+ let mut err = self.session.struct_span_err(ident.span, &msg);
+ self.suggest_macro_name(&ident.as_str(), kind, &mut err, ident.span);
err.emit();
- },
- (Some(legacy_binding), Ok((binding, FromPrelude(from_prelude))))
- if legacy_binding.def() != binding.def_ignoring_ambiguity() &&
- (!from_prelude &&
- !self.disambiguate_legacy_vs_modern(legacy_binding, binding) ||
- legacy_binding.may_appear_after(parent_scope.expansion, binding)) => {
- self.report_ambiguity_error(ident, legacy_binding, binding);
- },
- // OK, non-macro-expanded legacy wins over prelude even if defs are different
- // Also, non-macro-expanded legacy wins over modern from the same module
- // Also, legacy and modern can co-exist if their defs are same
- (Some(legacy_binding), Ok(_)) |
- // OK, unambiguous resolution
- (Some(legacy_binding), Err(_)) => {
- check_consistency(self, legacy_binding.def());
- }
- // OK, unambiguous resolution
- (None, Ok((binding, FromPrelude(from_prelude)))) => {
- check_consistency(self, binding.def_ignoring_ambiguity());
- if from_prelude {
- self.record_use(ident, MacroNS, binding);
- }
}
- };
+ }
}
let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
for (ident, parent_scope) in builtin_attrs {
- let resolve_legacy = |this: &mut Self| this.resolve_legacy_scope(
- ident, Some(MacroKind::Attr), &parent_scope, true
- );
- let resolve_modern = |this: &mut Self| this.resolve_lexical_macro_path_segment(
+ let binding = self.early_resolve_ident_in_lexical_scope(
ident, MacroNS, Some(MacroKind::Attr), &parent_scope, true, true, ident.span
- ).map(|(binding, _)| binding).ok();
-
- if let Some(binding) = resolve_legacy(self).or_else(|| resolve_modern(self)) {
+ );
+ if let Ok(binding) = binding {
if binding.def_ignoring_ambiguity() !=
Def::NonMacroAttr(NonMacroAttrKind::Builtin) {
let builtin_binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
// expansion. With restricted shadowing names from globs and macro expansions cannot
// shadow names from outer scopes, so we can freely fallback from module search to search
// in outer scopes. To continue search in outer scopes we have to lie a bit and return
- // `Determined` to `resolve_lexical_macro_path_segment` even if the correct answer
+ // `Determined` to `early_resolve_ident_in_lexical_scope` even if the correct answer
// for in-module resolution could be `Undetermined`.
if restricted_shadowing {
return Err(Determined);
overflows: vec![],
}),
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
+
ty::Infer(..) | ty::Error => {
// By the time this code runs, all type variables ought to
// be fully resolved.
match path.def {
Def::Existential(did) => {
// check for desugared impl trait
- if ty::is_impl_trait_defn(tcx, did).is_some() {
- let lifetimes = &path.segments[0].args.as_ref().unwrap().args;
- return self.impl_trait_ty_to_ty(did, lifetimes);
- }
+ assert!(ty::is_impl_trait_defn(tcx, did).is_none());
let item_segment = path.segments.split_last().unwrap();
self.prohibit_generics(item_segment.1);
let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
});
self.def_to_ty(opt_self_ty, path, false)
}
+ hir::TyKind::Def(item_id, ref lifetimes) => {
+ let did = tcx.hir.local_def_id(item_id.id);
+ self.impl_trait_ty_to_ty(did, lifetimes)
+ },
hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
let ty = self.ast_ty_to_ty(qself);
ty::Foreign(..) => Some(PointerKind::Thin),
// We should really try to normalize here.
ty::Projection(ref pi) => Some(PointerKind::OfProjection(pi)),
+ ty::UnnormalizedProjection(..) => bug!("only used with chalk-engine"),
ty::Opaque(def_id, substs) => Some(PointerKind::OfOpaque(def_id, substs)),
ty::Param(ref p) => Some(PointerKind::OfParam(p)),
// Insufficient type information.
// We create a mapping `dummy_substs` that maps from the impl type
// parameters to fresh types and regions. For type parameters,
// this is the identity transform, but we could as well use any
- // skolemized types. For regions, we convert from bound to free
+ // placeholder types. For regions, we convert from bound to free
// regions (Note: but only early-bound regions, i.e., those
// declared on the impl or used in type parameter bounds).
//
// impl_to_skol_substs = {'i => 'i0, U => U0, N => N0 }
//
// Now we can apply skol_substs to the type of the impl method
- // to yield a new function type in terms of our fresh, skolemized
+ // to yield a new function type in terms of our fresh, placeholder
// types:
//
// <'b> fn(t: &'i0 U0, m: &'b) -> Foo
// We do this by creating a parameter environment which contains a
// substitution corresponding to impl_to_skol_substs. We then build
// trait_to_skol_substs and use it to convert the predicates contained
- // in the trait_m.generics to the skolemized form.
+ // in the trait_m.generics to the placeholder form.
//
// Finally we register each of these predicates as an obligation in
// a fresh FulfillmentCtxt, and invoke select_all_or_error.
- // Create mapping from impl to skolemized.
+ // Create mapping from impl to placeholder.
let impl_to_skol_substs = Substs::identity_for_item(tcx, impl_m.def_id);
- // Create mapping from trait to skolemized.
+ // Create mapping from trait to placeholder.
let trait_to_skol_substs = impl_to_skol_substs.rebase_onto(tcx,
impl_m.container.id(),
trait_to_impl_substs);
hybrid_preds.predicates.extend(
trait_m_predicates.instantiate_own(tcx, trait_to_skol_substs).predicates);
- // Construct trait parameter environment and then shift it into the skolemized viewpoint.
+ // Construct trait parameter environment and then shift it into the placeholder viewpoint.
// The key step here is to update the caller_bounds's predicates to be
// the new hybrid bounds we computed.
let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_node_id);
// any associated types appearing in the fn arguments or return
// type.
- // Compute skolemized form of impl and trait method tys.
+ // Compute placeholder form of impl and trait method tys.
let tcx = infcx.tcx;
let (impl_sig, _) =
// method.
let impl_c_node_id = tcx.hir.as_local_node_id(impl_c.def_id).unwrap();
- // Compute skolemized form of impl and trait const tys.
+ // Compute placeholder form of impl and trait const tys.
let impl_ty = tcx.type_of(impl_c.def_id);
let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
let mut cause = ObligationCause::misc(impl_c_span, impl_c_node_id);
def_id: DefId,
) -> ty::GenericPredicates<'tcx> {
use rustc::hir::*;
+ use rustc_data_structures::fx::FxHashSet;
debug!("explicit_predicates_of(def_id={:?})", def_id);
+ /// A data structure with unique elements, which preserves order of insertion.
+ /// Preserving the order of insertion is important here so as not to break
+ /// compile-fail UI tests.
+ struct UniquePredicates<'tcx> {
+ predicates: Vec<(ty::Predicate<'tcx>, Span)>,
+ uniques: FxHashSet<(ty::Predicate<'tcx>, Span)>,
+ }
+
+ impl<'tcx> UniquePredicates<'tcx> {
+ fn new() -> Self {
+ UniquePredicates {
+ predicates: vec![],
+ uniques: FxHashSet::default(),
+ }
+ }
+
+ fn push(&mut self, value: (ty::Predicate<'tcx>, Span)) {
+ if self.uniques.insert(value) {
+ self.predicates.push(value);
+ }
+ }
+
+ fn extend<I: IntoIterator<Item = (ty::Predicate<'tcx>, Span)>>(&mut self, iter: I) {
+ for value in iter {
+ self.push(value);
+ }
+ }
+ }
+
let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
let node = tcx.hir.get(node_id);
let icx = ItemCtxt::new(tcx, def_id);
let no_generics = hir::Generics::empty();
- let mut predicates = vec![];
+ let mut predicates = UniquePredicates::new();
let ast_generics = match node {
Node::TraitItem(item) => &item.generics,
// on a trait we need to add in the supertrait bounds and bounds found on
// associated types.
if let Some((_trait_ref, _)) = is_trait {
- predicates = tcx.super_predicates_of(def_id).predicates;
+ predicates.extend(tcx.super_predicates_of(def_id).predicates);
}
// In default impls, we can assume that the self type implements
}))
}
+ let mut predicates = predicates.predicates;
+
// Subtle: before we store the predicates into the tcx, we
// sort them so that predicates like `T: Foo<Item=U>` come
// before uses of `U`. This avoids false ambiguity errors
| RegionKind::ReCanonical(..)
| RegionKind::ReScope(..)
| RegionKind::ReVar(..)
- | RegionKind::ReSkolemized(..)
+ | RegionKind::RePlaceholder(..)
| RegionKind::ReFree(..) => {
bug!("unexpected region in outlives inference: {:?}", region);
}
// types, where we use Error as the Self type
}
+ ty::UnnormalizedProjection(..) |
ty::GeneratorWitness(..) |
ty::Infer(..) => {
bug!("unexpected type encountered in \
ty::ReClosureBound(..) |
ty::ReScope(..) |
ty::ReVar(..) |
- ty::ReSkolemized(..) |
+ ty::RePlaceholder(..) |
ty::ReEmpty |
ty::ReErased => {
// We don't expect to see anything but 'static or bound
ty::ReFree(..) |
ty::ReScope(..) |
ty::ReVar(..) |
- ty::ReSkolemized(..) |
+ ty::RePlaceholder(..) |
ty::ReEmpty |
ty::ReClosureBound(_) |
ty::ReCanonical(_) |
Array(box ty.clean(cx), length)
},
TyKind::Tup(ref tys) => Tuple(tys.clean(cx)),
+ TyKind::Def(item_id, _) => {
+ let item = cx.tcx.hir.expect_item(item_id.id);
+ if let hir::ItemKind::Existential(ref ty) = item.node {
+ ImplTrait(ty.bounds.clean(cx))
+ } else {
+ unreachable!()
+ }
+ }
TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
if let Some(new_ty) = cx.ty_substs.borrow().get(&path.def).cloned() {
return new_ty;
if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did) {
return ImplTrait(bounds);
}
- } else if let Def::Existential(did) = path.def {
- // This block is for returned impl trait only.
- if let Some(node_id) = cx.tcx.hir.as_local_node_id(did) {
- let item = cx.tcx.hir.expect_item(node_id);
- if let hir::ItemKind::Existential(ref ty) = item.node {
- return ImplTrait(ty.bounds.clean(cx));
- }
- }
}
let mut alias = None;
ty::Closure(..) | ty::Generator(..) => Tuple(vec![]), // FIXME(pcwalton)
+ ty::UnnormalizedProjection(..) => panic!("UnnormalizedProjection"),
ty::GeneratorWitness(..) => panic!("GeneratorWitness"),
ty::Infer(..) => panic!("Infer"),
ty::Error => panic!("Error"),
h1.fqn {
border-bottom: 1px dashed;
margin-top: 0;
- overflow: auto;
}
h2, h3:not(.impl):not(.method):not(.type):not(.tymethod), h4:not(.method):not(.type):not(.tymethod):not(.associatedconstant) {
border-bottom: 1px solid;
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
+ /// Converts a type of [`Error`] into a box of dyn [`Error`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::error::Error;
+ /// use std::fmt;
+ /// use std::mem;
+ ///
+ /// #[derive(Debug)]
+ /// struct AnError;
+ ///
+ /// impl fmt::Display for AnError {
+ /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ /// write!(f , "An error")
+ /// }
+ /// }
+ ///
+ /// impl Error for AnError {
+ /// fn description(&self) -> &str {
+ /// "Description of an error"
+ /// }
+ /// }
+ ///
+ /// let an_error = AnError;
+ /// assert!(0 == mem::size_of_val(&an_error));
+ /// let a_boxed_error = Box::<Error>::from(an_error);
+ /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
+ /// ```
fn from(err: E) -> Box<dyn Error + 'a> {
Box::new(err)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
+ /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
+ /// [`Send`] + [`Sync`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::error::Error;
+ /// use std::fmt;
+ /// use std::mem;
+ ///
+ /// #[derive(Debug)]
+ /// struct AnError;
+ ///
+ /// impl fmt::Display for AnError {
+ /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ /// write!(f , "An error")
+ /// }
+ /// }
+ ///
+ /// impl Error for AnError {
+ /// fn description(&self) -> &str {
+ /// "Description of an error"
+ /// }
+ /// }
+ ///
+ /// unsafe impl Send for AnError {}
+ ///
+ /// unsafe impl Sync for AnError {}
+ ///
+ /// let an_error = AnError;
+ /// assert!(0 == mem::size_of_val(&an_error));
+ /// let a_boxed_error = Box::<Error + Send + Sync>::from(an_error);
+ /// assert!(
+ /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
+ /// ```
fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
Box::new(err)
}
#[stable(feature = "rust1", since = "1.0.0")]
impl From<String> for Box<dyn Error + Send + Sync> {
+ /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::error::Error;
+ /// use std::mem;
+ ///
+ /// let a_string_error = "a string error".to_string();
+ /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error);
+ /// assert!(
+ /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
+ /// ```
fn from(err: String) -> Box<dyn Error + Send + Sync> {
#[derive(Debug)]
struct StringError(String);
#[stable(feature = "string_box_error", since = "1.6.0")]
impl From<String> for Box<dyn Error> {
+ /// Converts a [`String`] into a box of dyn [`Error`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::error::Error;
+ /// use std::mem;
+ ///
+ /// let a_string_error = "a string error".to_string();
+ /// let a_boxed_error = Box::<Error>::from(a_string_error);
+ /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
+ /// ```
fn from(str_err: String) -> Box<dyn Error> {
let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
let err2: Box<dyn Error> = err1;
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, 'b> From<&'b str> for Box<dyn Error + Send + Sync + 'a> {
+ /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::error::Error;
+ /// use std::mem;
+ ///
+ /// let a_str_error = "a str error";
+ /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
+ /// assert!(
+ /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
+ /// ```
fn from(err: &'b str) -> Box<dyn Error + Send + Sync + 'a> {
From::from(String::from(err))
}
#[stable(feature = "string_box_error", since = "1.6.0")]
impl<'a> From<&'a str> for Box<dyn Error> {
+ /// Converts a [`str`] into a box of dyn [`Error`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::error::Error;
+ /// use std::mem;
+ ///
+ /// let a_str_error = "a str error";
+ /// let a_boxed_error = Box::<Error>::from(a_str_error);
+ /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
+ /// ```
fn from(err: &'a str) -> Box<dyn Error> {
From::from(String::from(err))
}
#[stable(feature = "cow_box_error", since = "1.22.0")]
impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
+ /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::error::Error;
+ /// use std::mem;
+ /// use std::borrow::Cow;
+ ///
+ /// let a_cow_str_error = Cow::from("a str error");
+ /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
+ /// assert!(
+ /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
+ /// ```
fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
From::from(String::from(err))
}
#[stable(feature = "cow_box_error", since = "1.22.0")]
impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
+ /// Converts a [`Cow`] into a box of dyn [`Error`].
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use std::error::Error;
+ /// use std::mem;
+ /// use std::borrow::Cow;
+ ///
+ /// let a_cow_str_error = Cow::from("a str error");
+ /// let a_boxed_error = Box::<Error>::from(a_cow_str_error);
+ /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
+ /// ```
fn from(err: Cow<'a, str>) -> Box<dyn Error> {
From::from(String::from(err))
}
#![feature(const_cstr_unchecked)]
#![feature(core_intrinsics)]
#![feature(dropck_eyepatch)]
+#![feature(duration_as_u128)]
#![feature(exact_size_is_empty)]
#![feature(external_doc)]
#![feature(fixed_size_array)]
rust_panic(&mut RewrapBox(msg))
}
-/// A private no-mangle function on which to slap yer breakpoints.
+/// An unmangled function (through `rustc_std_internal_symbol`) on which to slap
+/// yer breakpoints.
#[inline(never)]
-#[no_mangle]
-#[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints
-pub fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
+#[cfg_attr(not(test), rustc_std_internal_symbol)]
+fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! {
let code = unsafe {
let obj = &mut msg as *mut &mut dyn BoxMeUp;
__rust_start_panic(obj as usize)
//! Useful synchronization primitives.
//!
-//! This module contains useful safe and unsafe synchronization primitives.
-//! Most of the primitives in this module do not provide any sort of locking
-//! and/or blocking at all, but rather provide the necessary tools to build
-//! other types of concurrent primitives.
+//! ## The need for synchronization
+//!
+//! Conceptually, a Rust program is a series of operations which will
+//! be executed on a computer. The timeline of events happening in the
+//! program is consistent with the order of the operations in the code.
+//!
+//! Consider the following code, operating on some global static variables:
+//!
+//! ```rust
+//! static mut A: u32 = 0;
+//! static mut B: u32 = 0;
+//! static mut C: u32 = 0;
+//!
+//! fn main() {
+//! unsafe {
+//! A = 3;
+//! B = 4;
+//! A = A + B;
+//! C = B;
+//! println!("{} {} {}", A, B, C);
+//! C = A;
+//! }
+//! }
+//! ```
+//!
+//! It appears as if some variables stored in memory are changed, an addition
+//! is performed, result is stored in `A` and the variable `C` is
+//! modified twice.
+//!
+//! When only a single thread is involved, the results are as expected:
+//! the line `7 4 4` gets printed.
+//!
+//! As for what happens behind the scenes, when optimizations are enabled the
+//! final generated machine code might look very different from the code:
+//!
+//! - The first store to `C` might be moved before the store to `A` or `B`,
+//! _as if_ we had written `C = 4; A = 3; B = 4`.
+//!
+//! - Assignment of `A + B` to `A` might be removed, since the sum can be stored
+//! in a temporary location until it gets printed, with the global variable
+//! never getting updated.
+//!
+//! - The final result could be determined just by looking at the code
+//! at compile time, so [constant folding] might turn the whole
+//! block into a simple `println!("7 4 4")`.
+//!
+//! The compiler is allowed to perform any combination of these
+//! optimizations, as long as the final optimized code, when executed,
+//! produces the same results as the one without optimizations.
+//!
+//! Due to the [concurrency] involved in modern computers, assumptions
+//! about the program's execution order are often wrong. Access to
+//! global variables can lead to nondeterministic results, **even if**
+//! compiler optimizations are disabled, and it is **still possible**
+//! to introduce synchronization bugs.
+//!
+//! Note that thanks to Rust's safety guarantees, accessing global (static)
+//! variables requires `unsafe` code, assuming we don't use any of the
+//! synchronization primitives in this module.
+//!
+//! [constant folding]: https://en.wikipedia.org/wiki/Constant_folding
+//! [concurrency]: https://en.wikipedia.org/wiki/Concurrency_(computer_science)
+//!
+//! ## Out-of-order execution
+//!
+//! Instructions can execute in a different order from the one we define, due to
+//! various reasons:
+//!
+//! - The **compiler** reordering instructions: If the compiler can issue an
+//! instruction at an earlier point, it will try to do so. For example, it
+//! might hoist memory loads at the top of a code block, so that the CPU can
+//! start [prefetching] the values from memory.
+//!
+//! In single-threaded scenarios, this can cause issues when writing
+//! signal handlers or certain kinds of low-level code.
+//! Use [compiler fences] to prevent this reordering.
+//!
+//! - A **single processor** executing instructions [out-of-order]:
+//! Modern CPUs are capable of [superscalar] execution,
+//! i.e. multiple instructions might be executing at the same time,
+//! even though the machine code describes a sequential process.
+//!
+//! This kind of reordering is handled transparently by the CPU.
+//!
+//! - A **multiprocessor** system executing multiple hardware threads
+//! at the same time: In multi-threaded scenarios, you can use two
+//! kinds of primitives to deal with synchronization:
+//! - [memory fences] to ensure memory accesses are made visibile to
+//! other CPUs in the right order.
+//! - [atomic operations] to ensure simultaneous access to the same
+//! memory location doesn't lead to undefined behavior.
+//!
+//! [prefetching]: https://en.wikipedia.org/wiki/Cache_prefetching
+//! [compiler fences]: crate::sync::atomic::compiler_fence
+//! [out-of-order]: https://en.wikipedia.org/wiki/Out-of-order_execution
+//! [superscalar]: https://en.wikipedia.org/wiki/Superscalar_processor
+//! [memory fences]: crate::sync::atomic::fence
+//! [atomic operations]: crate::sync::atomic
+//!
+//! ## Higher-level synchronization objects
+//!
+//! Most of the low-level synchronization primitives are quite error-prone and
+//! inconvenient to use, which is why the standard library also exposes some
+//! higher-level synchronization objects.
+//!
+//! These abstractions can be built out of lower-level primitives.
+//! For efficiency, the sync objects in the standard library are usually
+//! implemented with help from the operating system's kernel, which is
+//! able to reschedule the threads while they are blocked on acquiring
+//! a lock.
+//!
+//! The following is an overview of the available synchronization
+//! objects:
+//!
+//! - [`Arc`]: Atomically Reference-Counted pointer, which can be used
+//! in multithreaded environments to prolong the lifetime of some
+//! data until all the threads have finished using it.
+//!
+//! - [`Barrier`]: Ensures multiple threads will wait for each other
+//! to reach a point in the program, before continuing execution all
+//! together.
+//!
+//! - [`Condvar`]: Condition Variable, providing the ability to block
+//! a thread while waiting for an event to occur.
+//!
+//! - [`mpsc`]: Multi-producer, single-consumer queues, used for
+//! message-based communication. Can provide a lightweight
+//! inter-thread synchronisation mechanism, at the cost of some
+//! extra memory.
+//!
+//! - [`Mutex`]: Mutual Exclusion mechanism, which ensures that at
+//! most one thread at a time is able to access some data.
+//!
+//! - [`Once`]: Used for thread-safe, one-time initialization of a
+//! global variable.
+//!
+//! - [`RwLock`]: Provides a mutual exclusion mechanism which allows
+//! multiple readers at the same time, while allowing only one
+//! writer at a time. In some cases, this can be more efficient than
+//! a mutex.
+//!
+//! [`Arc`]: crate::sync::Arc
+//! [`Barrier`]: crate::sync::Barrier
+//! [`Condvar`]: crate::sync::Condvar
+//! [`mpsc`]: crate::sync::mpsc
+//! [`Mutex`]: crate::sync::Mutex
+//! [`Once`]: crate::sync::Once
+//! [`RwLock`]: crate::sync::RwLock
#![stable(feature = "rust1", since = "1.0.0")]
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use arch::wasm32::atomic;
+use cmp;
+use mem;
+use sync::atomic::{AtomicUsize, Ordering::SeqCst};
+use sys::mutex::Mutex;
+use time::Duration;
+
+pub struct Condvar {
+ cnt: AtomicUsize,
+}
+
+// Condition variables are implemented with a simple counter internally that is
+// likely to cause spurious wakeups. Blocking on a condition variable will first
+// read the value of the internal counter, unlock the given mutex, and then
+// block if and only if the counter's value is still the same. Notifying a
+// condition variable will modify the counter (add one for now) and then wake up
+// a thread waiting on the address of the counter.
+//
+// A thread waiting on the condition variable will as a result avoid going to
+// sleep if it's notified after the lock is unlocked but before it fully goes to
+// sleep. A sleeping thread is guaranteed to be woken up at some point as it can
+// only be woken up with a call to `wake`.
+//
+// Note that it's possible for 2 or more threads to be woken up by a call to
+// `notify_one` with this implementation. That can happen where the modification
+// of `cnt` causes any threads in the middle of `wait` to avoid going to sleep,
+// and the subsequent `wake` may wake up a thread that's actually blocking. We
+// consider this a spurious wakeup, though, which all users of condition
+// variables must already be prepared to handle. As a result, this source of
+// spurious wakeups is currently though to be ok, although it may be problematic
+// later on if it causes too many spurious wakeups.
+
+impl Condvar {
+ pub const fn new() -> Condvar {
+ Condvar { cnt: AtomicUsize::new(0) }
+ }
+
+ #[inline]
+ pub unsafe fn init(&mut self) {
+ // nothing to do
+ }
+
+ pub unsafe fn notify_one(&self) {
+ self.cnt.fetch_add(1, SeqCst);
+ atomic::wake(self.ptr(), 1);
+ }
+
+ #[inline]
+ pub unsafe fn notify_all(&self) {
+ self.cnt.fetch_add(1, SeqCst);
+ atomic::wake(self.ptr(), -1); // -1 == "wake everyone"
+ }
+
+ pub unsafe fn wait(&self, mutex: &Mutex) {
+ // "atomically block and unlock" implemented by loading our current
+ // counter's value, unlocking the mutex, and blocking if the counter
+ // still has the same value.
+ //
+ // Notifications happen by incrementing the counter and then waking a
+ // thread. Incrementing the counter after we unlock the mutex will
+ // prevent us from sleeping and otherwise the call to `wake` will
+ // wake us up once we're asleep.
+ let ticket = self.cnt.load(SeqCst) as i32;
+ mutex.unlock();
+ let val = atomic::wait_i32(self.ptr(), ticket, -1);
+ // 0 == woken, 1 == not equal to `ticket`, 2 == timeout (shouldn't happen)
+ debug_assert!(val == 0 || val == 1);
+ mutex.lock();
+ }
+
+ pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
+ let ticket = self.cnt.load(SeqCst) as i32;
+ mutex.unlock();
+ let nanos = dur.as_nanos();
+ let nanos = cmp::min(i64::max_value() as u128, nanos);
+
+ // If the return value is 2 then a timeout happened, so we return
+ // `false` as we weren't actually notified.
+ let ret = atomic::wait_i32(self.ptr(), ticket, nanos as i64) != 2;
+ mutex.lock();
+ return ret
+ }
+
+ #[inline]
+ pub unsafe fn destroy(&self) {
+ // nothing to do
+ }
+
+ #[inline]
+ fn ptr(&self) -> *mut i32 {
+ assert_eq!(mem::size_of::<usize>(), mem::size_of::<i32>());
+ &self.cnt as *const AtomicUsize as *mut i32
+ }
+}
#[cfg(feature = "backtrace")]
pub mod backtrace;
pub mod cmath;
-pub mod condvar;
pub mod env;
pub mod fs;
pub mod memchr;
-pub mod mutex;
pub mod net;
pub mod os;
pub mod os_str;
pub mod path;
pub mod pipe;
pub mod process;
-pub mod rwlock;
pub mod stack_overflow;
pub mod thread;
-pub mod thread_local;
pub mod time;
pub mod stdio;
+cfg_if! {
+ if #[cfg(target_feature = "atomics")] {
+ #[path = "condvar_atomics.rs"]
+ pub mod condvar;
+ #[path = "mutex_atomics.rs"]
+ pub mod mutex;
+ #[path = "rwlock_atomics.rs"]
+ pub mod rwlock;
+ #[path = "thread_local_atomics.rs"]
+ pub mod thread_local;
+ } else {
+ pub mod condvar;
+ pub mod mutex;
+ pub mod rwlock;
+ pub mod thread_local;
+ }
+}
+
#[cfg(not(test))]
pub fn init() {
}
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use arch::wasm32::atomic;
+use cell::UnsafeCell;
+use mem;
+use sync::atomic::{AtomicUsize, AtomicU64, Ordering::SeqCst};
+
+pub struct Mutex {
+ locked: AtomicUsize,
+}
+
+// Mutexes have a pretty simple implementation where they contain an `i32`
+// internally that is 0 when unlocked and 1 when the mutex is locked.
+// Acquisition has a fast path where it attempts to cmpxchg the 0 to a 1, and
+// if it fails it then waits for a notification. Releasing a lock is then done
+// by swapping in 0 and then notifying any waiters, if present.
+
+impl Mutex {
+ pub const fn new() -> Mutex {
+ Mutex { locked: AtomicUsize::new(0) }
+ }
+
+ #[inline]
+ pub unsafe fn init(&mut self) {
+ // nothing to do
+ }
+
+ pub unsafe fn lock(&self) {
+ while !self.try_lock() {
+ let val = atomic::wait_i32(
+ self.ptr(),
+ 1, // we expect our mutex is locked
+ -1, // wait infinitely
+ );
+ // we should have either woke up (0) or got a not-equal due to a
+ // race (1). We should never time out (2)
+ debug_assert!(val == 0 || val == 1);
+ }
+ }
+
+ pub unsafe fn unlock(&self) {
+ let prev = self.locked.swap(0, SeqCst);
+ debug_assert_eq!(prev, 1);
+ atomic::wake(self.ptr(), 1); // wake up one waiter, if any
+ }
+
+ #[inline]
+ pub unsafe fn try_lock(&self) -> bool {
+ self.locked.compare_exchange(0, 1, SeqCst, SeqCst).is_ok()
+ }
+
+ #[inline]
+ pub unsafe fn destroy(&self) {
+ // nothing to do
+ }
+
+ #[inline]
+ fn ptr(&self) -> *mut i32 {
+ assert_eq!(mem::size_of::<usize>(), mem::size_of::<i32>());
+ &self.locked as *const AtomicUsize as *mut isize as *mut i32
+ }
+}
+
+pub struct ReentrantMutex {
+ owner: AtomicU64,
+ recursions: UnsafeCell<u32>,
+}
+
+unsafe impl Send for ReentrantMutex {}
+unsafe impl Sync for ReentrantMutex {}
+
+// Reentrant mutexes are similarly implemented to mutexs above except that
+// instead of "1" meaning unlocked we use the id of a thread to represent
+// whether it has locked a mutex. That way we have an atomic counter which
+// always holds the id of the thread that currently holds the lock (or 0 if the
+// lock is unlocked).
+//
+// Once a thread acquires a lock recursively, which it detects by looking at
+// the value that's already there, it will update a local `recursions` counter
+// in a nonatomic fashion (as we hold the lock). The lock is then fully
+// released when this recursion counter reaches 0.
+
+impl ReentrantMutex {
+ pub unsafe fn uninitialized() -> ReentrantMutex {
+ ReentrantMutex {
+ owner: AtomicU64::new(0),
+ recursions: UnsafeCell::new(0),
+ }
+ }
+
+ pub unsafe fn init(&mut self) {
+ // nothing to do...
+ }
+
+ pub unsafe fn lock(&self) {
+ let me = thread_id();
+ while let Err(owner) = self._try_lock(me) {
+ let val = atomic::wait_i64(self.ptr(), owner as i64, -1);
+ debug_assert!(val == 0 || val == 1);
+ }
+ }
+
+ #[inline]
+ pub unsafe fn try_lock(&self) -> bool {
+ self._try_lock(thread_id()).is_ok()
+ }
+
+ #[inline]
+ unsafe fn _try_lock(&self, id: u64) -> Result<(), u64> {
+ let id = id.checked_add(1).unwrap(); // make sure `id` isn't 0
+ match self.owner.compare_exchange(0, id, SeqCst, SeqCst) {
+ // we transitioned from unlocked to locked
+ Ok(_) => {
+ debug_assert_eq!(*self.recursions.get(), 0);
+ Ok(())
+ }
+
+ // we currently own this lock, so let's update our count and return
+ // true.
+ Err(n) if n == id => {
+ *self.recursions.get() += 1;
+ Ok(())
+ }
+
+ // Someone else owns the lock, let our caller take care of it
+ Err(other) => Err(other),
+ }
+ }
+
+ pub unsafe fn unlock(&self) {
+ // If we didn't ever recursively lock the lock then we fully unlock the
+ // mutex and wake up a waiter, if any. Otherwise we decrement our
+ // recursive counter and let some one else take care of the zero.
+ match *self.recursions.get() {
+ 0 => {
+ self.owner.swap(0, SeqCst);
+ atomic::wake(self.ptr() as *mut i32, 1); // wake up one waiter, if any
+ }
+ ref mut n => *n -= 1,
+ }
+ }
+
+ pub unsafe fn destroy(&self) {
+ // nothing to do...
+ }
+
+ #[inline]
+ fn ptr(&self) -> *mut i64 {
+ &self.owner as *const AtomicU64 as *mut i64
+ }
+}
+
+fn thread_id() -> u64 {
+ panic!("thread ids not implemented on wasm with atomics yet")
+}
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use cell::UnsafeCell;
+use sys::mutex::Mutex;
+use sys::condvar::Condvar;
+
+pub struct RWLock {
+ lock: Mutex,
+ cond: Condvar,
+ state: UnsafeCell<State>,
+}
+
+enum State {
+ Unlocked,
+ Reading(usize),
+ Writing,
+}
+
+unsafe impl Send for RWLock {}
+unsafe impl Sync for RWLock {}
+
+// This rwlock implementation is a relatively simple implementation which has a
+// condition variable for readers/writers as well as a mutex protecting the
+// internal state of the lock. A current downside of the implementation is that
+// unlocking the lock will notify *all* waiters rather than just readers or just
+// writers. This can cause lots of "thundering stampede" problems. While
+// hopefully correct this implementation is very likely to want to be changed in
+// the future.
+
+impl RWLock {
+ pub const fn new() -> RWLock {
+ RWLock {
+ lock: Mutex::new(),
+ cond: Condvar::new(),
+ state: UnsafeCell::new(State::Unlocked),
+ }
+ }
+
+ #[inline]
+ pub unsafe fn read(&self) {
+ self.lock.lock();
+ while !(*self.state.get()).inc_readers() {
+ self.cond.wait(&self.lock);
+ }
+ self.lock.unlock();
+ }
+
+ #[inline]
+ pub unsafe fn try_read(&self) -> bool {
+ self.lock.lock();
+ let ok = (*self.state.get()).inc_readers();
+ self.lock.unlock();
+ return ok
+ }
+
+ #[inline]
+ pub unsafe fn write(&self) {
+ self.lock.lock();
+ while !(*self.state.get()).inc_writers() {
+ self.cond.wait(&self.lock);
+ }
+ self.lock.unlock();
+ }
+
+ #[inline]
+ pub unsafe fn try_write(&self) -> bool {
+ self.lock.lock();
+ let ok = (*self.state.get()).inc_writers();
+ self.lock.unlock();
+ return ok
+ }
+
+ #[inline]
+ pub unsafe fn read_unlock(&self) {
+ self.lock.lock();
+ let notify = (*self.state.get()).dec_readers();
+ self.lock.unlock();
+ if notify {
+ // FIXME: should only wake up one of these some of the time
+ self.cond.notify_all();
+ }
+ }
+
+ #[inline]
+ pub unsafe fn write_unlock(&self) {
+ self.lock.lock();
+ (*self.state.get()).dec_writers();
+ self.lock.unlock();
+ // FIXME: should only wake up one of these some of the time
+ self.cond.notify_all();
+ }
+
+ #[inline]
+ pub unsafe fn destroy(&self) {
+ self.lock.destroy();
+ self.cond.destroy();
+ }
+}
+
+impl State {
+ fn inc_readers(&mut self) -> bool {
+ match *self {
+ State::Unlocked => {
+ *self = State::Reading(1);
+ true
+ }
+ State::Reading(ref mut cnt) => {
+ *cnt += 1;
+ true
+ }
+ State::Writing => false
+ }
+ }
+
+ fn inc_writers(&mut self) -> bool {
+ match *self {
+ State::Unlocked => {
+ *self = State::Writing;
+ true
+ }
+ State::Reading(_) |
+ State::Writing => false
+ }
+ }
+
+ fn dec_readers(&mut self) -> bool {
+ let zero = match *self {
+ State::Reading(ref mut cnt) => {
+ *cnt -= 1;
+ *cnt == 0
+ }
+ State::Unlocked |
+ State::Writing => invalid(),
+ };
+ if zero {
+ *self = State::Unlocked;
+ }
+ zero
+ }
+
+ fn dec_writers(&mut self) {
+ match *self {
+ State::Writing => {}
+ State::Unlocked |
+ State::Reading(_) => invalid(),
+ }
+ *self = State::Unlocked;
+ }
+}
+
+fn invalid() -> ! {
+ panic!("inconsistent rwlock");
+}
// nope
}
+ #[cfg(not(target_feature = "atomics"))]
pub fn sleep(_dur: Duration) {
panic!("can't sleep");
}
+ #[cfg(target_feature = "atomics")]
+ pub fn sleep(dur: Duration) {
+ use arch::wasm32::atomic;
+ use cmp;
+
+ // Use an atomic wait to block the current thread artificially with a
+ // timeout listed. Note that we should never be notified (return value
+ // of 0) or our comparison should never fail (return value of 1) so we
+ // should always only resume execution through a timeout (return value
+ // 2).
+ let mut nanos = dur.as_nanos();
+ while nanos > 0 {
+ let amt = cmp::min(i64::max_value() as u128, nanos);
+ let mut x = 0;
+ let val = unsafe { atomic::wait_i32(&mut x, 0, amt as i64) };
+ debug_assert_eq!(val, 2);
+ nanos -= amt;
+ }
+ }
+
pub fn join(self) {
match self.0 {}
}
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+pub type Key = usize;
+
+pub unsafe fn create(_dtor: Option<unsafe extern fn(*mut u8)>) -> Key {
+ panic!("TLS on wasm with atomics not implemented yet");
+}
+
+pub unsafe fn set(_key: Key, _value: *mut u8) {
+ panic!("TLS on wasm with atomics not implemented yet");
+}
+
+pub unsafe fn get(_key: Key) -> *mut u8 {
+ panic!("TLS on wasm with atomics not implemented yet");
+}
+
+pub unsafe fn destroy(_key: Key) {
+ panic!("TLS on wasm with atomics not implemented yet");
+}
+
+#[inline]
+pub fn requires_synchronized_create() -> bool {
+ false
+}
pub expansion_data: ExpansionData,
}
-// Needed for feature-gating attributes used after derives or together with test/bench
-#[derive(Clone, Copy, PartialEq)]
-pub enum TogetherWith {
- None,
- Derive,
- TestBench,
-}
-
pub enum InvocationKind {
Bang {
mac: ast::Mac,
attr: Option<ast::Attribute>,
traits: Vec<Path>,
item: Annotatable,
- together_with: TogetherWith,
+ // We temporarily report errors for attribute macros placed after derives
+ after_derive: bool,
},
Derive {
path: Path,
let (kind, gate) = match *item {
Annotatable::Item(ref item) => {
match item.node {
- ItemKind::Mod(_) if self.cx.ecfg.proc_macro_mod() => return,
- ItemKind::Mod(_) => ("modules", "proc_macro_mod"),
+ ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
+ ItemKind::Mod(_) => ("modules", "proc_macro_hygiene"),
_ => return,
}
}
Annotatable::ImplItem(_) => return,
Annotatable::ForeignItem(_) => return,
Annotatable::Stmt(_) |
- Annotatable::Expr(_) if self.cx.ecfg.proc_macro_expr() => return,
- Annotatable::Stmt(_) => ("statements", "proc_macro_expr"),
- Annotatable::Expr(_) => ("expressions", "proc_macro_expr"),
+ Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
+ Annotatable::Stmt(_) => ("statements", "proc_macro_hygiene"),
+ Annotatable::Expr(_) => ("expressions", "proc_macro_hygiene"),
};
emit_feature_err(
self.cx.parse_sess,
}
fn gate_proc_macro_expansion(&self, span: Span, fragment: &Option<AstFragment>) {
- if self.cx.ecfg.proc_macro_gen() {
+ if self.cx.ecfg.proc_macro_hygiene() {
return
}
let fragment = match fragment {
if let ast::ItemKind::MacroDef(_) = i.node {
emit_feature_err(
self.parse_sess,
- "proc_macro_gen",
+ "proc_macro_hygiene",
self.span,
GateIssue::Language,
&format!("procedural macros cannot expand to macro definitions"),
AstFragmentKind::ImplItems => return,
AstFragmentKind::ForeignItems => return,
};
- if self.cx.ecfg.proc_macro_non_items() {
+ if self.cx.ecfg.proc_macro_hygiene() {
return
}
emit_feature_err(
self.cx.parse_sess,
- "proc_macro_non_items",
+ "proc_macro_hygiene",
span,
GateIssue::Language,
&format!("procedural macros cannot be expanded to {}", kind),
AstFragmentKind::ForeignItems => {
let mut items = SmallVec::new();
while self.token != token::Eof {
- if let Some(item) = self.parse_foreign_item()? {
- items.push(item);
- }
+ items.push(self.parse_foreign_item()?);
}
AstFragment::ForeignItems(items)
}
traits: Vec<Path>,
item: Annotatable,
kind: AstFragmentKind,
- together_with: TogetherWith)
+ after_derive: bool)
-> AstFragment {
- self.collect(kind, InvocationKind::Attr { attr, traits, item, together_with })
+ self.collect(kind, InvocationKind::Attr { attr, traits, item, after_derive })
}
- fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, together_with: &mut TogetherWith)
+ fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
-> Option<ast::Attribute> {
let attr = attrs.iter()
.position(|a| {
if a.path == "derive" {
- *together_with = TogetherWith::Derive
- } else if a.path == "rustc_test_marker2" {
- *together_with = TogetherWith::TestBench
+ *after_derive = true;
}
!attr::is_known(a) && !is_builtin_attr(a)
})
"non-builtin inner attributes are unstable");
}
}
- if together_with == &TogetherWith::None &&
- attrs.iter().any(|a| a.path == "rustc_test_marker2") {
- *together_with = TogetherWith::TestBench;
- }
attr
}
/// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
fn classify_item<T>(&mut self, mut item: T)
- -> (Option<ast::Attribute>, Vec<Path>, T, TogetherWith)
+ -> (Option<ast::Attribute>, Vec<Path>, T, /* after_derive */ bool)
where T: HasAttrs,
{
- let (mut attr, mut traits, mut together_with) = (None, Vec::new(), TogetherWith::None);
+ let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
item = item.map_attrs(|mut attrs| {
if let Some(legacy_attr_invoc) = self.cx.resolver.find_legacy_attr_invoc(&mut attrs,
return attrs;
}
- attr = self.find_attr_invoc(&mut attrs, &mut together_with);
+ attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
traits = collect_derives(&mut self.cx, &mut attrs);
attrs
});
- (attr, traits, item, together_with)
+ (attr, traits, item, after_derive)
}
/// Alternative of `classify_item()` that ignores `#[derive]` so invocations fallthrough
/// to the unused-attributes lint (making it an error on statements and expressions
/// is a breaking change)
fn classify_nonitem<T: HasAttrs>(&mut self, mut item: T)
- -> (Option<ast::Attribute>, T, TogetherWith) {
- let (mut attr, mut together_with) = (None, TogetherWith::None);
+ -> (Option<ast::Attribute>, T, /* after_derive */ bool) {
+ let (mut attr, mut after_derive) = (None, false);
item = item.map_attrs(|mut attrs| {
if let Some(legacy_attr_invoc) = self.cx.resolver.find_legacy_attr_invoc(&mut attrs,
return attrs;
}
- attr = self.find_attr_invoc(&mut attrs, &mut together_with);
+ attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
attrs
});
- (attr, item, together_with)
+ (attr, item, after_derive)
}
fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
expr.node = self.cfg.configure_expr_kind(expr.node);
// ignore derives so they remain unused
- let (attr, expr, together_with) = self.classify_nonitem(expr);
+ let (attr, expr, after_derive) = self.classify_nonitem(expr);
if attr.is_some() {
// collect the invoc regardless of whether or not attributes are permitted here
// AstFragmentKind::Expr requires the macro to emit an expression
return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
- AstFragmentKind::Expr, together_with).make_expr();
+ AstFragmentKind::Expr, after_derive).make_expr();
}
if let ast::ExprKind::Mac(mac) = expr.node {
expr.node = self.cfg.configure_expr_kind(expr.node);
// ignore derives so they remain unused
- let (attr, expr, together_with) = self.classify_nonitem(expr);
+ let (attr, expr, after_derive) = self.classify_nonitem(expr);
if attr.is_some() {
attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
- AstFragmentKind::OptExpr, together_with).make_opt_expr();
+ AstFragmentKind::OptExpr, after_derive).make_opt_expr();
}
if let ast::ExprKind::Mac(mac) = expr.node {
// we'll expand attributes on expressions separately
if !stmt.is_expr() {
- let (attr, derives, stmt_, together_with) = if stmt.is_item() {
+ let (attr, derives, stmt_, after_derive) = if stmt.is_item() {
self.classify_item(stmt)
} else {
// ignore derives on non-item statements so it falls through
// to the unused-attributes lint
- let (attr, stmt, together_with) = self.classify_nonitem(stmt);
- (attr, vec![], stmt, together_with)
+ let (attr, stmt, after_derive) = self.classify_nonitem(stmt);
+ (attr, vec![], stmt, after_derive)
};
if attr.is_some() || !derives.is_empty() {
return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt_)),
- AstFragmentKind::Stmts, together_with).make_stmts();
+ AstFragmentKind::Stmts, after_derive).make_stmts();
}
stmt = stmt_;
fn fold_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
let item = configure!(self, item);
- let (attr, traits, item, together_with) = self.classify_item(item);
+ let (attr, traits, item, after_derive) = self.classify_item(item);
if attr.is_some() || !traits.is_empty() {
return self.collect_attr(attr, traits, Annotatable::Item(item),
- AstFragmentKind::Items, together_with).make_items();
+ AstFragmentKind::Items, after_derive).make_items();
}
match item.node {
fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
let item = configure!(self, item);
- let (attr, traits, item, together_with) = self.classify_item(item);
+ let (attr, traits, item, after_derive) = self.classify_item(item);
if attr.is_some() || !traits.is_empty() {
return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
- AstFragmentKind::TraitItems, together_with).make_trait_items()
+ AstFragmentKind::TraitItems, after_derive).make_trait_items()
}
match item.node {
fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
let item = configure!(self, item);
- let (attr, traits, item, together_with) = self.classify_item(item);
+ let (attr, traits, item, after_derive) = self.classify_item(item);
if attr.is_some() || !traits.is_empty() {
return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
- AstFragmentKind::ImplItems, together_with).make_impl_items();
+ AstFragmentKind::ImplItems, after_derive).make_impl_items();
}
match item.node {
fn fold_foreign_item(&mut self, foreign_item: ast::ForeignItem)
-> SmallVec<[ast::ForeignItem; 1]>
{
- let (attr, traits, foreign_item, together_with) = self.classify_item(foreign_item);
+ let (attr, traits, foreign_item, after_derive) = self.classify_item(foreign_item);
if attr.is_some() || !traits.is_empty() {
return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
- AstFragmentKind::ForeignItems, together_with)
+ AstFragmentKind::ForeignItems, after_derive)
.make_foreign_items();
}
fn enable_custom_derive = custom_derive,
fn enable_format_args_nl = format_args_nl,
fn macros_in_extern_enabled = macros_in_extern,
- fn proc_macro_mod = proc_macro_mod,
- fn proc_macro_gen = proc_macro_gen,
- fn proc_macro_expr = proc_macro_expr,
- fn proc_macro_non_items = proc_macro_non_items,
+ fn proc_macro_hygiene = proc_macro_hygiene,
}
fn enable_custom_inner_attributes(&self) -> bool {
// Allows macro invocations on modules expressions and statements and
// procedural macros to expand to non-items.
- (active, proc_macro_mod, "1.27.0", Some(54727), None),
- (active, proc_macro_expr, "1.27.0", Some(54727), None),
- (active, proc_macro_non_items, "1.27.0", Some(54727), None),
- (active, proc_macro_gen, "1.27.0", Some(54727), None),
+ (active, proc_macro_hygiene, "1.30.0", Some(54727), None),
// #[doc(alias = "...")]
(active, doc_alias, "1.27.0", Some(50146), None),
Some("merged into `#![feature(slice_patterns)]`")),
(removed, macro_reexport, "1.0.0", Some(29638), None,
Some("subsumed by `pub use`")),
+ (removed, proc_macro_mod, "1.27.0", Some(54727), None,
+ Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
+ (removed, proc_macro_expr, "1.27.0", Some(54727), None,
+ Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
+ (removed, proc_macro_non_items, "1.27.0", Some(54727), None,
+ Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
+ (removed, proc_macro_gen, "1.27.0", Some(54727), None,
+ Some("subsumed by `#![feature(proc_macro_hygiene)]`")),
);
declare_features! (
"the `#[rustc_test_marker]` attribute \
is used internally to track tests",
cfg_fn!(rustc_attrs))),
- ("rustc_test_marker2", Normal, Gated(Stability::Unstable,
- "rustc_attrs",
- "temporarily used by rustc to report some errors",
- cfg_fn!(rustc_attrs))),
("rustc_transparent_macro", Whitelisted, Gated(Stability::Unstable,
"rustc_attrs",
"used internally for testing macro hygiene",
require_name);
let pat = self.parse_pat()?;
- self.expect(&token::Colon)?;
+ if let Err(mut err) = self.expect(&token::Colon) {
+ // If we find a pattern followed by an identifier, it could be an (incorrect)
+ // C-style parameter declaration.
+ if self.check_ident() && self.look_ahead(1, |t| {
+ *t == token::Comma || *t == token::CloseDelim(token::Paren)
+ }) {
+ let ident = self.parse_ident().unwrap();
+ let span = pat.span.with_hi(ident.span.hi());
+
+ err.span_suggestion_with_applicability(
+ span,
+ "declare the type after the parameter binding",
+ String::from("<identifier>: <type>"),
+ Applicability::HasPlaceholders,
+ );
+ }
+
+ return Err(err);
+ }
+
(pat, self.parse_ty()?)
} else {
debug!("parse_arg_general ident_to_pat");
attrs.extend(self.parse_inner_attributes()?);
let mut foreign_items = vec![];
- while let Some(item) = self.parse_foreign_item()? {
- foreign_items.push(item);
+ while !self.eat(&token::CloseDelim(token::Brace)) {
+ foreign_items.push(self.parse_foreign_item()?);
}
- self.expect(&token::CloseDelim(token::Brace))?;
let prev_span = self.prev_span;
let m = ast::ForeignMod {
}
/// Parse a foreign item.
- crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
- maybe_whole!(self, NtForeignItem, |ni| Some(ni));
+ crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
+ maybe_whole!(self, NtForeignItem, |ni| ni);
let attrs = self.parse_outer_attributes()?;
let lo = self.span;
).emit();
}
self.bump(); // `static` or `const`
- return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
+ return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
}
// FOREIGN FUNCTION ITEM
if self.check_keyword(keywords::Fn) {
- return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
+ return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
}
// FOREIGN TYPE ITEM
if self.check_keyword(keywords::Type) {
- return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
+ return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
}
match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
Some(mac) => {
- Ok(Some(
+ Ok(
ForeignItem {
ident: keywords::Invalid.ident(),
span: lo.to(self.prev_span),
vis: visibility,
node: ForeignItemKind::Macro(mac),
}
- ))
+ )
}
None => {
- if !attrs.is_empty() {
+ if !attrs.is_empty() {
self.expected_item_err(&attrs);
}
- Ok(None)
+ self.unexpected()
}
}
}
self.word_nbsp("async")?;
self.print_capture_clause(capture_clause)?;
self.s.space()?;
+ // cbox/ibox in analogy to the `ExprKind::Block` arm above
+ self.cbox(INDENT_UNIT)?;
+ self.ibox(0)?;
self.print_block_with_attrs(blk, attrs)?;
}
ast::ExprKind::Assign(ref lhs, ref rhs) => {
// If we're not in test configuration, remove the annotated item
if !cx.ecfg.should_test { return vec![]; }
- let mut item =
+ let item =
if let Annotatable::Item(i) = item { i }
else {
cx.parse_sess.span_diagnostic.span_fatal(item.span(),
debug!("Synthetic test item:\n{}\n", pprust::item_to_string(&test_const));
- // Temporarily add another marker to the original item for error reporting
- let marker2 = cx.attribute(
- attr_sp, cx.meta_word(attr_sp, Symbol::intern("rustc_test_marker2"))
- );
- item.attrs.push(marker2);
-
vec![
// Access to libtest under a gensymed name
Annotatable::Item(test_extern),
-Subproject commit 05c2f61c384e2097a3a4c648344114fc4ac983be
+Subproject commit fe825c93788c841ac1872e8351a62c37a5f78427
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type = "lib"]
+
+mod private {
+ // CHECK: @FOO =
+ #[no_mangle]
+ pub static FOO: u32 = 3;
+
+ // CHECK: @BAR =
+ #[export_name = "BAR"]
+ static BAR: u32 = 3;
+
+ // CHECK: void @foo()
+ #[no_mangle]
+ pub extern fn foo() {}
+
+ // CHECK: void @bar()
+ #[export_name = "bar"]
+ extern fn bar() {}
+}
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// compile-flags: -O
+// `#[no_mangle]`d functions always have external linkage, i.e. no `internal` in their `define`s
+
+#![crate_type = "lib"]
+#![no_std]
+
+// CHECK: define void @a()
+#[no_mangle]
+fn a() {}
+
+// CHECK: define void @b()
+#[no_mangle]
+pub fn b() {}
+
+mod private {
+ // CHECK: define void @c()
+ #[no_mangle]
+ fn c() {}
+
+ // CHECK: define void @d()
+ #[no_mangle]
+ pub fn d() {}
+}
+
+const HIDDEN: () = {
+ // CHECK: define void @e()
+ #[no_mangle]
+ fn e() {}
+
+ // CHECK: define void @f()
+ #[no_mangle]
+ pub fn f() {}
+};
+
+// The surrounding item should not accidentally become external
+// CHECK: define internal {{.*}} void @_ZN22external_no_mangle_fns1x
+#[inline(never)]
+fn x() {
+ // CHECK: define void @g()
+ #[no_mangle]
+ fn g() {
+ x();
+ }
+
+ // CHECK: define void @h()
+ #[no_mangle]
+ pub fn h() {}
+
+ // side effect to keep `x` around
+ unsafe {
+ core::ptr::read_volatile(&42);
+ }
+}
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// compile-flags: -O
+// `#[no_mangle]`d static variables always have external linkage, i.e. no `internal` in their
+// definitions
+
+#![crate_type = "lib"]
+#![no_std]
+
+// CHECK: @A = local_unnamed_addr constant
+#[no_mangle]
+static A: u8 = 0;
+
+// CHECK: @B = local_unnamed_addr global
+#[no_mangle]
+static mut B: u8 = 0;
+
+// CHECK: @C = local_unnamed_addr constant
+#[no_mangle]
+pub static C: u8 = 0;
+
+// CHECK: @D = local_unnamed_addr global
+#[no_mangle]
+pub static mut D: u8 = 0;
+
+mod private {
+ // CHECK: @E = local_unnamed_addr constant
+ #[no_mangle]
+ static E: u8 = 0;
+
+ // CHECK: @F = local_unnamed_addr global
+ #[no_mangle]
+ static mut F: u8 = 0;
+
+ // CHECK: @G = local_unnamed_addr constant
+ #[no_mangle]
+ pub static G: u8 = 0;
+
+ // CHECK: @H = local_unnamed_addr global
+ #[no_mangle]
+ pub static mut H: u8 = 0;
+}
+
+const HIDDEN: () = {
+ // CHECK: @I = local_unnamed_addr constant
+ #[no_mangle]
+ static I: u8 = 0;
+
+ // CHECK: @J = local_unnamed_addr global
+ #[no_mangle]
+ static mut J: u8 = 0;
+
+ // CHECK: @K = local_unnamed_addr constant
+ #[no_mangle]
+ pub static K: u8 = 0;
+
+ // CHECK: @L = local_unnamed_addr global
+ #[no_mangle]
+ pub static mut L: u8 = 0;
+};
+
+// The surrounding item should not accidentally become external
+fn x() {
+ // CHECK: @M = local_unnamed_addr constant
+ #[no_mangle]
+ static M: fn() = x;
+
+ // CHECK: @N = local_unnamed_addr global
+ #[no_mangle]
+ static mut N: u8 = 0;
+
+ // CHECK: @O = local_unnamed_addr constant
+ #[no_mangle]
+ pub static O: u8 = 0;
+
+ // CHECK: @P = local_unnamed_addr global
+ #[no_mangle]
+ pub static mut P: u8 = 0;
+}
+// CHECK: define internal void @_ZN26external_no_mangle_statics1x{{.*$}}
#![crate_type = "rlib"]
#![feature(thread_local)]
-// CHECK: @STATIC_VAR_1 = internal thread_local unnamed_addr global <{ [32 x i8] }> zeroinitializer, section "__DATA,__thread_bss", align 4
+// CHECK: @STATIC_VAR_1 = thread_local local_unnamed_addr global <{ [32 x i8] }> zeroinitializer, section "__DATA,__thread_bss", align 4
#[no_mangle]
-#[allow(private_no_mangle_statics)]
#[thread_local]
static mut STATIC_VAR_1: [u32; 8] = [0; 8];
-// CHECK: @STATIC_VAR_2 = internal thread_local unnamed_addr global <{ [32 x i8] }> <{{[^>]*}}>, section "__DATA,__thread_data", align 4
+// CHECK: @STATIC_VAR_2 = thread_local local_unnamed_addr global <{ [32 x i8] }> <{{[^>]*}}>, section "__DATA,__thread_data", align 4
#[no_mangle]
-#[allow(private_no_mangle_statics)]
#[thread_local]
static mut STATIC_VAR_2: [u32; 8] = [4; 8];
fn foo() {
let _a = Box::new(3);
bar();
-// CHECK-LABEL: foo
-// CHECK: call {{.*}} void @bar
+// CHECK-LABEL: define void @foo
+// CHECK: call void @bar
}
#[inline(never)]
//! Attributes producing expressions in invalid locations
-#![feature(stmt_expr_attributes, proc_macro_expr)]
+#![feature(stmt_expr_attributes, proc_macro_hygiene)]
extern crate attr_stmt_expr;
use attr_stmt_expr::{duplicate, no_output};
// aux-build:attr-stmt-expr.rs
// ignore-stage1
-#![feature(proc_macro_expr)]
+#![feature(proc_macro_hygiene)]
extern crate attr_stmt_expr;
use attr_stmt_expr::{expect_let, expect_print_stmt, expect_expr, expect_print_expr};
// aux-build:bang_proc_macro2.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
#![allow(unused_macros)]
extern crate bang_proc_macro2;
// except according to those terms.
// aux-build:proc-macro-gates.rs
-// gate-test-proc_macro_non_items
-// gate-test-proc_macro_mod line
-// gate-test-proc_macro_expr
-// gate-test-proc_macro_mod
-// gate-test-proc_macro_gen
+// gate-test-proc_macro_hygiene
#![feature(stmt_expr_attributes)]
// compile-flags: -Z parse-only
-// error-pattern:expected one of `(`, `fn`, `static`, `type`, or `}` here
+// error-pattern:expected one of `(`, `fn`, `static`, or `type`
extern {
pub pub fn foo();
}
--- /dev/null
+#![feature(async_await)]
+#![allow(unused_parens)]
+
+// edition:2018
+// pp-exact
+
+fn main() { let _a = (async { }); }
let path = Path::new("libdylib.so");
let a = DynamicLibrary::open(Some(&path)).unwrap();
assert!(a.symbol::<isize>("fun1").is_ok());
- assert!(a.symbol::<isize>("fun2").is_err());
- assert!(a.symbol::<isize>("fun3").is_err());
+ assert!(a.symbol::<isize>("fun2").is_ok());
+ assert!(a.symbol::<isize>("fun3").is_ok());
assert!(a.symbol::<isize>("fun4").is_ok());
assert!(a.symbol::<isize>("fun5").is_ok());
}
CRATE_URL := https://github.com/rust-embedded/cortex-m
CRATE_SHA1 := a448e9156e2cb1e556e5441fd65426952ef4b927 # 0.5.0
+export RUSTFLAGS := --cap-lints=allow
+
all:
env
mkdir -p $(WORK_DIR)
--- /dev/null
+-include ../../run-make-fulldeps/tools.mk
+
+ifeq ($(TARGET),wasm32-unknown-unknown)
+all:
+ $(RUSTC) bar.rs --target wasm32-unknown-unknown
+ $(RUSTC) foo.rs --target wasm32-unknown-unknown
+ $(NODE) verify.js $(TMPDIR)/foo.wasm
+ $(RUSTC) bar.rs --target wasm32-unknown-unknown -O
+ $(RUSTC) foo.rs --target wasm32-unknown-unknown -O
+ $(NODE) verify.js $(TMPDIR)/foo.wasm
+ $(RUSTC) foo.rs --target wasm32-unknown-unknown -C lto
+ $(NODE) verify.js $(TMPDIR)/foo.wasm
+else
+all:
+endif
+
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type = "rlib"]
+
+#[no_mangle]
+pub extern fn foo() {}
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type = "cdylib"]
+
+extern crate bar;
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+const fs = require('fs');
+const process = require('process');
+const assert = require('assert');
+const buffer = fs.readFileSync(process.argv[2]);
+
+let m = new WebAssembly.Module(buffer);
+let list = WebAssembly.Module.exports(m);
+console.log('exports', list);
+
+const my_exports = {};
+let nexports = 0;
+for (const entry of list) {
+ if (entry.kind !== 'function')
+ continue;
+ my_exports[entry.name] = true;
+ nexports += 1;
+}
+
+if (nexports != 1)
+ throw new Error("should only have one function export");
+if (my_exports.foo === undefined)
+ throw new Error("`foo` wasn't defined");
// no-prefer-dynamic
#![crate_type = "proc-macro"]
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate proc_macro;
// no-prefer-dynamic
#![crate_type = "proc-macro"]
-#![feature(proc_macro_non_items, proc_macro_quote)]
+#![feature(proc_macro_hygiene, proc_macro_quote)]
extern crate proc_macro;
let lib = DynamicLibrary::open(None).unwrap();
unsafe {
assert!(lib.symbol::<isize>("foo").is_ok());
- assert!(lib.symbol::<isize>("baz").is_err());
- assert!(lib.symbol::<isize>("bar").is_err());
+ assert!(lib.symbol::<isize>("baz").is_ok());
+ assert!(lib.symbol::<isize>("bar").is_ok());
}
}
// no-prefer-dynamic
#![crate_type = "proc-macro"]
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate proc_macro;
#[macro_use] #[no_link]
extern crate macro_crate_test;
-#[derive(PartialEq, Clone, Debug)]
#[rustc_into_multi_foo]
+#[derive(PartialEq, Clone, Debug)]
fn foo() -> AnotherFakeTypeThatHadBetterGoAway {}
// Check that the `#[into_multi_foo]`-generated `foo2` is configured away
// aux-build:cond_plugin.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate cond_plugin;
// aux-build:hello_macro.rs
// ignore-stage1
-#![feature(proc_macro_non_items, proc_macro_gen)]
+#![feature(proc_macro_hygiene)]
extern crate hello_macro;
// aux-build:attr-stmt-expr.rs
// ignore-stage1
-#![feature(stmt_expr_attributes, proc_macro_expr)]
+#![feature(stmt_expr_attributes, proc_macro_hygiene)]
extern crate attr_stmt_expr;
use attr_stmt_expr::{expect_let, expect_print_stmt, expect_expr, expect_print_expr,
// no-prefer-dynamic
-#![feature(proc_macro_non_items, proc_macro_quote)]
+#![feature(proc_macro_hygiene, proc_macro_quote)]
#![crate_type = "proc-macro"]
extern crate proc_macro;
// no-prefer-dynamic
-#![feature(proc_macro_quote, proc_macro_non_items)]
+#![feature(proc_macro_quote, proc_macro_hygiene)]
#![crate_type = "proc-macro"]
extern crate proc_macro as proc_macro_renamed; // This does not break `quote!`
// aux-build:bang-macro.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate bang_macro;
use bang_macro::rewrite;
// aux-build:call-site.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate call_site;
use call_site::*;
// aux-build:count_compound_ops.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate count_compound_ops;
use count_compound_ops::count_compound_ops;
// aux-build:hygiene_example.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate hygiene_example;
use hygiene_example::hello;
// aux-build:negative-token.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate negative_token;
// ignore-stage1
// ignore-cross-compile
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate proc_macro_def;
// run-pass
// ignore-windows
// ignore-macos
+// ignore-wasm32-bare common linkage not implemented right now
#![feature(linkage)]
#![allow(dead_code)]
// Regression test for #37154: the problem here was that the cache
-// results in a false error because it was caching skolemized results
-// even after those skolemized regions had been popped.
+// results in a false error because it was caching placeholder results
+// even after those placeholder regions had been popped.
trait Foo {
fn method(&self) {}
// aux-build:attr_proc_macro.rs
-// compile-flags:--test
-#![feature(test)]
-
-extern crate test;
extern crate attr_proc_macro;
use attr_proc_macro::*;
#[attr_proc_macro] //~ ERROR macro attributes must be placed before `#[derive]`
struct After;
-#[attr_proc_macro] //~ ERROR macro attributes cannot be used together with `#[test]` or `#[bench]`
-#[test]
-fn test_before() {}
-
-#[test]
-#[attr_proc_macro] //~ ERROR macro attributes cannot be used together with `#[test]` or `#[bench]`
-fn test_after() {}
-
-#[attr_proc_macro] //~ ERROR macro attributes cannot be used together with `#[test]` or `#[bench]`
-#[bench]
-fn bench_before(b: &mut test::Bencher) {}
-
-#[bench]
-#[attr_proc_macro] //~ ERROR macro attributes cannot be used together with `#[test]` or `#[bench]`
-fn bench_after(b: &mut test::Bencher) {}
+fn main() {}
error: macro attributes must be placed before `#[derive]`
- --> $DIR/attribute-order-restricted.rs:15:1
+ --> $DIR/attribute-order-restricted.rs:11:1
|
LL | #[attr_proc_macro] //~ ERROR macro attributes must be placed before `#[derive]`
| ^^^^^^^^^^^^^^^^^^
-error: macro attributes cannot be used together with `#[test]` or `#[bench]`
- --> $DIR/attribute-order-restricted.rs:18:1
- |
-LL | #[attr_proc_macro] //~ ERROR macro attributes cannot be used together with `#[test]` or `#[bench]`
- | ^^^^^^^^^^^^^^^^^^
-
-error: macro attributes cannot be used together with `#[test]` or `#[bench]`
- --> $DIR/attribute-order-restricted.rs:23:1
- |
-LL | #[attr_proc_macro] //~ ERROR macro attributes cannot be used together with `#[test]` or `#[bench]`
- | ^^^^^^^^^^^^^^^^^^
-
-error: macro attributes cannot be used together with `#[test]` or `#[bench]`
- --> $DIR/attribute-order-restricted.rs:26:1
- |
-LL | #[attr_proc_macro] //~ ERROR macro attributes cannot be used together with `#[test]` or `#[bench]`
- | ^^^^^^^^^^^^^^^^^^
-
-error: macro attributes cannot be used together with `#[test]` or `#[bench]`
- --> $DIR/attribute-order-restricted.rs:31:1
- |
-LL | #[attr_proc_macro] //~ ERROR macro attributes cannot be used together with `#[test]` or `#[bench]`
- | ^^^^^^^^^^^^^^^^^^
-
-error: aborting due to 5 previous errors
+error: aborting due to previous error
// aux-build:lifetimes.rs
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate lifetimes;
// compile-pass
// aux-build:bang_proc_macro.rs
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
#[macro_use]
extern crate bang_proc_macro;
// aux-build:multispan.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate multispan;
// aux-build:parent-source-spans.rs
// ignore-stage1
-#![feature(decl_macro, proc_macro_non_items)]
+#![feature(decl_macro, proc_macro_hygiene)]
extern crate parent_source_spans;
// aux-build:three-equals.rs
// ignore-stage1
-#![feature(proc_macro_non_items)]
+#![feature(proc_macro_hygiene)]
extern crate three_equals;
| ^ borrow occurs here
...
LL | drop(bar);
- | --- borrow later used here
+ | --- first borrow later used here
error[E0501]: cannot borrow `*a` as immutable because previous closure requires unique access
--> $DIR/E0501.rs:31:23
| ^ borrow occurs here
...
LL | drop(bar);
- | --- borrow later used here
+ | --- first borrow later used here
error: aborting due to 2 previous errors
| ^ borrow occurs here
...
LL | drop(bar);
- | --- borrow later used here
+ | --- first borrow later used here
error[E0501]: cannot borrow `*a` as immutable because previous closure requires unique access
--> $DIR/E0501.rs:31:23
| ^ borrow occurs here
...
LL | drop(bar);
- | --- borrow later used here
+ | --- first borrow later used here
error: aborting due to 2 previous errors
LL | | &f; //~ ERROR: cannot borrow `f` as immutable because it is also borrowed as mutable
| | ^-
| |_____||
- | |borrow later used here
+ | |mutable borrow later used here
| immutable borrow occurs here
error[E0502]: cannot borrow `f` as mutable because it is also borrowed as immutable
LL | | &mut f; //~ ERROR: cannot borrow `f` as mutable because it is also borrowed as immutable
| | ^^^^^-
| |_____|____|
- | | borrow later used here
+ | | immutable borrow later used here
| mutable borrow occurs here
error: aborting due to 6 previous errors
LL | let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as
| ^^^^^^^^ mutable borrow occurs here
LL | a.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error[E0499]: cannot borrow `x.0` as mutable more than once at a time
--> $DIR/borrow-tuple-fields.rs:33:13
LL | let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable more than once at a time
| ^^^^^^^^ second mutable borrow occurs here
LL | a.use_ref();
- | - borrow later used here
+ | - first borrow later used here
error[E0505]: cannot move out of `x` because it is borrowed
--> $DIR/borrow-tuple-fields.rs:38:13
LL | let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable because it is also borrowed as
| ^^^^^^^^ mutable borrow occurs here
LL | a.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error[E0499]: cannot borrow `x.0` as mutable more than once at a time
--> $DIR/borrow-tuple-fields.rs:48:13
LL | let b = &mut x.0; //~ ERROR cannot borrow `x.0` as mutable more than once at a time
| ^^^^^^^^ second mutable borrow occurs here
LL | a.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error: aborting due to 6 previous errors
| ^^^^^^^^^ second mutable borrow occurs here
...
LL | *a += 1;
- | ------- borrow later used here
+ | ------- first borrow later used here
error: aborting due to previous error
| ^^^^^^^^^ second mutable borrow occurs here
...
LL | *a += 1;
- | ------- borrow later used here
+ | ------- first borrow later used here
error: aborting due to previous error
| ^^^^^^^^^ second mutable borrow occurs here
...
LL | *a += 1;
- | ------- borrow later used here
+ | ------- first borrow later used here
error: aborting due to previous error
| ^ mutable borrow occurs here
LL |
LL | println!("{}", *q);
- | -- borrow later used here
+ | -- immutable borrow later used here
error[E0502]: cannot borrow `p` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-assign-comp-idx.rs:37:9
|
-LL | / borrow(
-LL | | &p,
- | | -- immutable borrow occurs here
-LL | | || p[0] = 5); //~ ERROR cannot borrow `p` as mutable
- | |_________^^_-_______- borrow later used here
- | | |
- | | second borrow occurs due to use of `p` in closure
- | mutable borrow occurs here
+LL | borrow(
+ | ------ immutable borrow later used by call
+LL | &p,
+ | -- immutable borrow occurs here
+LL | || p[0] = 5); //~ ERROR cannot borrow `p` as mutable
+ | ^^ - second borrow occurs due to use of `p` in closure
+ | |
+ | mutable borrow occurs here
error: aborting due to 2 previous errors
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/borrowck-autoref-3261.rs:25:9
|
-LL | (&mut x).with(
- | --------
- | |
- | _____first mutable borrow occurs here
- | |
-LL | | |opt| { //~ ERROR cannot borrow `x` as mutable more than once at a time
- | | ^^^^^ second mutable borrow occurs here
-LL | | match opt {
-LL | | &Either::Right(ref f) => {
-LL | | x = X(Either::Left((0, 0)));
- | | - second borrow occurs due to use of `x` in closure
-... |
-LL | | }
-LL | | })
- | |__________- borrow later used here
+LL | (&mut x).with(
+ | -------- ---- first borrow later used by call
+ | |
+ | first mutable borrow occurs here
+LL | |opt| { //~ ERROR cannot borrow `x` as mutable more than once at a time
+ | ^^^^^ second mutable borrow occurs here
+...
+LL | x = X(Either::Left((0, 0)));
+ | - second borrow occurs due to use of `x` in closure
error: aborting due to previous error
error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-bad-nested-calls-free.rs:35:17
|
-LL | / add(
-LL | | &*a,
- | | --- immutable borrow occurs here
-LL | | rewrite(&mut a)); //~ ERROR cannot borrow
- | |_________________^^^^^^_- borrow later used here
- | |
- | mutable borrow occurs here
+LL | add(
+ | --- immutable borrow later used by call
+LL | &*a,
+ | --- immutable borrow occurs here
+LL | rewrite(&mut a)); //~ ERROR cannot borrow
+ | ^^^^^^ mutable borrow occurs here
error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-bad-nested-calls-free.rs:42:17
|
-LL | / add(
-LL | | &*a,
- | | --- immutable borrow occurs here
-LL | | rewrite(&mut a)); //~ ERROR cannot borrow
- | |_________________^^^^^^_- borrow later used here
- | |
- | mutable borrow occurs here
+LL | add(
+ | --- immutable borrow later used by call
+LL | &*a,
+ | --- immutable borrow occurs here
+LL | rewrite(&mut a)); //~ ERROR cannot borrow
+ | ^^^^^^ mutable borrow occurs here
error: aborting due to 2 previous errors
error[E0505]: cannot move out of `a` because it is borrowed
--> $DIR/borrowck-bad-nested-calls-move.rs:35:9
|
-LL | / add(
-LL | | &*a,
- | | --- borrow of `*a` occurs here
-LL | | a); //~ ERROR cannot move
- | |_________^- borrow later used here
- | |
- | move out of `a` occurs here
+LL | add(
+ | --- borrow later used by call
+LL | &*a,
+ | --- borrow of `*a` occurs here
+LL | a); //~ ERROR cannot move
+ | ^ move out of `a` occurs here
error[E0505]: cannot move out of `a` because it is borrowed
--> $DIR/borrowck-bad-nested-calls-move.rs:42:9
|
-LL | / add(
-LL | | &*a,
- | | --- borrow of `*a` occurs here
-LL | | a); //~ ERROR cannot move
- | |_________^- borrow later used here
- | |
- | move out of `a` occurs here
+LL | add(
+ | --- borrow later used by call
+LL | &*a,
+ | --- borrow of `*a` occurs here
+LL | a); //~ ERROR cannot move
+ | ^ move out of `a` occurs here
error: aborting due to 2 previous errors
LL | let _bar2 = &mut foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^^^^^ second mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0502]: cannot borrow `foo.bar1` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-borrow-from-owned-ptr.rs:36:17
LL | let _bar2 = &foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^ immutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- mutable borrow later used here
error[E0502]: cannot borrow `foo.bar1` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-borrow-from-owned-ptr.rs:43:17
LL | let _bar2 = &mut foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^^^^^ mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error[E0499]: cannot borrow `foo.bar1` as mutable more than once at a time
--> $DIR/borrowck-borrow-from-owned-ptr.rs:73:21
| ^^^^^^^^^^^^^ second mutable borrow occurs here
...
LL | *bar1;
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0502]: cannot borrow `foo.bar1` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-borrow-from-owned-ptr.rs:82:17
| ^^^^^^^^^ immutable borrow occurs here
LL | let _foo2 = &*foo; //~ ERROR cannot borrow
LL | *bar1;
- | ----- borrow later used here
+ | ----- mutable borrow later used here
error[E0502]: cannot borrow `*foo` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-borrow-from-owned-ptr.rs:83:17
LL | let _foo2 = &*foo; //~ ERROR cannot borrow
| ^^^^^ immutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- mutable borrow later used here
error[E0499]: cannot borrow `foo.bar1` as mutable more than once at a time
--> $DIR/borrowck-borrow-from-owned-ptr.rs:90:17
LL | let _foo1 = &mut foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^^^^^ second mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0499]: cannot borrow `*foo` as mutable more than once at a time
--> $DIR/borrowck-borrow-from-owned-ptr.rs:97:17
LL | let _foo2 = &mut *foo; //~ ERROR cannot borrow
| ^^^^^^^^^ second mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0502]: cannot borrow `foo.bar1` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-borrow-from-owned-ptr.rs:104:17
LL | let _foo1 = &mut foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^^^^^ mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error[E0502]: cannot borrow `*foo` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-borrow-from-owned-ptr.rs:111:17
LL | let _foo2 = &mut *foo; //~ ERROR cannot borrow
| ^^^^^^^^^ mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error[E0596]: cannot borrow `foo.bar1` as mutable, as `foo` is not declared as mutable
--> $DIR/borrowck-borrow-from-owned-ptr.rs:132:16
LL | let _bar2 = &mut foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^^^^^ second mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0502]: cannot borrow `foo.bar1` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-borrow-from-stack-variable.rs:35:17
LL | let _bar2 = &foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^ immutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- mutable borrow later used here
error[E0502]: cannot borrow `foo.bar1` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-borrow-from-stack-variable.rs:42:17
LL | let _bar2 = &mut foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^^^^^ mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error[E0499]: cannot borrow `foo.bar1` as mutable more than once at a time
--> $DIR/borrowck-borrow-from-stack-variable.rs:71:21
| ^^^^^^^^^^^^^ second mutable borrow occurs here
...
LL | *bar1;
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0502]: cannot borrow `foo.bar1` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-borrow-from-stack-variable.rs:80:17
| ^^^^^^^^^ immutable borrow occurs here
LL | let _foo2 = &foo; //~ ERROR cannot borrow
LL | *bar1;
- | ----- borrow later used here
+ | ----- mutable borrow later used here
error[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-borrow-from-stack-variable.rs:81:17
LL | let _foo2 = &foo; //~ ERROR cannot borrow
| ^^^^ immutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- mutable borrow later used here
error[E0499]: cannot borrow `foo.bar1` as mutable more than once at a time
--> $DIR/borrowck-borrow-from-stack-variable.rs:88:17
LL | let _foo1 = &mut foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^^^^^ second mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0499]: cannot borrow `foo` as mutable more than once at a time
--> $DIR/borrowck-borrow-from-stack-variable.rs:95:17
LL | let _foo2 = &mut foo; //~ ERROR cannot borrow
| ^^^^^^^^ second mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0502]: cannot borrow `foo.bar1` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-borrow-from-stack-variable.rs:102:17
LL | let _foo1 = &mut foo.bar1; //~ ERROR cannot borrow
| ^^^^^^^^^^^^^ mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error[E0502]: cannot borrow `foo` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-borrow-from-stack-variable.rs:109:17
LL | let _foo2 = &mut foo; //~ ERROR cannot borrow
| ^^^^^^^^ mutable borrow occurs here
LL | *bar1;
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error[E0596]: cannot borrow `foo.bar1` as mutable, as `foo` is not declared as mutable
--> $DIR/borrowck-borrow-from-stack-variable.rs:130:16
LL | let p: &isize = &**t0; //~ ERROR cannot borrow
| ^^^^^ immutable borrow occurs here
LL | **t1 = 22;
- | --------- borrow later used here
+ | --------- mutable borrow later used here
error[E0596]: cannot borrow `**t0` as mutable, as it is behind a `&` reference
--> $DIR/borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs:29:26
LL | x.f2(); //~ ERROR cannot borrow `*x` as mutable
| ^ second mutable borrow occurs here
LL | y.use_ref();
- | - borrow later used here
+ | - first borrow later used here
error: aborting due to previous error
| immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | drop(c1);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-closures-mut-and-imm.rs:39:14
| immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | drop(c1);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-closures-mut-and-imm.rs:47:14
| immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | drop(c1);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0506]: cannot assign to `x` because it is borrowed
--> $DIR/borrowck-closures-mut-and-imm.rs:55:5
| mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as mutable because it is also borrowed as immutable
LL | drop(c1);
- | -- borrow later used here
+ | -- immutable borrow later used here
error: aborting due to 8 previous errors
| immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | drop(c1);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-closures-mut-and-imm.rs:39:14
| immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | drop(c1);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-closures-mut-and-imm.rs:47:14
| immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | drop(c1);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0506]: cannot assign to `x` because it is borrowed
--> $DIR/borrowck-closures-mut-and-imm.rs:55:5
| mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as mutable because it is also borrowed as immutable
LL | drop(c1);
- | -- borrow later used here
+ | -- immutable borrow later used here
error: aborting due to 8 previous errors
| |
| second mutable borrow occurs here
LL | c1;
- | -- borrow later used here
+ | -- first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/borrowck-closures-two-mut-fail.rs:37:24
| |
| second mutable borrow occurs here
LL | c1;
- | -- borrow later used here
+ | -- first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/borrowck-closures-two-mut-fail.rs:44:24
| |
| second mutable borrow occurs here
LL | c1;
- | -- borrow later used here
+ | -- first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/borrowck-closures-two-mut-fail.rs:51:24
| second mutable borrow occurs here
LL | //~^ ERROR cannot borrow `x` as mutable more than once
LL | c1;
- | -- borrow later used here
+ | -- first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/borrowck-closures-two-mut-fail.rs:63:24
| second mutable borrow occurs here
LL | //~^ ERROR cannot borrow `x` as mutable more than once
LL | c1;
- | -- borrow later used here
+ | -- first borrow later used here
error: aborting due to 5 previous errors
| second mutable borrow occurs here
LL | //~| ERROR cannot borrow `x` as mutable more than once
LL | drop((c1, c2));
- | -- borrow later used here
+ | -- first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time (Mir)
--> $DIR/borrowck-closures-two-mut.rs:36:24
| second mutable borrow occurs here
LL | //~| ERROR cannot borrow `x` as mutable more than once
LL | drop((c1, c2));
- | -- borrow later used here
+ | -- first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time (Mir)
--> $DIR/borrowck-closures-two-mut.rs:44:24
| second mutable borrow occurs here
LL | //~| ERROR cannot borrow `x` as mutable more than once
LL | drop((c1, c2));
- | -- borrow later used here
+ | -- first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time (Mir)
--> $DIR/borrowck-closures-two-mut.rs:52:24
| second mutable borrow occurs here
...
LL | drop((c1, c2));
- | -- borrow later used here
+ | -- first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time (Mir)
--> $DIR/borrowck-closures-two-mut.rs:65:24
| second mutable borrow occurs here
...
LL | drop((c1, c2));
- | -- borrow later used here
+ | -- first borrow later used here
error: aborting due to 10 previous errors
LL | &mut this.x; //~ ERROR cannot borrow
| ^^^^^^^^^^^ mutable borrow occurs here
LL | p.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error: aborting due to previous error
| |
| closure construction occurs here
LL | c1;
- | -- borrow later used here
+ | -- first borrow later used here
error[E0500]: closure requires unique access to `x` but it is already borrowed
--> $DIR/borrowck-closures-unique.rs:42:14
| |
| closure construction occurs here
LL | c1;
- | -- borrow later used here
+ | -- first borrow later used here
error[E0524]: two closures require unique access to `x` at the same time
--> $DIR/borrowck-closures-unique.rs:48:14
| |
| second closure is constructed here
LL | c1;
- | -- borrow later used here
+ | -- first borrow later used here
error[E0594]: cannot assign to `x`, as it is not declared as mutable
--> $DIR/borrowck-closures-unique.rs:57:38
| --- first borrow occurs due to use of `ptr` in closure
LL | };
LL | test(&*ptr); //~ ERROR cannot borrow `*ptr`
- | -----^^^^^-
- | | |
- | | immutable borrow occurs here
- | borrow later used here
+ | ---- ^^^^^ immutable borrow occurs here
+ | |
+ | mutable borrow later used by call
error: aborting due to previous error
| ^^^^^^ second mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as mutable more than once at a time
LL | *y = 1;
- | ------ borrow later used here
+ | ------ first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/borrowck-describe-lvalue.rs:307:20
| ^^^^^^ second mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as mutable more than once at a time
LL | *y = 1;
- | ------ borrow later used here
+ | ------ first borrow later used here
error: unsatisfied lifetime constraints
--> $DIR/borrowck-describe-lvalue.rs:305:16
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `e.x` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:207:23
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `s.y.0` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:221:22
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `s.x.y` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:228:28
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0503]: cannot use `*v` because it was mutably borrowed
--> $DIR/borrowck-describe-lvalue.rs:271:9
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `*block.current` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:245:29
| ^^^^^^^^^^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `*block.current` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:260:33
| ^^^^^^^^^^^^^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0382]: use of moved value: `x`
--> $DIR/borrowck-describe-lvalue.rs:318:22
| ^^^^^^ second mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as mutable more than once at a time
LL | *y = 1;
- | ------ borrow later used here
+ | ------ first borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/borrowck-describe-lvalue.rs:307:20
| ^^^^^^ second mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `x` as mutable more than once at a time
LL | *y = 1;
- | ------ borrow later used here
+ | ------ first borrow later used here
error: unsatisfied lifetime constraints
--> $DIR/borrowck-describe-lvalue.rs:305:16
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `e.x` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:207:23
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `s.y.0` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:221:22
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `s.x.y` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:228:28
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0503]: cannot use `*v` because it was mutably borrowed
--> $DIR/borrowck-describe-lvalue.rs:271:9
| ^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `*block.current` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:245:29
| ^^^^^^^^^^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `*block.current` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-describe-lvalue.rs:260:33
| ^^^^^^^^^^^^^^^^^^ immutable borrow occurs here
...
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error[E0382]: use of moved value: `x`
--> $DIR/borrowck-describe-lvalue.rs:318:22
LL | let q = &mut x.a; //~ ERROR cannot borrow `x.a` as mutable more than once at a time
| ^^^^^^^^ second mutable borrow occurs here
LL | drop(*p);
- | -- borrow later used here
+ | -- first borrow later used here
error[E0382]: use of moved value: `x.b`
--> $DIR/borrowck-field-sensitivity.rs:66:10
| -------
| |
| immutable borrow occurs here
- | borrow used here, in later iteration of loop
+ | immutable borrow used here, in later iteration of loop
LL | let cap = vector.capacity();
LL | vector.extend(repeat(0)); //~ ERROR cannot borrow
| ^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
| -------
| |
| immutable borrow occurs here
- | borrow used here, in later iteration of loop
+ | immutable borrow used here, in later iteration of loop
...
LL | vector[1] = 5; //~ ERROR cannot borrow
| ^^^^^^ mutable borrow occurs here
error[E0501]: cannot borrow `*f` as mutable because previous closure requires unique access
--> $DIR/borrowck-insert-during-each.rs:26:3
|
-LL | f.foo(
- | ___^
- | |___|
- | ||
-LL | || |a| { //~ ERROR closure requires unique access to `f`
- | || --- closure construction occurs here
-LL | || f.n.insert(*a);
- | || - first borrow occurs due to use of `f` in closure
-LL | || })
- | || ^
- | ||__________|
- | |___________borrow occurs here
- | borrow later used here
-
-error[E0500]: closure requires unique access to `f` but it is already borrowed
- --> $DIR/borrowck-insert-during-each.rs:27:9
- |
LL | f.foo(
- | -
- | |
- | ___borrow occurs here
+ | ^ --- first borrow later used by call
+ | ___|
| |
LL | | |a| { //~ ERROR closure requires unique access to `f`
- | | ^^^ closure construction occurs here
+ | | --- closure construction occurs here
LL | | f.n.insert(*a);
- | | - second borrow occurs due to use of `f` in closure
+ | | - first borrow occurs due to use of `f` in closure
LL | | })
- | |__________- borrow later used here
+ | |__________^ borrow occurs here
+
+error[E0500]: closure requires unique access to `f` but it is already borrowed
+ --> $DIR/borrowck-insert-during-each.rs:27:9
+ |
+LL | f.foo(
+ | - --- first borrow later used by call
+ | |
+ | borrow occurs here
+LL | |a| { //~ ERROR closure requires unique access to `f`
+ | ^^^ closure construction occurs here
+LL | f.n.insert(*a);
+ | - second borrow occurs due to use of `f` in closure
error: aborting due to 2 previous errors
LL | borrow_mut(&mut *v); //~ ERROR cannot borrow
| ^^^^^^^ mutable borrow occurs here
LL | _w.use_ref();
- | -- borrow later used here
+ | -- immutable borrow later used here
error: aborting due to previous error
| ^^^ immutable borrow occurs here
LL | }
LL | *x = box 5;
- | -- borrow used here, in later iteration of loop
+ | -- mutable borrow used here, in later iteration of loop
error[E0502]: cannot borrow `*v` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-lend-flow-loop.rs:109:16
|
LL | **x += 1;
- | -------- borrow used here, in later iteration of loop
+ | -------- mutable borrow used here, in later iteration of loop
LL | borrow(&*v); //~ ERROR cannot borrow
| ^^^ immutable borrow occurs here
LL | if cond2 {
LL | borrow_mut(&mut *v); //~ ERROR cannot borrow
| ^^^^^^^ mutable borrow occurs here
LL | _w.use_ref();
- | -- borrow later used here
+ | -- immutable borrow later used here
error: aborting due to previous error
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-loan-blocks-mut-uniq.rs:20:12
|
-LL | borrow(&*v,
- | - --- immutable borrow occurs here
- | _____|
- | |
-LL | | |w| { //~ ERROR cannot borrow `v` as mutable
- | | ^^^ mutable borrow occurs here
-LL | | v = box 4;
- | | - second borrow occurs due to use of `v` in closure
-LL | | assert_eq!(*v, 3);
-LL | | assert_eq!(*w, 4);
-LL | | })
- | |__________- borrow later used here
+LL | borrow(&*v,
+ | ------ --- immutable borrow occurs here
+ | |
+ | immutable borrow later used by call
+LL | |w| { //~ ERROR cannot borrow `v` as mutable
+ | ^^^ mutable borrow occurs here
+LL | v = box 4;
+ | - second borrow occurs due to use of `v` in closure
error: aborting due to previous error
| ^ immutable borrow occurs here
LL |
LL | *q + 3; // OK to use the new alias `q`
- | -- borrow later used here
+ | -- mutable borrow later used here
error: aborting due to 2 previous errors
error[E0502]: cannot borrow `p` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-loan-rcvr.rs:34:14
|
-LL | p.blockm(|| { //~ ERROR cannot borrow `p` as mutable
- | - ^^ mutable borrow occurs here
- | |
- | _____immutable borrow occurs here
- | |
-LL | | p.x = 10;
- | | - second borrow occurs due to use of `p` in closure
-LL | | })
- | |______- borrow later used here
+LL | p.blockm(|| { //~ ERROR cannot borrow `p` as mutable
+ | - ------ ^^ mutable borrow occurs here
+ | | |
+ | | immutable borrow later used by call
+ | immutable borrow occurs here
+LL | p.x = 10;
+ | - second borrow occurs due to use of `p` in closure
error[E0502]: cannot borrow `p` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-loan-rcvr.rs:45:5
| ^ immutable borrow occurs here
LL |
LL | l.x += 1;
- | -------- borrow later used here
+ | -------- mutable borrow later used here
error: aborting due to 2 previous errors
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-loan-vec-content.rs:28:9
|
-LL | / takes_imm_elt(
-LL | | &v[0],
- | | - immutable borrow occurs here
-LL | | || { //~ ERROR cannot borrow `v` as mutable
- | | ^^ mutable borrow occurs here
-LL | | v[1] = 4;
- | | - second borrow occurs due to use of `v` in closure
-LL | | })
- | |__________- borrow later used here
+LL | takes_imm_elt(
+ | ------------- immutable borrow later used by call
+LL | &v[0],
+ | - immutable borrow occurs here
+LL | || { //~ ERROR cannot borrow `v` as mutable
+ | ^^ mutable borrow occurs here
+LL | v[1] = 4;
+ | - second borrow occurs due to use of `v` in closure
error: aborting due to previous error
--- /dev/null
+error[E0507]: cannot move out of an `Rc`
+ --> $DIR/borrowck-move-out-of-overloaded-auto-deref.rs:17:14
+ |
+LL | let _x = Rc::new(vec![1, 2]).into_iter();
+ | ^^^^^^^^^^^^^^^^^^^ cannot move out of an `Rc`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0507`.
-error[E0507]: cannot move out of borrowed content
+error[E0507]: cannot move out of an `Rc`
--> $DIR/borrowck-move-out-of-overloaded-auto-deref.rs:17:14
|
LL | let _x = Rc::new(vec![1, 2]).into_iter();
- | ^^^^^^^^^^^^^^^^^^^ cannot move out of borrowed content
+ | ^^^^^^^^^^^^^^^^^^^ cannot move out of an `Rc`
error: aborting due to previous error
-error[E0507]: cannot move out of borrowed content
+error[E0507]: cannot move out of an `Rc`
--> $DIR/borrowck-move-out-of-overloaded-deref.rs:14:14
|
LL | let _x = *Rc::new("hi".to_string());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
- | cannot move out of borrowed content
+ | cannot move out of an `Rc`
| help: consider removing the `*`: `Rc::new("hi".to_string())`
error: aborting due to previous error
LL | 1 => { addr.push(&mut x); } //[ast]~ ERROR [E0499]
| ---- ^^^^^^ second mutable borrow occurs here
| |
- | borrow used here, in later iteration of loop
+ | first borrow used here, in later iteration of loop
...
LL | _ => { addr.push(&mut x); } //[ast]~ ERROR [E0499]
| ------ first mutable borrow occurs here
--> $DIR/borrowck-mut-borrow-linear-errors.rs:25:30
|
LL | 1 => { addr.push(&mut x); } //[ast]~ ERROR [E0499]
- | ---- borrow used here, in later iteration of loop
+ | ---- first borrow used here, in later iteration of loop
LL | //[mir]~^ ERROR [E0499]
LL | 2 => { addr.push(&mut x); } //[ast]~ ERROR [E0499]
| ^^^^^^ second mutable borrow occurs here
LL | 1 => { addr.push(&mut x); } //[ast]~ ERROR [E0499]
| ---- ^^^^^^ second mutable borrow occurs here
| |
- | borrow used here, in later iteration of loop
+ | first borrow used here, in later iteration of loop
...
LL | _ => { addr.push(&mut x); } //[ast]~ ERROR [E0499]
| ------ first mutable borrow occurs here
--> $DIR/borrowck-mut-borrow-linear-errors.rs:25:30
|
LL | 1 => { addr.push(&mut x); } //[ast]~ ERROR [E0499]
- | ---- borrow used here, in later iteration of loop
+ | ---- first borrow used here, in later iteration of loop
LL | //[mir]~^ ERROR [E0499]
LL | 2 => { addr.push(&mut x); } //[ast]~ ERROR [E0499]
| ^^^^^^ second mutable borrow occurs here
| ^^^^^^^ mutable borrow occurs here
LL | **t2 += 1; // Mutates `*t0`
LL | p.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error[E0499]: cannot borrow `t0` as mutable more than once at a time
--> $DIR/borrowck-mut-borrow-of-mut-base-ptr.rs:29:18
| ^^^^^^^ second mutable borrow occurs here
LL | **t2 += 1; // Mutates `*t0` but not through `*p`
LL | p.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error: aborting due to 2 previous errors
LL | let z = x.mut_borrowed(); //~ ERROR cannot borrow
| ^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | y.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-object-lifetime.rs:36:13
LL | let z = &mut x; //~ ERROR cannot borrow
| ^^^^^^ mutable borrow occurs here
LL | y.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error: aborting due to 2 previous errors
LL | let q = &f[&s]; //~ ERROR cannot borrow
| ^ immutable borrow occurs here
LL | p.use_mut();
- | - borrow later used here
+ | - mutable borrow later used here
error[E0499]: cannot borrow `*f` as mutable more than once at a time
--> $DIR/borrowck-overloaded-index-autoderef.rs:53:18
LL | let q = &mut f[&s]; //~ ERROR cannot borrow
| ^ second mutable borrow occurs here
LL | p.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error[E0499]: cannot borrow `f.foo` as mutable more than once at a time
--> $DIR/borrowck-overloaded-index-autoderef.rs:63:18
LL | let q = &mut f.foo[&s]; //~ ERROR cannot borrow
| ^^^^^ second mutable borrow occurs here
LL | p.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error[E0502]: cannot borrow `f.foo` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-overloaded-index-autoderef.rs:75:18
LL | let q = &mut f.foo[&s]; //~ ERROR cannot borrow
| ^^^^^ mutable borrow occurs here
LL | p.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error[E0506]: cannot assign to `f.foo` because it is borrowed
--> $DIR/borrowck-overloaded-index-autoderef.rs:81:5
| ^^ immutable borrow occurs here
...
LL | drop(rs);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-overloaded-index-ref-index.rs:65:7
| ^^ immutable borrow occurs here
...
LL | drop(rs);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0594]: cannot assign to data in a `&` reference
--> $DIR/borrowck-overloaded-index-ref-index.rs:71:5
| ^^ immutable borrow occurs here
...
LL | drop(rs);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-overloaded-index-ref-index.rs:65:7
| ^^ immutable borrow occurs here
...
LL | drop(rs);
- | -- borrow later used here
+ | -- mutable borrow later used here
error[E0594]: cannot assign to data in a `&` reference
--> $DIR/borrowck-overloaded-index-ref-index.rs:71:5
| ^^ immutable borrow occurs here
...
LL | y.use_mut();
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-report-with-custom-diagnostic.rs:30:21
| ^^^^^^ mutable borrow occurs here
...
LL | y.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/borrowck-report-with-custom-diagnostic.rs:45:17
| ^^^^^^ second mutable borrow occurs here
...
LL | y.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error: aborting due to 3 previous errors
LL | if let [_, ref mut second2, ref mut third, ..] = *s { //~ERROR
| ^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[first, second, second2, third]);
- | ------ borrow later used here
+ | ------ immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:44:21
LL | if let [.., ref mut third2, _, _] = *s { //~ERROR
| ^^^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[first, third, third2, fourth]);
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:55:20
LL | if let [_, ref mut from_begin1, ..] = *s { //~ERROR
| ^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[from_begin1, from_end1, from_end3, from_end4]);
- | --------- borrow later used here
+ | --------- immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:58:23
LL | if let [_, _, ref mut from_begin2, ..] = *s { //~ERROR
| ^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[from_begin2, from_end1, from_end3, from_end4]);
- | --------- borrow later used here
+ | --------- immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:61:26
LL | if let [_, _, _, ref mut from_begin3, ..] = *s { //~ERROR
| ^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[from_begin3, from_end1, from_end3, from_end4]);
- | --------- borrow later used here
+ | --------- immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:69:21
LL | if let [.., ref mut from_end2, _] = *s { //~ERROR
| ^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[from_begin0, from_begin1, from_begin3, from_end2]);
- | ----------- borrow later used here
+ | ----------- immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:72:21
LL | if let [.., ref mut from_end3, _, _] = *s { //~ERROR
| ^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[from_begin0, from_begin1, from_begin3, from_end3]);
- | ----------- borrow later used here
+ | ----------- immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:75:21
LL | if let [.., ref mut from_end4, _, _, _] = *s { //~ERROR
| ^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[from_begin0, from_begin1, from_begin3, from_end4]);
- | ----------- borrow later used here
+ | ----------- immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:92:20
LL | if let [_, ref mut tail..] = *s { //~ERROR
| ^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[first, second]);
- | ------ borrow later used here
+ | ------ immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:110:17
LL | if let [ref mut tail.., _] = *s { //~ERROR
| ^^^^^^^^^^^^ mutable borrow occurs here
LL | nop(&[first, second]);
- | ------ borrow later used here
+ | ------ immutable borrow later used here
error[E0502]: cannot borrow `s[..]` as mutable because it is also borrowed as immutable
--> $DIR/borrowck-slice-pattern-element-loan.rs:119:17
LL | if let [ref mut s2.., _, _, _] = *s { //~ERROR
| ^^^^^^^^^^ mutable borrow occurs here
LL | nop_subslice(s1);
- | -- borrow later used here
+ | -- immutable borrow later used here
error: aborting due to 11 previous errors
| ^^^^^^^ mutable borrow occurs here
LL | *t1 = 22;
LL | p.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error: aborting due to previous error
| ^^^^^^^^ mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.a` as mutable because it is also borrowed as immutable
LL | drop(ra);
- | -- borrow later used here
+ | -- immutable borrow later used here
error[E0506]: cannot assign to `u.a` because it is borrowed
--> $DIR/borrowck-union-borrow.rs:43:13
| ^^^^^^^^ mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.b` as mutable because it is also borrowed as immutable
LL | drop(ra);
- | -- borrow later used here
+ | -- immutable borrow later used here
error[E0506]: cannot assign to `u.b` because it is borrowed
--> $DIR/borrowck-union-borrow.rs:66:13
| ^^^^ immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.a` as immutable because it is also borrowed as mutable
LL | drop(rma);
- | --- borrow later used here
+ | --- mutable borrow later used here
error[E0503]: cannot use `u.a` because it was mutably borrowed
--> $DIR/borrowck-union-borrow.rs:79:21
| ^^^^^^^^ second mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.a` as mutable more than once at a time
LL | drop(rma);
- | --- borrow later used here
+ | --- first borrow later used here
error[E0506]: cannot assign to `u.a` because it is borrowed
--> $DIR/borrowck-union-borrow.rs:91:13
| ^^^^ immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.b` as immutable because it is also borrowed as mutable
LL | drop(rma);
- | --- borrow later used here
+ | --- mutable borrow later used here
error[E0503]: cannot use `u.b` because it was mutably borrowed
--> $DIR/borrowck-union-borrow.rs:104:21
| ^^^^^^^^ second mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.b` as mutable more than once at a time
LL | drop(rma);
- | --- borrow later used here
+ | --- first borrow later used here
error[E0506]: cannot assign to `u.b` because it is borrowed
--> $DIR/borrowck-union-borrow.rs:117:13
| ^^^^^^^^ mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.a` as mutable because it is also borrowed as immutable
LL | drop(ra);
- | -- borrow later used here
+ | -- immutable borrow later used here
error[E0506]: cannot assign to `u.a` because it is borrowed
--> $DIR/borrowck-union-borrow.rs:43:13
| ^^^^^^^^ mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.b` as mutable because it is also borrowed as immutable
LL | drop(ra);
- | -- borrow later used here
+ | -- immutable borrow later used here
error[E0506]: cannot assign to `u.b` because it is borrowed
--> $DIR/borrowck-union-borrow.rs:66:13
| ^^^^ immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.a` as immutable because it is also borrowed as mutable
LL | drop(rma);
- | --- borrow later used here
+ | --- mutable borrow later used here
error[E0503]: cannot use `u.a` because it was mutably borrowed
--> $DIR/borrowck-union-borrow.rs:79:21
| ^^^^^^^^ second mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.a` as mutable more than once at a time
LL | drop(rma);
- | --- borrow later used here
+ | --- first borrow later used here
error[E0506]: cannot assign to `u.a` because it is borrowed
--> $DIR/borrowck-union-borrow.rs:91:13
| ^^^^ immutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.b` as immutable because it is also borrowed as mutable
LL | drop(rma);
- | --- borrow later used here
+ | --- mutable borrow later used here
error[E0503]: cannot use `u.b` because it was mutably borrowed
--> $DIR/borrowck-union-borrow.rs:104:21
| ^^^^^^^^ second mutable borrow occurs here
LL | //[mir]~^ ERROR cannot borrow `u.b` as mutable more than once at a time
LL | drop(rma);
- | --- borrow later used here
+ | --- first borrow later used here
error[E0506]: cannot assign to `u.b` because it is borrowed
--> $DIR/borrowck-union-borrow.rs:117:13
LL | borrow(&*v); //~ ERROR cannot borrow `*v`
| ^^^ immutable borrow occurs here
LL | w.use_mut();
- | - borrow later used here
+ | - mutable borrow later used here
error[E0502]: cannot borrow `*v` as immutable because it is also borrowed as mutable
--> $DIR/borrowck-uniq-via-lend.rs:63:12
LL | borrow(&*v); //~ ERROR cannot borrow `*v`
| ^^^ immutable borrow occurs here
LL | x.use_mut();
- | - borrow later used here
+ | - mutable borrow later used here
error: aborting due to 2 previous errors
| ------ first mutable borrow occurs here
...
LL | v.push(tail[0] + tail[1]); //~ ERROR cannot borrow
- | ^ ------- borrow later used here
+ | ^ ------- first borrow later used here
| |
| second mutable borrow occurs here
LL | bar.take(); //~ ERROR cannot borrow
| ^^^ second mutable borrow occurs here
LL | drop(baz);
- | --- borrow later used here
+ | --- first borrow later used here
error: aborting due to previous error
LL | (self.func)(arg) //~ ERROR cannot borrow
| ^^^ mutable borrow starts here in previous iteration of loop
|
-note: borrowed value must be valid for the lifetime 'a as defined on the impl at 17:6...
+note: first borrowed value must be valid for the lifetime 'a as defined on the impl at 17:6...
--> $DIR/mut-borrow-in-loop.rs:17:6
|
LL | impl<'a, T : 'a> FuncWrapper<'a, T> {
LL | (self.func)(arg) //~ ERROR cannot borrow
| ^^^ mutable borrow starts here in previous iteration of loop
|
-note: borrowed value must be valid for the lifetime 'a as defined on the impl at 17:6...
+note: first borrowed value must be valid for the lifetime 'a as defined on the impl at 17:6...
--> $DIR/mut-borrow-in-loop.rs:17:6
|
LL | impl<'a, T : 'a> FuncWrapper<'a, T> {
LL | (self.func)(arg) //~ ERROR cannot borrow
| ^^^ mutable borrow starts here in previous iteration of loop
|
-note: borrowed value must be valid for the lifetime 'a as defined on the impl at 17:6...
+note: first borrowed value must be valid for the lifetime 'a as defined on the impl at 17:6...
--> $DIR/mut-borrow-in-loop.rs:17:6
|
LL | impl<'a, T : 'a> FuncWrapper<'a, T> {
LL | let second = &mut void; //~ ERROR cannot borrow
| ^^^^^^^^^ second mutable borrow occurs here
LL | first.use_mut();
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0499]: cannot borrow `inner_void` as mutable more than once at a time
--> $DIR/mut-borrow-outside-loop.rs:25:28
| ^^^^^^^^^^^^^^^ second mutable borrow occurs here
LL | inner_second.use_mut();
LL | inner_first.use_mut();
- | ----------- borrow used here, in later iteration of loop
+ | ----------- first borrow used here, in later iteration of loop
error: aborting due to 2 previous errors
| ^^ immutable borrow occurs here
LL | //[nll_target]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | *y += 1;
- | ------- borrow later used here
+ | ------- mutable borrow later used here
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-activation-sharing-interference.rs:50:13
| ^^ immutable borrow occurs here
LL | //[nll_target]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | *y += 1;
- | ------- borrow later used here
+ | ------- mutable borrow later used here
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-activation-sharing-interference.rs:61:13
| ^^ immutable borrow occurs here
...
LL | *y += 1;
- | ------- borrow later used here
+ | ------- mutable borrow later used here
error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-activation-sharing-interference.rs:72:14
| ^^ immutable borrow occurs here
LL | //[nll_target]~^ ERROR cannot borrow `x` as immutable because it is also borrowed as mutable
LL | *y += 1;
- | ------- borrow later used here
+ | ------- mutable borrow later used here
error: aborting due to 4 previous errors
error[E0502]: cannot borrow `vec` as mutable because it is also borrowed as immutable
--> $DIR/two-phase-cannot-nest-mut-self-calls.rs:26:9
|
-LL | vec.get({
- | ---
- | |
- | _____immutable borrow occurs here
- | |
-LL | |
-LL | | vec.push(2);
- | | ^^^^^^^^^^^ mutable borrow occurs here
-LL | | //~^ ERROR cannot borrow `vec` as mutable because it is also borrowed as immutable
-LL | |
-LL | | 0
-LL | | });
- | |______- borrow later used here
+LL | vec.get({
+ | --- --- immutable borrow later used by call
+ | |
+ | immutable borrow occurs here
+LL |
+LL | vec.push(2);
+ | ^^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error
--> $DIR/two-phase-multi-mut.rs:23:5
|
LL | foo.method(&mut foo);
- | ^^^^^^^^^^^--------^
- | | |
- | | first mutable borrow occurs here
+ | ^^^^------^--------^
+ | | | |
+ | | | first mutable borrow occurs here
+ | | first borrow later used by call
| second mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `foo` as mutable more than once at a time
--> $DIR/two-phase-multi-mut.rs:23:16
|
LL | foo.method(&mut foo);
- | -----------^^^^^^^^-
- | | |
- | | second mutable borrow occurs here
+ | --- ------ ^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error: aborting due to 2 previous errors
--> $DIR/two-phase-nonrecv-autoref.rs:70:11
|
LL | f(f(10));
- | --^-----
- | | |
- | | second mutable borrow occurs here
+ | - ^ second mutable borrow occurs here
+ | |
| first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error[E0382]: use of moved value: `*f`
--> $DIR/two-phase-nonrecv-autoref.rs:79:11
--> $DIR/two-phase-nonrecv-autoref.rs:86:11
|
LL | f(f(10));
- | --^-----
- | | |
- | | second mutable borrow occurs here
+ | - ^ second mutable borrow occurs here
+ | |
| first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error[E0161]: cannot move a value of type dyn std::ops::FnOnce(i32) -> i32: the size of dyn std::ops::FnOnce(i32) -> i32 cannot be statically determined
--> $DIR/two-phase-nonrecv-autoref.rs:95:9
--> $DIR/two-phase-nonrecv-autoref.rs:139:27
|
LL | double_access(&mut a, &a);
- | ----------------------^^-
- | | | |
- | | | immutable borrow occurs here
+ | ------------- ------ ^^ immutable borrow occurs here
+ | | |
| | mutable borrow occurs here
- | borrow later used here
+ | mutable borrow later used by call
error[E0502]: cannot borrow `i` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-nonrecv-autoref.rs:167:7
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
- | borrow later used here
+ | mutable borrow later used here
error[E0502]: cannot borrow `i` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-nonrecv-autoref.rs:173:7
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
- | borrow later used here
+ | mutable borrow later used here
error: aborting due to 9 previous errors
--> $DIR/two-phase-nonrecv-autoref.rs:70:11
|
LL | f(f(10));
- | --^-----
- | | |
- | | second mutable borrow occurs here
+ | - ^ second mutable borrow occurs here
+ | |
| first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error[E0382]: use of moved value: `*f`
--> $DIR/two-phase-nonrecv-autoref.rs:79:11
--> $DIR/two-phase-nonrecv-autoref.rs:86:11
|
LL | f(f(10));
- | --^-----
- | | |
- | | second mutable borrow occurs here
+ | - ^ second mutable borrow occurs here
+ | |
| first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error[E0161]: cannot move a value of type dyn std::ops::FnOnce(i32) -> i32: the size of dyn std::ops::FnOnce(i32) -> i32 cannot be statically determined
--> $DIR/two-phase-nonrecv-autoref.rs:95:9
--> $DIR/two-phase-nonrecv-autoref.rs:139:27
|
LL | double_access(&mut a, &a);
- | ----------------------^^-
- | | | |
- | | | immutable borrow occurs here
+ | ------------- ------ ^^ immutable borrow occurs here
+ | | |
| | mutable borrow occurs here
- | borrow later used here
+ | mutable borrow later used by call
error[E0502]: cannot borrow `i` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-nonrecv-autoref.rs:167:7
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
- | borrow later used here
+ | mutable borrow later used here
error[E0502]: cannot borrow `i` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-nonrecv-autoref.rs:173:7
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
- | borrow later used here
+ | mutable borrow later used here
error: aborting due to 9 previous errors
| ^^^^^^^^ mutable borrow occurs here
...
LL | shared[0];
- | ------ borrow later used here
+ | ------ immutable borrow later used here
error: aborting due to previous error
error[E0499]: cannot borrow `v` as mutable more than once at a time
--> $DIR/two-phase-sneaky.rs:22:9
|
-LL | v[0].push_str({
- | -
- | |
- | _____first mutable borrow occurs here
- | |
-LL | |
-LL | | v.push(format!("foo"));
- | | ^ second mutable borrow occurs here
-LL | | //~^ ERROR cannot borrow `v` as mutable more than once at a time [E0499]
-LL | |
-LL | | "World!"
-LL | | });
- | |______- borrow later used here
+LL | v[0].push_str({
+ | - -------- first borrow later used by call
+ | |
+ | first mutable borrow occurs here
+LL |
+LL | v.push(format!("foo"));
+ | ^ second mutable borrow occurs here
error: aborting due to previous error
--> $DIR/two-phase-surprise-no-conflict.rs:79:17
|
LL | self.hash_expr(&self.cx_mut.body(eid).value);
- | ^^^^^^^^^^^^^^^^-----------^^^^^^^^^^^^^^^^^
- | | |
- | | immutable borrow occurs here
+ | ^^^^^---------^^-----------^^^^^^^^^^^^^^^^^
+ | | | |
+ | | | immutable borrow occurs here
+ | | immutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:151:51
|
LL | reg.register_static(Box::new(TrivialPass::new(&mut reg.sess_mut)));
- | ----------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- --------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:156:54
|
LL | reg.register_bound(Box::new(TrivialPass::new_mut(&mut reg.sess_mut)));
- | -------------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- -------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:161:53
|
LL | reg.register_univ(Box::new(TrivialPass::new_mut(&mut reg.sess_mut)));
- | ------------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- ------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:166:44
|
LL | reg.register_ref(&TrivialPass::new_mut(&mut reg.sess_mut));
- | ---------------------------------------^^^^^^^^^^^^^^^^^--
- | | |
- | | second mutable borrow occurs here
+ | --- ------------ ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `*reg` as mutable because it is also borrowed as immutable
--> $DIR/two-phase-surprise-no-conflict.rs:178:5
|
LL | reg.register_bound(Box::new(CapturePass::new(®.sess_mut)));
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-------------^^^
- | | |
- | | immutable borrow occurs here
+ | ^^^^--------------^^^^^^^^^^^^^^^^^^^^^^^^^^^-------------^^^
+ | | | |
+ | | | immutable borrow occurs here
+ | | immutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `*reg` as mutable because it is also borrowed as immutable
--> $DIR/two-phase-surprise-no-conflict.rs:183:5
| | immutable borrow occurs here
| mutable borrow occurs here
|
-note: borrowed value must be valid for the lifetime 'a as defined on the function body at 122:21...
+note: immutable borrowed value must be valid for the lifetime 'a as defined on the function body at 122:21...
--> $DIR/two-phase-surprise-no-conflict.rs:122:21
|
LL | fn register_plugins<'a>(mk_reg: impl Fn() -> &'a mut Registry<'a>) {
--> $DIR/two-phase-surprise-no-conflict.rs:188:5
|
LL | reg.register_ref(&CapturePass::new(®.sess_mut));
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-------------^^
- | | |
- | | immutable borrow occurs here
+ | ^^^^------------^^^^^^^^^^^^^^^^^^^-------------^^
+ | | | |
+ | | | immutable borrow occurs here
+ | | immutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `*reg` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:200:5
|
LL | reg.register_bound(Box::new(CapturePass::new_mut(&mut reg.sess_mut)));
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----------------^^^
- | | |
- | | first mutable borrow occurs here
+ | ^^^^--------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----------------^^^
+ | | | |
+ | | | first mutable borrow occurs here
+ | | first borrow later used by call
| second mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:200:54
|
LL | reg.register_bound(Box::new(CapturePass::new_mut(&mut reg.sess_mut)));
- | -------------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- -------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `*reg` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:206:5
| | first mutable borrow occurs here
| second mutable borrow occurs here
|
-note: borrowed value must be valid for the lifetime 'a as defined on the function body at 122:21...
+note: first borrowed value must be valid for the lifetime 'a as defined on the function body at 122:21...
--> $DIR/two-phase-surprise-no-conflict.rs:122:21
|
LL | fn register_plugins<'a>(mk_reg: impl Fn() -> &'a mut Registry<'a>) {
--> $DIR/two-phase-surprise-no-conflict.rs:206:53
|
LL | reg.register_univ(Box::new(CapturePass::new_mut(&mut reg.sess_mut)));
- | ------------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- ------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `*reg` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:212:5
|
LL | reg.register_ref(&CapturePass::new_mut(&mut reg.sess_mut));
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----------------^^
- | | |
- | | first mutable borrow occurs here
+ | ^^^^------------^^^^^^^^^^^^^^^^^^^^^^^-----------------^^
+ | | | |
+ | | | first mutable borrow occurs here
+ | | first borrow later used by call
| second mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:212:44
|
LL | reg.register_ref(&CapturePass::new_mut(&mut reg.sess_mut));
- | ---------------------------------------^^^^^^^^^^^^^^^^^--
- | | |
- | | second mutable borrow occurs here
+ | --- ------------ ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error: aborting due to 15 previous errors
--> $DIR/two-phase-surprise-no-conflict.rs:64:33
|
LL | self.hash_expr(&self.cx.body(eid).value);
- | ----------------^^^^^^^-----------------
- | | |
- | | immutable borrow occurs here
+ | ---- --------- ^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `*self.cx_mut` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-surprise-no-conflict.rs:79:33
|
LL | self.hash_expr(&self.cx_mut.body(eid).value);
- | ----------------^^^^^^^^^^^-----------------
- | | |
- | | immutable borrow occurs here
+ | ---- --------- ^^^^^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `reg.sess_mut` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-surprise-no-conflict.rs:131:51
|
LL | reg.register_static(Box::new(TrivialPass::new(®.sess_mut)));
- | ----------------------------------------------^^^^^^^^^^^^^---
- | | |
- | | immutable borrow occurs here
+ | --- --------------- ^^^^^^^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `reg.sess_mut` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-surprise-no-conflict.rs:135:50
|
LL | reg.register_bound(Box::new(TrivialPass::new(®.sess_mut)));
- | ---------------------------------------------^^^^^^^^^^^^^---
- | | |
- | | immutable borrow occurs here
+ | --- -------------- ^^^^^^^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `reg.sess_mut` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-surprise-no-conflict.rs:139:49
|
LL | reg.register_univ(Box::new(TrivialPass::new(®.sess_mut)));
- | --------------------------------------------^^^^^^^^^^^^^---
- | | |
- | | immutable borrow occurs here
+ | --- ------------- ^^^^^^^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `reg.sess_mut` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-surprise-no-conflict.rs:143:40
|
LL | reg.register_ref(&TrivialPass::new(®.sess_mut));
- | -----------------------------------^^^^^^^^^^^^^--
- | | |
- | | immutable borrow occurs here
+ | --- ------------ ^^^^^^^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:151:51
|
LL | reg.register_static(Box::new(TrivialPass::new(&mut reg.sess_mut)));
- | ----------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- --------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:156:54
|
LL | reg.register_bound(Box::new(TrivialPass::new_mut(&mut reg.sess_mut)));
- | -------------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- -------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:161:53
|
LL | reg.register_univ(Box::new(TrivialPass::new_mut(&mut reg.sess_mut)));
- | ------------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- ------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:166:44
|
LL | reg.register_ref(&TrivialPass::new_mut(&mut reg.sess_mut));
- | ---------------------------------------^^^^^^^^^^^^^^^^^--
- | | |
- | | second mutable borrow occurs here
+ | --- ------------ ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `reg.sess_mut` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-surprise-no-conflict.rs:178:50
|
LL | reg.register_bound(Box::new(CapturePass::new(®.sess_mut)));
- | ---------------------------------------------^^^^^^^^^^^^^---
- | | |
- | | immutable borrow occurs here
+ | --- -------------- ^^^^^^^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `reg.sess_mut` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-surprise-no-conflict.rs:183:49
|
LL | reg.register_univ(Box::new(CapturePass::new(®.sess_mut)));
- | --------------------------------------------^^^^^^^^^^^^^---
- | | |
- | | immutable borrow occurs here
+ | --- ------------- ^^^^^^^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `reg.sess_mut` as immutable because it is also borrowed as mutable
--> $DIR/two-phase-surprise-no-conflict.rs:188:40
|
LL | reg.register_ref(&CapturePass::new(®.sess_mut));
- | -----------------------------------^^^^^^^^^^^^^--
- | | |
- | | immutable borrow occurs here
+ | --- ------------ ^^^^^^^^^^^^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:200:54
|
LL | reg.register_bound(Box::new(CapturePass::new_mut(&mut reg.sess_mut)));
- | -------------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- -------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:206:53
|
LL | reg.register_univ(Box::new(CapturePass::new_mut(&mut reg.sess_mut)));
- | ------------------------------------------------^^^^^^^^^^^^^^^^^---
- | | |
- | | second mutable borrow occurs here
+ | --- ------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time
--> $DIR/two-phase-surprise-no-conflict.rs:212:44
|
LL | reg.register_ref(&CapturePass::new_mut(&mut reg.sess_mut));
- | ---------------------------------------^^^^^^^^^^^^^^^^^--
- | | |
- | | second mutable borrow occurs here
+ | --- ------------ ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error: aborting due to 17 previous errors
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: FromEnv(Self: Foo) :- FromEnv(Self: Bar).
- = note: FromEnv(Self: Foo) :- FromEnv(Self: Bar).
= note: Implemented(Self: Bar) :- FromEnv(Self: Bar).
- = note: WellFormed(Self: Bar) :- Implemented(Self: Bar), WellFormed(Self: Foo), WellFormed(Self: Foo).
+ = note: WellFormed(Self: Bar) :- Implemented(Self: Bar), WellFormed(Self: Foo).
error: program clause dump
--> $DIR/lower_env1.rs:19:1
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: FromEnv(Self: Foo) :- FromEnv(Self: Bar).
- = note: FromEnv(Self: Foo) :- FromEnv(Self: Bar).
= note: Implemented(Self: Bar) :- FromEnv(Self: Bar).
= note: Implemented(Self: Foo) :- FromEnv(Self: Foo).
= note: Implemented(Self: std::marker::Sized) :- FromEnv(Self: std::marker::Sized).
- = note: WellFormed(Self: Bar) :- Implemented(Self: Bar), WellFormed(Self: Foo), WellFormed(Self: Foo).
+ = note: WellFormed(Self: Bar) :- Implemented(Self: Bar), WellFormed(Self: Foo).
= note: WellFormed(Self: Foo) :- Implemented(Self: Foo).
= note: WellFormed(Self: std::marker::Sized) :- Implemented(Self: std::marker::Sized).
| ^^^^^^ second mutable borrow occurs here
LL | z.use_mut();
LL | y.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error: aborting due to previous error
--> $DIR/one_line.rs:13:12
|
LL | v.push(v.pop().unwrap()); //~ ERROR cannot borrow
- | -------^----------------
- | | |
- | | second mutable borrow occurs here
+ | - ---- ^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
| first mutable borrow occurs here
- | borrow later used here
error: aborting due to previous error
| ^ second mutable borrow occurs here
...
LL | drop((y, z));
- | - borrow later used here
+ | - first borrow later used here
error[E0506]: cannot assign to `**x` because it is borrowed
--> $DIR/coerce-overloaded-autoderef.rs:31:5
--> $DIR/coerce-overloaded-autoderef.rs:38:20
|
LL | borrow_mut2(x, x);
- | ---------------^-
- | | | |
- | | | second mutable borrow occurs here
+ | ----------- - ^ second mutable borrow occurs here
+ | | |
| | first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error[E0502]: cannot borrow `*x` as mutable because it is also borrowed as immutable
--> $DIR/coerce-overloaded-autoderef.rs:44:5
|
LL | borrow2(x, x);
- | ^^^^^^^^^^^-^
+ | -------^^^^-^
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
- | borrow later used here
+ | immutable borrow later used by call
error: aborting due to 4 previous errors
| ^ second mutable borrow occurs here
...
LL | drop((y, z));
- | - borrow later used here
+ | - first borrow later used here
error[E0506]: cannot assign to `**x` because it is borrowed
--> $DIR/coerce-overloaded-autoderef.rs:31:5
--> $DIR/coerce-overloaded-autoderef.rs:38:20
|
LL | borrow_mut2(x, x);
- | ---------------^-
- | | | |
- | | | second mutable borrow occurs here
+ | ----------- - ^ second mutable borrow occurs here
+ | | |
| | first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error[E0502]: cannot borrow `*x` as mutable because it is also borrowed as immutable
--> $DIR/coerce-overloaded-autoderef.rs:44:5
|
LL | borrow2(x, x);
- | ^^^^^^^^^^^-^
+ | -------^^^^-^
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
- | borrow later used here
+ | immutable borrow later used by call
error: aborting due to 4 previous errors
| ^ second mutable borrow occurs here
...
LL | drop((y, z));
- | - borrow later used here
+ | - first borrow later used here
error[E0506]: cannot assign to `**x` because it is borrowed
--> $DIR/coerce-overloaded-autoderef.rs:31:5
--> $DIR/coerce-overloaded-autoderef.rs:38:20
|
LL | borrow_mut2(x, x);
- | ---------------^-
- | | | |
- | | | second mutable borrow occurs here
+ | ----------- - ^ second mutable borrow occurs here
+ | | |
| | first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error[E0502]: cannot borrow `*x` as immutable because it is also borrowed as mutable
--> $DIR/coerce-overloaded-autoderef.rs:44:16
|
LL | borrow2(x, x);
- | -----------^-
- | | | |
- | | | immutable borrow occurs here
+ | ------- - ^ immutable borrow occurs here
+ | | |
| | mutable borrow occurs here
- | borrow later used here
+ | mutable borrow later used by call
error: aborting due to 4 previous errors
--> $DIR/issue-34126.rs:16:18
|
LL | self.run(&mut self); //~ ERROR cannot borrow
- | ---------^^^^^^^^^-
- | | |
- | | mutable borrow occurs here
+ | ---- --- ^^^^^^^^^ mutable borrow occurs here
+ | | |
+ | | immutable borrow later used by call
| immutable borrow occurs here
- | borrow later used here
error: aborting due to 2 previous errors
| -
| |
| `c_shortest` dropped here while still borrowed
- | borrow later used here, when `dt` is dropped
+ | borrow might be used here, when `dt` is dropped and runs the `Drop` code for type `other::Dt`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `c_shortest` dropped here while still borrowed
- | borrow later used here, when `dt` is dropped
+ | borrow might be used here, when `dt` is dropped and runs the `Drop` code for type `Dt`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `c_shortest` dropped here while still borrowed
- | borrow later used here, when `dt` is dropped
+ | borrow might be used here, when `dt` is dropped and runs the `Drop` code for type `Dt`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `v` dropped here while still borrowed
- | borrow later used here, when `v` is dropped
+ | borrow might be used here, when `v` is dropped and runs the `Drop` code for type `Wrap`
error: aborting due to previous error
| ^^^^^^ second mutable borrow occurs here
LL | a.use_mut();
LL | x.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error: aborting due to previous error
LL | bar(a); //~ ERROR E0502
| ^^^^^^ mutable borrow occurs here
LL | y.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error: aborting due to previous error
| -
| |
| `y` dropped here while still borrowed
- | borrow later used here, when `x` is dropped
+ | borrow might be used here, when `x` is dropped and runs the `Drop` code for type `Foo`
|
= note: values in a scope are dropped in the opposite order they are defined
mod inner { #![no_mangle="3500"] }
#[no_mangle = "3500"] fn f() { }
- //~^ WARN function is marked #[no_mangle], but not exported
#[no_mangle = "3500"] struct S;
| ^^^^^
warning: macro_escape is a deprecated synonym for macro_use
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:501:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:500:1
|
LL | #[macro_escape]
| ^^^^^^^^^^^^^^^
warning: macro_escape is a deprecated synonym for macro_use
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:504:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:503:17
|
LL | mod inner { #![macro_escape] }
| ^^^^^^^^^^^^^^^^
LL | #[automatically_derived = "3600"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-warning: function is marked #[no_mangle], but not exported
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:395:27
- |
-LL | #[no_mangle = "3500"] fn f() { }
- | -^^^^^^^^^
- | |
- | help: try making it public: `pub`
- |
- = note: #[warn(private_no_mangle_fns)] on by default
-
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:408:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:407:17
|
LL | mod inner { #![no_link="3400"] }
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:411:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:410:5
|
LL | #[no_link = "3400"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:414:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:413:5
|
LL | #[no_link = "3400"] struct S;
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:417:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:416:5
|
LL | #[no_link = "3400"]type T = S;
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:420:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:419:5
|
LL | #[no_link = "3400"] impl S { }
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:405:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:404:1
|
LL | #[no_link = "3400"]
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:427:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:426:17
|
LL | mod inner { #![should_panic="3200"] }
| ^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:430:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:429:5
|
LL | #[should_panic = "3200"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:433:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:432:5
|
LL | #[should_panic = "3200"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:436:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:435:5
|
LL | #[should_panic = "3200"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:439:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:438:5
|
LL | #[should_panic = "3200"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:424:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:423:1
|
LL | #[should_panic = "3200"]
| ^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:446:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:445:17
|
LL | mod inner { #![ignore="3100"] }
| ^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:449:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:448:5
|
LL | #[ignore = "3100"] fn f() { }
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:452:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:451:5
|
LL | #[ignore = "3100"] struct S;
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:455:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:454:5
|
LL | #[ignore = "3100"] type T = S;
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:458:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:457:5
|
LL | #[ignore = "3100"] impl S { }
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:443:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:442:1
|
LL | #[ignore = "3100"]
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:465:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:464:17
|
LL | mod inner { #![no_implicit_prelude="3000"] }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:468:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:467:5
|
LL | #[no_implicit_prelude = "3000"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:471:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:470:5
|
LL | #[no_implicit_prelude = "3000"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:474:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:473:5
|
LL | #[no_implicit_prelude = "3000"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:477:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:476:5
|
LL | #[no_implicit_prelude = "3000"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:462:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:461:1
|
LL | #[no_implicit_prelude = "3000"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:484:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:483:17
|
LL | mod inner { #![reexport_test_harness_main="2900"] }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:487:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:486:5
|
LL | #[reexport_test_harness_main = "2900"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:490:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:489:5
|
LL | #[reexport_test_harness_main = "2900"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:493:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:492:5
|
LL | #[reexport_test_harness_main = "2900"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:496:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:495:5
|
LL | #[reexport_test_harness_main = "2900"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:481:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:480:1
|
LL | #[reexport_test_harness_main = "2900"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:507:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:506:5
|
LL | #[macro_escape] fn f() { }
| ^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:510:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:509:5
|
LL | #[macro_escape] struct S;
| ^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:513:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:512:5
|
LL | #[macro_escape] type T = S;
| ^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:516:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:515:5
|
LL | #[macro_escape] impl S { }
| ^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:524:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:523:17
|
LL | mod inner { #![no_std="2600"] }
| ^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be in the root module
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:524:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:523:17
|
LL | mod inner { #![no_std="2600"] }
| ^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:528:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:527:5
|
LL | #[no_std = "2600"] fn f() { }
| ^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:528:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:527:5
|
LL | #[no_std = "2600"] fn f() { }
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:532:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:531:5
|
LL | #[no_std = "2600"] struct S;
| ^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:532:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:531:5
|
LL | #[no_std = "2600"] struct S;
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:536:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:535:5
|
LL | #[no_std = "2600"] type T = S;
| ^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:536:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:535:5
|
LL | #[no_std = "2600"] type T = S;
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:540:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:539:5
|
LL | #[no_std = "2600"] impl S { }
| ^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:540:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:539:5
|
LL | #[no_std = "2600"] impl S { }
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:520:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:519:1
|
LL | #[no_std = "2600"]
| ^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:520:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:519:1
|
LL | #[no_std = "2600"]
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:679:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:678:17
|
LL | mod inner { #![crate_name="0900"] }
| ^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be in the root module
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:679:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:678:17
|
LL | mod inner { #![crate_name="0900"] }
| ^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:683:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:682:5
|
LL | #[crate_name = "0900"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:683:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:682:5
|
LL | #[crate_name = "0900"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:687:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:686:5
|
LL | #[crate_name = "0900"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:687:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:686:5
|
LL | #[crate_name = "0900"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:691:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:690:5
|
LL | #[crate_name = "0900"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:691:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:690:5
|
LL | #[crate_name = "0900"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:695:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:694:5
|
LL | #[crate_name = "0900"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:695:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:694:5
|
LL | #[crate_name = "0900"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:675:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:674:1
|
LL | #[crate_name = "0900"]
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:675:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:674:1
|
LL | #[crate_name = "0900"]
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:704:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:703:17
|
LL | mod inner { #![crate_type="0800"] }
| ^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be in the root module
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:704:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:703:17
|
LL | mod inner { #![crate_type="0800"] }
| ^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:708:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:707:5
|
LL | #[crate_type = "0800"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:708:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:707:5
|
LL | #[crate_type = "0800"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:712:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:711:5
|
LL | #[crate_type = "0800"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:712:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:711:5
|
LL | #[crate_type = "0800"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:716:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:715:5
|
LL | #[crate_type = "0800"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:716:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:715:5
|
LL | #[crate_type = "0800"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:720:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:719:5
|
LL | #[crate_type = "0800"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:720:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:719:5
|
LL | #[crate_type = "0800"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:700:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:699:1
|
LL | #[crate_type = "0800"]
| ^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:700:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:699:1
|
LL | #[crate_type = "0800"]
| ^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:729:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:728:17
|
LL | mod inner { #![feature(x0600)] }
| ^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be in the root module
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:729:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:728:17
|
LL | mod inner { #![feature(x0600)] }
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:733:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:732:5
|
LL | #[feature(x0600)] fn f() { }
| ^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:733:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:732:5
|
LL | #[feature(x0600)] fn f() { }
| ^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:737:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:736:5
|
LL | #[feature(x0600)] struct S;
| ^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:737:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:736:5
|
LL | #[feature(x0600)] struct S;
| ^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:741:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:740:5
|
LL | #[feature(x0600)] type T = S;
| ^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:741:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:740:5
|
LL | #[feature(x0600)] type T = S;
| ^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:745:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:744:5
|
LL | #[feature(x0600)] impl S { }
| ^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:745:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:744:5
|
LL | #[feature(x0600)] impl S { }
| ^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:725:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:724:1
|
LL | #[feature(x0600)]
| ^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:725:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:724:1
|
LL | #[feature(x0600)]
| ^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:755:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:754:17
|
LL | mod inner { #![no_main="0400"] }
| ^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be in the root module
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:755:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:754:17
|
LL | mod inner { #![no_main="0400"] }
| ^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:759:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:758:5
|
LL | #[no_main = "0400"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:759:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:758:5
|
LL | #[no_main = "0400"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:763:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:762:5
|
LL | #[no_main = "0400"] struct S;
| ^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:763:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:762:5
|
LL | #[no_main = "0400"] struct S;
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:767:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:766:5
|
LL | #[no_main = "0400"] type T = S;
| ^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:767:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:766:5
|
LL | #[no_main = "0400"] type T = S;
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:771:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:770:5
|
LL | #[no_main = "0400"] impl S { }
| ^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:771:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:770:5
|
LL | #[no_main = "0400"] impl S { }
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:751:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:750:1
|
LL | #[no_main = "0400"]
| ^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:751:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:750:1
|
LL | #[no_main = "0400"]
| ^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:793:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:792:17
|
LL | mod inner { #![recursion_limit="0200"] }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be in the root module
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:793:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:792:17
|
LL | mod inner { #![recursion_limit="0200"] }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:797:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:796:5
|
LL | #[recursion_limit="0200"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:797:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:796:5
|
LL | #[recursion_limit="0200"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:801:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:800:5
|
LL | #[recursion_limit="0200"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:801:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:800:5
|
LL | #[recursion_limit="0200"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:805:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:804:5
|
LL | #[recursion_limit="0200"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:805:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:804:5
|
LL | #[recursion_limit="0200"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:809:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:808:5
|
LL | #[recursion_limit="0200"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:809:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:808:5
|
LL | #[recursion_limit="0200"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:789:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:788:1
|
LL | #[recursion_limit="0200"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:789:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:788:1
|
LL | #[recursion_limit="0200"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:818:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:817:17
|
LL | mod inner { #![type_length_limit="0100"] }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be in the root module
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:818:17
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:817:17
|
LL | mod inner { #![type_length_limit="0100"] }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:822:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:821:5
|
LL | #[type_length_limit="0100"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:822:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:821:5
|
LL | #[type_length_limit="0100"] fn f() { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:826:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:825:5
|
LL | #[type_length_limit="0100"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:826:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:825:5
|
LL | #[type_length_limit="0100"] struct S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:830:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:829:5
|
LL | #[type_length_limit="0100"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:830:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:829:5
|
LL | #[type_length_limit="0100"] type T = S;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:834:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:833:5
|
LL | #[type_length_limit="0100"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:834:5
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:833:5
|
LL | #[type_length_limit="0100"] impl S { }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused attribute
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:814:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:813:1
|
LL | #[type_length_limit="0100"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: crate-level attribute should be an inner attribute: add an exclamation mark: #![foo]
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:814:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:813:1
|
LL | #[type_length_limit="0100"]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: compilation successful
- --> $DIR/issue-43106-gating-of-builtin-attrs.rs:845:1
+ --> $DIR/issue-43106-gating-of-builtin-attrs.rs:844:1
|
LL | / fn main() { //~ ERROR compilation successful
LL | | println!("Hello World");
--> $DIR/borrowing.rs:18:18
|
LL | unsafe { (|| yield &a).resume() }
- | ^^^^^^^^^^^^^ borrowed value does not live long enough
+ | ^^^^^^^^^^^^^
+ | |
+ | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
LL | //~^ ERROR: `a` does not live long enough
LL | };
- | - `a` dropped here while still borrowed
+ | -- ... and the borrow might be used here, when that temporary is dropped and runs the destructor for generator
+ | |
+ | `a` dropped here while still borrowed
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.
error[E0597]: `a` does not live long enough
--> $DIR/borrowing.rs:24:9
| -
| |
| `*cell` dropped here while still borrowed
- | borrow later used here, when `gen` is dropped
+ | borrow might be used here, when `gen` is dropped and runs the destructor for generator
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `ref_` dropped here while still borrowed
- | borrow later used here, when `gen` is dropped
+ | borrow might be used here, when `gen` is dropped and runs the destructor for generator
|
= note: values in a scope are dropped in the opposite order they are defined
LL | println!("{}", x[0]); //~ ERROR
| ^ immutable borrow occurs here
LL | b.resume();
- | - borrow later used here
+ | - mutable borrow later used here
error: aborting due to 2 previous errors
LL | println!("{}", x); //~ ERROR
| ^ borrow occurs here
LL | b.resume();
- | - borrow later used here
+ | - first borrow later used here
error: aborting due to previous error
| ^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL |
LL | println!("{}", *thing);
- | ------ borrow later used here
+ | ------ immutable borrow later used here
error: aborting due to previous error
LL | my_stuff.insert(1, 43); //~ ERROR cannot borrow
| ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL | it;
- | -- borrow later used here
+ | -- immutable borrow later used here
error: aborting due to previous error
| ^^^
| |
| second mutable borrow occurs here
- | borrow later used here
+ | first borrow later used here
error: aborting due to previous error
| ^^^^^^^^^^^^^^^ second mutable borrow occurs here
...
LL | borrow1.use_mut();
- | ------- borrow later used here
+ | ------- first borrow later used here
error: aborting due to previous error
"##);
//~^^^ ERROR: there is no argument named `foo`
+
+ // bad syntax in format string with multiple newlines, #53836
+ format!("first number: {}
+second number: {}
+third number: {}
+fourth number: {}
+fifth number: {}
+sixth number: {}
+seventh number: {}
+eighth number: {}
+ninth number: {
+tenth number: {}",
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ //~^^ ERROR: invalid format string
}
LL | {foo}
| ^^^^^
-error: aborting due to 27 previous errors
+error: invalid format string: expected `'}'`, found `'t'`
+ --> $DIR/ifmt-bad-arg.rs:85:1
+ |
+LL | tenth number: {}",
+ | ^ expected `}` in format string
+
+error: aborting due to 28 previous errors
--- /dev/null
+// compile-pass
+
+#![deny(warnings)]
+
+#[deprecated]
+trait Deprecated {}
+
+#[deprecated]
+struct DeprecatedTy;
+
+#[allow(deprecated)]
+impl Deprecated for DeprecatedTy {}
+
+#[allow(deprecated)]
+fn foo() -> impl Deprecated { DeprecatedTy }
+
+fn main() {
+ foo();
+}
-error[E0659]: `panic` is ambiguous
- --> $DIR/shadow_builtin_macros.rs:43:5
- |
-LL | panic!(); //~ ERROR `panic` is ambiguous
- | ^^^^^ ambiguous name
- |
-note: `panic` could refer to the name defined here
- --> $DIR/shadow_builtin_macros.rs:40:9
- |
-LL | macro_rules! panic { () => {} }
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-LL | } }
-LL | m!();
- | ----- in this macro invocation
- = note: `panic` is also a builtin macro
- = note: macro-expanded macros do not shadow
-
error[E0659]: `panic` is ambiguous
--> $DIR/shadow_builtin_macros.rs:25:14
|
= note: `panic` is also a builtin macro
= note: macro-expanded macro imports do not shadow
+error[E0659]: `panic` is ambiguous
+ --> $DIR/shadow_builtin_macros.rs:43:5
+ |
+LL | panic!(); //~ ERROR `panic` is ambiguous
+ | ^^^^^ ambiguous name
+ |
+note: `panic` could refer to the name defined here
+ --> $DIR/shadow_builtin_macros.rs:40:9
+ |
+LL | macro_rules! panic { () => {} }
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+LL | } }
+LL | m!();
+ | ----- in this macro invocation
+ = note: `panic` is also a builtin macro
+ = note: macro-expanded macros do not shadow
+
error[E0659]: `n` is ambiguous
--> $DIR/shadow_builtin_macros.rs:59:5
|
| --- first borrow occurs due to use of `ptr` in closure
...
LL | test(&*ptr);
- | -----^^^^^-
- | | |
- | | immutable borrow occurs here
- | borrow later used here
+ | ---- ^^^^^ immutable borrow occurs here
+ | |
+ | mutable borrow later used by call
error: aborting due to previous error
-error[E0308]: mismatched types
- --> $DIR/issue-13058.rs:36:11
+error[E0621]: explicit lifetime required in the type of `cont`
+ --> $DIR/issue-13058.rs:24:21
|
-LL | check((3, 5));
- | ^^^^^^
- | |
- | expected reference, found tuple
- | help: consider borrowing here: `&(3, 5)`
- |
- = note: expected type `&_`
- found type `({integer}, {integer})`
+LL | fn check<'r, I: Iterator<Item=usize>, T: Itble<'r, usize, I>>(cont: &T) -> bool
+ | -- help: add explicit lifetime `'r` to the type of `cont`: `&'r T`
+LL | {
+LL | let cont_iter = cont.iter();
+ | ^^^^^^^^^^^ lifetime `'r` required
error: aborting due to previous error
-For more information about this error, try `rustc --explain E0308`.
+For more information about this error, try `rustc --explain E0621`.
}
fn main() {
- check((3, 5));
-//~^ ERROR mismatched types
+ check(&(3, 5));
}
LL | let cont_iter = cont.iter();
| ^^^^ lifetime `'r` required
-error[E0308]: mismatched types
- --> $DIR/issue-13058.rs:36:11
- |
-LL | check((3, 5));
- | ^^^^^^
- | |
- | expected reference, found tuple
- | help: consider borrowing here: `&(3, 5)`
- |
- = note: expected type `&_`
- found type `({integer}, {integer})`
-
-error: aborting due to 2 previous errors
+error: aborting due to previous error
-Some errors occurred: E0308, E0621.
-For more information about an error, try `rustc --explain E0308`.
+For more information about this error, try `rustc --explain E0621`.
--> $DIR/issue-18566.rs:33:19
|
LL | MyPtr(s).poke(s);
- | --------------^-
- | | | |
- | | | second mutable borrow occurs here
- | | first mutable borrow occurs here
- | borrow later used here
+ | - ---- ^ second mutable borrow occurs here
+ | | |
+ | | first borrow later used by call
+ | first mutable borrow occurs here
error: aborting due to previous error
| second mutable borrow occurs here
LL | //~^ ERROR cannot borrow `y` as mutable more than once at a time
LL | }
- | - borrow later used here, when `c` is dropped
+ | - first borrow might be used here, when `c` is dropped and runs the destructor for type `std::cell::RefCell<std::vec::Vec<std::boxed::Box<dyn std::ops::FnMut()>>>`
error[E0499]: cannot borrow `y` as mutable more than once at a time
--> $DIR/issue-18783.rs:26:29
| second mutable borrow occurs here
LL | //~^ ERROR cannot borrow `y` as mutable more than once at a time
LL | }
- | - borrow later used here, when `c` is dropped
+ | - first borrow might be used here, when `c` is dropped and runs the destructor for type `std::cell::RefCell<std::vec::Vec<std::boxed::Box<dyn std::ops::FnMut()>>>`
error: aborting due to 2 previous errors
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+//
+// compile-pass
+
+trait DictLike<'a> {
+ type ItemsIterator: Iterator<Item=u8>;
+ fn get(c: Self::ItemsIterator) {
+ c.into_iter();
+ }
+}
+
+trait DictLike2<'a> {
+ type ItemsIterator: Iterator<Item=u8>;
+
+ fn items(&self) -> Self::ItemsIterator;
+
+ fn get(&self) {
+ for _ in self.items() {}
+ }
+}
+
+fn main() {}
LL | let r = &mut *self;
| ---------- borrow of `*self` occurs here
LL | r.get_size(width!(self))
- | ------------------------
- | | |
- | | in this macro invocation
- | borrow later used here
+ | -------- ------------ in this macro invocation
+ | |
+ | borrow later used by call
error: aborting due to previous error
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+// compile-flags: --test
+
+#![test] //~ ERROR only functions may be used as tests
--- /dev/null
+error: only functions may be used as tests
+ --> $DIR/issue-28134.rs:13:1
+ |
+LL | #![test] //~ ERROR only functions may be used as tests
+ | ^^^^^^^^
+
+error: aborting due to previous error
+
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+//
+// compile-pass
+
+fn main() {
+ let mut i = [1, 2, 3];
+ i[i[0]] = 0;
+ i[i[0] - 1] = 0;
+}
LL | collection.swap(1, 2); //~ ERROR also borrowed as immutable
| ^^^^^^^^^^ mutable borrow occurs here
LL | _a.use_ref();
- | -- borrow later used here
+ | -- immutable borrow later used here
error: aborting due to previous error
| ^^^^^^ immutable borrow occurs here
LL | //~^ ERROR cannot borrow `u.z.c` as immutable because it is also borrowed as mutable [E0502]
LL | println!("{} {}", mref, nref)
- | ---- borrow later used here
+ | ---- mutable borrow later used here
error: aborting due to previous error
|
LL | let borrow = heap.peek_mut();
| ---- mutable borrow occurs here
-...
+LL |
+LL | match (borrow, ()) {
+ | ------------ a temporary with access to the mutable borrow is created here ...
+LL | (Some(_), ()) => {
LL | println!("{:?}", heap); //~ ERROR cannot borrow `heap` as immutable
| ^^^^ immutable borrow occurs here
+...
+LL | };
+ | - ... and the mutable borrow might be used here, when that temporary is dropped and runs the destructor for type `(std::option::Option<std::collections::binary_heap::PeekMut<'_, i32>>, ())`
error: aborting due to previous error
// compile-flags:-F private_no_mangle_fns -F no_mangle_const_items -F private_no_mangle_statics
#[no_mangle]
-fn foo() { //~ ERROR function is marked #[no_mangle], but not exported
+fn foo() {
}
#[allow(dead_code)]
#[allow(dead_code)]
#[no_mangle]
-static PRIVATE_BAR: u64 = 1; //~ ERROR static is marked #[no_mangle], but not exported
+static PRIVATE_BAR: u64 = 1;
fn main() {
-error: function is marked #[no_mangle], but not exported
- --> $DIR/lint-unexported-no-mangle.rs:14:1
+warning: lint `private_no_mangle_fns` has been removed: `no longer an warning, #[no_mangle] functions always exported`
|
-LL | fn foo() { //~ ERROR function is marked #[no_mangle], but not exported
- | ^
- | |
- | _help: try making it public: `pub`
- | |
-LL | | }
- | |_^
+ = note: requested on the command line with `-F private_no_mangle_fns`
+
+warning: lint `private_no_mangle_statics` has been removed: `no longer an warning, #[no_mangle] statics always exported`
|
- = note: requested on the command line with `-F private-no-mangle-fns`
+ = note: requested on the command line with `-F private_no_mangle_statics`
error: const items should never be #[no_mangle]
--> $DIR/lint-unexported-no-mangle.rs:19:1
| |
| help: try a static value: `pub static`
-error: static is marked #[no_mangle], but not exported
- --> $DIR/lint-unexported-no-mangle.rs:33:1
- |
-LL | static PRIVATE_BAR: u64 = 1; //~ ERROR static is marked #[no_mangle], but not exported
- | -^^^^^^^^^^^^^^^^^^^^^^^^^^^
- | |
- | help: try making it public: `pub`
- |
- = note: requested on the command line with `-F private-no-mangle-statics`
-
-error: aborting due to 4 previous errors
+error: aborting due to 2 previous errors
#![warn(unused_mut, unused_parens)] // UI tests pass `-A unused`—see Issue #43896
#![feature(no_debug)]
-#[no_mangle] static SHENZHOU: usize = 1;
-//~^ WARN static is marked #[no_mangle]
-//~| HELP try making it public
#[no_mangle] const DISCOVERY: usize = 1;
//~^ ERROR const items should never be #[no_mangle]
//~| HELP try a static value
#[no_mangle]
fn rio_grande() {}
-//~^ WARN function is marked
-//~| HELP try making it public
mod badlands {
// The private-no-mangle lints shouldn't suggest inserting `pub` when the
// item is already `pub` (but triggered the lint because, e.g., it's in a
// private module). (Issue #47383)
- #[no_mangle] pub static DAUNTLESS: bool = true;
- //~^ WARN static is marked
- //~| HELP try exporting the item with a `pub use` statement
- #[no_mangle] pub fn val_jean() {}
- //~^ WARN function is marked
- //~| HELP try exporting the item with a `pub use` statement
+ #[no_mangle] pub const DAUNTLESS: bool = true;
+ //~^ ERROR const items should never be #[no_mangle]
+ //~| HELP try a static value
+ #[no_mangle] pub fn val_jean<T>() {}
+ //~^ WARN functions generic over types must be mangled
+ //~| HELP remove this attribute
// ... but we can suggest just-`pub` instead of restricted
- #[no_mangle] pub(crate) static VETAR: bool = true;
- //~^ WARN static is marked
- //~| HELP try making it public
- #[no_mangle] pub(crate) fn crossfield() {}
- //~^ WARN function is marked
- //~| HELP try making it public
+ #[no_mangle] pub(crate) const VETAR: bool = true;
+ //~^ ERROR const items should never be #[no_mangle]
+ //~| HELP try a static value
+ #[no_mangle] pub(crate) fn crossfield<T>() {}
+ //~^ WARN functions generic over types must be mangled
+ //~| HELP remove this attribute
}
struct Equinox {
warning: unnecessary parentheses around assigned value
- --> $DIR/suggestions.rs:64:21
+ --> $DIR/suggestions.rs:59:21
|
LL | let mut a = (1);
| ^^^ help: remove these parentheses
| ^^^^^^^^^^^^^
warning: use of deprecated attribute `no_debug`: the `#[no_debug]` attribute was an experimental feature that has been deprecated due to lack of demand. See https://github.com/rust-lang/rust/issues/29721
- --> $DIR/suggestions.rs:57:1
+ --> $DIR/suggestions.rs:52:1
|
LL | #[no_debug] // should suggest removal of deprecated attribute
| ^^^^^^^^^^^ help: remove this attribute
= note: #[warn(deprecated)] on by default
warning: variable does not need to be mutable
- --> $DIR/suggestions.rs:64:13
+ --> $DIR/suggestions.rs:59:13
|
LL | let mut a = (1);
| ----^
| ^^^^^^^^^^
warning: variable does not need to be mutable
- --> $DIR/suggestions.rs:70:13
+ --> $DIR/suggestions.rs:65:13
|
LL | let mut
| _____________^
| |____________|
| help: remove this `mut`
-warning: static is marked #[no_mangle], but not exported
- --> $DIR/suggestions.rs:16:14
- |
-LL | #[no_mangle] static SHENZHOU: usize = 1;
- | -^^^^^^^^^^^^^^^^^^^^^^^^^^
- | |
- | help: try making it public: `pub`
- |
- = note: #[warn(private_no_mangle_statics)] on by default
-
error: const items should never be #[no_mangle]
- --> $DIR/suggestions.rs:19:14
+ --> $DIR/suggestions.rs:16:14
|
LL | #[no_mangle] const DISCOVERY: usize = 1;
| -----^^^^^^^^^^^^^^^^^^^^^^
= note: #[deny(no_mangle_const_items)] on by default
warning: functions generic over types must be mangled
- --> $DIR/suggestions.rs:25:1
+ --> $DIR/suggestions.rs:22:1
|
LL | #[no_mangle]
| ------------ help: remove this attribute
|
= note: #[warn(no_mangle_generic_items)] on by default
-warning: function is marked #[no_mangle], but not exported
- --> $DIR/suggestions.rs:29:1
- |
-LL | fn rio_grande() {}
- | -^^^^^^^^^^^^^^^^^
- | |
- | help: try making it public: `pub`
+error: const items should never be #[no_mangle]
+ --> $DIR/suggestions.rs:32:18
|
- = note: #[warn(private_no_mangle_fns)] on by default
+LL | #[no_mangle] pub const DAUNTLESS: bool = true;
+ | ---------^^^^^^^^^^^^^^^^^^^^^^^^
+ | |
+ | help: try a static value: `pub static`
-warning: static is marked #[no_mangle], but not exported
- --> $DIR/suggestions.rs:37:18
- |
-LL | #[no_mangle] pub static DAUNTLESS: bool = true;
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+warning: functions generic over types must be mangled
+ --> $DIR/suggestions.rs:35:18
|
- = help: try exporting the item with a `pub use` statement
+LL | #[no_mangle] pub fn val_jean<T>() {}
+ | ------------ ^^^^^^^^^^^^^^^^^^^^^^^
+ | |
+ | help: remove this attribute
-warning: function is marked #[no_mangle], but not exported
+error: const items should never be #[no_mangle]
--> $DIR/suggestions.rs:40:18
|
-LL | #[no_mangle] pub fn val_jean() {}
- | ^^^^^^^^^^^^^^^^^^^^
- |
- = help: try exporting the item with a `pub use` statement
-
-warning: static is marked #[no_mangle], but not exported
- --> $DIR/suggestions.rs:45:18
- |
-LL | #[no_mangle] pub(crate) static VETAR: bool = true;
- | ----------^^^^^^^^^^^^^^^^^^^^^^^^^^^
+LL | #[no_mangle] pub(crate) const VETAR: bool = true;
+ | ----------------^^^^^^^^^^^^^^^^^^^^
| |
- | help: try making it public: `pub`
+ | help: try a static value: `pub static`
-warning: function is marked #[no_mangle], but not exported
- --> $DIR/suggestions.rs:48:18
+warning: functions generic over types must be mangled
+ --> $DIR/suggestions.rs:43:18
|
-LL | #[no_mangle] pub(crate) fn crossfield() {}
- | ----------^^^^^^^^^^^^^^^^^^^
- | |
- | help: try making it public: `pub`
+LL | #[no_mangle] pub(crate) fn crossfield<T>() {}
+ | ------------ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ | |
+ | help: remove this attribute
warning: denote infinite loops with `loop { ... }`
- --> $DIR/suggestions.rs:61:5
+ --> $DIR/suggestions.rs:56:5
|
LL | while true {
| ^^^^^^^^^^ help: use `loop`
= note: #[warn(while_true)] on by default
warning: the `warp_factor:` in this pattern is redundant
- --> $DIR/suggestions.rs:76:23
+ --> $DIR/suggestions.rs:71:23
|
LL | Equinox { warp_factor: warp_factor } => {}
| ------------^^^^^^^^^^^^
|
= note: #[warn(non_shorthand_field_patterns)] on by default
-error: aborting due to previous error
+error: aborting due to 3 previous errors
--- /dev/null
+#![feature(macros_in_extern)]
+
+macro_rules! m {
+ () => {
+ let //~ ERROR expected
+ };
+}
+
+extern "C" {
+ m!();
+}
+
+fn main() {}
--- /dev/null
+error: expected one of `crate`, `fn`, `pub`, `static`, or `type`, found `let`
+ --> $DIR/issue-54441.rs:5:9
+ |
+LL | #![feature(macros_in_extern)]
+ | - expected one of `crate`, `fn`, `pub`, `static`, or `type` here
+...
+LL | let //~ ERROR expected
+ | ^^^ unexpected token
+...
+LL | m!();
+ | ----- in this macro invocation
+
+error: aborting due to previous error
+
LL | Foo::bar(&x); //~ERROR cannot borrow `x`
| ^^ immutable borrow occurs here
LL | y.use_mut();
- | - borrow later used here
+ | - mutable borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/method-self-arg-2.rs:30:14
LL | Foo::baz(&mut x); //~ERROR cannot borrow `x`
| ^^^^^^ second mutable borrow occurs here
LL | y.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error: aborting due to 2 previous errors
--> $DIR/moves-based-on-type-no-recursive-stack-closure.rs:30:27
|
LL | (f.c)(f, true);
- | ------^-------
- | | |
- | | second mutable borrow occurs here
+ | ----- ^ second mutable borrow occurs here
+ | |
| first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error[E0382]: borrow of moved value: `f`
--> $DIR/moves-based-on-type-no-recursive-stack-closure.rs:42:5
LL | let b2 = &mut *b; //~ ERROR cannot borrow
| ^ second mutable borrow occurs here
LL | b1.use_mut();
- | -- borrow later used here
+ | -- first borrow later used here
error: aborting due to previous error
--- /dev/null
+// run-pass
+
+#![deny(unused_mut)]
+#![allow(unreachable_code)]
+
+fn main() {
+ for _ in { return (); 0..3 } {} // ok
+}
error[E0597]: `v` does not live long enough
--> $DIR/borrowed-local-error.rs:20:9
|
-LL | let x = gimme({
- | _____________-
-LL | | let v = (22,);
-LL | | &v
- | | ^^ borrowed value does not live long enough
-LL | | //~^ ERROR `v` does not live long enough [E0597]
-LL | | });
- | |_____-- borrow later used here
- | |
- | `v` dropped here while still borrowed
+LL | let x = gimme({
+ | ----- borrow later used by call
+LL | let v = (22,);
+LL | &v
+ | ^^ borrowed value does not live long enough
+LL | //~^ ERROR `v` does not live long enough [E0597]
+LL | });
+ | - `v` dropped here while still borrowed
error: aborting due to previous error
| ^^^^^^^^^^^^^^^ immutable borrow occurs here
LL | //~^ ERROR cannot borrow `*block.current` as immutable because it is also borrowed as mutable
LL | drop(x);
- | - borrow later used here
+ | - mutable borrow later used here
error: aborting due to previous error
| |
| immutable borrow occurs here
LL | r.use_mut();
- | - borrow later used here
+ | - mutable borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/closure-access-spans.rs:23:5
| |
| second mutable borrow occurs here
LL | r.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error[E0500]: closure requires unique access to `x` but it is already borrowed
--> $DIR/closure-access-spans.rs:29:5
| |
| closure construction occurs here
LL | r.use_mut();
- | - borrow later used here
+ | - first borrow later used here
error[E0503]: cannot use `x` because it was mutably borrowed
--> $DIR/closure-access-spans.rs:35:13
LL | let y = &mut x; //~ ERROR
| ^^^^^^ mutable borrow occurs here
LL | f.use_ref();
- | - borrow later used here
+ | - immutable borrow later used here
error[E0597]: `x` does not live long enough
--> $DIR/closure-borrow-spans.rs:31:16
LL | let y = &x; //~ ERROR
| ^^ immutable borrow occurs here
LL | f.use_ref();
- | - borrow later used here
+ | - mutable borrow later used here
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> $DIR/closure-borrow-spans.rs:56:13
LL | let y = &mut x; //~ ERROR
| ^^^^^^ second mutable borrow occurs here
LL | f.use_ref();
- | - borrow later used here
+ | - first borrow later used here
error[E0597]: `x` does not live long enough
--> $DIR/closure-borrow-spans.rs:64:16
LL | let y = &x; //~ ERROR
| ^^ borrow occurs here
LL | f.use_ref();
- | - borrow later used here
+ | - first borrow later used here
error[E0501]: cannot borrow `x` as mutable because previous closure requires unique access
--> $DIR/closure-borrow-spans.rs:89:13
LL | let y = &mut x; //~ ERROR
| ^^^^^^ borrow occurs here
LL | f.use_ref();
- | - borrow later used here
+ | - first borrow later used here
error[E0597]: `x` does not live long enough
--> $DIR/closure-borrow-spans.rs:98:17
| ^^^^^^^^^ assignment to borrowed `v[..]` occurs here
...
LL | }
- | - borrow later used here, when `p` is dropped
+ | - borrow might be used here, when `p` is dropped and runs the `Drop` code for type `WrapMayNotDangle`
error[E0506]: cannot assign to `v[..]` because it is borrowed
--> $DIR/drop-no-may-dangle.rs:33:5
LL | v[0] += 1; //~ ERROR cannot assign to `v[..]` because it is borrowed
| ^^^^^^^^^ assignment to borrowed `v[..]` occurs here
LL | }
- | - borrow later used here, when `p` is dropped
+ | - borrow might be used here, when `p` is dropped and runs the `Drop` code for type `WrapMayNotDangle`
error: aborting due to 2 previous errors
LL | map.set(String::new()); // Ideally, this would not error.
| ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
|
-note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 26:1...
+note: immutable borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 26:1...
--> $DIR/get_default.rs:26:1
|
LL | / fn ok(map: &mut Map) -> &String {
LL | map.set(String::new()); // Both AST and MIR error here
| ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
|
-note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 41:1...
+note: immutable borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 41:1...
--> $DIR/get_default.rs:41:1
|
LL | / fn err(map: &mut Map) -> &String {
LL | map.set(String::new()); // Ideally, just AST would error here
| ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
|
-note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 41:1...
+note: immutable borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 41:1...
--> $DIR/get_default.rs:41:1
|
LL | / fn err(map: &mut Map) -> &String {
LL | map.set(String::new()); // Ideally, this would not error.
| ^^^ mutable borrow occurs here
|
-note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 26:1...
+note: immutable borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 26:1...
--> $DIR/get_default.rs:26:1
|
LL | / fn ok(map: &mut Map) -> &String {
LL | map.set(String::new()); // Both AST and MIR error here
| ^^^ mutable borrow occurs here
|
-note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 41:1...
+note: immutable borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 41:1...
--> $DIR/get_default.rs:41:1
|
LL | / fn err(map: &mut Map) -> &String {
LL | map.set(String::new()); // Ideally, just AST would error here
| ^^^ mutable borrow occurs here
|
-note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 41:1...
+note: immutable borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 41:1...
--> $DIR/get_default.rs:41:1
|
LL | / fn err(map: &mut Map) -> &String {
--- /dev/null
+// (this works, but only in NLL)
+// compile-pass
+#![feature(nll)]
+
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+fn i_used_to_be_able_to(foo: &Mutex<HashMap<usize, usize>>) -> Vec<(usize, usize)> {
+ let mut foo = foo.lock().unwrap();
+
+ foo.drain().collect()
+}
+
+fn but_after_nightly_update_now_i_gotta(foo: &Mutex<HashMap<usize, usize>>) -> Vec<(usize, usize)> {
+ let mut foo = foo.lock().unwrap();
+
+ return foo.drain().collect();
+}
+
+fn main() {}
--- /dev/null
+// (this works, but only in NLL)
+// compile-pass
+#![feature(nll)]
+
+fn from_stdin(min: u64) -> Vec<u64> {
+ use std::io::BufRead;
+
+ let stdin = std::io::stdin();
+ let stdin = stdin.lock();
+
+ stdin.lines()
+ .map(Result::unwrap)
+ .map(|val| val.parse())
+ .map(Result::unwrap)
+ .filter(|val| *val >= min)
+ .collect()
+}
+
+fn main() {}
--- /dev/null
+#![feature(nll)]
+// compile-pass
+
+// rust-lang/rust#32382: Borrow checker used to complain about
+// `foobar_3` in the `impl` below, presumably due to some interaction
+// between the use of a lifetime in the associated type and the use of
+// the overloaded operator[]. This regression test ensures that we do
+// not resume complaining about it in the future.
+
+
+use std::marker::PhantomData;
+use std::ops::Index;
+
+pub trait Context: Clone {
+ type Container: ?Sized;
+ fn foobar_1( container: &Self::Container ) -> &str;
+ fn foobar_2( container: &Self::Container ) -> &str;
+ fn foobar_3( container: &Self::Container ) -> &str;
+}
+
+#[derive(Clone)]
+struct Foobar<'a> {
+ phantom: PhantomData<&'a ()>
+}
+
+impl<'a> Context for Foobar<'a> {
+ type Container = [&'a str];
+
+ fn foobar_1<'r>( container: &'r [&'a str] ) -> &'r str {
+ container[0]
+ }
+
+ fn foobar_2<'r>( container: &'r Self::Container ) -> &'r str {
+ container.index( 0 )
+ }
+
+ fn foobar_3<'r>( container: &'r Self::Container ) -> &'r str {
+ container[0]
+ }
+}
+
+fn main() { }
error[E0502]: cannot borrow `self.thing` as mutable because it is also borrowed as immutable
--> $DIR/issue-51268.rs:28:9
|
-LL | self.thing.bar(|| {
- | ^ -- immutable borrow occurs here
- | _________|
- | |_________|
- | ||
-LL | || //~^ ERROR cannot borrow `self.thing` as mutable because it is also borrowed as immutable [E0502]
-LL | || &self.number;
- | || ---- first borrow occurs due to use of `self` in closure
-LL | || });
- | || ^
- | ||__________|
- | |___________mutable borrow occurs here
- | borrow later used here
+LL | self.thing.bar(|| {
+ | ^ --- -- immutable borrow occurs here
+ | | |
+ | _________| immutable borrow later used by call
+ | |
+LL | | //~^ ERROR cannot borrow `self.thing` as mutable because it is also borrowed as immutable [E0502]
+LL | | &self.number;
+ | | ---- first borrow occurs due to use of `self` in closure
+LL | | });
+ | |__________^ mutable borrow occurs here
error: aborting due to previous error
--- /dev/null
+// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![feature(nll)]
+
+use std::rc::Rc;
+use std::sync::Arc;
+
+struct Bar { field: Vec<i32> }
+
+fn main() {
+ let x = Rc::new(Bar { field: vec![] });
+ drop(x.field);
+
+ let y = Arc::new(Bar { field: vec![] });
+ drop(y.field);
+}
--- /dev/null
+error[E0507]: cannot move out of an `Rc`
+ --> $DIR/issue-52086.rs:20:10
+ |
+LL | drop(x.field);
+ | ^^^^^^^ cannot move out of an `Rc`
+
+error[E0507]: cannot move out of an `Arc`
+ --> $DIR/issue-52086.rs:23:10
+ |
+LL | drop(y.field);
+ | ^^^^^^^ cannot move out of an `Arc`
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0507`.
--- /dev/null
+error[E0597]: `counter` does not live long enough
+ --> $DIR/issue-54556-niconii.rs:22:20
+ |
+LL | if let Ok(_) = counter.lock() { }
+ | ^^^^^^^-------
+ | |
+ | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+...
+LL | }
+ | -
+ | |
+ | `counter` dropped here while still borrowed
+ | ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `std::result::Result<MutexGuard<'_>, ()>`
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped.
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+// This is a reduction of a concrete test illustrating a case that was
+// annoying to Rust developer niconii (see comment thread on #21114).
+//
+// With resolving issue #54556, pnkfelix hopes that the new diagnostic
+// output produced by NLL helps to *explain* the semantic significance
+// of temp drop order, and thus why inserting a semi-colon after the
+// `if let` expression in `main` works.
+
+struct Mutex;
+struct MutexGuard<'a>(&'a Mutex);
+
+impl Drop for Mutex { fn drop(&mut self) { println!("Mutex::drop"); } }
+impl<'a> Drop for MutexGuard<'a> { fn drop(&mut self) { println!("MutexGuard::drop"); } }
+
+impl Mutex {
+ fn lock(&self) -> Result<MutexGuard, ()> { Ok(MutexGuard(self)) }
+}
+
+fn main() {
+ let counter = Mutex;
+
+ if let Ok(_) = counter.lock() { }
+
+ // With this code as written, the dynamic semantics here implies
+ // that `Mutex::drop` for `counter` runs *before*
+ // `MutexGuard::drop`, which would be unsound since `MutexGuard`
+ // still has a reference to `counter`.
+ //
+ // The goal of #54556 is to explain that within a compiler
+ // diagnostic.
+}
--- /dev/null
+error[E0597]: `counter` does not live long enough
+ --> $DIR/issue-54556-niconii.rs:22:20
+ |
+LL | if let Ok(_) = counter.lock() { }
+ | ^^^^^^^ borrowed value does not live long enough
+...
+LL | }
+ | - `counter` dropped here while still borrowed
+ |
+ = note: values in a scope are dropped in the opposite order they are created
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+error[E0597]: `stmt` does not live long enough
+ --> $DIR/issue-54556-stephaneyfx.rs:27:21
+ |
+LL | let rows = Rows(&stmt);
+ | ^^^^^ borrowed value does not live long enough
+LL | rows.map(|row| row).next()
+ | ------------------- a temporary with access to the borrow is created here ...
+...
+LL | }
+ | -
+ | |
+ | `stmt` dropped here while still borrowed
+ | ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `std::iter::Map<Rows<'_>, [closure@$DIR/issue-54556-stephaneyfx.rs:28:14: 28:23]>`
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+// This is a reduction of a concrete test illustrating a case that was
+// annoying to Rust developer stephaneyfx (see issue #46413).
+//
+// With resolving issue #54556, pnkfelix hopes that the new diagnostic
+// output produced by NLL helps to *explain* the semantic significance
+// of temp drop order, and thus why storing the result in `x` and then
+// returning `x` works.
+
+pub struct Statement;
+
+pub struct Rows<'stmt>(&'stmt Statement);
+
+impl<'stmt> Drop for Rows<'stmt> {
+ fn drop(&mut self) {}
+}
+
+impl<'stmt> Iterator for Rows<'stmt> {
+ type Item = String;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ None
+ }
+}
+
+fn get_names() -> Option<String> {
+ let stmt = Statement;
+ let rows = Rows(&stmt);
+ rows.map(|row| row).next()
+ // let x = rows.map(|row| row).next();
+ // x
+ //
+ // Removing the map works too as does removing the Drop impl.
+}
+
+fn main() {}
--- /dev/null
+error[E0597]: `stmt` does not live long enough
+ --> $DIR/issue-54556-stephaneyfx.rs:27:22
+ |
+LL | let rows = Rows(&stmt);
+ | ^^^^ borrowed value does not live long enough
+...
+LL | }
+ | - `stmt` dropped here while still borrowed
+ |
+ = note: values in a scope are dropped in the opposite order they are created
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+error[E0597]: `_thing1` does not live long enough
+ --> $DIR/issue-54556-temps-in-tail-diagnostic.rs:5:11
+ |
+LL | D(&_thing1).end()
+ | --^^^^^^^^-
+ | | |
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+LL | }
+ | - `_thing1` dropped here while still borrowed
+LL |
+LL | ;
+ | - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped.
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+fn main() {
+ {
+ let mut _thing1 = D(Box::new("thing1"));
+ // D("other").next(&_thing1).end()
+ D(&_thing1).end()
+ }
+
+ ;
+}
+
+#[derive(Debug)]
+struct D<T: std::fmt::Debug>(T);
+
+impl<T: std::fmt::Debug> Drop for D<T> {
+ fn drop(&mut self) {
+ println!("dropping {:?})", self);
+ }
+}
+
+impl<T: std::fmt::Debug> D<T> {
+ fn next<U: std::fmt::Debug>(&self, _other: U) -> D<U> { D(_other) }
+ fn end(&self) { }
+}
--- /dev/null
+error[E0597]: `_thing1` does not live long enough
+ --> $DIR/issue-54556-temps-in-tail-diagnostic.rs:5:12
+ |
+LL | D(&_thing1).end()
+ | ^^^^^^^ borrowed value does not live long enough
+LL | }
+ | - `_thing1` dropped here while still borrowed
+LL |
+LL | ;
+ | - borrowed value needs to live until here
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:10:55
+ |
+LL | { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // suggest `;`
+ | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped.
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:12:55
+ |
+LL | { { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } } ; // suggest `;`
+ | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped.
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:14:55
+ |
+LL | { { let mut _t1 = D(Box::new("t1")); D(&_t1).end() }; } // suggest `;`
+ | --^^^^- -- ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped.
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:16:55
+ |
+LL | let _ = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // suggest `;`
+ | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped.
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:18:55
+ |
+LL | let _u = { let mut _t1 = D(Box::new("t1")); D(&_t1).unit() } ; // suggest `;`
+ | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped.
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:20:55
+ |
+LL | let _x = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // `let x = ...; x`
+ | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:24:55
+ |
+LL | _y = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // `let x = ...; x`
+ | --^^^^- - - ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:30:55
+ |
+LL | fn f_local_ref() { let mut _t1 = D(Box::new("t1")); D(&_t1).unit() } // suggest `;`
+ | --^^^^- -
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider adding semicolon after the expression so its temporaries are dropped sooner, before the local variables declared by the block are dropped.
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:32:55
+ |
+LL | fn f() -> String { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } // `let x = ...; x`
+ | --^^^^- -
+ | | | |
+ | | | `_t1` dropped here while still borrowed
+ | | | ... and the borrow might be used here, when that temporary is dropped and runs the `Drop` code for type `D`
+ | | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.
+
+error: aborting due to 9 previous errors
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+// Ths test case is exploring the space of how blocs with tail
+// expressions and statements can be composed, trying to keep each
+// case on one line so that we can compare them via a vertical scan
+// with the human eye.
+
+// Each comment on the right side of the line is summarizing the
+// expected suggestion from the diagnostic for issue #54556.
+
+fn main() {
+ { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // suggest `;`
+
+ { { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } } ; // suggest `;`
+
+ { { let mut _t1 = D(Box::new("t1")); D(&_t1).end() }; } // suggest `;`
+
+ let _ = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // suggest `;`
+
+ let _u = { let mut _t1 = D(Box::new("t1")); D(&_t1).unit() } ; // suggest `;`
+
+ let _x = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // `let x = ...; x`
+ let _x = { let mut _t1 = D(Box::new("t1")); let x = D(&_t1).end(); x } ; // no error
+
+ let mut _y;
+ _y = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // `let x = ...; x`
+ _y = { let mut _t1 = D(Box::new("t1")); let x = D(&_t1).end(); x } ; // no error
+}
+
+fn f_param_ref(_t1: D<Box<&'static str>>) { D(&_t1).unit() } // no error
+
+fn f_local_ref() { let mut _t1 = D(Box::new("t1")); D(&_t1).unit() } // suggest `;`
+
+fn f() -> String { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } // `let x = ...; x`
+
+
+#[derive(Debug)]
+struct D<T: std::fmt::Debug>(T);
+
+impl<T: std::fmt::Debug> Drop for D<T> {
+ fn drop(&mut self) {
+ println!("dropping {:?})", self);
+ }
+}
+
+impl<T: std::fmt::Debug> D<T> {
+ fn next<U: std::fmt::Debug>(&self, _other: U) -> D<U> { D(_other) }
+ fn end(&self) -> String { format!("End({:?})", self.0) }
+ fn unit(&self) { }
+}
--- /dev/null
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:10:56
+ |
+LL | { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // suggest `;`
+ | ^^^ - - borrowed value needs to live until here
+ | | |
+ | | `_t1` dropped here while still borrowed
+ | borrowed value does not live long enough
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:12:56
+ |
+LL | { { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } } ; // suggest `;`
+ | ^^^ - - borrowed value needs to live until here
+ | | |
+ | | `_t1` dropped here while still borrowed
+ | borrowed value does not live long enough
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:14:56
+ |
+LL | { { let mut _t1 = D(Box::new("t1")); D(&_t1).end() }; } // suggest `;`
+ | ^^^ -- borrowed value needs to live until here
+ | | |
+ | | `_t1` dropped here while still borrowed
+ | borrowed value does not live long enough
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:16:56
+ |
+LL | let _ = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // suggest `;`
+ | ^^^ - - borrowed value needs to live until here
+ | | |
+ | | `_t1` dropped here while still borrowed
+ | borrowed value does not live long enough
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:18:56
+ |
+LL | let _u = { let mut _t1 = D(Box::new("t1")); D(&_t1).unit() } ; // suggest `;`
+ | ^^^ - - borrowed value needs to live until here
+ | | |
+ | | `_t1` dropped here while still borrowed
+ | borrowed value does not live long enough
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:20:56
+ |
+LL | let _x = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // `let x = ...; x`
+ | ^^^ - - borrowed value needs to live until here
+ | | |
+ | | `_t1` dropped here while still borrowed
+ | borrowed value does not live long enough
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:24:56
+ |
+LL | _y = { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } ; // `let x = ...; x`
+ | ^^^ - - borrowed value needs to live until here
+ | | |
+ | | `_t1` dropped here while still borrowed
+ | borrowed value does not live long enough
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:30:56
+ |
+LL | fn f_local_ref() { let mut _t1 = D(Box::new("t1")); D(&_t1).unit() } // suggest `;`
+ | ^^^ - `_t1` dropped here while still borrowed
+ | |
+ | borrowed value does not live long enough
+ |
+ = note: values in a scope are dropped in the opposite order they are created
+
+error[E0597]: `_t1` does not live long enough
+ --> $DIR/issue-54556-used-vs-unused-tails.rs:32:56
+ |
+LL | fn f() -> String { let mut _t1 = D(Box::new("t1")); D(&_t1).end() } // `let x = ...; x`
+ | ^^^ - `_t1` dropped here while still borrowed
+ | |
+ | borrowed value does not live long enough
+ |
+ = note: values in a scope are dropped in the opposite order they are created
+
+error: aborting due to 9 previous errors
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+error[E0506]: cannot assign to `x` because it is borrowed
+ --> $DIR/issue-54556-wrap-it-up.rs:27:5
+ |
+LL | let wrap = Wrap { p: &mut x };
+ | ------ borrow of `x` occurs here
+...
+LL | x = 1; //~ ERROR cannot assign to `x` because it is borrowed [E0506]
+ | ^^^^^ assignment to borrowed `x` occurs here
+LL | }
+ | - borrow might be used here, when `foo` is dropped and runs the destructor for type `Foo<'_>`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0506`.
--- /dev/null
+// This is testing how the diagnostic from issue #54556 behaves when
+// the destructor code is attached to a place held in a field of the
+// temporary being dropped.
+//
+// Eventually it would be nice if the diagnostic would actually report
+// that specific place and its type that implements the `Drop` trait.
+// But for the short term, it is acceptable to just print out the
+// whole type of the temporary.
+
+#![allow(warnings)]
+
+struct Wrap<'p> { p: &'p mut i32 }
+
+impl<'p> Drop for Wrap<'p> {
+ fn drop(&mut self) {
+ *self.p += 1;
+ }
+}
+
+struct Foo<'p> { a: String, b: Wrap<'p> }
+
+fn main() {
+ let mut x = 0;
+ let wrap = Wrap { p: &mut x };
+ let s = String::from("str");
+ let foo = Foo { a: s, b: wrap };
+ x = 1; //~ ERROR cannot assign to `x` because it is borrowed [E0506]
+}
--- /dev/null
+error[E0506]: cannot assign to `x` because it is borrowed
+ --> $DIR/issue-54556-wrap-it-up.rs:27:5
+ |
+LL | let wrap = Wrap { p: &mut x };
+ | - borrow of `x` occurs here
+...
+LL | x = 1; //~ ERROR cannot assign to `x` because it is borrowed [E0506]
+ | ^^^^^ assignment to borrowed `x` occurs here
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0506`.
| ^^^^ second mutable borrow occurs here
...
LL | capitalize(slice);
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0499]: cannot borrow `data` as mutable more than once at a time (Mir)
--> $DIR/loan_ends_mid_block_vec.rs:27:5
| ^^^^ second mutable borrow occurs here
...
LL | capitalize(slice);
- | ----- borrow later used here
+ | ----- first borrow later used here
error[E0499]: cannot borrow `data` as mutable more than once at a time (Mir)
--> $DIR/loan_ends_mid_block_vec.rs:30:5
| ^^^^ second mutable borrow occurs here
...
LL | capitalize(slice);
- | ----- borrow later used here
+ | ----- first borrow later used here
error: aborting due to 9 previous errors
| ^^^^^ assignment to borrowed `x` occurs here
LL | // FIXME ^ Should not error in the future with implicit dtors, only manually implemented ones
LL | }
- | - borrow later used here, when `foo` is dropped
+ | - borrow might be used here, when `foo` is dropped and runs the destructor for type `Foo<'_>`
error: aborting due to previous error
LL | x = 1; //~ ERROR cannot assign to `x` because it is borrowed [E0506]
| ^^^^^ assignment to borrowed `x` occurs here
LL | }
- | - borrow later used here, when `foo` is dropped
+ | - borrow might be used here, when `foo` is dropped and runs the destructor for type `Foo<'_>`
error: aborting due to previous error
| ^^^^^ assignment to borrowed `x` occurs here
LL | // FIXME ^ This currently errors and it should not.
LL | }
- | - borrow later used here, when `foo` is dropped
+ | - borrow might be used here, when `foo` is dropped and runs the destructor for type `Foo<'_>`
error: aborting due to previous error
LL | x = 1; //~ ERROR cannot assign to `x` because it is borrowed [E0506]
| ^^^^^ assignment to borrowed `x` occurs here
LL | }
- | - borrow later used here, when `wrap` is dropped
+ | - borrow might be used here, when `wrap` is dropped and runs the `Drop` code for type `Wrap`
error: aborting due to previous error
| cannot move out of borrowed content
| help: consider removing the `*`: `*r`
-error[E0507]: cannot move out of borrowed content
+error[E0507]: cannot move out of an `Rc`
--> $DIR/move-errors.rs:40:13
|
LL | let s = *r;
| ^^
| |
- | cannot move out of borrowed content
+ | cannot move out of an `Rc`
| help: consider removing the `*`: `r`
error[E0508]: cannot move out of type `[A; 1]`, a non-copy array
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
...
LL | drop(value);
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error: aborting due to 3 previous errors
| ^^^^^^^^^^^^^^^ mutable borrow occurs here
...
LL | drop(value);
- | ----- borrow later used here
+ | ----- immutable borrow later used here
error: aborting due to 3 previous errors
| ^^^^^^^^^^^^^^^ second mutable borrow occurs here
...
LL | value.len();
- | ----- borrow later used here
+ | ----- first borrow later used here
error: aborting due to 3 previous errors
--- /dev/null
+// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+struct S;
+
+impl S {
+ fn foo(&self, &str bar) {}
+ //~^ ERROR expected one of `:` or `@`
+ //~| HELP declare the type after the parameter binding
+ //~| SUGGESTION <identifier>: <type>
+}
+
+fn baz(S quux, xyzzy: i32) {}
+//~^ ERROR expected one of `:` or `@`
+//~| HELP declare the type after the parameter binding
+//~| SUGGESTION <identifier>: <type>
+
+fn one(i32 a b) {}
+//~^ ERROR expected one of `:` or `@`
+
+fn pattern((i32, i32) (a, b)) {}
+//~^ ERROR expected `:`
+
+fn fizz(i32) {}
+//~^ ERROR expected one of `:` or `@`
+
+fn missing_colon(quux S) {}
+//~^ ERROR expected one of `:` or `@`
+//~| HELP declare the type after the parameter binding
+//~| SUGGESTION <identifier>: <type>
+
+fn main() {}
--- /dev/null
+error: expected one of `:` or `@`, found `bar`
+ --> $DIR/inverted-parameters.rs:14:24
+ |
+LL | fn foo(&self, &str bar) {}
+ | -----^^^
+ | | |
+ | | expected one of `:` or `@` here
+ | help: declare the type after the parameter binding: `<identifier>: <type>`
+
+error: expected one of `:` or `@`, found `quux`
+ --> $DIR/inverted-parameters.rs:20:10
+ |
+LL | fn baz(S quux, xyzzy: i32) {}
+ | --^^^^
+ | | |
+ | | expected one of `:` or `@` here
+ | help: declare the type after the parameter binding: `<identifier>: <type>`
+
+error: expected one of `:` or `@`, found `a`
+ --> $DIR/inverted-parameters.rs:25:12
+ |
+LL | fn one(i32 a b) {}
+ | ^ expected one of `:` or `@` here
+
+error: expected `:`, found `(`
+ --> $DIR/inverted-parameters.rs:28:23
+ |
+LL | fn pattern((i32, i32) (a, b)) {}
+ | ^ expected `:`
+
+error: expected one of `:` or `@`, found `)`
+ --> $DIR/inverted-parameters.rs:31:12
+ |
+LL | fn fizz(i32) {}
+ | ^ expected one of `:` or `@` here
+
+error: expected one of `:` or `@`, found `S`
+ --> $DIR/inverted-parameters.rs:34:23
+ |
+LL | fn missing_colon(quux S) {}
+ | -----^
+ | | |
+ | | expected one of `:` or `@` here
+ | help: declare the type after the parameter binding: `<identifier>: <type>`
+
+error: aborting due to 6 previous errors
+
trait Tr2<T> {}
impl<T> Tr2<T> for u8 {}
fn g() -> impl Tr2<m::Alias> { 0 } //~ ERROR type `m::Priv` is private
-//~^ ERROR type `m::Priv` is private
fn g_ext() -> impl Tr2<ext::Alias> { 0 } //~ ERROR type `ext::Priv` is private
-//~^ ERROR type `ext::Priv` is private
fn main() {}
LL | fn g() -> impl Tr2<m::Alias> { 0 } //~ ERROR type `m::Priv` is private
| ^^^^^^^^^^^^^^^^^^
-error: type `m::Priv` is private
- --> $DIR/private-type-in-interface.rs:37:16
- |
-LL | fn g() -> impl Tr2<m::Alias> { 0 } //~ ERROR type `m::Priv` is private
- | ^^^^^^^^^^^^^
-
error: type `ext::Priv` is private
- --> $DIR/private-type-in-interface.rs:39:15
+ --> $DIR/private-type-in-interface.rs:38:15
|
LL | fn g_ext() -> impl Tr2<ext::Alias> { 0 } //~ ERROR type `ext::Priv` is private
| ^^^^^^^^^^^^^^^^^^^^
-error: type `ext::Priv` is private
- --> $DIR/private-type-in-interface.rs:39:20
- |
-LL | fn g_ext() -> impl Tr2<ext::Alias> { 0 } //~ ERROR type `ext::Priv` is private
- | ^^^^^^^^^^^^^^^
-
-error: aborting due to 11 previous errors
+error: aborting due to 9 previous errors
--> $DIR/region-bound-on-closure-outlives-call.rs:12:25
|
LL | (|x| f(x))(call_rec(f)) //~ ERROR cannot move out of `f`
- | --------------------^--
- | || | |
- | || | move out of `f` occurs here
+ | ---------- ^ move out of `f` occurs here
+ | || |
| || borrow occurs due to use in closure
| |borrow of `f` occurs here
- | borrow later used here
+ | borrow later used by call
error: aborting due to previous error
--> $DIR/regions-adjusted-lvalue-op.rs:24:16
|
LL | v[0].oh_no(&v); //~ ERROR cannot borrow `v` as immutable because
- | -----------^^-
- | | |
- | | immutable borrow occurs here
+ | - ----- ^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
| mutable borrow occurs here
- | borrow later used here
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
--> $DIR/regions-adjusted-lvalue-op.rs:25:16
|
LL | (*v).oh_no(&v); //~ ERROR cannot borrow `v` as immutable because
- | -----------^^-
- | | | |
- | | | immutable borrow occurs here
- | | mutable borrow occurs here
- | borrow later used here
+ | - ----- ^^ immutable borrow occurs here
+ | | |
+ | | mutable borrow later used by call
+ | mutable borrow occurs here
error: aborting due to 2 previous errors
| ^^^^^^^^^^^^ mutable borrow occurs here
LL | //~^ ERROR cannot borrow `foo` as mutable
LL | println!("foo={:?}", *string);
- | ------- borrow used here, in later iteration of loop
+ | ------- immutable borrow used here, in later iteration of loop
error: aborting due to previous error
error[E0499]: cannot borrow `f` as mutable more than once at a time
--> $DIR/borrowck-call-is-borrow-issue-12224.rs:22:16
|
-LL | f(Box::new(|| {
- | - ^^ second mutable borrow occurs here
- | |
- | _____first mutable borrow occurs here
- | |
-LL | | //~^ ERROR: cannot borrow `f` as mutable more than once
-LL | | f((Box::new(|| {})))
- | | - second borrow occurs due to use of `f` in closure
-LL | | }));
- | |_______- borrow later used here
+LL | f(Box::new(|| {
+ | - ^^ second mutable borrow occurs here
+ | |
+ | first mutable borrow occurs here
+ | first borrow later used by call
+LL | //~^ ERROR: cannot borrow `f` as mutable more than once
+LL | f((Box::new(|| {})))
+ | - second borrow occurs due to use of `f` in closure
error[E0596]: cannot borrow `*f` as mutable, as it is behind a `&` reference
--> $DIR/borrowck-call-is-borrow-issue-12224.rs:35:5
error[E0505]: cannot move out of `f` because it is borrowed
--> $DIR/borrowck-call-is-borrow-issue-12224.rs:65:16
|
-LL | f(Box::new(|a| {
- | - ^^^ move out of `f` occurs here
- | |
- | _____borrow of `f` occurs here
- | |
-LL | | foo(f);
- | | - move occurs due to use in closure
-LL | | //~^ ERROR cannot move `f` into closure because it is borrowed
-LL | | //~| ERROR cannot move out of captured outer variable in an `FnMut` closure
-LL | | }), 3);
- | |__________- borrow later used here
+LL | f(Box::new(|a| {
+ | - ^^^ move out of `f` occurs here
+ | |
+ | borrow of `f` occurs here
+ | borrow later used by call
+LL | foo(f);
+ | - move occurs due to use in closure
error: aborting due to 5 previous errors
--> $DIR/destructor-restrictions.rs:18:10
|
LL | *a.borrow() + 1
- | ^ borrowed value does not live long enough
+ | ^---------
+ | |
+ | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
LL | }; //~^ ERROR `*a` does not live long enough
- | - `*a` dropped here while still borrowed
+ | -- ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `std::cell::Ref<'_, i32>`
+ | |
+ | `*a` dropped here while still borrowed
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.
error: aborting due to previous error
| -
| |
| `*m` dropped here while still borrowed
- | borrow later used here, when `m` is dropped
+ | borrow might be used here, when `m` is dropped and runs the destructor for type `std::boxed::Box<dyn Trait<'_>>`
error: aborting due to previous error
| -
| |
| `b2` dropped here while still borrowed
- | borrow later used here, when `b1` is dropped
+ | borrow might be used here, when `b1` is dropped and runs the destructor for type `B<'_>`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `b3` dropped here while still borrowed
- | borrow later used here, when `b1` is dropped
+ | borrow might be used here, when `b1` is dropped and runs the destructor for type `B<'_>`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `b1` dropped here while still borrowed
- | borrow later used here, when `b1` is dropped
+ | borrow might be used here, when `b1` is dropped and runs the destructor for type `B<'_>`
error: aborting due to 3 previous errors
| -
| |
| `d2` dropped here while still borrowed
- | borrow later used here, when `d1` is dropped
+ | borrow might be used here, when `d1` is dropped and runs the `Drop` code for type `D`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `d1` dropped here while still borrowed
- | borrow later used here, when `d1` is dropped
+ | borrow might be used here, when `d1` is dropped and runs the `Drop` code for type `D`
error: aborting due to 2 previous errors
| -
| |
| `bomb` dropped here while still borrowed
- | borrow later used here, when `_w` is dropped
+ | borrow might be used here, when `_w` is dropped and runs the destructor for type `Wrap<&[&str]>`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `v` dropped here while still borrowed
- | borrow later used here, when `_w` is dropped
+ | borrow might be used here, when `_w` is dropped and runs the destructor for closure
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `c2` dropped here while still borrowed
- | borrow later used here, when `c1` is dropped
+ | borrow might be used here, when `c1` is dropped and runs the destructor for type `C<'_>`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `c3` dropped here while still borrowed
- | borrow later used here, when `c1` is dropped
+ | borrow might be used here, when `c1` is dropped and runs the destructor for type `C<'_>`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `c1` dropped here while still borrowed
- | borrow later used here, when `c1` is dropped
+ | borrow might be used here, when `c1` is dropped and runs the destructor for type `C<'_>`
error: aborting due to 3 previous errors
--> $DIR/issue-23338-locals-die-before-temps-of-body.rs:20:5
|
LL | y.borrow().clone()
- | ^ borrowed value does not live long enough
+ | ^---------
+ | |
+ | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
LL | }
- | - `y` dropped here while still borrowed
+ | -
+ | |
+ | `y` dropped here while still borrowed
+ | ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `std::cell::Ref<'_, std::string::String>`
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.
error[E0597]: `y` does not live long enough
--> $DIR/issue-23338-locals-die-before-temps-of-body.rs:27:9
|
LL | y.borrow().clone()
- | ^ borrowed value does not live long enough
+ | ^---------
+ | |
+ | borrowed value does not live long enough
+ | a temporary with access to the borrow is created here ...
LL | };
- | - `y` dropped here while still borrowed
+ | -- ... and the borrow might be used here, when that temporary is dropped and runs the destructor for type `std::cell::Ref<'_, std::string::String>`
+ | |
+ | `y` dropped here while still borrowed
+ |
+ = note: The temporary is part of an expression at the end of a block. Consider forcing this temporary to be dropped sooner, before the block's local variables are dropped. For example, you could save the expression's value in a new local variable `x` and then make `x` be the expression at the end of the block.
error: aborting due to 2 previous errors
| -
| |
| `d1` dropped here while still borrowed
- | borrow later used here, when `_d` is dropped
+ | borrow might be used here, when `_d` is dropped and runs the `Drop` code for type `D_Child`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `d1` dropped here while still borrowed
- | borrow later used here, when `_d` is dropped
+ | borrow might be used here, when `_d` is dropped and runs the `Drop` code for type `D_HasSelfMethod`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `d1` dropped here while still borrowed
- | borrow later used here, when `_d` is dropped
+ | borrow might be used here, when `_d` is dropped and runs the `Drop` code for type `D_HasMethodWithSelfArg`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `d1` dropped here while still borrowed
- | borrow later used here, when `_d` is dropped
+ | borrow might be used here, when `_d` is dropped and runs the `Drop` code for type `D_HasType`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `d1` dropped here while still borrowed
- | borrow later used here, when `d2` is dropped
+ | borrow might be used here, when `d2` is dropped and runs the `Drop` code for type `D`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `container` dropped here while still borrowed
- | borrow later used here, when `container` is dropped
+ | borrow might be used here, when `container` is dropped and runs the destructor for type `Container<'_>`
error: aborting due to previous error
| -
| |
| `ticking` dropped here while still borrowed
- | borrow later used here, when `zook` is dropped
+ | borrow might be used here, when `zook` is dropped and runs the `Drop` code for type `Zook`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `x` dropped here while still borrowed
- | borrow later used here, when `y` is dropped
+ | borrow might be used here, when `y` is dropped and runs the `Drop` code for type `std::sync::Arc`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `x` dropped here while still borrowed
- | borrow later used here, when `y` is dropped
+ | borrow might be used here, when `y` is dropped and runs the `Drop` code for type `std::rc::Rc`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| here, drop of `foo` needs exclusive access to `foo.data`, because the type `Foo<Concrete<'_>>` implements the `Drop` trait
- | borrow later used here, when `foo` is dropped
+ | borrow might be used here, when `foo` is dropped and runs the `Drop` code for type `Foo`
|
= note: consider using a `let` binding to create a longer lived value
| -
| |
| `first_dropped` dropped here while still borrowed
- | borrow later used here, when `foo1` is dropped
+ | borrow might be used here, when `foo1` is dropped and runs the `Drop` code for type `Foo`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `first_dropped` dropped here while still borrowed
- | borrow later used here, when `foo1` is dropped
+ | borrow might be used here, when `foo1` is dropped and runs the `Drop` code for type `Foo`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `first_dropped` dropped here while still borrowed
- | borrow later used here, when `foo1` is dropped
+ | borrow might be used here, when `foo1` is dropped and runs the `Drop` code for type `Foo`
|
= note: values in a scope are dropped in the opposite order they are defined
LL | }
| - temporary value is freed at the end of this statement
LL | }
- | - borrow later used here, when `blah` is dropped
+ | - borrow might be used here, when `blah` is dropped and runs the destructor for type `std::boxed::Box<dyn Foo>`
|
= note: consider using a `let` binding to create a longer lived value
| - `z` dropped here while still borrowed
...
LL | }
- | - borrow later used here, when `tx` is dropped
+ | - borrow might be used here, when `tx` is dropped and runs the `Drop` code for type `std::sync::mpsc::Sender`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `c2` dropped here while still borrowed
- | borrow later used here, when `c1` is dropped
+ | borrow might be used here, when `c1` is dropped and runs the destructor for type `C<'_>`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `c1` dropped here while still borrowed
- | borrow later used here, when `c1` is dropped
+ | borrow might be used here, when `c1` is dropped and runs the destructor for type `C<'_>`
error: aborting due to 2 previous errors
| -
| |
| `x` dropped here while still borrowed
- | borrow later used here, when `v` is dropped
+ | borrow might be used here, when `v` is dropped and runs the `Drop` code for type `Bag`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `y` dropped here while still borrowed
- | borrow later used here, when `v` is dropped
+ | borrow might be used here, when `v` is dropped and runs the `Drop` code for type `Bag`
|
= note: values in a scope are dropped in the opposite order they are defined
| -
| |
| `factorial` dropped here while still borrowed
- | borrow later used here, when `factorial` is dropped
+ | borrow might be used here, when `factorial` is dropped and runs the destructor for type `std::option::Option<std::boxed::Box<dyn std::ops::Fn(u32) -> u32>>`
error[E0506]: cannot assign to `factorial` because it is borrowed
--> $DIR/unboxed-closures-failed-recursive-fn-1.rs:30:5
--> $DIR/unboxed-closures-recursive-fn-using-fn-mut.rs:32:21
|
LL | (self.func)(self, arg)
- | ------------^^^^------
- | | |
- | | second mutable borrow occurs here
+ | ----------- ^^^^ second mutable borrow occurs here
+ | |
| first mutable borrow occurs here
- | borrow later used here
+ | first borrow later used by call
error: aborting due to previous error
| -------
| |
| first mutable borrow occurs here
- | borrow used here, in later iteration of loop
+ | first borrow used here, in later iteration of loop
LL | xs.push(1) //~ ERROR cannot borrow `xs`
| ^^ second mutable borrow occurs here
Test {
name: "servo",
repo: "https://github.com/servo/servo",
- sha: "17e97b9320fdb7cdb33bbc5f4d0fde0653bbf2e4",
+ sha: "987e376ca7a4245dbc3e0c06e963278ee1ac92d1",
lock: None,
// Only test Stylo a.k.a. Quantum CSS, the parts of Servo going into Firefox.
// This takes much less time to build than all of Servo and supports stable Rust.
- packages: &["stylo_tests", "selectors"],
+ packages: &["selectors"],
},
Test {
name: "webrender",
-Subproject commit e69fe2fb19b7b2f3b07fe1178c536810dabf896f
+Subproject commit 32b1d1fc157f71ed2f10b60fe28abe087a743618
"wincon",
"wincrypt",
]
+
+[dependencies.serde_json]
+version = "1.0.31"
+features = ["raw_value"]
+
+[dependencies.rand]
+version = "0.5.5"
+features = ["i128_support"]