about summary refs log tree commit diff
path: root/library/core/src
AgeCommit message (Collapse)AuthorLines
2024-04-10Add basic f16 and f128 modulesTrevor Gross-0/+36
Create empty modules so `rustdoc` has someplace to link to for these types.
2024-04-10Add basic library support for `f16` and `f128`Trevor Gross-11/+20
Implement basic operation traits that get lowered to intrinsics. This includes codegen tests for implemented operations.
2024-04-10Revert "Put basic impls for f16 and f128 behind cfg(not(bootstrap))"Trevor Gross-21/+6
This reverts commit 049a91753594422b6c672bf5a46e04076fc45d9e. The resolution to <https://github.com/rust-lang/rust/issues/123282> is that the `f16`/`f128` regression in the beta compiler was fixable without a revert, so the commit adding `#[cfg(not(bootstrap))]` is no longer useful (added in <https://github.com/rust-lang/rust/pull/123390>). Revert this commit because not having these basic impls bootstrap-gated simplifies everything else that uses them.
2024-04-09Fix typo in `Future::poll()` docsJules Bertholet-1/+1
2024-04-08Stabilize `cstr_count_bytes`Trevor Gross-3/+1
Newly stable API: ```rust impl CStr { pub fn count_bytes(&self) -> usize; } ``` Const stabilization has not yet been decided, so that will continue to be gated under <https://github.com/rust-lang/rust/issues/113219>. Fixes: <https://github.com/rust-lang/rust/issues/114441>
2024-04-08Rollup merge of #123564 - scottmcm:step-by-div-zero, r=joboetMatthias Krüger-31/+49
Don't emit divide-by-zero panic paths in `StepBy::len` I happened to notice today that there's actually two such calls emitted in the assembly: <https://rust.godbolt.org/z/1Wbbd3Ts6> Since they're impossible, hopefully telling LLVM that will also help optimizations elsewhere.
2024-04-08Auto merge of #120131 - oli-obk:pattern_types_syntax, r=compiler-errorsbors-0/+17
Implement minimal, internal-only pattern types in the type system rebase of https://github.com/rust-lang/rust/pull/107606 You can create pattern types with `std::pat::pattern_type!(ty is pat)`. The feature is incomplete and will panic on you if you use any pattern other than integral range patterns. The only way to create or deconstruct a pattern type is via `transmute`. This PR's implementation differs from the MCP's text. Specifically > This means you could implement different traits for different pattern types with the same base type. Thus, we just forbid implementing any traits for pattern types. is violated in this PR. The reason is that we do need impls after all in order to make them usable as fields. constants of type `std::time::Nanoseconds` struct are used in patterns, so the type must be structural-eq, which it only can be if you derive several traits on it. It doesn't need to be structural-eq recursively, so we can just manually implement the relevant traits on the pattern type and use the pattern type as a private field. Waiting on: * [x] move all unrelated commits into their own PRs. * [x] fix niche computation (see 2db07f94f44f078daffe5823680d07d4fded883f) * [x] add lots more tests * [x] T-types MCP https://github.com/rust-lang/types-team/issues/126 to finish * [x] some commit cleanup * [x] full self-review * [x] remove 61bd325da19a918cc3e02bbbdce97281a389c648, it's not necessary anymore I think. * [ ] ~~make sure we never accidentally leak pattern types to user code (add stability checks or feature gate checks and appopriate tests)~~ we don't even do this for the new float primitives * [x] get approval that [the scope expansion to trait impls](https://rust-lang.zulipchat.com/#narrow/stream/326866-t-types.2Fnominated/topic/Pattern.20types.20types-team.23126/near/427670099) is ok r? `@BoxyUwU`
2024-04-08Rollup merge of #123595 - balaganesh102004:master, r=joboetMatthias Krüger-1/+1
Documentation fix Changed "It must not be an identical residual when interconversion is involved" to "The residual is not mandated to be identical when interconversion is involved." as the previous parenthetical appears to state that the residual is not permitted to be identical when interconversion is involved. However the intention of the original wording was to convey that the residual is not required to be identical when interconversion is involved, which makes more sense contextually.
2024-04-08Add pattern types to parserOli Scherer-0/+17
2024-04-07Fix typo in library/core/src/iter/traits/iterator.rsGabriel Dolberg-1/+1
2024-04-07Made changes in documentationBALAGANESH-1/+1
2024-04-07Auto merge of #123561 - saethlin:str-unchecked-sub-index, r=scottmcmbors-6/+9
Use unchecked_sub in str indexing https://github.com/rust-lang/rust/pull/108763 applied this logic to indexing for slices, but of course `str` has its own separate impl. Found this by skimming over the codegen for https://github.com/oxidecomputer/hubris/; their dist builds enable overflow checks so the lack of `unchecked_sub` was producing an impossible-to-hit overflow check and also inhibiting some inlining. r? scottmcm
2024-04-07Rollup merge of #123522 - dtolnay:constatomicintoinner, r=NilstriebMatthias Krüger-6/+48
Stabilize const Atomic*::into_inner Partial stabilization for https://github.com/rust-lang/rust/issues/78729, for which the FCP has already completed. The other `into_inner` functions in that tracking issue (`UnsafeCell`, `Cell`, `RefCell`) are blocked on https://github.com/rust-lang/rust/issues/73255 for now. ```console error[E0493]: destructor of `UnsafeCell<T>` cannot be evaluated at compile-time --> library/core/src/cell.rs:2076:29 | 2076 | pub const fn into_inner(self) -> T { | ^^^^ the destructor for this type cannot be evaluated in constant functions 2077 | self.value 2078 | } | - value is dropped here ```
2024-04-07Rollup merge of #123411 - saethlin:ub-checks, r=Urgau,RalfJungMatthias Krüger-7/+7
Put checks that detect UB under their own flag below debug_assertions Implementation of https://github.com/rust-lang/compiler-team/issues/725
2024-04-06Don't emit divide-by-zero panic paths in `StepBy::len`Scott McMurray-31/+49
I happened to notice today that there's actually two such calls emitted in the assembly: <https://rust.godbolt.org/z/1Wbbd3Ts6> Since they're impossible, hopefully telling LLVM that will also help optimizations elsewhere.
2024-04-06Use unchecked_sub in str indexingBen Kimock-6/+9
2024-04-06Rollup merge of #123541 - RalfJung:remove-old-hacks, r=Mark-SimulacrumGuillaume Gomez-5/+1
remove miri-test-libstd hacks that are no longer needed In https://github.com/rust-lang/rust/pull/123317 we developed a different approach to testing the standard library in Miri, and with https://github.com/rust-lang/miri-test-libstd/pull/56 the out-of-tree miri-test-libstd has been switched to that approach. That makes these hacks here no longer necessary.
2024-04-06Put checks that detect UB under their own flag below debug_assertionsBen Kimock-7/+7
2024-04-06Rollup merge of #122291 - lilasta:stabilize_const_location_fields, r=dtolnayMatthias Krüger-6/+5
Stabilize `const_caller_location` and `const_location_fields` Closes #102911. Closes #76156. tests: [library/core/tests/panic/location.rs](https://github.com/rust-lang/rust/blob/3521a2f2f317cb978063842485c7d1bc86ec82b6/library/core/tests/panic/location.rs) API: ```rust // core::panic::location impl Location { pub const fn caller() -> &'static Location<'static>; pub const fn file(&self) -> &str; pub const fn line(&self) -> u32; pub const fn column(&self) -> u32; } ```
2024-04-06Rollup merge of #114788 - tisonkun:get_mut_or_init, r=dtolnayMatthias Krüger-9/+84
impl get_mut_or_init and get_mut_or_try_init for OnceCell and OnceLock See also https://github.com/rust-lang/rust/issues/74465#issuecomment-1676522051 I'm trying to understand the process for such proposal. And I'll appreciate it if anyone can guide me the next step for consensus or adding tests.
2024-04-06remove miri-test-libstd hacks that are no longer neededRalf Jung-5/+1
2024-04-05Hide async_gen_internals from standard library documentationDavid Tolnay-0/+3
2024-04-05Stabilize const Atomic*::into_innerDavid Tolnay-6/+48
2024-04-05Auto merge of #123317 - RalfJung:test-in-miri, r=m-ou-se,saethlin,onur-ozkanbors-0/+4
Support running library tests in Miri This adds a new bootstrap subcommand `./x.py miri` which can test libraries in Miri. This is in preparation for eventually doing that as part of bors CI, but this PR only adds the infrastructure, and doesn't enable it yet. `@rust-lang/bootstrap` should this be `x.py test --miri library/core` or `x.py miri library/core`? The flag has the advantage that we don't have to copy all the arguments from `Subcommand::Test`. It has the disadvantage that most test steps just ignore `--miri` and still run tests the regular way. For clippy you went the route of making it a separate subcommand. ~~I went with a flag now as that seemed easier, but I can change this.~~ I made it a new subcommand. Note however that the regular cargo invocation would be `cargo miri test ...`, so `x.py` is still going to be different in that the `test` is omitted. That said, we could also make it `./x.py miri-test` to make that difference smaller -- that's in fact more consistent with the internal name of the command when bootstrap invokes cargo. `@rust-lang/libs` ~~unfortunately this PR does some unholy things to the `lib.rs` files of our library crates.~~ `@m-ou-se` found a way that entirely avoids library-level hacks, except for some new small `lib.miri.rs` files that hopefully you will never have to touch. There's a new hack in cargo-miri but there it is in good company...
2024-04-04Rollup merge of #123206 - stepancheg:pointee-metadata-freeze, r=AmanieuJacob Pratt-1/+2
Require Pointee::Metadata to be Freeze So pointee metadata can be used in anonymous statics. This is prerequisite for implementing ThinBox without allocation for ZST. See https://github.com/rust-lang/rust/pull/123184#discussion_r1544627488 r? joboet
2024-04-05Impl `DerefPure` for more std typesNadrieril-3/+15
2024-04-04force exhaustion in iter::ArrayChunks::into_remainderArthur Carcano-1/+14
2024-04-03Rollup merge of #122964 - joboet:pointer_expose, r=AmanieuMatthias Krüger-20/+25
Rename `expose_addr` to `expose_provenance` `expose_addr` is a bad name, an address is just a number and cannot be exposed. The operation is actually about the provenance of the pointer. This PR thus changes the name of the method to `expose_provenance` without changing its return type. There is sufficient precedence for returning a useful value from an operation that does something else without the name indicating such, e.g. [`Option::insert`](https://doc.rust-lang.org/nightly/std/option/enum.Option.html#method.insert) and [`MaybeUninit::write`](https://doc.rust-lang.org/nightly/std/mem/union.MaybeUninit.html#method.write). Returning the address is merely convenient, not a fundamental part of the operation. This is implied by the fact that integers do not have provenance since ```rust let addr = ptr.addr(); ptr.expose_provenance(); let new = ptr::with_exposed_provenance(addr); ``` must behave exactly like ```rust let addr = ptr.expose_provenance(); let new = ptr::with_exposed_provenance(addr); ``` as the result of `ptr.expose_provenance()` and `ptr.addr()` is the same integer. Therefore, this PR removes the `#[must_use]` annotation on the function and updates the documentation to reflect the important part. ~~An alternative name would be `expose_provenance`. I'm not at all opposed to that, but it makes a stronger implication than we might want that the provenance of the pointer returned by `ptr::with_exposed_provenance`[^1] is the same as that what was exposed, which is not yet specified as such IIUC. IMHO `expose` does not make that connection.~~ A previous version of this PR suggested `expose` as name, libs-api [decided on](https://github.com/rust-lang/rust/pull/122964#issuecomment-2033194319) `expose_provenance` to keep the symmetry with `with_exposed_provenance`. CC `@RalfJung` r? libs-api [^1]: I'm using the new name for `from_exposed_addr` suggested by #122935 here.
2024-04-03add 'x.py miri', and make it work for 'library/{core,alloc,std}'Ralf Jung-0/+4
2024-04-03Add docs for `FromIterator<(AE, BE)> for (A, B)`Maybe Waffle-0/+19
2024-04-03Implement `FromIterator<(AE, BE)>` for `(impl Default+Extend<AE>, impl ↵Maybe Waffle-0/+14
Default+Extend<BE>)`
2024-04-03rename `expose_addr` to `expose_provenance`joboet-20/+25
2024-04-03Auto merge of #123390 - tgross35:f16-f128-libs-basic-impls-bootstrap, r=jhprattbors-6/+21
Put basic impls for f16 and f128 behind cfg(not(bootstrap)) We will lose `f16` and `f128` in the beta compiler after the revert for <https://github.com/rust-lang/rust/issues/123282> lands. Change what was added in <https://github.com/rust-lang/rust/pull/123085> to be behind `#[cfg(not(bootstrap))]` to account for this.
2024-04-02Rollup merge of #123203 - jkarneges:context-ext, r=AmanieuJacob Pratt-3/+64
Add `Context::ext` This change enables `Context` to carry arbitrary extension data via a single `&mut dyn Any` field. ```rust #![feature(context_ext)] impl Context { fn ext(&mut self) -> &mut dyn Any; } impl ContextBuilder { fn ext(self, data: &'a mut dyn Any) -> Self; fn from(cx: &'a mut Context<'_>) -> Self; fn waker(self, waker: &'a Waker) -> Self; } ``` Basic usage: ```rust struct MyExtensionData { executor_name: String, } let mut ext = MyExtensionData { executor_name: "foo".to_string(), }; let mut cx = ContextBuilder::from_waker(&waker).ext(&mut ext).build(); if let Some(ext) = cx.ext().downcast_mut::<MyExtensionData>() { println!("{}", ext.executor_name); } ``` Currently, `Context` only carries a `Waker`, but there is interest in having it carry other kinds of data. Examples include [LocalWaker](https://github.com/rust-lang/rust/issues/118959), [a reactor interface](https://github.com/rust-lang/libs-team/issues/347), and [multiple arbitrary values by type](https://docs.rs/context-rs/latest/context_rs/). There is also a general practice in the ecosystem of sharing data between executors and futures via thread-locals or globals that would arguably be better shared via `Context`, if it were possible. The `ext` field would provide a low friction (to stabilization) solution to enable experimentation. It would enable experimenting with what kinds of data we want to carry as well as with what data structures we may want to use to carry such data. Dedicated fields for specific kinds of data could still be added directly on `Context` when we have sufficient experience or understanding about the problem they are solving, such as with `LocalWaker`. The `ext` field would be for data for which we don't have such experience or understanding, and that could be graduated to dedicated fields once proven. Both the provider and consumer of the extension data must be aware of the concrete type behind the `Any`. This means it is not possible for the field to carry an abstract interface. However, the field can carry a concrete type which in turn carries an interface. There are different ways one can imagine an interface-carrying concrete type to work, hence the benefit of being able to experiment with such data structures. ## Passing interfaces Interfaces can be placed in a concrete type, such as a struct, and then that type can be casted to `Any`. However, one gotcha is `Any` cannot contain non-static references. This means one cannot simply do: ```rust struct Extensions<'a> { interface1: &'a mut dyn Trait1, interface2: &'a mut dyn Trait2, } let mut ext = Extensions { interface1: &mut impl1, interface2: &mut impl2, }; let ext: &mut dyn Any = &mut ext; ``` To work around this without boxing, unsafe code can be used to create a safe projection using accessors. For example: ```rust pub struct Extensions { interface1: *mut dyn Trait1, interface2: *mut dyn Trait2, } impl Extensions { pub fn new<'a>( interface1: &'a mut (dyn Trait1 + 'static), interface2: &'a mut (dyn Trait2 + 'static), scratch: &'a mut MaybeUninit<Self>, ) -> &'a mut Self { scratch.write(Self { interface1, interface2, }) } pub fn interface1(&mut self) -> &mut dyn Trait1 { unsafe { self.interface1.as_mut().unwrap() } } pub fn interface2(&mut self) -> &mut dyn Trait2 { unsafe { self.interface2.as_mut().unwrap() } } } let mut scratch = MaybeUninit::uninit(); let ext: &mut Extensions = Extensions::new(&mut impl1, &mut impl2, &mut scratch); // ext can now be casted to `&mut dyn Any` and back, and used safely let ext: &mut dyn Any = ext; ``` ## Context inheritance Sometimes when futures poll other futures they want to provide their own `Waker` which requires creating their own `Context`. Unfortunately, polling sub-futures with a fresh `Context` means any properties on the original `Context` won't get propagated along to the sub-futures. To help with this, some additional methods are added to `ContextBuilder`. Here's how to derive a new `Context` from another, overriding only the `Waker`: ```rust let mut cx = ContextBuilder::from(parent_cx).waker(&new_waker).build(); ```
2024-04-02Rollup merge of #122935 - RalfJung:with-exposed-provenance, r=AmanieuJacob Pratt-26/+33
rename ptr::from_exposed_addr -> ptr::with_exposed_provenance As discussed on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-opsem/topic/To.20expose.20or.20not.20to.20expose/near/427757066). The old name, `from_exposed_addr`, makes little sense as it's not the address that is exposed, it's the provenance. (`ptr.expose_addr()` stays unchanged as we haven't found a better option yet. The intended interpretation is "expose the provenance and return the address".) The new name nicely matches `ptr::without_provenance`.
2024-04-02set tracking issueJustin Karneges-4/+4
2024-04-02Auto merge of #123385 - matthiaskrgr:rollup-v69vjbn, r=matthiaskrgrbors-32/+77
Rollup of 8 pull requests Successful merges: - #123198 (Add fn const BuildHasherDefault::new) - #123226 (De-LLVM the unchecked shifts [MCP#693]) - #123302 (Make sure to insert `Sized` bound first into clauses list) - #123348 (rustdoc: add a couple of regression tests) - #123362 (Check that nested statics in thread locals are duplicated per thread.) - #123368 (CFI: Support non-general coroutines) - #123375 (rustdoc: synthetic auto trait impls: accept unresolved region vars for now) - #123378 (Update sysinfo to 0.30.8) Failed merges: - #123349 (Fix capture analysis for by-move closure bodies) r? `@ghost` `@rustbot` modify labels: rollup
2024-04-02Put basic impls for f16 and f128 behind cfg(not(bootstrap))Trevor Gross-6/+21
We will lose `f16` and `f128` in the beta compiler after the revert for <https://github.com/rust-lang/rust/issues/123282> lands. Change what was added in <https://github.com/rust-lang/rust/pull/123085> to be behind `#[cfg(not(bootstrap))]` to account for this.
2024-04-02Rollup merge of #123226 - scottmcm:u32-shifts, r=WaffleLapkinMatthias Krüger-31/+64
De-LLVM the unchecked shifts [MCP#693] This is just one part of the MCP (https://github.com/rust-lang/compiler-team/issues/693), but it's the one that IMHO removes the most noise from the standard library code. Seems net simpler this way, since MIR already supported heterogeneous shifts anyway, and thus it's not more work for backends than before. r? WaffleLapkin
2024-04-02Rollup merge of #123198 - krtab:build_hasher_default_const_new, r=AmanieuMatthias Krüger-1/+13
Add fn const BuildHasherDefault::new See [tracking issue](https://github.com/rust-lang/rust/issues/123197) for justification.
2024-04-02Auto merge of #118310 - scottmcm:three-way-compare, r=davidtwcobors-6/+36
Add `Ord::cmp` for primitives as a `BinOp` in MIR Update: most of this OP was written months ago. See https://github.com/rust-lang/rust/pull/118310#issuecomment-2016940014 below for where we got to recently that made it ready for review. --- There are dozens of reasonable ways to implement `Ord::cmp` for integers using comparison, bit-ops, and branches. Those differences are irrelevant at the rust level, however, so we can make things better by adding `BinOp::Cmp` at the MIR level: 1. Exactly how to implement it is left up to the backends, so LLVM can use whatever pattern its optimizer best recognizes and cranelift can use whichever pattern codegens the fastest. 2. By not inlining those details for every use of `cmp`, we drastically reduce the amount of MIR generated for `derive`d `PartialOrd`, while also making it more amenable to MIR-level optimizations. Having extremely careful `if` ordering to μoptimize resource usage on broadwell (#63767) is great, but it really feels to me like libcore is the wrong place to put that logic. Similarly, using subtraction [tricks](https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign) (#105840) is arguably even nicer, but depends on the optimizer understanding it (https://github.com/llvm/llvm-project/issues/73417) to be practical. Or maybe [bitor is better than add](https://discourse.llvm.org/t/representing-in-ir/67369/2?u=scottmcm)? But maybe only on a future version that [has `or disjoint` support](https://discourse.llvm.org/t/rfc-add-or-disjoint-flag/75036?u=scottmcm)? And just because one of those forms happens to be good for LLVM, there's no guarantee that it'd be the same form that GCC or Cranelift would rather see -- especially given their very different optimizers. Not to mention that if LLVM gets a spaceship intrinsic -- [which it should](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Suboptimal.20inlining.20in.20std.20function.20.60binary_search.60/near/404250586) -- we'll need at least a rustc intrinsic to be able to call it. As for simplifying it in Rust, we now regularly inline `{integer}::partial_cmp`, but it's quite a large amount of IR. The best way to see that is with https://github.com/rust-lang/rust/commit/8811efa88b25b5e41d63850e6047e8257c677858#diff-d134c32d028fbe2bf835fef2df9aca9d13332dd82284ff21ee7ebf717bfa4765R113 -- I added a new pre-codegen MIR test for a simple 3-tuple struct, and this PR change it from 36 locals and 26 basic blocks down to 24 locals and 8 basic blocks. Even better, as soon as the construct-`Some`-then-match-it-in-same-BB noise is cleaned up, this'll expose the `Cmp == 0` branches clearly in MIR, so that an InstCombine (#105808) can simplify that to just a `BinOp::Eq` and thus fix some of our generated code perf issues. (Tracking that through today's `if a < b { Less } else if a == b { Equal } else { Greater }` would be *much* harder.) --- r? `@ghost` But first I should check that perf is ok with this ~~...and my true nemesis, tidy.~~
2024-04-02DOC: Add FFI example for slice::from_raw_parts()Matthias Geier-0/+21
2024-04-02Auto merge of #122945 - andy-k:sorted-vec-example, r=jhprattbors-3/+5
improve example on inserting to a sorted vector to avoid shifting equal elements
2024-04-01Fix error message for `env!` when env var is not valid Unicodebeetrees-1/+2
2024-03-31Rollup merge of #123271 - JaniM:janim/sliceindex-doc, r=NilstriebJubilee-0/+11
doc: describe panic conditions for SliceIndex implementations Implementation note: The most probable place for users to find the documentation is at https://doc.rust-lang.org/std/slice/trait.SliceIndex.html On that page, documentation added to specific methods will not be visible. As such, I opted to add the comments to the impl blocks directly. Helps with #121568.
2024-03-31warn against implementing FreezeRalf Jung-0/+7
2024-03-31doc: describe panic conditions for SliceIndex implementationsJani Mustonen-0/+11
Implementation note: The most probable place for users to find the documentation is at https://doc.rust-lang.org/std/slice/trait.SliceIndex.html On that page, documentation added to specific methods will not be visible. As such, I opted to add the comments to the impl blocks directly. Helps with #121568.
2024-03-31Require Pointee::Metadata to be FreezeStepan Koltsov-1/+2
So pointee metadata can be used in anonymous statics. This is prerequisite for implementing ThinBox without allocation for ZST. See https://github.com/rust-lang/rust/pull/123184#discussion_r1544627488
2024-03-31Auto merge of #123181 - stepancheg:pointee-metadata-debug, r=the8472,Amanieubors-1/+1
Require Debug for Pointee::Metadata Useful for debugging.
2024-03-30Auto merge of #123085 - tgross35:f16-f128-step4.0-libs-basic-impls, r=Amanieubors-4/+10
Add basic trait impls for `f16` and `f128` Split off part of <https://github.com/rust-lang/rust/pull/122470> so the compiler doesn't ICE because it expects primitives to have some minimal traits. Fixes <https://github.com/rust-lang/rust/issues/123074>