Commit Graph

189 Commits

Author SHA1 Message Date
Mark Rousskov f99929f24a Remove some more consts 2021-05-03 14:52:12 -04:00
Yuki Okushi c46f948a80
Rollup merge of #79208 - LeSeulArtichaut:stable-unsafe_op_in_unsafe_fn, r=nikomatsakis
Stabilize `unsafe_op_in_unsafe_fn` lint

This makes it possible to override the level of the `unsafe_op_in_unsafe_fn`, as proposed in https://github.com/rust-lang/rust/issues/71668#issuecomment-729770896.

Tracking issue: #71668
r? ```@nikomatsakis``` cc ```@SimonSapin``` ```@RalfJung```

# Stabilization report

This is a stabilization report for `#![feature(unsafe_block_in_unsafe_fn)]`.

## Summary

Currently, the body of unsafe functions is an unsafe block, i.e. you can perform unsafe operations inside.

The `unsafe_op_in_unsafe_fn` lint, stabilized here, can be used to change this behavior, so performing unsafe operations in unsafe functions requires an unsafe block.

For now, the lint is allow-by-default, which means that this PR does not change anything without overriding the lint level.

For more information, see [RFC 2585](https://github.com/rust-lang/rfcs/blob/master/text/2585-unsafe-block-in-unsafe-fn.md)

### Example

```rust
// An `unsafe fn` for demonstration purposes.
// Calling this is an unsafe operation.
unsafe fn unsf() {}

// #[allow(unsafe_op_in_unsafe_fn)] by default,
// the behavior of `unsafe fn` is unchanged
unsafe fn allowed() {
    // Here, no `unsafe` block is needed to
    // perform unsafe operations...
    unsf();

    // ...and any `unsafe` block is considered
    // unused and is warned on by the compiler.
    unsafe {
        unsf();
    }
}

#[warn(unsafe_op_in_unsafe_fn)]
unsafe fn warned() {
    // Removing this `unsafe` block will
    // cause the compiler to emit a warning.
    // (Also, no "unused unsafe" warning will be emitted here.)
    unsafe {
        unsf();
    }
}

#[deny(unsafe_op_in_unsafe_fn)]
unsafe fn denied() {
    // Removing this `unsafe` block will
    // cause a compilation error.
    // (Also, no "unused unsafe" warning will be emitted here.)
    unsafe {
        unsf();
    }
}
```
2021-03-10 08:01:25 +09:00
Yuki Okushi 1d5b2dc945
Rollup merge of #82292 - SkiFire13:fix-issue-82291, r=m-ou-se
Prevent specialized ZipImpl from calling `__iterator_get_unchecked` twice with the same index

Fixes #82291

It's open for review, but conflicts with #82289, wait before merging. The conflict involves only the new test, so it should be rather trivial to fix.
2021-03-07 10:41:10 +09:00
bors caca2121ff Auto merge of #74024 - Folyd:master, r=m-ou-se
Improve slice.binary_search_by()'s best-case performance to O(1)

This PR aimed to improve the [slice.binary_search_by()](https://doc.rust-lang.org/std/primitive.slice.html#method.binary_search_by)'s best-case performance to O(1).

# Noticed

I don't know why the docs of `binary_search_by` said `"If there are multiple matches, then any one of the matches could be returned."`, but the implementation isn't the same thing. Actually, it returns the **last one** if multiple matches found.

Then we got two options:

## If returns the last one is the correct or desired result

Then I can rectify the docs and revert my changes.

## If the docs are correct or desired result

Then my changes can be merged after fully reviewed.

However, if my PR gets merged, another issue raised: this could be a **breaking change** since if multiple matches found, the returning order no longer the last one instead of it could be any one.

For example:
```rust
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 1;
let idx = s.binary_search(&num);
s.insert(idx, 2);

// Old implementations
assert_eq!(s, [0, 1, 1, 1, 1, 2, 2, 3, 5, 8, 13, 21, 34, 42, 55]);

// New implementations
assert_eq!(s, [0, 1, 1, 1, 2, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
```

# Benchmarking

**Old implementations**
```sh
$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          59 ns/iter (+/- 4)
test slice::binary_search_l1_with_dups ... bench:          59 ns/iter (+/- 3)
test slice::binary_search_l2           ... bench:          76 ns/iter (+/- 5)
test slice::binary_search_l2_with_dups ... bench:          77 ns/iter (+/- 17)
test slice::binary_search_l3           ... bench:         183 ns/iter (+/- 23)
test slice::binary_search_l3_with_dups ... bench:         185 ns/iter (+/- 19)
```

**New implementations (1)**

Implemented by this PR.
```rust
if cmp == Equal {
    return Ok(mid);
} else if cmp == Less {
    base = mid
}
```
```sh
$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          58 ns/iter (+/- 2)
test slice::binary_search_l1_with_dups ... bench:          37 ns/iter (+/- 4)
test slice::binary_search_l2           ... bench:          76 ns/iter (+/- 3)
test slice::binary_search_l2_with_dups ... bench:          57 ns/iter (+/- 6)
test slice::binary_search_l3           ... bench:         200 ns/iter (+/- 30)
test slice::binary_search_l3_with_dups ... bench:         157 ns/iter (+/- 6)

$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          59 ns/iter (+/- 8)
test slice::binary_search_l1_with_dups ... bench:          37 ns/iter (+/- 2)
test slice::binary_search_l2           ... bench:          77 ns/iter (+/- 2)
test slice::binary_search_l2_with_dups ... bench:          57 ns/iter (+/- 2)
test slice::binary_search_l3           ... bench:         198 ns/iter (+/- 21)
test slice::binary_search_l3_with_dups ... bench:         158 ns/iter (+/- 11)

```

**New implementations (2)**

Suggested by `@nbdd0121` in [comment](https://github.com/rust-lang/rust/pull/74024#issuecomment-665430239).
```rust
base = if cmp == Greater { base } else { mid };
if cmp == Equal { break }
```

```sh
$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          59 ns/iter (+/- 7)
test slice::binary_search_l1_with_dups ... bench:          37 ns/iter (+/- 5)
test slice::binary_search_l2           ... bench:          75 ns/iter (+/- 3)
test slice::binary_search_l2_with_dups ... bench:          56 ns/iter (+/- 3)
test slice::binary_search_l3           ... bench:         195 ns/iter (+/- 15)
test slice::binary_search_l3_with_dups ... bench:         151 ns/iter (+/- 7)

$ ./x.py bench --stage 1 library/libcore
test slice::binary_search_l1           ... bench:          57 ns/iter (+/- 2)
test slice::binary_search_l1_with_dups ... bench:          38 ns/iter (+/- 2)
test slice::binary_search_l2           ... bench:          77 ns/iter (+/- 11)
test slice::binary_search_l2_with_dups ... bench:          57 ns/iter (+/- 4)
test slice::binary_search_l3           ... bench:         194 ns/iter (+/- 15)
test slice::binary_search_l3_with_dups ... bench:         151 ns/iter (+/- 18)

```

I run some benchmarking testings against on two implementations. The new implementation has a lot of improvement in duplicates cases, while in `binary_search_l3` case, it's a little bit slower than the old one.
2021-03-05 20:12:13 +00:00
Giacomo Stevanato c1bfb9a78d Add relevant test 2021-03-05 19:09:23 +01:00
Mara ee796c6523
Rollup merge of #82289 - SkiFire13:fix-issue-82282, r=m-ou-se
Fix underflow in specialized ZipImpl::size_hint

Fixes #82282
2021-03-05 10:57:19 +01:00
Mara e6a6df5daa
Rollup merge of #80723 - rylev:noop-lint-pass, r=estebank
Implement NOOP_METHOD_CALL lint

Implements the beginnings of https://github.com/rust-lang/lang-team/issues/67 - a lint for detecting noop method calls (e.g, calling `<&T as Clone>::clone()` when `T: !Clone`).

This PR does not fully realize the vision and has a few limitations that need to be addressed either before merging or in subsequent PRs:
* [ ] No UFCS support
* [ ] The warning message is pretty plain
* [ ] Doesn't work for `ToOwned`

The implementation uses [`Instance::resolve`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/instance/struct.Instance.html#method.resolve) which is normally later in the compiler. It seems that there are some invariants that this function relies on that we try our best to respect. For instance, it expects substitutions to have happened, which haven't yet performed, but we check first for `needs_subst` to ensure we're dealing with a monomorphic type.

Thank you to ```@davidtwco,``` ```@Aaron1011,``` and ```@wesleywiser``` for helping me at various points through out this PR ❤️.
2021-03-05 10:57:14 +01:00
Giacomo Stevanato 8b9ac4d415 Add test for underflow in specialized Zip's size_hint 2021-03-03 21:16:08 +01:00
Ryan Levick 1999a3147f Fix borrow and deref 2021-03-03 11:23:29 +01:00
Ryan Levick d3b49c2ed2 Only allow new lint when not bootstrapping - since beta doesn't know about the lint 2021-03-03 11:22:50 +01:00
Ryan Levick ee65416f0d Fix core tests 2021-03-03 11:22:49 +01:00
Ralf Jung dc685f6815 enable atomic_min/max tests in Miri 2021-03-02 19:58:55 +01:00
Folyd 3eb5bee242 Fix `binary_search_by()` overflow issue in ZST case 2021-02-27 22:11:44 +08:00
Dylan DPC 4b9c213d6f
Rollup merge of #81167 - usbalbin:const_write, r=oli-obk
Make ptr::write const

~~The code in this PR as of right now is not much more than an experiment.~~

~~This should, if I am not mistaken, in theory compile and pass the tests once the bootstraping compiler is updated. Thus the PR is blocked on that which should happen some time after the February the 9th. Also we might want to wait for #79989 to avoid regressing performance due to using `mem::forget` over `intrinsics::forget`~~.
2021-02-25 14:33:51 +01:00
Albin Hedman 89c761058a
Constify ptr::write and the write[_unaligned] methods on *mut T
Constify intrinsics::forget
2021-02-23 18:00:01 +01:00
Dylan DPC 51511c75b5
Rollup merge of #82391 - RalfJung:miri-atomic-minmax, r=dtolnay
disable atomic_max/min tests in Miri

Disable some tests that currently [fail in Miri](https://travis-ci.com/github/RalfJung/miri-test-libstd/builds/217788631).
2021-02-23 16:10:30 +01:00
Ralf Jung dd9ab160a1 disable atomic_max/min tests in Miri 2021-02-22 10:06:51 +01:00
Joshua Nelson 3733275854 Update the bootstrap compiler
Note this does not change `core::derive` since it was merged after the
beta bump.
2021-02-20 17:19:30 -05:00
Dylan DPC f8b61d852c
Rollup merge of #82093 - bjorn3:more_atomic_tests, r=kennytm
Add tests for Atomic*::fetch_{min,max}

This ensures that all atomic operations except for fences are tested. This has been useful to test my work on using atomic instructions for atomic operations in cg_clif instead of a global lock.
2021-02-19 02:49:07 +01:00
LeSeulArtichaut ec20993c4d Stabilize `unsafe_op_in_unsafe_fn` lint 2021-02-18 17:12:15 +01:00
bors d1462d8558 Auto merge of #81172 - SimonSapin:ptr-metadata, r=oli-obk
Implement RFC 2580: Pointer metadata & VTable

RFC: https://github.com/rust-lang/rfcs/pull/2580

~~Before merging this PR:~~

* [x] Wait for the end of the RFC’s [FCP to merge](https://github.com/rust-lang/rfcs/pull/2580#issuecomment-759145278).
* [x] Open a tracking issue: https://github.com/rust-lang/rust/issues/81513
* [x] Update `#[unstable]` attributes in the PR with the tracking issue number

----

This PR extends the language with a new lang item for the `Pointee` trait which is special-cased in trait resolution to implement it for all types. Even in generic contexts, parameters can be assumed to implement it without a corresponding bound.

For this I mostly imitated what the compiler was already doing for the `DiscriminantKind` trait. I’m very unfamiliar with compiler internals, so careful review is appreciated.

This PR also extends the standard library with new unstable APIs in `core::ptr` and `std::ptr`:

```rust
pub trait Pointee {
    /// One of `()`, `usize`, or `DynMetadata<dyn SomeTrait>`
    type Metadata: Copy + Send + Sync + Ord + Hash + Unpin;
}

pub trait Thin = Pointee<Metadata = ()>;

pub const fn metadata<T: ?Sized>(ptr: *const T) -> <T as Pointee>::Metadata {}

pub const fn from_raw_parts<T: ?Sized>(*const (), <T as Pointee>::Metadata) -> *const T {}
pub const fn from_raw_parts_mut<T: ?Sized>(*mut (),<T as Pointee>::Metadata) -> *mut T {}

impl<T: ?Sized> NonNull<T> {
    pub const fn from_raw_parts(NonNull<()>, <T as Pointee>::Metadata) -> NonNull<T> {}

    /// Convenience for `(ptr.cast(), metadata(ptr))`
    pub const fn to_raw_parts(self) -> (NonNull<()>, <T as Pointee>::Metadata) {}
}

impl<T: ?Sized> *const T {
    pub const fn to_raw_parts(self) -> (*const (), <T as Pointee>::Metadata) {}
}

impl<T: ?Sized> *mut T {
    pub const fn to_raw_parts(self) -> (*mut (), <T as Pointee>::Metadata) {}
}

/// `<dyn SomeTrait as Pointee>::Metadata == DynMetadata<dyn SomeTrait>`
pub struct DynMetadata<Dyn: ?Sized> {
    // Private pointer to vtable
}

impl<Dyn: ?Sized> DynMetadata<Dyn> {
    pub fn size_of(self) -> usize {}
    pub fn align_of(self) -> usize {}
    pub fn layout(self) -> crate::alloc::Layout {}
}

unsafe impl<Dyn: ?Sized> Send for DynMetadata<Dyn> {}
unsafe impl<Dyn: ?Sized> Sync for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Debug for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Unpin for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Copy for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Clone for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Eq for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> PartialEq for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Ord for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> PartialOrd for DynMetadata<Dyn> {}
impl<Dyn: ?Sized> Hash for DynMetadata<Dyn> {}
```

API differences from the RFC, in areas noted as unresolved questions in the RFC:

* Module-level functions instead of associated `from_raw_parts` functions on `*const T` and `*mut T`, following the precedent of `null`, `slice_from_raw_parts`, etc.
* Added `to_raw_parts`
2021-02-18 04:22:16 +00:00
Thom Chiovoloni 2711b011e6 Rename Result::ok_or_err to Result::into_ok_or_err 2021-02-17 08:54:52 -08:00
Thom Chiovoloni f688bee4ec Add a `Result::ok_or_err` method to extract a `T` from `Result<T, T>` 2021-02-17 08:51:58 -08:00
bjorn3 4fa9e08e3d Enable the tests on Arm Linux too 2021-02-17 10:01:39 +01:00
bjorn3 dfdadad228 Ignore Atomic*::fetch_{min,max} tests on ARM 2021-02-16 09:45:27 +01:00
Simon Sapin 5ade3fe32c Add a ThinBox library as a libcore test for pointer metadata APIs 2021-02-15 14:27:51 +01:00
Simon Sapin 642486c2b2 Fix libcore unit tests in stage 0 2021-02-15 14:27:48 +01:00
Simon Sapin 937d580a25 Add `ptr::from_raw_parts`, `ptr::from_raw_parts_mut`, and `NonNull::from_raw_parts`
The use of module-level functions instead of associated functions
on `<*const T>` or `<*mut T>` follows the precedent of
`ptr::slice_from_raw_parts` and `ptr::slice_from_raw_parts_mut`.
2021-02-15 14:27:31 +01:00
Simon Sapin 9ab83b9338 Add `size_of`, `align_of`, and `layout` methods to `DynMetadata` 2021-02-15 14:27:17 +01:00
Simon Sapin b1e15fa8a2 Parameterize `DynMetadata` over its `dyn SomeTrait` type 2021-02-15 14:27:16 +01:00
Simon Sapin 696b239f72 Add `ptr::Pointee` trait (for all types) and `ptr::metadata` function
RFC: https://github.com/rust-lang/rfcs/pull/2580
2021-02-15 14:27:12 +01:00
bjorn3 d1a541e342 Add tests for Atomic*::fetch_{min,max} 2021-02-14 11:31:33 +01:00
VillSnow afdc8c7918 stabilize partition_point 2021-02-12 21:57:17 +09:00
Scott McMurray 1b7309edd6 Expand the docs for ops::ControlFlow a bit
Since I was writing some examples for an RFC anyway.
2021-02-06 22:36:05 -08:00
Mara Bos cc882fc3be
Rollup merge of #80011 - Stupremee:stabilize-peekable-next-if, r=dtolnay
Stabilize `peekable_next_if`

This PR stabilizes the `peekable_next_if` feature

Resolves #72480
2021-02-06 00:14:06 +01:00
Mara Bos 89882388d9 Revert stabilizing integer::BITS. 2021-02-03 22:23:58 +01:00
Ashley Mannix 8940a2652e stabilize int_bits_const 2021-01-31 21:50:47 +10:00
Jonas Schievink 1e99f26894
Rollup merge of #80470 - SimonSapin:array-intoiter-type, r=m-ou-se
Stabilize by-value `[T; N]` iterator `core::array::IntoIter`

Tracking issue: https://github.com/rust-lang/rust/issues/65798

This is unblocked now that `min_const_generics` has been stabilized in https://github.com/rust-lang/rust/pull/79135.

This PR does *not* include the corresponding `IntoIterator` impl, which is https://github.com/rust-lang/rust/pull/65819. Instead, an iterator can be constructed through the `new` method.

`new` would become unnecessary when `IntoIterator` is implemented and might be deprecated then, although it will stay stable.
2021-01-31 01:47:25 +01:00
Folyd 7d078cfb94 Simplify binary search logic to full branch code to let CPU guessing branch more precisely 2021-01-30 14:11:47 +08:00
Folyd 18e44a1be4 Improve slice.binary_search_by()'s best-case performance to O(1) 2021-01-30 14:11:47 +08:00
Yuki Okushi 94e093ab97
Rollup merge of #81306 - SkiFire13:fuse-flatten, r=cuviper
Fuse inner iterator in FlattenCompat and improve related tests

Fixes #81248
2021-01-29 09:17:36 +09:00
Yuki Okushi b2f6c2aa9b
Rollup merge of #81412 - hyd-dev:array-assume-init-wrong-assertion, r=m-ou-se
Fix assertion in `MaybeUninit::array_assume_init()` for zero-length arrays

That assertion has a false positive ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=63922b8c897b04112adcdf346deb1d0e)):
```rust
#![feature(maybe_uninit_array_assume_init)]

use std::mem::MaybeUninit;

enum Uninhabited {}

fn main() {
    unsafe {
        // thread 'main' panicked at 'attempted to instantiate uninhabited type `Uninhabited`'
        MaybeUninit::<Uninhabited>::array_assume_init([]);
    }
}
```
*Previously reported in https://github.com/rust-lang/rust/pull/80600#discussion_r564496692.*

This PR makes it ignore zero-length arrays.

cc #80908
2021-01-27 04:43:37 +09:00
Yuki Okushi fe6b3a9792
Rollup merge of #80876 - ojeda:option-result-unwrap_unchecked, r=m-ou-se
Add `unwrap_unchecked()` methods for `Option` and `Result`

In particular:
  - `unwrap_unchecked()` for `Option`.
  - `unwrap_unchecked()` and `unwrap_err_unchecked()` for `Result`.

These complement other `*_unchecked()` methods in `core` etc.

Currently there are a couple of places it may be used inside rustc (`LinkedList`, `BTree`). It is also easy to find other repositories with similar functionality.

Fixes #48278.
2021-01-27 04:43:14 +09:00
hyd-dev f52066726d
Fix assertion in `MaybeUninit::array_assume_init()` for zero-length arrays 2021-01-27 00:16:58 +08:00
Giacomo Stevanato f241c10223 Improve flatten-fuse tests 2021-01-23 21:33:38 +01:00
Daniel Conley 0c78500426 library/core/tests/iter documentation and cleanup 2021-01-22 17:57:08 -05:00
Daniel Conley bc830a274b library/core/tests/iter rearrange & add back missed doc comments 2021-01-22 17:57:07 -05:00
Daniel Conley 1e3a2def67 library/core/test/iter add newlines between tests 2021-01-22 16:58:21 -05:00
Daniel Conley 3ce97000e1 library/core/test/iter.rs split attempt 2 2021-01-21 19:36:32 -05:00
Mara Bos 9272d53c5a Stop `fold` at first None when iterator yield 2021-01-19 12:17:58 +00:00