Skip to main content

core/
lib.rs

1//! # The Rust Core Library
2//!
3//! The Rust Core Library is the dependency-free[^free] foundation of [The
4//! Rust Standard Library](../std/index.html). It is the portable glue
5//! between the language and its libraries, defining the intrinsic and
6//! primitive building blocks of all Rust code. It links to no
7//! upstream libraries, no system libraries, and no libc.
8//!
9//! [^free]: Strictly speaking, there are some symbols which are needed but
10//!          they aren't always necessary.
11//!
12//! The core library is *minimal*: it isn't even aware of heap allocation,
13//! nor does it provide concurrency or I/O. These things require
14//! platform integration, and this library is platform-agnostic.
15//!
16//! # How to use the core library
17//!
18//! Please note that all of these details are currently not considered stable.
19//!
20// FIXME: Fill me in with more detail when the interface settles
21//! This library is built on the assumption of a few existing symbols:
22//!
23//! * `memcpy`, `memmove`, `memset`, `memcmp`, `bcmp`, `strlen` - These are core memory routines
24//!   which are generated by Rust codegen backends. Additionally, this library can make explicit
25//!   calls to `strlen`. Their signatures are the same as found in C, but there are extra
26//!   assumptions about their semantics: For `memcpy`, `memmove`, `memset`, `memcmp`, and `bcmp`, if
27//!   the `n` parameter is 0, the function is assumed to not be UB, even if the pointers are NULL or
28//!   dangling. (Note that making extra assumptions about these functions is common among compilers:
29//!   [clang](https://reviews.llvm.org/D86993) and [GCC](https://gcc.gnu.org/onlinedocs/gcc/Standards.html#C-Language) do the same.)
30//!   These functions are often provided by the system libc, but can also be provided by the
31//!   [compiler-builtins crate](https://crates.io/crates/compiler_builtins).
32//!   Note that the library does not guarantee that it will always make these assumptions, so Rust
33//!   user code directly calling the C functions should follow the C specification! The advice for
34//!   Rust user code is to call the functions provided by this library instead (such as
35//!   `ptr::copy`).
36//!
37//! * Panic handler - This function takes one argument, a `&panic::PanicInfo`. It is up to consumers of this core
38//!   library to define this panic function; it is only required to never
39//!   return. You should mark your implementation using `#[panic_handler]`.
40//!
41//! * `rust_eh_personality` - is used by the failure mechanisms of the
42//!   compiler. This is often mapped to GCC's personality function, but crates
43//!   which do not trigger a panic can be assured that this function is never
44//!   called. The `lang` attribute is called `eh_personality`.
45
46#![stable(feature = "core", since = "1.6.0")]
47#![doc(
48    html_playground_url = "https://play.rust-lang.org/",
49    issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
50    test(no_crate_inject, attr(deny(warnings))),
51    test(attr(allow(dead_code, deprecated, unused_variables, unused_mut, duplicate_features)))
52)]
53#![doc(rust_logo)]
54#![doc(auto_cfg(
55    hide(no_fp_fmt_parse),
56    hide(target_pointer_width, values("16", "32", "64")),
57    hide(
58        target_has_atomic,
59        target_has_atomic_primitive_alignment,
60        target_has_atomic_load_store,
61        values("8", "16", "32", "64", "ptr"),
62    ),
63))]
64#![no_core]
65#![rustc_coherence_is_core]
66#![rustc_preserve_ub_checks]
67//
68// Lints:
69#![deny(rust_2021_incompatible_or_patterns)]
70#![deny(unsafe_op_in_unsafe_fn)]
71#![deny(implicit_provenance_casts)]
72#![warn(deprecated_in_future)]
73#![warn(missing_debug_implementations)]
74#![warn(missing_docs)]
75#![allow(explicit_outlives_requirements)]
76#![allow(incomplete_features)]
77#![warn(multiple_supertrait_upcastable)]
78#![allow(internal_features)]
79#![allow(unused_features)]
80#![deny(ffi_unwind_calls)]
81#![warn(unreachable_pub)]
82// Do not check link redundancy on bootstrapping phase
83#![allow(rustdoc::redundant_explicit_links)]
84#![warn(rustdoc::unescaped_backticks)]
85//
86// Library features:
87// tidy-alphabetical-start
88#![feature(asm_experimental_arch)]
89#![feature(bstr_internals)]
90#![feature(cfg_target_has_reliable_f16_f128)]
91#![feature(const_carrying_mul_add)]
92#![feature(const_cmp)]
93#![feature(const_destruct)]
94#![feature(const_eval_select)]
95#![feature(const_select_unpredictable)]
96#![feature(core_intrinsics)]
97#![feature(coverage_attribute)]
98#![feature(disjoint_bitor)]
99#![feature(io_const_error)]
100#![feature(offset_of_enum)]
101#![feature(panic_internals)]
102#![feature(pattern_type_macro)]
103#![feature(ub_checks)]
104// tidy-alphabetical-end
105//
106// Language features:
107// tidy-alphabetical-start
108#![feature(adt_const_params)]
109#![feature(allow_internal_unsafe)]
110#![feature(allow_internal_unstable)]
111#![feature(auto_traits)]
112#![feature(cfg_sanitize)]
113#![feature(cfg_target_has_atomic)]
114#![feature(cfg_ub_checks)]
115#![feature(const_closures)]
116#![feature(const_precise_live_drops)]
117#![feature(const_trait_impl)]
118#![feature(decl_macro)]
119#![feature(deprecated_suggestion)]
120#![feature(derive_const)]
121#![feature(diagnostic_on_const)]
122#![feature(diagnostic_on_unmatched_args)]
123#![feature(diagnostic_opaque)]
124#![feature(doc_cfg)]
125#![feature(doc_notable_trait)]
126#![feature(extern_types)]
127#![feature(f16)]
128#![feature(f128)]
129#![feature(field_projections)]
130#![feature(final_associated_functions)]
131#![feature(freeze_impls)]
132#![feature(fundamental)]
133#![feature(funnel_shifts)]
134#![feature(impl_restriction)]
135#![feature(intra_doc_pointers)]
136#![feature(intrinsics)]
137#![feature(lang_items)]
138#![feature(link_cfg)]
139#![feature(link_llvm_intrinsics)]
140#![feature(macro_metavar_expr)]
141#![feature(macro_metavar_expr_concat)]
142#![feature(marker_trait_attr)]
143#![feature(min_specialization)]
144#![feature(multiple_supertrait_upcastable)]
145#![feature(must_not_suspend)]
146#![feature(negative_impls)]
147#![feature(no_core)]
148#![feature(optimize_attribute)]
149#![feature(pattern_types)]
150#![feature(pin_macro_internals)]
151#![feature(prelude_import)]
152#![feature(repr_simd)]
153#![feature(rustc_attrs)]
154#![feature(rustdoc_internals)]
155#![feature(simd_ffi)]
156#![feature(splat)]
157#![feature(staged_api)]
158#![feature(stmt_expr_attributes)]
159#![feature(strict_provenance_lints)]
160#![feature(trait_alias)]
161#![feature(transparent_unions)]
162#![feature(try_blocks)]
163#![feature(uint_carryless_mul)]
164#![feature(unboxed_closures)]
165#![feature(unsized_fn_params)]
166#![feature(with_negative_coherence)]
167// tidy-alphabetical-end
168//
169// Target features:
170// tidy-alphabetical-start
171#![feature(aarch64_unstable_target_feature)]
172#![feature(arm_target_feature)]
173#![feature(avx10_target_feature)]
174#![feature(clflushopt_target_feature)]
175#![feature(hexagon_target_feature)]
176#![feature(loongarch_target_feature)]
177#![feature(mips_target_feature)]
178#![feature(movrs_target_feature)]
179#![feature(nvptx_target_feature)]
180#![feature(powerpc_target_feature)]
181#![feature(riscv_target_feature)]
182#![feature(rtm_target_feature)]
183#![feature(s390x_target_feature)]
184#![feature(wasm_target_feature)]
185#![feature(x86_amx_intrinsics)]
186// tidy-alphabetical-end
187
188// tidy-alphabetical-start
189#![expect(clippy::partialeq_ne_impl, reason = "we need to implement ne for a lot of core types")]
190// tidy-alphabetical-end
191
192// allow using `core::` in intra-doc links
193#[allow(unused_extern_crates)]
194extern crate self as core;
195
196/* The core prelude, not as all-encompassing as the std prelude */
197// The compiler expects the prelude definition to be defined before it's use statement.
198pub mod prelude;
199
200#[prelude_import]
201#[allow(unused)]
202use prelude::rust_2024::*;
203
204#[macro_use]
205mod macros;
206
207#[stable(feature = "assert_matches", since = "1.96.0")]
208pub use crate::macros::{assert_matches, debug_assert_matches};
209
210#[unstable(feature = "derive_from", issue = "144889")]
211/// Unstable module containing the unstable `From` derive macro.
212pub mod from {
213    #[unstable(feature = "derive_from", issue = "144889")]
214    pub use crate::macros::builtin::From;
215}
216
217// We don't export this through #[macro_export] for now, to avoid breakage.
218#[unstable(feature = "autodiff", issue = "124509")]
219#[doc = "This module provides support for automatic differentiation. For precise information on\ndifferences between the `autodiff_forward` and `autodiff_reverse` macros and how to\nuse them, see their respective documentation.\n\n## General usage\n\nAutodiff macros can be applied to almost all function definitions, see below for examples.\nThey can be applied to functions accepting structs, arrays, slices, vectors, tuples, and more.\n\nIt is possible to apply multiple autodiff macros to the same function. As an example, this can\nbe helpful to compute the partial derivatives with respect to `x` and `y` independently:\n```rust,ignore (optional component)\n#[autodiff_forward(dsquare1, Dual, Const, Dual)]\n#[autodiff_forward(dsquare2, Const, Dual, Dual)]\n#[autodiff_forward(dsquare3, Active, Active, Active)]\nfn square(x: f64, y: f64) -> f64 {\n  x * x + 2.0 * y\n}\n```\n\nWe also support autodiff on functions with generic parameters:\n```rust,ignore (optional component)\n#[autodiff_forward(generic_derivative, Duplicated, Active)]\nfn generic_f<T: std::ops::Mul<Output = T> + Copy>(x: &T) -> T {\n x * x\n}\n```\n\nor applying autodiff to nested functions:\n```rust,ignore (optional component)\nfn outer(x: f64) -> f64 {\n  #[autodiff_forward(inner_derivative, Dual, Const)]\n  fn inner(y: f64) -> f64 {\n    y * y\n  }\n  inner_derivative(x, 1.0)\n}\n\nfn main() {\n    assert_eq!(outer(3.14), 6.28);\n}\n```\nThe generated function will be available in the same scope as the function differentiated, and\nhave the same private/pub usability.\n\n## Traits and impls\nAutodiff macros can be used in multiple ways in combination with traits:\n```rust,ignore (optional component)\nstruct Foo {\n    a: f64,\n}\n\ntrait MyTrait {\n    #[autodiff_reverse(df, Const, Active, Active)]\n    fn f(&self, x: f64) -> f64;\n}\n\nimpl MyTrait for Foo {\n    fn f(&self, x: f64) -> f64 {\n        x.sin()\n    }\n}\n\nfn main() {\n    let foo = Foo { a: 3.0f64 };\n    assert_eq!(foo.f(2.0), 2.0_f64.sin());\n    assert_eq!(foo.df(2.0, 1.0).1, 2.0_f64.cos());\n}\n```\nIn this case `df` will be the default implementation provided by the library who provided the\ntrait. A user implementing `MyTrait` could then decide to use the default implementation of\n`df`, or overwrite it with a custom implementation as a form of \"custom derivatives\".\n\nOn the other hand, a function generated by either autodiff macro can also be used to implement a\ntrait:\n```rust,ignore (optional component)\nstruct Foo {\n    a: f64,\n}\n\ntrait MyTrait {\n    fn f(&self, x: f64) -> f64;\n    fn df(&self, x: f64, seed: f64) -> (f64, f64);\n}\n\nimpl MyTrait for Foo {\n    #[autodiff_reverse(df, Const, Active, Active)]\n    fn f(&self, x: f64) -> f64 {\n        self.a * 0.25 * (x * x - 1.0 - 2.0 * x.ln())\n    }\n}\n```\n\nSimple `impl` blocks without traits are also supported. Differentiating with respect to the\nimplemented struct will then require the use of a \"shadow struct\" to hold the derivatives of the\nstruct fields:\n\n```rust,ignore (optional component)\nstruct OptProblem {\n    a: f64,\n    b: f64,\n}\n\nimpl OptProblem {\n    #[autodiff_reverse(d_objective, Duplicated, Duplicated, Duplicated)]\n    fn objective(&self, x: &[f64], out: &mut f64) {\n        *out = self.a + x[0].sqrt() * self.b\n    }\n}\nfn main() {\n    let p = OptProblem { a: 1., b: 2. };\n    let mut p_shadow = OptProblem { a: 0., b: 0. };\n    let mut dx = [0.0];\n    let mut out = 0.0;\n    let mut dout = 1.0;\n\n    p.d_objective(&mut p_shadow, &x, &mut dx, &mut out, &mut dout);\n}\n```\n\n## Higher-order derivatives\nFinally, it is possible to generate higher-order derivatives (e.g. Hessian) by applying an\nautodiff macro to a function that is already generated by an autodiff macro, via a thin wrapper.\nThe following example uses Forward mode over Reverse mode\n\n```rust,ignore (optional component)\n#[autodiff_reverse(df, Duplicated, Duplicated)]\nfn f(x: &[f64;2], y: &mut f64) {\n  *y = x[0] * x[0] + x[1] * x[0]\n}\n\n#[autodiff_forward(h, Dual, Dual, Dual, Dual)]\nfn wrapper(x: &[f64;2], dx: &mut [f64;2], y: &mut f64, dy: &mut f64) {\n  df(x, dx, y, dy);\n}\n\nfn main() {\n    let mut y = 0.0;\n    let x = [2.0, 2.0];\n\n    let mut dy = 0.0;\n    let mut dx = [1.0, 0.0];\n\n    let mut bx = [0.0, 0.0];\n    let mut by = 1.0;\n    let mut dbx = [0.0, 0.0];\n    let mut dby = 0.0;\n    h(&x, &mut dx, &mut bx, &mut dbx, &mut y, &mut dy, &mut by, &mut dby);\n    assert_eq!(&dbx, [2.0, 1.0]);\n}\n```\n\n## Current limitations:\n\n- Differentiating a function which accepts a `dyn Trait` is currently not supported.\n- Builds without `lto=\"fat\"` are not yet supported.\n- Builds in debug mode are currently more likely to fail compilation.\n"include_str!("../../core/src/autodiff.md")]
220pub mod autodiff {
221    #[unstable(feature = "autodiff", issue = "124509")]
222    pub use crate::macros::builtin::{autodiff_forward, autodiff_reverse};
223}
224
225#[unstable(feature = "gpu_offload", issue = "131513")]
226#[doc = "This module provides support for gpu offloading. For technical details regarding the `offload_kernel`\nand `offload!` macros, see their respective documentation.\n\n## General usage\nThe `offload_kernel` macro can be applied to a function to generate the necessary code to launch a\nkernel on the target device.\n\n```rust,ignore (optional component)\n#[offload_kernel]\nfn kernel(x: *mut [f64; 256]) {\n    // SAFETY:\n    // calling our `arch` functions and dereferencing a raw pointer is unsafe\n    unsafe {\n        let n = (*x).len();\n        let i = (thread_idx_x() + block_idx_x() * block_dim_x()) as usize;\n        if i < n {\n            (*x)[i] = i as f64;\n        }\n    }\n}\n```\n\nTo launch an offloaded kernel, use the `offload!` macro. It lets you specify the kernel, the\nworkgroup and thread dimensions, the device to offload to, and the arguments to forward to the\ndevice.\n\n```rust,ignore (optional component)\nlet mut x = [0.0f64; 256];\ncore::offload::offload! {\n    kernel = kernel,\n    workgroup_dim = [256, 1, 1],\n    args = (&mut x as *mut [f64; 256],),\n}\n```\n\nFor precise information on the underlying `offload` intrinsic, see its respective documentation.\n\n## Current limitations:\n\n- Usage is restricted to types supported by the current device-mapping implementation.\n- Functions accepting dyn Trait are not supported.\n"include_str!("../../core/src/offload.md")]
227pub mod offload;
228
229#[unstable(feature = "contracts", issue = "128044")]
230pub mod contracts;
231
232#[unstable(feature = "derive_macro_global_path", issue = "154645")]
233pub use crate::macros::builtin::derive;
234#[stable(feature = "cfg_select", since = "1.95.0")]
235pub use crate::macros::cfg_select;
236
237#[macro_use]
238mod internal_macros;
239
240#[path = "num/shells/legacy_int_modules.rs"]
241mod legacy_int_modules;
242#[stable(feature = "rust1", since = "1.0.0")]
243#[allow(deprecated, clippy::legacy_numeric_constants)]
244pub use legacy_int_modules::{i8, i16, i32, i64, isize, u8, u16, u32, u64, usize};
245#[stable(feature = "i128", since = "1.26.0")]
246#[allow(deprecated, clippy::legacy_numeric_constants)]
247pub use legacy_int_modules::{i128, u128};
248
249#[path = "num/f128.rs"]
250pub mod f128;
251#[path = "num/f16.rs"]
252pub mod f16;
253#[path = "num/f32.rs"]
254pub mod f32;
255#[path = "num/f64.rs"]
256pub mod f64;
257
258#[macro_use]
259pub mod num;
260
261/* Core modules for ownership management */
262
263pub mod hint;
264pub mod intrinsics;
265pub mod mem;
266#[unstable(feature = "profiling_marker_api", issue = "148197")]
267pub mod profiling;
268pub mod ptr;
269#[unstable(feature = "ub_checks", issue = "none")]
270pub mod ub_checks;
271
272/* Core language traits */
273
274pub mod borrow;
275pub mod clone;
276pub mod cmp;
277pub mod convert;
278pub mod default;
279pub mod error;
280#[unstable(feature = "field_projections", issue = "145383")]
281pub mod field;
282pub mod index;
283pub mod marker;
284pub mod ops;
285
286/* Core types and methods on primitives */
287
288pub mod any;
289pub mod array;
290pub mod ascii;
291pub mod asserting;
292#[unstable(feature = "async_iterator", issue = "79024")]
293pub mod async_iter;
294#[unstable(feature = "bstr", issue = "134915")]
295pub mod bstr;
296pub mod cell;
297pub mod char;
298pub mod ffi;
299#[unstable(feature = "core_io", issue = "154046")]
300pub mod io;
301pub mod iter;
302pub mod net;
303pub mod option;
304pub mod os;
305pub mod panic;
306pub mod panicking;
307#[unstable(feature = "pattern_type_macro", issue = "123646")]
308pub mod pat;
309pub mod pin;
310#[unstable(feature = "abort_immediate", issue = "154601")]
311pub mod process;
312#[unstable(feature = "random", issue = "130703")]
313pub mod random;
314#[stable(feature = "new_range_inclusive_api", since = "1.95.0")]
315pub mod range;
316pub mod result;
317pub mod sync;
318#[unstable(feature = "unsafe_binders", issue = "130516")]
319pub mod unsafe_binder;
320
321pub mod fmt;
322pub mod hash;
323pub mod slice;
324pub mod str;
325pub mod time;
326
327pub mod wtf8;
328
329pub mod unicode;
330
331/* Async */
332pub mod future;
333pub mod task;
334
335/* Heap memory allocator trait */
336#[allow(missing_docs)]
337pub mod alloc;
338
339// note: does not need to be public
340mod bool;
341mod escape;
342mod tuple;
343mod unit;
344#[unstable(feature = "view_type_macro", issue = "155938")]
345pub mod view;
346
347#[stable(feature = "core_primitive", since = "1.43.0")]
348pub mod primitive;
349
350// Pull in the `core_arch` crate directly into core. The contents of
351// `core_arch` are in a different repository: rust-lang/stdarch.
352//
353// `core_arch` depends on core, but the contents of this module are
354// set up in such a way that directly pulling it here works such that the
355// crate uses the this crate as its core.
356#[path = "../../stdarch/crates/core_arch/src/mod.rs"]
357#[allow(
358    missing_docs,
359    missing_debug_implementations,
360    dead_code,
361    unused_imports,
362    unsafe_op_in_unsafe_fn,
363    ambiguous_glob_reexports,
364    deprecated_in_future,
365    unreachable_pub,
366    // FIXME: stdach is a submodule so clippy lints should be fixed (and ideally enforced) there
367    clippy::all,
368)]
369#[allow(rustdoc::bare_urls)]
370mod core_arch;
371
372#[stable(feature = "simd_arch", since = "1.27.0")]
373pub mod arch;
374
375// Pull in the `core_simd` crate directly into core. The contents of
376// `core_simd` are in a different repository: rust-lang/portable-simd.
377//
378// `core_simd` depends on core, but the contents of this module are
379// set up in such a way that directly pulling it here works such that the
380// crate uses this crate as its core.
381#[path = "../../portable-simd/crates/core_simd/src/mod.rs"]
382#[allow(missing_debug_implementations, dead_code, unsafe_op_in_unsafe_fn)]
383#[allow(rustdoc::bare_urls)]
384#[unstable(feature = "portable_simd", issue = "86656")]
385mod core_simd;
386
387#[unstable(feature = "portable_simd", issue = "86656")]
388pub mod simd {
389    #![doc = "Portable SIMD module.\n\nThis module offers a portable abstraction for SIMD operations\nthat is not bound to any particular hardware architecture.\n\n# What is \"portable\"?\n\nThis module provides a SIMD implementation that is fast and predictable on any target.\n\n### Portable SIMD works on every target\n\nUnlike target-specific SIMD in `std::arch`, portable SIMD compiles for every target.\nIn this regard, it is just like \"regular\" Rust.\n\n### Portable SIMD is consistent between targets\n\nA program using portable SIMD can expect identical behavior on any target.\nIn most regards, [`Simd<T, N>`] can be thought of as a parallelized `[T; N]` and operates like a sequence of `T`.\n\nThis has one notable exception: a handful of older architectures (e.g. `armv7` and `powerpc`) flush [subnormal](`f32::is_subnormal`) `f32` values to zero.\nOn these architectures, subnormal `f32` input values are replaced with zeros, and any operation producing subnormal `f32` values produces zeros instead.\nThis doesn\'t affect most architectures or programs.\n\n### Operations use the best instructions available\n\nOperations provided by this module compile to the best available SIMD instructions.\n\nPortable SIMD is not a low-level vendor library, and operations in portable SIMD _do not_ necessarily map to a single instruction.\nInstead, they map to a reasonable implementation of the operation for the target.\n\nConsistency between targets is not compromised to use faster or fewer instructions.\nIn some cases, `std::arch` will provide a faster function that has slightly different behavior than the `std::simd` equivalent.\nFor example, `_mm_min_ps`[^1] can be slightly faster than [`SimdFloat::simd_min`](`num::SimdFloat::simd_min`), but does not conform to the IEEE standard also used by [`f32::min`].\nWhen necessary, [`Simd<T, N>`] can be converted to the types provided by `std::arch` to make use of target-specific functions.\n\nMany targets simply don\'t have SIMD, or don\'t support SIMD for a particular element type.\nIn those cases, regular scalar operations are generated instead.\n\n[^1]: `_mm_min_ps(x, y)` is equivalent to `x.simd_lt(y).select(x, y)`\n"include_str!("../../portable-simd/crates/core_simd/src/core_simd_docs.md")]
390
391    #[unstable(feature = "portable_simd", issue = "86656")]
392    pub use crate::core_simd::simd::*;
393}
394
395// Include private modules that exist solely to provide rustdoc
396// documentation for built-in attributes. Using `include!` because rustdoc
397// only looks for these modules at the crate level.
398include!("attribute_docs.rs");
399
400// Include a number of private modules that exist solely to provide
401// the rustdoc documentation for the existing keywords. Using `include!`
402// because rustdoc only looks for these modules at the crate level.
403include!("keyword_docs.rs");
404
405// Include a number of private modules that exist solely to provide
406// the rustdoc documentation for primitive types. Using `include!`
407// because rustdoc only looks for these modules at the crate level.
408include!("primitive_docs.rs");