Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Rollup of 5 pull requests #63325

Closed
wants to merge 23 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
112a347
Fix theme picker blur handler: always hide instead of switching
Kinrany Jul 20, 2019
3e39ac7
Update render.rs
Kinrany Jul 20, 2019
2e41ba8
Use internal iteration in the Sum and Product impls of Result and Option
timvermeulen Jul 6, 2019
83b5eb9
Always error on `SizeOverflow` during mir evaluation
estebank Jul 31, 2019
58bd878
Do not lint on SizeOverflow, always error
estebank Jul 31, 2019
d3da411
Nicer labels for type layout errors
estebank Jul 31, 2019
2c56842
avoid mutable state and override main message
estebank Aug 3, 2019
db099fb
Point to local place span on "type too big" error
estebank Aug 3, 2019
2340067
Simplify change to layout_of
estebank Aug 4, 2019
387dcff
review comments: clean up
estebank Aug 4, 2019
bdd79b8
tweak output and tests
estebank Aug 4, 2019
f621f89
revert change to single test
estebank Aug 4, 2019
18130ef
Replace error callback with Result
Mark-Simulacrum Aug 5, 2019
3cd7f08
Force callers of resolve_ast_path to deal with Res::Err correctly
Mark-Simulacrum Aug 5, 2019
e187574
assume_init: warn about valid != safe
RalfJung Aug 5, 2019
ce8510a
fix tests
estebank Aug 5, 2019
1b9eb4a
be clear that 1-init Vec being valid (but not safe) is not a stable g…
RalfJung Aug 6, 2019
1821414
clarify
RalfJung Aug 6, 2019
f45cdea
Rollup merge of #62459 - timvermeulen:result_sum_internal_iteration, …
Centril Aug 6, 2019
ab2a368
Rollup merge of #62837 - Kinrany:patch-1, r=GuillaumeGomez
Centril Aug 6, 2019
44eab0c
Rollup merge of #63152 - estebank:big-array, r=oli-obk
Centril Aug 6, 2019
3b0c864
Rollup merge of #63286 - Mark-Simulacrum:resolve-no-cb, r=petrochenkov
Centril Aug 6, 2019
05f771b
Rollup merge of #63298 - RalfJung:assume_init, r=Mark-Simulacrum,Centril
Centril Aug 6, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 37 additions & 109 deletions src/libcore/iter/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2180,137 +2180,65 @@ impl<I: ExactSizeIterator, F> ExactSizeIterator for Inspect<I, F>
impl<I: FusedIterator, F> FusedIterator for Inspect<I, F>
where F: FnMut(&I::Item) {}

/// An iterator adapter that produces output as long as the underlying
/// iterator produces `Option::Some` values.
pub(crate) struct OptionShunt<I> {
iter: I,
exited_early: bool,
}

impl<I, T> OptionShunt<I>
where
I: Iterator<Item = Option<T>>,
{
/// Process the given iterator as if it yielded a `T` instead of a
/// `Option<T>`. Any `None` value will stop the inner iterator and
/// the overall result will be a `None`.
pub fn process<F, U>(iter: I, mut f: F) -> Option<U>
where
F: FnMut(&mut Self) -> U,
{
let mut shunt = OptionShunt::new(iter);
let value = f(shunt.by_ref());
shunt.reconstruct(value)
}

fn new(iter: I) -> Self {
OptionShunt {
iter,
exited_early: false,
}
}

/// Consume the adapter and rebuild a `Option` value.
fn reconstruct<U>(self, val: U) -> Option<U> {
if self.exited_early {
None
} else {
Some(val)
}
}
}

impl<I, T> Iterator for OptionShunt<I>
where
I: Iterator<Item = Option<T>>,
{
type Item = T;

fn next(&mut self) -> Option<Self::Item> {
match self.iter.next() {
Some(Some(v)) => Some(v),
Some(None) => {
self.exited_early = true;
None
}
None => None,
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
if self.exited_early {
(0, Some(0))
} else {
let (_, upper) = self.iter.size_hint();
(0, upper)
}
}
}

/// An iterator adapter that produces output as long as the underlying
/// iterator produces `Result::Ok` values.
///
/// If an error is encountered, the iterator stops and the error is
/// stored. The error may be recovered later via `reconstruct`.
pub(crate) struct ResultShunt<I, E> {
/// stored.
pub(crate) struct ResultShunt<'a, I, E> {
iter: I,
error: Option<E>,
error: &'a mut Result<(), E>,
}

impl<I, T, E> ResultShunt<I, E>
where I: Iterator<Item = Result<T, E>>
/// Process the given iterator as if it yielded a `T` instead of a
/// `Result<T, _>`. Any errors will stop the inner iterator and
/// the overall result will be an error.
pub(crate) fn process_results<I, T, E, F, U>(iter: I, mut f: F) -> Result<U, E>
where
I: Iterator<Item = Result<T, E>>,
for<'a> F: FnMut(ResultShunt<'a, I, E>) -> U,
{
/// Process the given iterator as if it yielded a `T` instead of a
/// `Result<T, _>`. Any errors will stop the inner iterator and
/// the overall result will be an error.
pub fn process<F, U>(iter: I, mut f: F) -> Result<U, E>
where F: FnMut(&mut Self) -> U
{
let mut shunt = ResultShunt::new(iter);
let value = f(shunt.by_ref());
shunt.reconstruct(value)
}

fn new(iter: I) -> Self {
ResultShunt {
iter,
error: None,
}
}

/// Consume the adapter and rebuild a `Result` value. This should
/// *always* be called, otherwise any potential error would be
/// lost.
fn reconstruct<U>(self, val: U) -> Result<U, E> {
match self.error {
None => Ok(val),
Some(e) => Err(e),
}
}
let mut error = Ok(());
let shunt = ResultShunt {
iter,
error: &mut error,
};
let value = f(shunt);
error.map(|()| value)
}

impl<I, T, E> Iterator for ResultShunt<I, E>
impl<I, T, E> Iterator for ResultShunt<'_, I, E>
where I: Iterator<Item = Result<T, E>>
{
type Item = T;

fn next(&mut self) -> Option<Self::Item> {
match self.iter.next() {
Some(Ok(v)) => Some(v),
Some(Err(e)) => {
self.error = Some(e);
None
}
None => None,
}
self.find(|_| true)
}

fn size_hint(&self) -> (usize, Option<usize>) {
if self.error.is_some() {
if self.error.is_err() {
(0, Some(0))
} else {
let (_, upper) = self.iter.size_hint();
(0, upper)
}
}

fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
where
F: FnMut(B, Self::Item) -> R,
R: Try<Ok = B>,
{
let error = &mut *self.error;
self.iter
.try_fold(init, |acc, x| match x {
Ok(x) => LoopState::from_try(f(acc, x)),
Err(e) => {
*error = Err(e);
LoopState::Break(Try::from_ok(acc))
}
})
.into_try()
}
}
2 changes: 1 addition & 1 deletion src/libcore/iter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ pub use self::adapters::Flatten;
#[stable(feature = "iter_copied", since = "1.36.0")]
pub use self::adapters::Copied;

pub(crate) use self::adapters::{TrustedRandomAccess, OptionShunt, ResultShunt};
pub(crate) use self::adapters::{TrustedRandomAccess, process_results};

mod range;
mod sources;
Expand Down
10 changes: 5 additions & 5 deletions src/libcore/iter/traits/accum.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::ops::{Mul, Add};
use crate::num::Wrapping;
use crate::iter::adapters::{OptionShunt, ResultShunt};
use crate::iter;

/// Trait to represent types that can be created by summing up an iterator.
///
Expand Down Expand Up @@ -139,7 +139,7 @@ impl<T, U, E> Sum<Result<U, E>> for Result<T, E>
fn sum<I>(iter: I) -> Result<T, E>
where I: Iterator<Item = Result<U, E>>,
{
ResultShunt::process(iter, |i| i.sum())
iter::process_results(iter, |i| i.sum())
}
}

Expand All @@ -153,7 +153,7 @@ impl<T, U, E> Product<Result<U, E>> for Result<T, E>
fn product<I>(iter: I) -> Result<T, E>
where I: Iterator<Item = Result<U, E>>,
{
ResultShunt::process(iter, |i| i.product())
iter::process_results(iter, |i| i.product())
}
}

Expand All @@ -180,7 +180,7 @@ where
where
I: Iterator<Item = Option<U>>,
{
OptionShunt::process(iter, |i| i.sum())
iter.map(|x| x.ok_or(())).sum::<Result<_, _>>().ok()
}
}

Expand All @@ -196,6 +196,6 @@ where
where
I: Iterator<Item = Option<U>>,
{
OptionShunt::process(iter, |i| i.product())
iter.map(|x| x.ok_or(())).product::<Result<_, _>>().ok()
}
}
11 changes: 10 additions & 1 deletion src/libcore/mem/maybe_uninit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ use crate::mem::ManuallyDrop;
///
/// On top of that, remember that most types have additional invariants beyond merely
/// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
/// is considered initialized because the only requirement the compiler knows about it
/// is considered initialized (under the current implementation; this does not constitute
/// a stable guarantee) because the only requirement the compiler knows about it
/// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
/// *immediate* undefined behavior, but will cause undefined behavior with most
/// safe operations (including dropping it).
Expand Down Expand Up @@ -402,6 +403,14 @@ impl<T> MaybeUninit<T> {
///
/// [inv]: #initialization-invariant
///
/// On top of that, remember that most types have additional invariants beyond merely
/// being considered initialized at the type level. For example, a `1`-initialized [`Vec<T>`]
/// is considered initialized (under the current implementation; this does not constitute
/// a stable guarantee) because the only requirement the compiler knows about it
/// is that the data pointer must be non-null. Creating such a `Vec<T>` does not cause
/// *immediate* undefined behavior, but will cause undefined behavior with most
/// safe operations (including dropping it).
///
/// # Examples
///
/// Correct usage of this method:
Expand Down
7 changes: 5 additions & 2 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@

#![stable(feature = "rust1", since = "1.0.0")]

use crate::iter::{FromIterator, FusedIterator, TrustedLen, OptionShunt};
use crate::iter::{FromIterator, FusedIterator, TrustedLen};
use crate::{convert, fmt, hint, mem, ops::{self, Deref, DerefMut}};
use crate::pin::Pin;

Expand Down Expand Up @@ -1499,7 +1499,10 @@ impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
// FIXME(#11084): This could be replaced with Iterator::scan when this
// performance bug is closed.

OptionShunt::process(iter.into_iter(), |i| i.collect())
iter.into_iter()
.map(|x| x.ok_or(()))
.collect::<Result<_, _>>()
.ok()
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@
#![stable(feature = "rust1", since = "1.0.0")]

use crate::fmt;
use crate::iter::{FromIterator, FusedIterator, TrustedLen, ResultShunt};
use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
use crate::ops::{self, Deref, DerefMut};

/// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
Expand Down Expand Up @@ -1343,7 +1343,7 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
// FIXME(#11084): This could be replaced with Iterator::scan when this
// performance bug is closed.

ResultShunt::process(iter.into_iter(), |i| i.collect())
iter::process_results(iter.into_iter(), |i| i.collect())
}
}

Expand Down
17 changes: 17 additions & 0 deletions src/libcore/tests/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1203,6 +1203,23 @@ fn test_iterator_sum_result() {
assert_eq!(v.iter().cloned().sum::<Result<i32, _>>(), Ok(10));
let v: &[Result<i32, ()>] = &[Ok(1), Err(()), Ok(3), Ok(4)];
assert_eq!(v.iter().cloned().sum::<Result<i32, _>>(), Err(()));

#[derive(PartialEq, Debug)]
struct S(Result<i32, ()>);

impl Sum<Result<i32, ()>> for S {
fn sum<I: Iterator<Item = Result<i32, ()>>>(mut iter: I) -> Self {
// takes the sum by repeatedly calling `next` on `iter`,
// thus testing that repeated calls to `ResultShunt::try_fold`
// produce the expected results
Self(iter.by_ref().sum())
}
}

let v: &[Result<i32, ()>] = &[Ok(1), Ok(2), Ok(3), Ok(4)];
assert_eq!(v.iter().cloned().sum::<S>(), S(Ok(10)));
let v: &[Result<i32, ()>] = &[Ok(1), Err(()), Ok(3), Ok(4)];
assert_eq!(v.iter().cloned().sum::<S>(), S(Err(())));
}

#[test]
Expand Down
18 changes: 11 additions & 7 deletions src/librustc/mir/interpret/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,17 +137,17 @@ impl<'tcx> ConstEvalErr<'tcx> {
message: &str,
lint_root: Option<hir::HirId>,
) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> {
match self.error {
let must_error = match self.error {
err_inval!(Layout(LayoutError::Unknown(_))) |
err_inval!(TooGeneric) =>
return Err(ErrorHandled::TooGeneric),
err_inval!(Layout(LayoutError::SizeOverflow(_))) |
err_inval!(TypeckError) =>
return Err(ErrorHandled::Reported),
_ => {},
}
err_inval!(Layout(LayoutError::SizeOverflow(_))) => true,
_ => false,
};
trace!("reporting const eval failure at {:?}", self.span);
let mut err = if let Some(lint_root) = lint_root {
let mut err = if let (Some(lint_root), false) = (lint_root, must_error) {
let hir_id = self.stacktrace
.iter()
.rev()
Expand All @@ -160,10 +160,14 @@ impl<'tcx> ConstEvalErr<'tcx> {
tcx.span,
message,
)
} else if must_error {
struct_error(tcx, &self.error.to_string())
} else {
struct_error(tcx, message)
};
err.span_label(self.span, self.error.to_string());
if !must_error {
err.span_label(self.span, self.error.to_string());
}
// Skip the last, which is just the environment of the constant. The stacktrace
// is sometimes empty because we create "fake" eval contexts in CTFE to do work
// on constant values.
Expand Down Expand Up @@ -335,7 +339,7 @@ impl fmt::Debug for InvalidProgramInfo<'tcx> {
TypeckError =>
write!(f, "encountered constants with type errors, stopping evaluation"),
Layout(ref err) =>
write!(f, "rustc layout computation failed: {:?}", err),
write!(f, "{}", err),
}
}
}
Expand Down
7 changes: 6 additions & 1 deletion src/librustc_codegen_llvm/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use std::iter;
use std::str;
use std::sync::Arc;
use syntax::symbol::LocalInternedString;
use syntax::source_map::{DUMMY_SP, Span};
use crate::abi::Abi;

/// There is one `CodegenCx` per compilation unit. Each one has its own LLVM
Expand Down Expand Up @@ -860,9 +861,13 @@ impl LayoutOf for CodegenCx<'ll, 'tcx> {
type TyLayout = TyLayout<'tcx>;

fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
self.spanned_layout_of(ty, DUMMY_SP)
}

fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::TyLayout {
self.tcx.layout_of(ty::ParamEnv::reveal_all().and(ty))
.unwrap_or_else(|e| if let LayoutError::SizeOverflow(_) = e {
self.sess().fatal(&e.to_string())
self.sess().span_fatal(span, &e.to_string())
} else {
bug!("failed to get layout for `{}`: {}", ty, e)
})
Expand Down
Loading