Language
- Remove migrate borrowck mode for pre-NLL errors.
- Modify MIR building to drop repeat expressions with length zero.
- Remove label/lifetime shadowing warnings.
- Allow explicit generic arguments in the presence of
impl Traitargs. - Make
cenum_impl_drop_castwarnings deny-by-default. - Prevent unwinding when
-C panic=abortis used regardless of declared ABI. - lub: don't bail out due to empty binders.
Compiler
- Stabilize the
bundlenative library modifier, also removing the deprecatedstatic-nobundlelinking kind. - Add Apple WatchOS compile targets*.
- Add a Windows application manifest to rustc-main.
* Refer to Rust's platform support page for more information on Rust's tiered platform support.
Libraries
- Implement
Copy,Clone,PartialEqandEqforcore::fmt::Alignment. - Extend
ptr::nullandnull_mutto all thin (including extern) types. impl Read and Write for VecDeque<u8>.- STD support for the Nintendo 3DS.
- Use rounding in float to Duration conversion methods.
- Make write/print macros eagerly drop temporaries.
- Implement internal traits that enable
[OsStr]::join. - Implement
Hashforcore::alloc::Layout. - Add capacity documentation for
OsString. - Put a bound on collection misbehavior.
- Make
std::mem::needs_dropaccept?Sized. impl Termination for Infallibleand then make theResultimpls ofTerminationmore generic.- Document Rust's stance on
/proc/self/mem.
Stabilized APIs
array::from_fnBox::into_pinBinaryHeap::try_reserveBinaryHeap::try_reserve_exactOsString::try_reserveOsString::try_reserve_exactPathBuf::try_reservePathBuf::try_reserve_exactPath::try_existsRef::filter_mapRefMut::filter_mapNonNull::<[T]>::lenToOwned::clone_intoIpv6Addr::to_ipv4_mappedunix::io::AsFdunix::io::BorrowedFd<'fd>unix::io::OwnedFdwindows::io::AsHandlewindows::io::BorrowedHandle<'handle>windows::io::OwnedHandlewindows::io::HandleOrInvalidwindows::io::HandleOrNullwindows::io::InvalidHandleErrorwindows::io::NullHandleErrorwindows::io::AsSocketwindows::io::BorrowedSocket<'handle>windows::io::OwnedSocketthread::scopethread::Scopethread::ScopedJoinHandle
These APIs are now usable in const contexts:
array::from_refslice::from_refintrinsics::copyintrinsics::copy_nonoverlapping<*const T>::copy_to<*const T>::copy_to_nonoverlapping<*mut T>::copy_to<*mut T>::copy_to_nonoverlapping<*mut T>::copy_from<*mut T>::copy_from_nonoverlappingstr::from_utf8Utf8Error::error_lenUtf8Error::valid_up_toCondvar::newMutex::newRwLock::new
Cargo
- Stabilize the
--config pathcommand-line argument. - Expose rust-version in the environment as
CARGO_PKG_RUST_VERSION.
Compatibility Notes
#[link]attributes are now checked more strictly, which may introduce errors for invalid attribute arguments that were previously ignored.- Rounding is now used when converting a float to a
Duration. The converted duration can differ slightly from what it was.
Internal Changes
These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools.
Rust 1.62.1 addresses a few recent regressions in the compiler and standard library, and also mitigates a CPU vulnerability on Intel SGX.
- The compiler fixed unsound function coercions involving
impl Traitreturn types. - The compiler fixed an incremental compilation bug with
async fnlifetimes. - Windows added a fallback for overlapped I/O in synchronous reads and writes.
- The
x86_64-fortanix-unknown-sgxtarget added a mitigation for the MMIO stale data vulnerability, advisory INTEL-SA-00615.
Language
- Stabilize
#[derive(Default)]on enums with a#[default]variant - Teach flow sensitive checks that visibly uninhabited call expressions never return
- Fix constants not getting dropped if part of a diverging expression
- Support unit struct/enum variant in destructuring assignment
- Remove mutable_borrow_reservation_conflict lint and allow the code pattern
Compiler
- linker: Stop using whole-archive on dependencies of dylibs
- Make
unaligned_referenceslint deny-by-default This lint is also a future compatibility lint, and is expected to eventually become a hard error. - Only add codegen backend to dep info if -Zbinary-dep-depinfo is used
- Reject
#[thread_local]attribute on non-static items - Add tier 3
aarch64-pc-windows-gnullvmandx86_64-pc-windows-gnullvmtargets* - Implement a lint to warn about unused macro rules
- Promote
x86_64-unknown-nonetarget to Tier 2*
* Refer to Rust's platform support page for more information on Rust's tiered platform support.
Libraries
- Windows: Use a pipe relay for chaining pipes
- Replace Linux Mutex and Condvar with futex based ones.
- Replace RwLock by a futex based one on Linux
- std: directly use pthread in UNIX parker implementation
Stabilized APIs
bool::then_somef32::total_cmpf64::total_cmpStdin::lineswindows::CommandExt::raw_argimpl<T: Default> Default for AssertUnwindSafe<T>From<Rc<str>> for Rc<[u8]>From<Arc<str>> for Arc<[u8]>FusedIterator for EncodeWide- RDM intrinsics on aarch64
Clippy
Cargo
- Added the
cargo addcommand for adding dependencies toCargo.tomlfrom the command-line. docs - Package ID specs now support
name@versionsyntax in addition to the previousname:versionto align with the behavior incargo addand other tools.cargo installandcargo yankalso now support this syntax so the version does not need to passed as a separate flag. - The
gitandregistrydirectories in Cargo's home directory (usually~/.cargo) are now marked as cache directories so that they are not included in backups or content indexing (on Windows). - Added automatic
@argfile support, which will use "response files" if the command-line torustcexceeds the operating system's limit.
Compatibility Notes
cargo testnow passes--targettorustdocif the specified target is the same as the host target. #10594- rustdoc: doctests are now run on unexported
macro_rules!macros, matching other private items - rustdoc: Remove .woff font files
- Enforce Copy bounds for repeat elements while considering lifetimes
- Windows: Fix potentinal unsoundness by aborting if
Filereads or writes cannot complete synchronously.
Internal Changes
These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools.
Language
const fnsignatures can now include generic trait boundsconst fnsignatures can now useimpl Traitin argument and return position- Function pointers can now be created, cast, and passed around in a
const fn - Recursive calls can now set the value of a function's opaque
impl Traitreturn type
Compiler
- Linking modifier syntax in
#[link]attributes and on the command line, as well as thewhole-archivemodifier specifically, are now supported - The
chartype is now described as UTF-32 in debuginfo - The
#[target_feature]attribute can now be used with aarch64 features - X86
#[target_feature = "adx"]is now stable
Libraries
ManuallyDrop<T>is now documented to have the same layout asT#[ignore = "…"]messages are printed when running tests- Consistently show absent stdio handles on Windows as NULL handles
- Make
std::io::stdio::lock()return'statichandles. Previously, the creation of locked handles to stdin/stdout/stderr would borrow the handles being locked, which prevented writinglet out = std::io::stdout().lock();becauseoutwould outlive the return value ofstdout(). Such code now works, eliminating a common pitfall that affected many Rust users. Vec::from_raw_partsis now less restrictive about its inputsstd::thread::available_parallelismnow takes cgroup quotas into account. Sinceavailable_parallelismis often used to create a thread pool for parallel computation, which may be CPU-bound for performance,available_parallelismwill return a value consistent with the ability to use that many threads continuously, if possible. For instance, in a container with 8 virtual CPUs but quotas only allowing for 50% usage,available_parallelismwill return 4.
Stabilized APIs
Pin::static_mutPin::static_refVec::retain_mutVecDeque::retain_mutWriteforCursor<[u8; N]>std::os::unix::net::SocketAddr::from_pathnamestd::process::ExitCodeandstd::process::Termination. The stabilization of these two APIs now makes it possible for programs to return errors frommainwith custom exit codes.std::thread::JoinHandle::is_finished
These APIs are now usable in const contexts:
<*const T>::offsetand<*mut T>::offset<*const T>::wrapping_offsetand<*mut T>::wrapping_offset<*const T>::addand<*mut T>::add<*const T>::suband<*mut T>::sub<*const T>::wrapping_addand<*mut T>::wrapping_add<*const T>::wrapping_suband<*mut T>::wrapping_sub<[T]>::as_mut_ptr<[T]>::as_ptr_range<[T]>::as_mut_ptr_range
Cargo
No feature changes, but see compatibility notes.
Compatibility Notes
- Previously native static libraries were linked as
whole-archivein some cases, but now rustc tries not to usewhole-archiveunless explicitly requested. This change may result in linking errors in some cases. To fix such errors, native libraries linked from the command line, build scripts, or#[link]attributes need to- (more common) either be reordered to respect dependencies between them (if
adepends onbthenashould go first andbsecond) - (less common) or be updated to use the
+whole-archivemodifier.
- (more common) either be reordered to respect dependencies between them (if
- Catching a second unwind from FFI code while cleaning up from a Rust panic now causes the process to abort
- Proc macros no longer see
identmatchers wrapped in groups - The number of
#inr#raw string literals is now required to be less than 256 - When checking that a dyn type satisfies a trait bound, supertrait bounds are now enforced
cargo vendornow only accepts one value for each--syncflagcfgpredicates inall()andany()are always evaluated to detect errors, instead of short-circuiting. The compatibility considerations here arise in nightly-only code that used the short-circuiting behavior ofallto write something likecfg(all(feature = "nightly", syntax-requiring-nightly)), which will now fail to compile. Instead, use eithercfg_attr(feature = "nightly", ...)or nested uses ofcfg.- bootstrap: static-libstdcpp is now enabled by default, and can now be disabled when llvm-tools is enabled
Internal Changes
These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools.
Language
- Stabilize
#[cfg(panic = "...")]for either"unwind"or"abort". - Stabilize
#[cfg(target_has_atomic = "...")]for each integer size and"ptr".
Compiler
- Enable combining
+crt-staticandrelocation-model=piconx86_64-unknown-linux-gnu - Fixes wrong
unreachable_publints on nested and glob public reexport - Stabilize
-Z instrument-coverageas-C instrument-coverage - Stabilize
-Z print-link-argsas--print link-args - Add new Tier 3 target
mips64-openwrt-linux-musl* - Add new Tier 3 target
armv7-unknown-linux-uclibceabi(softfloat)* - Fix invalid removal of newlines from doc comments
- Add kernel target for RustyHermit
- Deny mixing bin crate type with lib crate types
- Make rustc use
RUST_BACKTRACE=fullby default - Upgrade to LLVM 14
* Refer to Rust's platform support page for more information on Rust's tiered platform support.
Libraries
- Guarantee call order for
sort_by_cached_key - Improve
Duration::try_from_secs_f32/f64accuracy by directly processing exponent and mantissa - Make
Instant::{duration_since, elapsed, sub}saturating - Remove non-monotonic clocks workarounds in
Instant::now - Make
BuildHasherDefault,iter::Emptyandfuture::Pendingcovariant
Stabilized APIs
Arc::new_cyclicRc::new_cyclicslice::EscapeAscii<[u8]>::escape_asciiu8::escape_asciiVec::spare_capacity_mutMaybeUninit::assume_init_dropMaybeUninit::assume_init_readi8::abs_diffi16::abs_diffi32::abs_diffi64::abs_diffi128::abs_diffisize::abs_diffu8::abs_diffu16::abs_diffu32::abs_diffu64::abs_diffu128::abs_diffusize::abs_diffDisplay for io::ErrorKindFrom<u8> for ExitCodeNot for !(the "never" type)- _Op_
Assign<$t> for Wrapping<$t> arch::is_aarch64_feature_detected!
Cargo
- Port cargo from
toml-rstotoml_edit - Stabilize
-Ztimingsas--timings - Stabilize namespaced and weak dependency features.
- Accept more
cargo:rustc-link-arg-*types from build script output. - cargo-new should not add ignore rule on Cargo.lock inside subdirs
Misc
- Ship docs on Tier 2 platforms by reusing the closest Tier 1 platform docs
- Drop rustc-docs from complete profile
- bootstrap: tidy up flag handling for llvm build
Compatibility Notes
- Remove compiler-rt linking hack on Android
- Mitigations for platforms with non-monotonic clocks have been removed from
Instant::now. On platforms that don't provide monotonic clocks, an instant is not guaranteed to be greater than an earlier instant anymore. Instant::{duration_since, elapsed, sub}do not panic anymore on underflow, saturating to0instead. In the real world the panic happened mostly on platforms with buggy monotonic clock implementations rather than catching programming errors like reversing the start and end times. Such programming errors will now results in0rather than a panic.- In a future release we're planning to increase the baseline requirements for the Linux kernel to version 3.2, and for glibc to version 2.17. We'd love your feedback in PR #95026.
Internal Changes
These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools.
Language
- Stabilize default arguments for const parameters and remove the ordering restriction for type and const parameters
- Stabilize destructuring assignment
- Relax private in public lint on generic bounds and where clauses of trait impls
- Stabilize asm! and global_asm! for x86, x86_64, ARM, Aarch64, and RISC-V
Compiler
- Stabilize new symbol mangling format, leaving it opt-in (-Csymbol-mangling-version=v0)
- Emit LLVM optimization remarks when enabled with
-Cremark - Fix sparc64 ABI for aggregates with floating point members
- Warn when a
#[test]-like built-in attribute macro is present multiple times. - Add support for riscv64gc-unknown-freebsd
- Stabilize
-Z emit-future-incompatas--json future-incompat - Soft disable incremental compilation
This release disables incremental compilation, unless the user has explicitly opted in via the newly added RUSTC_FORCE_INCREMENTAL=1 environment variable. This is due to a known and relatively frequently occurring bug in incremental compilation, which causes builds to issue internal compiler errors. This particular bug is already fixed on nightly, but that fix has not yet rolled out to stable and is deemed too risky for a direct stable backport.
As always, we encourage users to test with nightly and report bugs so that we can track failures and fix issues earlier.
See 94124 for more details.
Libraries
Stabilized APIs
std::thread::available_parallelismResult::copiedResult::clonedarch::asm!arch::global_asm!ops::ControlFlow::is_breakops::ControlFlow::is_continueTryFrom<char> for u8char::TryFromCharErrorimplementingClone,Debug,Display,PartialEq,Copy,Eq,Erroriter::zipNonZeroU8::is_power_of_twoNonZeroU16::is_power_of_twoNonZeroU32::is_power_of_twoNonZeroU64::is_power_of_twoNonZeroU128::is_power_of_twoNonZeroUsize::is_power_of_twoDoubleEndedIterator for ToLowercaseDoubleEndedIterator for ToUppercaseTryFrom<&mut [T]> for [T; N]UnwindSafe for OnceRefUnwindSafe for Once- armv8 neon intrinsics for aarch64
Const-stable:
mem::MaybeUninit::as_ptrmem::MaybeUninit::assume_initmem::MaybeUninit::assume_init_refffi::CStr::from_bytes_with_nul_unchecked
Cargo
- Stabilize the
stripprofile option - Stabilize future-incompat-report
- Support abbreviating
--releaseas-r - Support
term.quietconfiguration - Remove
--hostfrom cargo {publish,search,login}
Compatibility Notes
- Refactor weak symbols in std::sys::unix This may add new, versioned, symbols when building with a newer glibc, as the standard library uses weak linkage rather than dynamically attempting to load certain symbols at runtime.
- Deprecate crate_type and crate_name nested inside
#![cfg_attr]This adds a future compatibility lint to supporting the use of cfg_attr wrapping either crate_type or crate_name specification within Rust files; it is recommended that users migrate to setting the equivalent command line flags. - Remove effect of
#[no_link]attribute on name resolution This may expose new names, leading to conflicts with preexisting names in a given namespace and a compilation failure. - Cargo will document libraries before binaries.
- Respect doc=false in dependencies, not just the root crate
- Weaken guarantee around advancing underlying iterators in zip
- Make split_inclusive() on an empty slice yield an empty output
- Update std::env::temp_dir to use GetTempPath2 on Windows when available.
- unreachable! was updated to match other formatting macro behavior on Rust 2021
Internal Changes
These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools.
Language
- Format strings can now capture arguments simply by writing
{ident}in the string. This works in all macros accepting format strings. Support for this inpanic!(panic!("{ident}")) requires the 2021 edition; panic invocations in previous editions that appear to be trying to use this will result in a warning lint about not having the intended effect. *const Tpointers can now be dereferenced in const contexts.- The rules for when a generic struct implements
Unsizehave been relaxed.
Compiler
- Add LLVM CFI support to the Rust compiler
- Stabilize -Z strip as -C strip. Note that while release builds already don't add debug symbols for the code you compile, the compiled standard library that ships with Rust includes debug symbols, so you may want to use the
stripoption to remove these symbols to produce smaller release binaries. Note that this release only includes support in rustc, not directly in cargo. - Add support for LLVM coverage mapping format versions 5 and 6
- Emit LLVM optimization remarks when enabled with
-Cremark - Update the minimum external LLVM to 12
- Add
x86_64-unknown-noneat Tier 3* - Build musl dist artifacts with debuginfo enabled. When building release binaries using musl, you may want to use the newly stabilized strip option to remove these debug symbols, reducing the size of your binaries.
- Don't abort compilation after giving a lint error
- Error messages point at the source of trait bound obligations in more places
* Refer to Rust's platform support page for more information on Rust's tiered platform support.
Libraries
- All remaining functions in the standard library have
#[must_use]annotations where appropriate, producing a warning when ignoring their return value. This helps catch mistakes such as expecting a function to mutate a value in place rather than return a new value. - Paths are automatically canonicalized on Windows for operations that support it
- Re-enable debug checks for
copyandcopy_nonoverlapping - Implement
RefUnwindSafeforRc<T> - Make RSplit<T, P>: Clone not require T: Clone
- Implement
TerminationforResult<Infallible, E>. This allows writingfn main() -> Result<Infallible, ErrorType>, for a program whose successful exits never involve returning frommain(for instance, a program that callsexit, or that usesexecto run another program).
Stabilized APIs
Metadata::is_symlinkPath::is_symlink{integer}::saturating_divOption::unwrap_uncheckedResult::unwrap_uncheckedResult::unwrap_err_uncheckedFile::options
These APIs are now usable in const contexts:
Duration::newDuration::checked_addDuration::saturating_addDuration::checked_subDuration::saturating_subDuration::checked_mulDuration::saturating_mulDuration::checked_div
Cargo
Rustdoc
Compatibility Notes
- Try all stable method candidates first before trying unstable ones. This change ensures that adding new nightly-only methods to the Rust standard library will not break code invoking methods of the same name from traits outside the standard library.
- Windows:
std::process::Commandwill no longer search the current directory for executables. - All proc-macro backward-compatibility lints are now deny-by-default.
- proc_macro: Append .0 to unsuffixed float if it would otherwise become int token
- Refactor weak symbols in std::sys::unix. This optimizes accesses to glibc functions, by avoiding the use of dlopen. This does not increase the minimum expected version of glibc. However, software distributions that use symbol versions to detect library dependencies, and which take weak symbols into account in that analysis, may detect rust binaries as requiring newer versions of glibc.
- rustdoc now rejects some unexpected semicolons in doctests
Internal Changes
These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools.
Language
- Macro attributes may follow
#[derive]and will see the original (pre-cfg) input. - Accept curly-brace macros in expressions, like
m!{ .. }.method()andm!{ .. }?. - Allow panicking in constant evaluation.
- Ignore derived
CloneandDebugimplementations during dead code analysis.
Compiler
- Create more accurate debuginfo for vtables.
- Add
armv6k-nintendo-3dsat Tier 3*. - Add
armv7-unknown-linux-uclibceabihfat Tier 3*. - Add
m68k-unknown-linux-gnuat Tier 3*. - Add SOLID targets at Tier 3*:
aarch64-kmc-solid_asp3,armv7a-kmc-solid_asp3-eabi,armv7a-kmc-solid_asp3-eabihf
* Refer to Rust's platform support page for more information on Rust's tiered platform support.
Libraries
- Avoid allocations and copying in
Vec::leak - Add
#[repr(i8)]toOrdering - Optimize
File::read_to_endandread_to_string - Update to Unicode 14.0
- Many more functions are marked
#[must_use], producing a warning when ignoring their return value. This helps catch mistakes such as expecting a function to mutate a value in place rather than return a new value.
Stabilised APIs
[T; N]::as_mut_slice[T; N]::as_slicecollections::TryReserveErrorHashMap::try_reserveHashSet::try_reserveString::try_reserveString::try_reserve_exactVec::try_reserveVec::try_reserve_exactVecDeque::try_reserveVecDeque::try_reserve_exactIterator::map_whileiter::MapWhileproc_macro::is_availableCommand::get_programCommand::get_argsCommand::get_envsCommand::get_current_dirCommandArgsCommandEnvs
These APIs are now usable in const contexts:
Cargo
Compatibility notes
- Ignore derived
CloneandDebugimplementations during dead code analysis. This will break some builds that set#![deny(dead_code)].
Internal changes
These changes provide no direct user facing benefits, but represent significant improvements to the internals and overall performance of rustc and related tools.
- New lints to detect the presence of bidirectional-override Unicode codepoints in the compiled source code (CVE-2021-42574)