diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index caf97abf78d9e..02a2193ad883f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -28,6 +28,7 @@ name: CI
- "**"
permissions:
contents: read
+ packages: write
defaults:
run:
shell: bash
@@ -42,6 +43,7 @@ jobs:
CI_JOB_NAME: "${{ matrix.name }}"
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
HEAD_SHA: "${{ github.event.pull_request.head.sha || github.sha }}"
+ DOCKER_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
SCCACHE_BUCKET: rust-lang-ci-sccache2
TOOLSTATE_REPO: "https://github.com/rust-lang-nursery/rust-toolstate"
CACHE_DOMAIN: ci-caches.rust-lang.org
@@ -172,6 +174,7 @@ jobs:
CI_JOB_NAME: "${{ matrix.name }}"
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
HEAD_SHA: "${{ github.event.pull_request.head.sha || github.sha }}"
+ DOCKER_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
SCCACHE_BUCKET: rust-lang-ci-sccache2
DEPLOY_BUCKET: rust-lang-ci2
TOOLSTATE_REPO: "https://github.com/rust-lang-nursery/rust-toolstate"
@@ -291,7 +294,7 @@ jobs:
- name: x86_64-gnu-integration
env:
CI_ONLY_WHEN_CHANNEL: nightly
- os: ubuntu-20.04-16core-64gb
+ os: ubuntu-20.04-8core-32gb
- name: x86_64-gnu-debug
os: ubuntu-20.04-8core-32gb
env: {}
@@ -316,7 +319,7 @@ jobs:
- name: dist-x86_64-apple
env:
SCRIPT: "./x.py dist bootstrap --include-default-paths --host=x86_64-apple-darwin --target=x86_64-apple-darwin"
- RUST_CONFIGURE_ARGS: "--enable-full-tools --enable-sanitizers --enable-profiler --set rust.jemalloc --set llvm.ninja=false --set rust.lto=thin"
+ RUST_CONFIGURE_ARGS: "--enable-full-tools --enable-sanitizers --enable-profiler --set rust.jemalloc --set rust.lto=thin"
RUSTC_RETRY_LINKER_ON_SEGFAULT: 1
MACOSX_DEPLOYMENT_TARGET: 10.12
SELECT_XCODE: /Applications/Xcode_13.4.1.app
@@ -329,7 +332,7 @@ jobs:
- name: dist-apple-various
env:
SCRIPT: "./x.py dist bootstrap --include-default-paths --host='' --target=aarch64-apple-ios,x86_64-apple-ios,aarch64-apple-ios-sim"
- RUST_CONFIGURE_ARGS: "--enable-sanitizers --enable-profiler --set rust.jemalloc --set llvm.ninja=false"
+ RUST_CONFIGURE_ARGS: "--enable-sanitizers --enable-profiler --set rust.jemalloc"
RUSTC_RETRY_LINKER_ON_SEGFAULT: 1
MACOSX_DEPLOYMENT_TARGET: 10.12
SELECT_XCODE: /Applications/Xcode_13.4.1.app
@@ -340,7 +343,7 @@ jobs:
- name: x86_64-apple-1
env:
SCRIPT: "./x.py --stage 2 test --skip tests/ui --skip tests/rustdoc --skip tests/run-make-fulldeps"
- RUST_CONFIGURE_ARGS: "--build=x86_64-apple-darwin --enable-sanitizers --enable-profiler --set rust.jemalloc --set llvm.ninja=false"
+ RUST_CONFIGURE_ARGS: "--build=x86_64-apple-darwin --enable-sanitizers --enable-profiler --set rust.jemalloc"
RUSTC_RETRY_LINKER_ON_SEGFAULT: 1
MACOSX_DEPLOYMENT_TARGET: 10.12
MACOSX_STD_DEPLOYMENT_TARGET: 10.12
@@ -351,7 +354,7 @@ jobs:
- name: x86_64-apple-2
env:
SCRIPT: "./x.py --stage 2 test tests/ui tests/rustdoc tests/run-make-fulldeps"
- RUST_CONFIGURE_ARGS: "--build=x86_64-apple-darwin --enable-sanitizers --enable-profiler --set rust.jemalloc --set llvm.ninja=false"
+ RUST_CONFIGURE_ARGS: "--build=x86_64-apple-darwin --enable-sanitizers --enable-profiler --set rust.jemalloc"
RUSTC_RETRY_LINKER_ON_SEGFAULT: 1
MACOSX_DEPLOYMENT_TARGET: 10.12
MACOSX_STD_DEPLOYMENT_TARGET: 10.12
@@ -362,7 +365,7 @@ jobs:
- name: dist-aarch64-apple
env:
SCRIPT: "./x.py dist bootstrap --include-default-paths --stage 2"
- RUST_CONFIGURE_ARGS: "--build=x86_64-apple-darwin --host=aarch64-apple-darwin --target=aarch64-apple-darwin --enable-full-tools --enable-sanitizers --enable-profiler --disable-docs --set rust.jemalloc --set llvm.ninja=false"
+ RUST_CONFIGURE_ARGS: "--build=x86_64-apple-darwin --host=aarch64-apple-darwin --target=aarch64-apple-darwin --enable-full-tools --enable-sanitizers --enable-profiler --disable-docs --set rust.jemalloc"
RUSTC_RETRY_LINKER_ON_SEGFAULT: 1
SELECT_XCODE: /Applications/Xcode_13.4.1.app
USE_XCODE_CLANG: 1
@@ -554,6 +557,7 @@ jobs:
CI_JOB_NAME: "${{ matrix.name }}"
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
HEAD_SHA: "${{ github.event.pull_request.head.sha || github.sha }}"
+ DOCKER_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
SCCACHE_BUCKET: rust-lang-ci-sccache2
DEPLOY_BUCKET: rust-lang-ci2
TOOLSTATE_REPO: "https://github.com/rust-lang-nursery/rust-toolstate"
diff --git a/Cargo.lock b/Cargo.lock
index 09eb0d98efc90..8a2c6536d08c8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -212,9 +212,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711"
[[package]]
name = "askama"
-version = "0.12.0"
+version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "47cbc3cf73fa8d9833727bbee4835ba5c421a0d65b72daf9a7b5d0e0f9cfb57e"
+checksum = "b79091df18a97caea757e28cd2d5fda49c6cd4bd01ddffd7ff01ace0c0ad2c28"
dependencies = [
"askama_derive",
"askama_escape",
@@ -222,14 +222,14 @@ dependencies = [
[[package]]
name = "askama_derive"
-version = "0.12.1"
+version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c22fbe0413545c098358e56966ff22cdd039e10215ae213cfbd65032b119fc94"
+checksum = "19fe8d6cb13c4714962c072ea496f3392015f0989b1a2847bb4b2d9effd71d83"
dependencies = [
+ "askama_parser",
"basic-toml",
"mime",
"mime_guess",
- "nom",
"proc-macro2",
"quote",
"serde",
@@ -242,6 +242,15 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "619743e34b5ba4e9703bba34deac3427c72507c7159f5fd030aea8cac0cfe341"
+[[package]]
+name = "askama_parser"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "acb1161c6b64d1c3d83108213c2a2533a342ac225aabd0bda218278c2ddb00c0"
+dependencies = [
+ "nom",
+]
+
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -373,9 +382,9 @@ dependencies = [
[[package]]
name = "byteorder"
-version = "1.4.3"
+version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
@@ -587,11 +596,11 @@ dependencies = [
name = "clippy_dev"
version = "0.0.1"
dependencies = [
- "aho-corasick 0.7.20",
+ "aho-corasick 1.0.2",
"clap",
"indoc",
"itertools",
- "opener 0.5.2",
+ "opener",
"shell-escape",
"walkdir",
]
@@ -601,7 +610,7 @@ name = "clippy_lints"
version = "0.1.77"
dependencies = [
"arrayvec",
- "cargo_metadata 0.15.4",
+ "cargo_metadata 0.18.0",
"clippy_config",
"clippy_utils",
"declare_clippy_lint",
@@ -1259,7 +1268,6 @@ name = "error_index_generator"
version = "0.0.0"
dependencies = [
"mdbook",
- "rustc_error_codes",
]
[[package]]
@@ -2161,9 +2169,9 @@ checksum = "db13adb97ab515a3691f56e4dbab09283d0b86cb45abd991d8634a9d6f501760"
[[package]]
name = "libc"
-version = "0.2.150"
+version = "0.2.153"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"
+checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
dependencies = [
"rustc-std-workspace-core",
]
@@ -2342,7 +2350,7 @@ dependencies = [
"log",
"memchr",
"once_cell",
- "opener 0.6.1",
+ "opener",
"pathdiff",
"pulldown-cmark",
"regex",
@@ -2587,9 +2595,9 @@ checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
[[package]]
name = "object"
-version = "0.32.1"
+version = "0.32.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0"
+checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441"
dependencies = [
"compiler_builtins",
"crc32fast",
@@ -2617,16 +2625,6 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
-[[package]]
-name = "opener"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "293c15678e37254c15bd2f092314abb4e51d7fdde05c2021279c12631b54f005"
-dependencies = [
- "bstr",
- "winapi",
-]
-
[[package]]
name = "opener"
version = "0.6.1"
@@ -3005,11 +3003,11 @@ dependencies = [
[[package]]
name = "pulldown-cmark"
-version = "0.9.3"
+version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77a1a2f1f0a7ecff9c31abbe177637be0e97a0aef46cf8738ece09327985d998"
+checksum = "57206b407293d2bcd3af849ce869d52068623f19e1b5ff8e8778e3309439682b"
dependencies = [
- "bitflags 1.3.2",
+ "bitflags 2.4.1",
"memchr",
"unicase",
]
@@ -3702,7 +3700,6 @@ dependencies = [
"rustc_codegen_ssa",
"rustc_const_eval",
"rustc_data_structures",
- "rustc_error_codes",
"rustc_errors",
"rustc_expand",
"rustc_feature",
@@ -3775,9 +3772,11 @@ dependencies = [
"rustc_ast",
"rustc_ast_pretty",
"rustc_data_structures",
+ "rustc_error_codes",
"rustc_error_messages",
"rustc_fluent_macro",
"rustc_hir",
+ "rustc_index",
"rustc_lint_defs",
"rustc_macros",
"rustc_serialize",
@@ -4343,7 +4342,6 @@ dependencies = [
name = "rustc_pattern_analysis"
version = "0.0.0"
dependencies = [
- "derivative",
"rustc-hash",
"rustc_apfloat",
"rustc_arena",
@@ -4788,12 +4786,12 @@ checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06"
[[package]]
name = "ruzstd"
-version = "0.4.0"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ac3ffab8f9715a0d455df4bbb9d21e91135aab3cd3ca187af0cd0c3c3f868fdc"
+checksum = "58c4eb8a81997cf040a091d1f7e1938aeab6749d3a0dfa73af43cdc32393483d"
dependencies = [
"byteorder",
- "thiserror-core",
+ "derive_more",
"twox-hash",
]
@@ -5356,26 +5354,6 @@ dependencies = [
"thiserror-impl",
]
-[[package]]
-name = "thiserror-core"
-version = "1.0.38"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0d97345f6437bb2004cd58819d8a9ef8e36cdd7661c2abc4bbde0a7c40d9f497"
-dependencies = [
- "thiserror-core-impl",
-]
-
-[[package]]
-name = "thiserror-core-impl"
-version = "1.0.38"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "10ac1c5050e43014d16b2f94d0d2ce79e65ffdd8b38d8048f9c8f6a8a6da62ac"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "thiserror-impl"
version = "1.0.47"
@@ -5748,9 +5726,9 @@ dependencies = [
[[package]]
name = "unic-langid"
-version = "0.9.1"
+version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "398f9ad7239db44fd0f80fe068d12ff22d78354080332a5077dc6f52f14dcf2f"
+checksum = "238722e6d794ed130f91f4ea33e01fcff4f188d92337a21297892521c72df516"
dependencies = [
"unic-langid-impl",
"unic-langid-macros",
@@ -5758,18 +5736,18 @@ dependencies = [
[[package]]
name = "unic-langid-impl"
-version = "0.9.1"
+version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e35bfd2f2b8796545b55d7d3fd3e89a0613f68a0d1c8bc28cb7ff96b411a35ff"
+checksum = "4bd55a2063fdea4ef1f8633243a7b0524cbeef1905ae04c31a1c9b9775c55bc6"
dependencies = [
"tinystr",
]
[[package]]
name = "unic-langid-macros"
-version = "0.9.1"
+version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "055e618bf694161ffff0466d95cef3e1a5edc59f6ba1888e97801f2b4ebdc4fe"
+checksum = "5c854cefb82ff2816410ce606acbad1b3af065140907b29be9229040752b83ec"
dependencies = [
"proc-macro-hack",
"tinystr",
@@ -5779,13 +5757,13 @@ dependencies = [
[[package]]
name = "unic-langid-macros-impl"
-version = "0.9.1"
+version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1f5cdec05b907f4e2f6843f4354f4ce6a5bebe1a56df320a49134944477ce4d8"
+checksum = "fea2a4c80deb4fb3ca51f66b5e2dd91e3642bbce52234bcf22e41668281208e4"
dependencies = [
"proc-macro-hack",
"quote",
- "syn 1.0.109",
+ "syn 2.0.32",
"unic-langid-impl",
]
diff --git a/RELEASES.md b/RELEASES.md
index 3fb74b52292c1..038a83cde84d6 100644
--- a/RELEASES.md
+++ b/RELEASES.md
@@ -1,3 +1,96 @@
+Version 1.76.0 (2024-02-08)
+==========================
+
+
+
+Language
+--------
+- [Document Rust ABI compatibility between various types](https://github.com/rust-lang/rust/pull/115476/)
+- [Also: guarantee that char and u32 are ABI-compatible](https://github.com/rust-lang/rust/pull/118032/)
+- [Warn against ambiguous wide pointer comparisons](https://github.com/rust-lang/rust/pull/117758/)
+
+
+
+Compiler
+--------
+- [Lint pinned `#[must_use]` pointers (in particular, `Box` where `T` is `#[must_use]`) in `unused_must_use`.](https://github.com/rust-lang/rust/pull/118054/)
+- [Soundness fix: fix computing the offset of an unsized field in a packed struct](https://github.com/rust-lang/rust/pull/118540/)
+- [Soundness fix: fix dynamic size/align computation logic for packed types with dyn Trait tail](https://github.com/rust-lang/rust/pull/118538/)
+- [Add `$message_type` field to distinguish json diagnostic outputs](https://github.com/rust-lang/rust/pull/115691/)
+- [Enable Rust to use the EHCont security feature of Windows](https://github.com/rust-lang/rust/pull/118013/)
+- [Add tier 3 {x86_64,i686}-win7-windows-msvc targets](https://github.com/rust-lang/rust/pull/118150/)
+- [Add tier 3 aarch64-apple-watchos target](https://github.com/rust-lang/rust/pull/119074/)
+- [Add tier 3 arm64e-apple-ios & arm64e-apple-darwin targets](https://github.com/rust-lang/rust/pull/115526/)
+
+Refer to Rust's [platform support page][platform-support-doc]
+for more information on Rust's tiered platform support.
+
+
+
+Libraries
+---------
+- [Add a column number to `dbg!()`](https://github.com/rust-lang/rust/pull/114962/)
+- [Add `std::hash::{DefaultHasher, RandomState}` exports](https://github.com/rust-lang/rust/pull/115694/)
+- [Fix rounding issue with exponents in fmt](https://github.com/rust-lang/rust/pull/116301/)
+- [Add T: ?Sized to `RwLockReadGuard` and `RwLockWriteGuard`'s Debug impls.](https://github.com/rust-lang/rust/pull/117138/)
+- [Windows: Allow `File::create` to work on hidden files](https://github.com/rust-lang/rust/pull/116438/)
+
+
+
+Stabilized APIs
+---------------
+
+- [`Arc::unwrap_or_clone`](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.unwrap_or_clone)
+- [`Rc::unwrap_or_clone`](https://doc.rust-lang.org/stable/std/rc/struct.Rc.html#method.unwrap_or_clone)
+- [`Result::inspect`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.inspect)
+- [`Result::inspect_err`](https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.inspect_err)
+- [`Option::inspect`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.inspect)
+- [`type_name_of_val`](https://doc.rust-lang.org/stable/std/any/fn.type_name_of_val.html)
+- [`std::hash::{DefaultHasher, RandomState}`](https://doc.rust-lang.org/stable/std/hash/index.html#structs)
+ These were previously available only through `std::collections::hash_map`.
+- [`ptr::{from_ref, from_mut}`](https://doc.rust-lang.org/stable/std/ptr/fn.from_ref.html)
+- [`ptr::addr_eq`](https://doc.rust-lang.org/stable/std/ptr/fn.addr_eq.html)
+
+
+
+Cargo
+-----
+
+See [Cargo release notes](https://github.com/rust-lang/cargo/blob/master/CHANGELOG.md#cargo-176-2024-02-08).
+
+
+
+Rustdoc
+-------
+
+- [Don't merge cfg and doc(cfg) attributes for re-exports](https://github.com/rust-lang/rust/pull/113091/)
+- [rustdoc: allow resizing the sidebar / hiding the top bar](https://github.com/rust-lang/rust/pull/115660/)
+- [rustdoc-search: add support for traits and associated types](https://github.com/rust-lang/rust/pull/116085/)
+- [rustdoc: Add highlighting for comments in items declaration](https://github.com/rust-lang/rust/pull/117869/)
+
+
+
+Compatibility Notes
+-------------------
+- [Add allow-by-default lint for unit bindings](https://github.com/rust-lang/rust/pull/112380/)
+ This is expected to be upgraded to a warning by default in a future Rust
+ release. Some macros emit bindings with type `()` with user-provided spans,
+ which means that this lint will warn for user code.
+- [Remove x86_64-sun-solaris target.](https://github.com/rust-lang/rust/pull/118091/)
+- [Remove asmjs-unknown-emscripten target](https://github.com/rust-lang/rust/pull/117338/)
+- [Report errors in jobserver inherited through environment variables](https://github.com/rust-lang/rust/pull/113730/)
+ This [may warn](https://github.com/rust-lang/rust/issues/120515) on benign problems too.
+- [Update the minimum external LLVM to 16.](https://github.com/rust-lang/rust/pull/117947/)
+- [Improve `print_tts`](https://github.com/rust-lang/rust/pull/114571/)
+ This change can break some naive manual parsing of token trees in proc macro
+ code which expect a particular structure after `.to_string()`, rather than just arbitrary Rust code.
+- [Make `IMPLIED_BOUNDS_ENTAILMENT` into a hard error from a lint](https://github.com/rust-lang/rust/pull/117984/)
+- [Vec's allocation behavior was changed when collecting some iterators](https://github.com/rust-lang/rust/pull/110353)
+ Allocation behavior is currently not specified, nevertheless changes can be surprising.
+ See [`impl FromIterator for Vec`](https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#impl-FromIterator%3CT%3E-for-Vec%3CT%3E)
+ for more details.
+- [Properly reject `default` on free const items](https://github.com/rust-lang/rust/pull/117818/)
+
Version 1.75.0 (2023-12-28)
==========================
diff --git a/compiler/rustc_ast/src/lib.rs b/compiler/rustc_ast/src/lib.rs
index 7e713a49a8cfa..76d838308b461 100644
--- a/compiler/rustc_ast/src/lib.rs
+++ b/compiler/rustc_ast/src/lib.rs
@@ -13,13 +13,11 @@
#![feature(rustdoc_internals)]
#![feature(associated_type_bounds)]
#![feature(box_patterns)]
-#![feature(const_trait_impl)]
#![feature(if_let_guard)]
#![feature(let_chains)]
#![feature(min_specialization)]
#![feature(negative_impls)]
#![feature(stmt_expr_attributes)]
-#![recursion_limit = "256"]
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]
diff --git a/compiler/rustc_ast/src/util/literal.rs b/compiler/rustc_ast/src/util/literal.rs
index 7b781ba1e1121..aaeb1bb9bff82 100644
--- a/compiler/rustc_ast/src/util/literal.rs
+++ b/compiler/rustc_ast/src/util/literal.rs
@@ -3,8 +3,7 @@
use crate::ast::{self, LitKind, MetaItemLit, StrStyle};
use crate::token::{self, Token};
use rustc_lexer::unescape::{
- byte_from_char, unescape_byte, unescape_c_string, unescape_char, unescape_literal, CStrUnit,
- Mode,
+ byte_from_char, unescape_byte, unescape_char, unescape_mixed, unescape_unicode, MixedUnit, Mode,
};
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::Span;
@@ -48,6 +47,9 @@ impl LitKind {
return Err(LitError::InvalidSuffix);
}
+ // For byte/char/string literals, chars and escapes have already been
+ // checked in the lexer (in `cook_lexer_literal`). So we can assume all
+ // chars and escapes are valid here.
Ok(match kind {
token::Bool => {
assert!(symbol.is_bool_lit());
@@ -56,12 +58,12 @@ impl LitKind {
token::Byte => {
return unescape_byte(symbol.as_str())
.map(LitKind::Byte)
- .map_err(|_| LitError::LexerError);
+ .map_err(|_| panic!("failed to unescape byte literal"));
}
token::Char => {
return unescape_char(symbol.as_str())
.map(LitKind::Char)
- .map_err(|_| LitError::LexerError);
+ .map_err(|_| panic!("failed to unescape char literal"));
}
// There are some valid suffixes for integer and float literals,
@@ -77,26 +79,22 @@ impl LitKind {
let s = symbol.as_str();
// Vanilla strings are so common we optimize for the common case where no chars
// requiring special behaviour are present.
- let symbol = if s.contains(['\\', '\r']) {
+ let symbol = if s.contains('\\') {
let mut buf = String::with_capacity(s.len());
- let mut error = Ok(());
// Force-inlining here is aggressive but the closure is
- // called on every char in the string, so it can be
- // hot in programs with many long strings.
- unescape_literal(
+ // called on every char in the string, so it can be hot in
+ // programs with many long strings containing escapes.
+ unescape_unicode(
s,
Mode::Str,
&mut #[inline(always)]
- |_, unescaped_char| match unescaped_char {
+ |_, c| match c {
Ok(c) => buf.push(c),
Err(err) => {
- if err.is_fatal() {
- error = Err(LitError::LexerError);
- }
+ assert!(!err.is_fatal(), "failed to unescape string literal")
}
},
);
- error?;
Symbol::intern(&buf)
} else {
symbol
@@ -104,86 +102,46 @@ impl LitKind {
LitKind::Str(symbol, ast::StrStyle::Cooked)
}
token::StrRaw(n) => {
- // Raw strings have no escapes, so we only need to check for invalid chars, and we
- // can reuse the symbol on success.
- let mut error = Ok(());
- unescape_literal(symbol.as_str(), Mode::RawStr, &mut |_, unescaped_char| {
- match unescaped_char {
- Ok(_) => {}
- Err(err) => {
- if err.is_fatal() {
- error = Err(LitError::LexerError);
- }
- }
- }
- });
- error?;
+ // Raw strings have no escapes so no work is needed here.
LitKind::Str(symbol, ast::StrStyle::Raw(n))
}
token::ByteStr => {
let s = symbol.as_str();
let mut buf = Vec::with_capacity(s.len());
- let mut error = Ok(());
- unescape_literal(s, Mode::ByteStr, &mut |_, c| match c {
+ unescape_unicode(s, Mode::ByteStr, &mut |_, c| match c {
Ok(c) => buf.push(byte_from_char(c)),
Err(err) => {
- if err.is_fatal() {
- error = Err(LitError::LexerError);
- }
+ assert!(!err.is_fatal(), "failed to unescape string literal")
}
});
- error?;
LitKind::ByteStr(buf.into(), StrStyle::Cooked)
}
token::ByteStrRaw(n) => {
- // Raw strings have no escapes, so we only need to check for invalid chars, and we
- // can convert the symbol directly to a `Lrc` on success.
- let s = symbol.as_str();
- let mut error = Ok(());
- unescape_literal(s, Mode::RawByteStr, &mut |_, c| match c {
- Ok(_) => {}
- Err(err) => {
- if err.is_fatal() {
- error = Err(LitError::LexerError);
- }
- }
- });
- LitKind::ByteStr(s.to_owned().into_bytes().into(), StrStyle::Raw(n))
+ // Raw strings have no escapes so we can convert the symbol
+ // directly to a `Lrc`.
+ let buf = symbol.as_str().to_owned().into_bytes();
+ LitKind::ByteStr(buf.into(), StrStyle::Raw(n))
}
token::CStr => {
let s = symbol.as_str();
let mut buf = Vec::with_capacity(s.len());
- let mut error = Ok(());
- unescape_c_string(s, Mode::CStr, &mut |_span, c| match c {
- Ok(CStrUnit::Byte(b)) => buf.push(b),
- Ok(CStrUnit::Char(c)) => {
+ unescape_mixed(s, Mode::CStr, &mut |_span, c| match c {
+ Ok(MixedUnit::Char(c)) => {
buf.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes())
}
+ Ok(MixedUnit::HighByte(b)) => buf.push(b),
Err(err) => {
- if err.is_fatal() {
- error = Err(LitError::LexerError);
- }
+ assert!(!err.is_fatal(), "failed to unescape C string literal")
}
});
- error?;
buf.push(0);
LitKind::CStr(buf.into(), StrStyle::Cooked)
}
token::CStrRaw(n) => {
- // Raw strings have no escapes, so we only need to check for invalid chars, and we
- // can convert the symbol directly to a `Lrc` on success.
- let s = symbol.as_str();
- let mut error = Ok(());
- unescape_c_string(s, Mode::RawCStr, &mut |_, c| match c {
- Ok(_) => {}
- Err(err) => {
- if err.is_fatal() {
- error = Err(LitError::LexerError);
- }
- }
- });
- error?;
- let mut buf = s.to_owned().into_bytes();
+ // Raw strings have no escapes so we can convert the symbol
+ // directly to a `Lrc` after appending the terminating NUL
+ // char.
+ let mut buf = symbol.as_str().to_owned().into_bytes();
buf.push(0);
LitKind::CStr(buf.into(), StrStyle::Raw(n))
}
diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs
index 89f50d3a0a7b8..8d084ee29a7db 100644
--- a/compiler/rustc_ast/src/visit.rs
+++ b/compiler/rustc_ast/src/visit.rs
@@ -375,11 +375,11 @@ pub fn walk_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a Item) {
}
ItemKind::MacCall(mac) => visitor.visit_mac_call(mac),
ItemKind::MacroDef(ts) => visitor.visit_mac_def(ts, item.id),
- ItemKind::Delegation(box Delegation { id: _, qself, path, body }) => {
+ ItemKind::Delegation(box Delegation { id, qself, path, body }) => {
if let Some(qself) = qself {
visitor.visit_ty(&qself.ty);
}
- walk_path(visitor, path);
+ visitor.visit_path(path, *id);
if let Some(body) = body {
visitor.visit_block(body);
}
@@ -502,7 +502,7 @@ where
}
GenericArgs::Parenthesized(data) => {
walk_list!(visitor, visit_ty, &data.inputs);
- walk_fn_ret_ty(visitor, &data.output);
+ visitor.visit_fn_ret_ty(&data.output);
}
}
}
@@ -713,11 +713,11 @@ pub fn walk_assoc_item<'a, V: Visitor<'a>>(visitor: &mut V, item: &'a AssocItem,
AssocItemKind::MacCall(mac) => {
visitor.visit_mac_call(mac);
}
- AssocItemKind::Delegation(box Delegation { id: _, qself, path, body }) => {
+ AssocItemKind::Delegation(box Delegation { id, qself, path, body }) => {
if let Some(qself) = qself {
visitor.visit_ty(&qself.ty);
}
- walk_path(visitor, path);
+ visitor.visit_path(path, *id);
if let Some(body) = body {
visitor.visit_block(body);
}
diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs
index 4843d36372dcc..51bb8a96fad26 100644
--- a/compiler/rustc_ast_lowering/src/errors.rs
+++ b/compiler/rustc_ast_lowering/src/errors.rs
@@ -1,9 +1,9 @@
-use rustc_errors::DiagnosticArgFromDisplay;
+use rustc_errors::{codes::*, DiagnosticArgFromDisplay};
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{symbol::Ident, Span, Symbol};
#[derive(Diagnostic, Clone, Copy)]
-#[diag(ast_lowering_generic_type_with_parentheses, code = "E0214")]
+#[diag(ast_lowering_generic_type_with_parentheses, code = E0214)]
pub struct GenericTypeWithParentheses {
#[primary_span]
#[label]
@@ -22,7 +22,7 @@ pub struct UseAngleBrackets {
}
#[derive(Diagnostic)]
-#[diag(ast_lowering_invalid_abi, code = "E0703")]
+#[diag(ast_lowering_invalid_abi, code = E0703)]
#[note]
pub struct InvalidAbi {
#[primary_span]
@@ -89,7 +89,7 @@ pub enum AssocTyParenthesesSub {
}
#[derive(Diagnostic)]
-#[diag(ast_lowering_misplaced_impl_trait, code = "E0562")]
+#[diag(ast_lowering_misplaced_impl_trait, code = E0562)]
#[note]
pub struct MisplacedImplTrait<'a> {
#[primary_span]
@@ -114,7 +114,7 @@ pub struct UnderscoreExprLhsAssign {
}
#[derive(Diagnostic, Clone, Copy)]
-#[diag(ast_lowering_base_expression_double_dot, code = "E0797")]
+#[diag(ast_lowering_base_expression_double_dot, code = E0797)]
pub struct BaseExpressionDoubleDot {
#[primary_span]
#[suggestion(code = "/* expr */", applicability = "has-placeholders", style = "verbose")]
@@ -122,7 +122,7 @@ pub struct BaseExpressionDoubleDot {
}
#[derive(Diagnostic, Clone, Copy)]
-#[diag(ast_lowering_await_only_in_async_fn_and_blocks, code = "E0728")]
+#[diag(ast_lowering_await_only_in_async_fn_and_blocks, code = E0728)]
pub struct AwaitOnlyInAsyncFnAndBlocks {
#[primary_span]
#[label]
@@ -132,14 +132,14 @@ pub struct AwaitOnlyInAsyncFnAndBlocks {
}
#[derive(Diagnostic, Clone, Copy)]
-#[diag(ast_lowering_coroutine_too_many_parameters, code = "E0628")]
+#[diag(ast_lowering_coroutine_too_many_parameters, code = E0628)]
pub struct CoroutineTooManyParameters {
#[primary_span]
pub fn_decl_span: Span,
}
#[derive(Diagnostic, Clone, Copy)]
-#[diag(ast_lowering_closure_cannot_be_static, code = "E0697")]
+#[diag(ast_lowering_closure_cannot_be_static, code = E0697)]
pub struct ClosureCannotBeStatic {
#[primary_span]
pub fn_decl_span: Span,
@@ -154,14 +154,14 @@ pub struct FunctionalRecordUpdateDestructuringAssignment {
}
#[derive(Diagnostic, Clone, Copy)]
-#[diag(ast_lowering_async_coroutines_not_supported, code = "E0727")]
+#[diag(ast_lowering_async_coroutines_not_supported, code = E0727)]
pub struct AsyncCoroutinesNotSupported {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic, Clone, Copy)]
-#[diag(ast_lowering_inline_asm_unsupported_target, code = "E0472")]
+#[diag(ast_lowering_inline_asm_unsupported_target, code = E0472)]
pub struct InlineAsmUnsupportedTarget {
#[primary_span]
pub span: Span,
diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs
index cc172b376573f..0ad4a59c17eb1 100644
--- a/compiler/rustc_ast_lowering/src/expr.rs
+++ b/compiler/rustc_ast_lowering/src/expr.rs
@@ -153,7 +153,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
ExprKind::Let(pat, scrutinee, span, is_recovered) => {
hir::ExprKind::Let(self.arena.alloc(hir::Let {
- hir_id: self.next_id(),
span: self.lower_span(*span),
pat: self.lower_pat(pat),
ty: None,
diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs
index dd3f7289a60b2..6b772c1295f55 100644
--- a/compiler/rustc_ast_lowering/src/item.rs
+++ b/compiler/rustc_ast_lowering/src/item.rs
@@ -25,7 +25,7 @@ pub(super) struct ItemLowerer<'a, 'hir> {
pub(super) tcx: TyCtxt<'hir>,
pub(super) resolver: &'a mut ResolverAstLowering,
pub(super) ast_index: &'a IndexSlice>,
- pub(super) owners: &'a mut IndexVec>>,
+ pub(super) owners: &'a mut IndexVec>,
}
/// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
@@ -64,10 +64,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> {
}
}
- pub(super) fn lower_node(
- &mut self,
- def_id: LocalDefId,
- ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> {
+ pub(super) fn lower_node(&mut self, def_id: LocalDefId) -> hir::MaybeOwner<'hir> {
let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
if let hir::MaybeOwner::Phantom = owner {
let node = self.ast_index[def_id];
diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index 057fe65d0afad..f26b1331ef388 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -33,10 +33,8 @@
#![allow(internal_features)]
#![feature(rustdoc_internals)]
#![doc(rust_logo)]
-#![feature(if_let_guard)]
#![feature(box_patterns)]
#![feature(let_chains)]
-#![recursion_limit = "256"]
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]
@@ -101,7 +99,7 @@ struct LoweringContext<'a, 'hir> {
/// Attributes inside the owner being lowered.
attrs: SortedMap,
/// Collect items that were created by lowering the current owner.
- children: Vec<(LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>)>,
+ children: Vec<(LocalDefId, hir::MaybeOwner<'hir>)>,
coroutine_kind: Option,
@@ -417,7 +415,7 @@ fn index_crate<'a>(
/// This hash will then be part of the crate_hash which is stored in the metadata.
fn compute_hir_hash(
tcx: TyCtxt<'_>,
- owners: &IndexSlice>>,
+ owners: &IndexSlice>,
) -> Fingerprint {
let mut hir_body_nodes: Vec<_> = owners
.iter_enumerated()
@@ -2307,7 +2305,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
match c.value.kind {
ExprKind::Underscore => {
if self.tcx.features().generic_arg_infer {
- hir::ArrayLen::Infer(self.lower_node_id(c.id), self.lower_span(c.value.span))
+ hir::ArrayLen::Infer(hir::InferArg {
+ hir_id: self.lower_node_id(c.id),
+ span: self.lower_span(c.value.span),
+ })
} else {
feature_err(
&self.tcx.sess,
diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs
index e2b8e64b115e5..5f54a0ddf8c38 100644
--- a/compiler/rustc_ast_passes/src/errors.rs
+++ b/compiler/rustc_ast_passes/src/errors.rs
@@ -1,7 +1,7 @@
//! Errors emitted by ast_passes.
use rustc_ast::ParamKindOrd;
-use rustc_errors::{AddToDiagnostic, Applicability};
+use rustc_errors::{codes::*, AddToDiagnostic, Applicability};
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{symbol::Ident, Span, Symbol};
@@ -23,7 +23,7 @@ pub struct InvalidLabel {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_visibility_not_permitted, code = "E0449")]
+#[diag(ast_passes_visibility_not_permitted, code = E0449)]
pub struct VisibilityNotPermitted {
#[primary_span]
pub span: Span,
@@ -44,7 +44,7 @@ pub enum VisibilityNotPermittedNote {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_trait_fn_const, code = "E0379")]
+#[diag(ast_passes_trait_fn_const, code = E0379)]
pub struct TraitFnConst {
#[primary_span]
#[label]
@@ -302,14 +302,14 @@ pub struct ItemUnderscore<'a> {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_nomangle_ascii, code = "E0754")]
+#[diag(ast_passes_nomangle_ascii, code = E0754)]
pub struct NoMangleAscii {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(ast_passes_module_nonascii, code = "E0754")]
+#[diag(ast_passes_module_nonascii, code = E0754)]
#[help]
pub struct ModuleNonAscii {
#[primary_span]
@@ -318,7 +318,7 @@ pub struct ModuleNonAscii {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_auto_generic, code = "E0567")]
+#[diag(ast_passes_auto_generic, code = E0567)]
pub struct AutoTraitGeneric {
#[primary_span]
#[suggestion(code = "", applicability = "machine-applicable")]
@@ -328,7 +328,7 @@ pub struct AutoTraitGeneric {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_auto_super_lifetime, code = "E0568")]
+#[diag(ast_passes_auto_super_lifetime, code = E0568)]
pub struct AutoTraitBounds {
#[primary_span]
#[suggestion(code = "", applicability = "machine-applicable")]
@@ -338,7 +338,7 @@ pub struct AutoTraitBounds {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_auto_items, code = "E0380")]
+#[diag(ast_passes_auto_items, code = E0380)]
pub struct AutoTraitItems {
#[primary_span]
pub spans: Vec,
@@ -384,28 +384,28 @@ impl AddToDiagnostic for EmptyLabelManySpans {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_pattern_in_fn_pointer, code = "E0561")]
+#[diag(ast_passes_pattern_in_fn_pointer, code = E0561)]
pub struct PatternFnPointer {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(ast_passes_trait_object_single_bound, code = "E0226")]
+#[diag(ast_passes_trait_object_single_bound, code = E0226)]
pub struct TraitObjectBound {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(ast_passes_impl_trait_path, code = "E0667")]
+#[diag(ast_passes_impl_trait_path, code = E0667)]
pub struct ImplTraitPath {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(ast_passes_nested_impl_trait, code = "E0666")]
+#[diag(ast_passes_nested_impl_trait, code = E0666)]
pub struct NestedImplTrait {
#[primary_span]
pub span: Span,
@@ -443,7 +443,7 @@ pub struct ObsoleteAuto {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_unsafe_negative_impl, code = "E0198")]
+#[diag(ast_passes_unsafe_negative_impl, code = E0198)]
pub struct UnsafeNegativeImpl {
#[primary_span]
pub span: Span,
@@ -468,7 +468,7 @@ pub struct InherentImplCannot<'a> {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_inherent_cannot_be, code = "E0197")]
+#[diag(ast_passes_inherent_cannot_be, code = E0197)]
pub struct InherentImplCannotUnsafe<'a> {
#[primary_span]
pub span: Span,
@@ -536,7 +536,7 @@ pub struct GenericDefaultTrailing {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_nested_lifetimes, code = "E0316")]
+#[diag(ast_passes_nested_lifetimes, code = E0316)]
pub struct NestedLifetimes {
#[primary_span]
pub span: Span,
@@ -655,7 +655,7 @@ pub struct ConstAndCVariadic {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_pattern_in_foreign, code = "E0130")]
+#[diag(ast_passes_pattern_in_foreign, code = E0130)]
pub struct PatternInForeign {
#[primary_span]
#[label]
@@ -663,7 +663,7 @@ pub struct PatternInForeign {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_pattern_in_bodiless, code = "E0642")]
+#[diag(ast_passes_pattern_in_bodiless, code = E0642)]
pub struct PatternInBodiless {
#[primary_span]
#[label]
@@ -711,14 +711,14 @@ pub struct AssociatedSuggestion2 {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_stability_outside_std, code = "E0734")]
+#[diag(ast_passes_stability_outside_std, code = E0734)]
pub struct StabilityOutsideStd {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(ast_passes_feature_on_non_nightly, code = "E0554")]
+#[diag(ast_passes_feature_on_non_nightly, code = E0554)]
pub struct FeatureOnNonNightly {
#[primary_span]
pub span: Span,
diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs
index 82236d2e30678..409aef9185d92 100644
--- a/compiler/rustc_ast_passes/src/feature_gate.rs
+++ b/compiler/rustc_ast_passes/src/feature_gate.rs
@@ -362,6 +362,19 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
}
}
+ fn visit_generic_args(&mut self, args: &'a ast::GenericArgs) {
+ // This check needs to happen here because the never type can be returned from a function,
+ // but cannot be used in any other context. If this check was in `visit_fn_ret_ty`, it
+ // include both functions and generics like `impl Fn() -> !`.
+ if let ast::GenericArgs::Parenthesized(generic_args) = args
+ && let ast::FnRetTy::Ty(ref ty) = generic_args.output
+ && matches!(ty.kind, ast::TyKind::Never)
+ {
+ gate!(&self, never_type, ty.span, "the `!` type is experimental");
+ }
+ visit::walk_generic_args(self, args);
+ }
+
fn visit_expr(&mut self, e: &'a ast::Expr) {
match e.kind {
ast::ExprKind::TryBlock(_) => {
diff --git a/compiler/rustc_ast_passes/src/lib.rs b/compiler/rustc_ast_passes/src/lib.rs
index ba09183374e10..fa6cdd55c3dcb 100644
--- a/compiler/rustc_ast_passes/src/lib.rs
+++ b/compiler/rustc_ast_passes/src/lib.rs
@@ -11,7 +11,6 @@
#![feature(if_let_guard)]
#![feature(iter_is_partitioned)]
#![feature(let_chains)]
-#![recursion_limit = "256"]
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]
diff --git a/compiler/rustc_ast_pretty/src/lib.rs b/compiler/rustc_ast_pretty/src/lib.rs
index 100b298898224..61617beb86b5a 100644
--- a/compiler/rustc_ast_pretty/src/lib.rs
+++ b/compiler/rustc_ast_pretty/src/lib.rs
@@ -4,8 +4,6 @@
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]
#![feature(box_patterns)]
-#![feature(let_chains)]
-#![recursion_limit = "256"]
mod helpers;
pub mod pp;
diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs
index c2fd4558fd76e..a6f6f0b29a040 100644
--- a/compiler/rustc_ast_pretty/src/pprust/state.rs
+++ b/compiler/rustc_ast_pretty/src/pprust/state.rs
@@ -160,6 +160,10 @@ fn space_between(tt1: &TokenTree, tt2: &TokenTree) -> bool {
use TokenTree::Delimited as Del;
use TokenTree::Token as Tok;
+ fn is_punct(tt: &TokenTree) -> bool {
+ matches!(tt, TokenTree::Token(tok, _) if tok.is_punct())
+ }
+
// Each match arm has one or more examples in comments. The default is to
// insert space between adjacent tokens, except for the cases listed in
// this match.
@@ -167,24 +171,35 @@ fn space_between(tt1: &TokenTree, tt2: &TokenTree) -> bool {
// No space after line doc comments.
(Tok(Token { kind: DocComment(CommentKind::Line, ..), .. }, _), _) => false,
- // `.` + ANYTHING: `x.y`, `tup.0`
- // `$` + ANYTHING: `$e`
- (Tok(Token { kind: Dot | Dollar, .. }, _), _) => false,
-
- // ANYTHING + `,`: `foo,`
- // ANYTHING + `.`: `x.y`, `tup.0`
- // ANYTHING + `!`: `foo! { ... }`
- //
- // FIXME: Incorrect cases:
- // - Logical not: `x =! y`, `if! x { f(); }`
- // - Never type: `Fn() ->!`
- (_, Tok(Token { kind: Comma | Dot | Not, .. }, _)) => false,
-
- // IDENT + `(`: `f(3)`
- //
- // FIXME: Incorrect cases:
- // - Let: `let(a, b) = (1, 2)`
- (Tok(Token { kind: Ident(..), .. }, _), Del(_, _, Parenthesis, _)) => false,
+ // `.` + NON-PUNCT: `x.y`, `tup.0`
+ (Tok(Token { kind: Dot, .. }, _), tt2) if !is_punct(tt2) => false,
+
+ // `$` + IDENT: `$e`
+ (Tok(Token { kind: Dollar, .. }, _), Tok(Token { kind: Ident(..), .. }, _)) => false,
+
+ // NON-PUNCT + `,`: `foo,`
+ // NON-PUNCT + `;`: `x = 3;`, `[T; 3]`
+ // NON-PUNCT + `.`: `x.y`, `tup.0`
+ (tt1, Tok(Token { kind: Comma | Semi | Dot, .. }, _)) if !is_punct(tt1) => false,
+
+ // IDENT + `!`: `println!()`, but `if !x { ... }` needs a space after the `if`
+ (Tok(Token { kind: Ident(sym, is_raw), span }, _), Tok(Token { kind: Not, .. }, _))
+ if !Ident::new(*sym, *span).is_reserved() || *is_raw =>
+ {
+ false
+ }
+
+ // IDENT|`fn`|`Self`|`pub` + `(`: `f(3)`, `fn(x: u8)`, `Self()`, `pub(crate)`,
+ // but `let (a, b) = (1, 2)` needs a space after the `let`
+ (Tok(Token { kind: Ident(sym, is_raw), span }, _), Del(_, _, Parenthesis, _))
+ if !Ident::new(*sym, *span).is_reserved()
+ || *sym == kw::Fn
+ || *sym == kw::SelfUpper
+ || *sym == kw::Pub
+ || *is_raw =>
+ {
+ false
+ }
// `#` + `[`: `#[attr]`
(Tok(Token { kind: Pound, .. }, _), Del(_, _, Bracket, _)) => false,
diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs
index 315a00c8d2fc0..79370602842b0 100644
--- a/compiler/rustc_attr/src/session_diagnostics.rs
+++ b/compiler/rustc_attr/src/session_diagnostics.rs
@@ -2,8 +2,7 @@ use std::num::IntErrorKind;
use rustc_ast as ast;
use rustc_errors::{
- error_code, Applicability, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic,
- Level,
+ codes::*, Applicability, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, Level,
};
use rustc_macros::Diagnostic;
use rustc_span::{Span, Symbol};
@@ -12,14 +11,14 @@ use crate::fluent_generated as fluent;
use crate::UnsupportedLiteralReason;
#[derive(Diagnostic)]
-#[diag(attr_expected_one_cfg_pattern, code = "E0536")]
+#[diag(attr_expected_one_cfg_pattern, code = E0536)]
pub(crate) struct ExpectedOneCfgPattern {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_invalid_predicate, code = "E0537")]
+#[diag(attr_invalid_predicate, code = E0537)]
pub(crate) struct InvalidPredicate {
#[primary_span]
pub span: Span,
@@ -28,7 +27,7 @@ pub(crate) struct InvalidPredicate {
}
#[derive(Diagnostic)]
-#[diag(attr_multiple_item, code = "E0538")]
+#[diag(attr_multiple_item, code = E0538)]
pub(crate) struct MultipleItem {
#[primary_span]
pub span: Span,
@@ -37,7 +36,7 @@ pub(crate) struct MultipleItem {
}
#[derive(Diagnostic)]
-#[diag(attr_incorrect_meta_item, code = "E0539")]
+#[diag(attr_incorrect_meta_item, code = E0539)]
pub(crate) struct IncorrectMetaItem {
#[primary_span]
pub span: Span,
@@ -56,7 +55,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnknownMetaItem<'_> {
let expected = self.expected.iter().map(|name| format!("`{name}`")).collect::>();
DiagnosticBuilder::new(dcx, level, fluent::attr_unknown_meta_item)
.with_span(self.span)
- .with_code(error_code!(E0541))
+ .with_code(E0541)
.with_arg("item", self.item)
.with_arg("expected", expected.join(", "))
.with_span_label(self.span, fluent::attr_label)
@@ -64,28 +63,28 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnknownMetaItem<'_> {
}
#[derive(Diagnostic)]
-#[diag(attr_missing_since, code = "E0542")]
+#[diag(attr_missing_since, code = E0542)]
pub(crate) struct MissingSince {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_missing_note, code = "E0543")]
+#[diag(attr_missing_note, code = E0543)]
pub(crate) struct MissingNote {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_multiple_stability_levels, code = "E0544")]
+#[diag(attr_multiple_stability_levels, code = E0544)]
pub(crate) struct MultipleStabilityLevels {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_invalid_issue_string, code = "E0545")]
+#[diag(attr_invalid_issue_string, code = E0545)]
pub(crate) struct InvalidIssueString {
#[primary_span]
pub span: Span,
@@ -143,21 +142,21 @@ impl InvalidIssueStringCause {
}
#[derive(Diagnostic)]
-#[diag(attr_missing_feature, code = "E0546")]
+#[diag(attr_missing_feature, code = E0546)]
pub(crate) struct MissingFeature {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_non_ident_feature, code = "E0546")]
+#[diag(attr_non_ident_feature, code = E0546)]
pub(crate) struct NonIdentFeature {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_missing_issue, code = "E0547")]
+#[diag(attr_missing_issue, code = E0547)]
pub(crate) struct MissingIssue {
#[primary_span]
pub span: Span,
@@ -166,14 +165,14 @@ pub(crate) struct MissingIssue {
// FIXME: Why is this the same error code as `InvalidReprHintNoParen` and `InvalidReprHintNoValue`?
// It is more similar to `IncorrectReprFormatGeneric`.
#[derive(Diagnostic)]
-#[diag(attr_incorrect_repr_format_packed_one_or_zero_arg, code = "E0552")]
+#[diag(attr_incorrect_repr_format_packed_one_or_zero_arg, code = E0552)]
pub(crate) struct IncorrectReprFormatPackedOneOrZeroArg {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_invalid_repr_hint_no_paren, code = "E0552")]
+#[diag(attr_invalid_repr_hint_no_paren, code = E0552)]
pub(crate) struct InvalidReprHintNoParen {
#[primary_span]
pub span: Span,
@@ -182,7 +181,7 @@ pub(crate) struct InvalidReprHintNoParen {
}
#[derive(Diagnostic)]
-#[diag(attr_invalid_repr_hint_no_value, code = "E0552")]
+#[diag(attr_invalid_repr_hint_no_value, code = E0552)]
pub(crate) struct InvalidReprHintNoValue {
#[primary_span]
pub span: Span,
@@ -215,7 +214,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnsupportedLiteral {
},
);
diag.span(self.span);
- diag.code(error_code!(E0565));
+ diag.code(E0565);
if self.is_bytestr {
diag.span_suggestion(
self.start_point_span,
@@ -229,7 +228,7 @@ impl<'a, G: EmissionGuarantee> IntoDiagnostic<'a, G> for UnsupportedLiteral {
}
#[derive(Diagnostic)]
-#[diag(attr_invalid_repr_align_need_arg, code = "E0589")]
+#[diag(attr_invalid_repr_align_need_arg, code = E0589)]
pub(crate) struct InvalidReprAlignNeedArg {
#[primary_span]
#[suggestion(code = "align(...)", applicability = "has-placeholders")]
@@ -237,7 +236,7 @@ pub(crate) struct InvalidReprAlignNeedArg {
}
#[derive(Diagnostic)]
-#[diag(attr_invalid_repr_generic, code = "E0589")]
+#[diag(attr_invalid_repr_generic, code = E0589)]
pub(crate) struct InvalidReprGeneric<'a> {
#[primary_span]
pub span: Span,
@@ -247,14 +246,14 @@ pub(crate) struct InvalidReprGeneric<'a> {
}
#[derive(Diagnostic)]
-#[diag(attr_incorrect_repr_format_align_one_arg, code = "E0693")]
+#[diag(attr_incorrect_repr_format_align_one_arg, code = E0693)]
pub(crate) struct IncorrectReprFormatAlignOneArg {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_incorrect_repr_format_generic, code = "E0693")]
+#[diag(attr_incorrect_repr_format_generic, code = E0693)]
pub(crate) struct IncorrectReprFormatGeneric<'a> {
#[primary_span]
pub span: Span,
@@ -305,14 +304,14 @@ impl<'a> IncorrectReprFormatGenericCause<'a> {
}
#[derive(Diagnostic)]
-#[diag(attr_rustc_promotable_pairing, code = "E0717")]
+#[diag(attr_rustc_promotable_pairing, code = E0717)]
pub(crate) struct RustcPromotablePairing {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(attr_rustc_allowed_unstable_pairing, code = "E0789")]
+#[diag(attr_rustc_allowed_unstable_pairing, code = E0789)]
pub(crate) struct RustcAllowedUnstablePairing {
#[primary_span]
pub span: Span,
diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs
index 351976cdaea6b..6cbcda37f50b8 100644
--- a/compiler/rustc_borrowck/src/borrowck_errors.rs
+++ b/compiler/rustc_borrowck/src/borrowck_errors.rs
@@ -1,4 +1,4 @@
-use rustc_errors::{struct_span_code_err, DiagCtxt, DiagnosticBuilder};
+use rustc_errors::{codes::*, struct_span_code_err, DiagCtxt, DiagnosticBuilder};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span;
@@ -130,7 +130,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
noun_old: &str,
old_opt_via: &str,
previous_end_span: Option,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let mut err = struct_span_code_err!(
self.dcx(),
new_loan_span,
@@ -162,7 +162,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
old_opt_via: &str,
previous_end_span: Option,
second_borrow_desc: &str,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let mut err = struct_span_code_err!(
self.dcx(),
new_loan_span,
@@ -194,7 +194,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
kind_old: &str,
msg_old: &str,
old_load_end_span: Option,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let via = |msg: &str| if msg.is_empty() { "".to_string() } else { format!(" (via {msg})") };
let mut err = struct_span_code_err!(
self.dcx(),
@@ -235,7 +235,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
span: Span,
borrow_span: Span,
desc: &str,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
struct_span_code_err!(
self.dcx(),
span,
@@ -252,7 +252,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
span: Span,
desc: &str,
is_arg: bool,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let msg = if is_arg { "to immutable argument" } else { "twice to immutable variable" };
struct_span_code_err!(self.dcx(), span, E0384, "cannot assign {} {}", msg, desc)
}
@@ -265,7 +265,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
&self,
move_from_span: Span,
move_from_desc: &str,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
struct_span_code_err!(
self.dcx(),
move_from_span,
@@ -283,7 +283,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
move_from_span: Span,
ty: Ty<'_>,
is_index: Option,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let type_name = match (&ty.kind(), is_index) {
(&ty::Array(_, _), Some(true)) | (&ty::Array(_, _), None) => "array",
(&ty::Slice(_), _) => "slice",
@@ -304,7 +304,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
&self,
move_from_span: Span,
container_ty: Ty<'_>,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
struct_span_code_err!(
self.dcx(),
move_from_span,
diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
index da67862a48dc9..b0b7cc076bab5 100644
--- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
@@ -3,7 +3,9 @@
use either::Either;
use rustc_data_structures::captures::Captures;
use rustc_data_structures::fx::FxIndexSet;
-use rustc_errors::{struct_span_code_err, Applicability, Diagnostic, DiagnosticBuilder, MultiSpan};
+use rustc_errors::{
+ codes::*, struct_span_code_err, Applicability, Diagnostic, DiagnosticBuilder, MultiSpan,
+};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::intravisit::{walk_block, walk_expr, Visitor};
@@ -325,7 +327,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&mut self,
mpi: MovePathIndex,
move_span: Span,
- err: &mut DiagnosticBuilder<'_>,
+ err: &mut DiagnosticBuilder<'tcx>,
in_pattern: &mut bool,
move_spans: UseSpans<'_>,
) {
@@ -484,7 +486,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
desired_action: InitializationRequiringAction,
span: Span,
use_spans: UseSpans<'tcx>,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
// We need all statements in the body where the binding was assigned to later find all
// the branching code paths where the binding *wasn't* assigned to.
let inits = &self.move_data.init_path_map[mpi];
@@ -878,7 +880,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
location: Location,
(place, _span): (Place<'tcx>, Span),
borrow: &BorrowData<'tcx>,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let borrow_spans = self.retrieve_borrow_spans(borrow);
let borrow_span = borrow_spans.args_or_use();
@@ -928,7 +930,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
(place, span): (Place<'tcx>, Span),
gen_borrow_kind: BorrowKind,
issued_borrow: &BorrowData<'tcx>,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let issued_spans = self.retrieve_borrow_spans(issued_borrow);
let issued_span = issued_spans.args_or_use();
@@ -2127,7 +2129,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
drop_span: Span,
borrow_spans: UseSpans<'tcx>,
explanation: BorrowExplanation<'tcx>,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
debug!(
"report_local_value_does_not_live_long_enough(\
{:?}, {:?}, {:?}, {:?}, {:?}\
@@ -2302,7 +2304,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&mut self,
drop_span: Span,
borrow_span: Span,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
debug!(
"report_thread_local_value_does_not_live_long_enough(\
{:?}, {:?}\
@@ -2327,7 +2329,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
borrow_spans: UseSpans<'tcx>,
proper_span: Span,
explanation: BorrowExplanation<'tcx>,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
if let BorrowExplanation::MustBeValidFor { category, span, from_closure: false, .. } =
explanation
{
@@ -2438,7 +2440,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
"consider consuming the `{ty}` when turning it into an \
`Iterator`",
),
- "into_iter".to_string(),
+ "into_iter",
Applicability::MaybeIncorrect,
);
}
@@ -2494,7 +2496,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
return_span: Span,
category: ConstraintCategory<'tcx>,
opt_place_desc: Option<&String>,
- ) -> Option> {
+ ) -> Option> {
let return_kind = match category {
ConstraintCategory::Return(_) => "return",
ConstraintCategory::Yield => "yield",
@@ -2589,7 +2591,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
constraint_span: Span,
captured_var: &str,
scope: &str,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let tcx = self.infcx.tcx;
let args_span = use_span.args_or_use();
@@ -2697,7 +2699,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
upvar_span: Span,
upvar_name: Symbol,
escape_span: Span,
- ) -> DiagnosticBuilder<'cx> {
+ ) -> DiagnosticBuilder<'tcx> {
let tcx = self.infcx.tcx;
let escapes_from = tcx.def_descr(self.mir_def_id().to_def_id());
diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs
index fb3525e8998c0..0a0bb75a2a3a6 100644
--- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs
@@ -288,7 +288,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
&mut self,
place: Place<'tcx>,
span: Span,
- ) -> DiagnosticBuilder<'a> {
+ ) -> DiagnosticBuilder<'tcx> {
let description = if place.projection.len() == 1 {
format!("static item {}", self.describe_any_place(place.as_ref()))
} else {
@@ -310,7 +310,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
deref_target_place: Place<'tcx>,
span: Span,
use_spans: Option>,
- ) -> DiagnosticBuilder<'a> {
+ ) -> DiagnosticBuilder<'tcx> {
// Inspect the type of the content behind the
// borrow to provide feedback about why this
// was a move rather than a copy.
diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
index 0a6b758efa564..3fddf67f55b97 100644
--- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
@@ -198,12 +198,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
{
let span = self.body.local_decls[local].source_info.span;
mut_error = Some(span);
- if let Some((buffer, c)) = self.get_buffered_mut_error(span) {
+ if let Some((buffered_err, c)) = self.get_buffered_mut_error(span) {
// We've encountered a second (or more) attempt to mutably borrow an
// immutable binding, so the likely problem is with the binding
// declaration, not the use. We collect these in a single diagnostic
// and make the binding the primary span of the error.
- err = buffer;
+ err = buffered_err;
count = c + 1;
if count == 2 {
err.replace_span_with(span, false);
@@ -924,7 +924,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
err.span_suggestion_verbose(
expr.span.shrink_to_lo(),
"use a mutable iterator instead",
- "mut ".to_string(),
+ "mut ",
Applicability::MachineApplicable,
);
}
diff --git a/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs b/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs
index ad66c677c78f5..bac1d9dd57f6b 100644
--- a/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs
@@ -251,6 +251,6 @@ impl OutlivesSuggestionBuilder {
diag.sort_span = mir_span.shrink_to_hi();
// Buffer the diagnostic
- mbcx.buffer_non_error_diag(diag);
+ mbcx.buffer_non_error(diag);
}
}
diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs
index 4cb49362863fc..15e1066e983a9 100644
--- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs
@@ -188,7 +188,7 @@ impl Display for RegionName {
}
impl rustc_errors::IntoDiagnosticArg for RegionName {
- fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
+ fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue {
self.to_string().into_diagnostic_arg()
}
}
diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs
index 177fc1deca12a..8b5e548345c97 100644
--- a/compiler/rustc_borrowck/src/lib.rs
+++ b/compiler/rustc_borrowck/src/lib.rs
@@ -8,12 +8,9 @@
#![feature(let_chains)]
#![feature(min_specialization)]
#![feature(never_type)]
-#![feature(lazy_cell)]
#![feature(rustc_attrs)]
#![feature(stmt_expr_attributes)]
-#![feature(trusted_step)]
#![feature(try_blocks)]
-#![recursion_limit = "256"]
#[macro_use]
extern crate rustc_middle;
@@ -22,7 +19,7 @@ extern crate tracing;
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_data_structures::graph::dominators::Dominators;
-use rustc_errors::{Diagnostic, DiagnosticBuilder};
+use rustc_errors::DiagnosticBuilder;
use rustc_hir as hir;
use rustc_hir::def_id::LocalDefId;
use rustc_index::bit_set::{BitSet, ChunkedBitSet};
@@ -176,12 +173,11 @@ fn do_mir_borrowck<'tcx>(
}
}
- let mut errors = error::BorrowckErrors::new(infcx.tcx);
+ let mut diags = diags::BorrowckDiags::new();
// Gather the upvars of a closure, if any.
if let Some(e) = input_body.tainted_by_errors {
infcx.set_tainted_by_errors(e);
- errors.set_tainted_by_errors(e);
}
// Replace all regions with fresh inference variables. This
@@ -247,7 +243,7 @@ fn do_mir_borrowck<'tcx>(
®ioncx,
&opt_closure_req,
&opaque_type_values,
- &mut errors,
+ &mut diags,
);
// The various `flow_*` structures can be large. We drop `flow_inits` here
@@ -308,11 +304,11 @@ fn do_mir_borrowck<'tcx>(
next_region_name: RefCell::new(1),
polonius_output: None,
move_errors: Vec::new(),
- errors,
+ diags,
};
MoveVisitor { ctxt: &mut promoted_mbcx }.visit_body(promoted_body);
promoted_mbcx.report_move_errors();
- errors = promoted_mbcx.errors;
+ diags = promoted_mbcx.diags;
struct MoveVisitor<'a, 'cx, 'tcx> {
ctxt: &'a mut MirBorrowckCtxt<'cx, 'tcx>,
@@ -349,7 +345,7 @@ fn do_mir_borrowck<'tcx>(
next_region_name: RefCell::new(1),
polonius_output,
move_errors: Vec::new(),
- errors,
+ diags,
};
// Compute and report region errors, if any.
@@ -577,7 +573,7 @@ struct MirBorrowckCtxt<'cx, 'tcx> {
/// Results of Polonius analysis.
polonius_output: Option>,
- errors: error::BorrowckErrors<'tcx>,
+ diags: diags::BorrowckDiags<'tcx>,
move_errors: Vec>,
}
@@ -2128,7 +2124,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
| WriteKind::MutableBorrow(BorrowKind::Fake),
) => {
if self.is_mutable(place.as_ref(), is_local_mutation_allowed).is_err()
- && !self.has_buffered_errors()
+ && !self.has_buffered_diags()
{
// rust-lang/rust#46908: In pure NLL mode this code path should be
// unreachable, but we use `span_delayed_bug` because we can hit this when
@@ -2386,17 +2382,30 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}
}
-mod error {
+mod diags {
use rustc_errors::ErrorGuaranteed;
use super::*;
- pub struct BorrowckErrors<'tcx> {
- tcx: TyCtxt<'tcx>,
+ enum BufferedDiag<'tcx> {
+ Error(DiagnosticBuilder<'tcx>),
+ NonError(DiagnosticBuilder<'tcx, ()>),
+ }
+
+ impl<'tcx> BufferedDiag<'tcx> {
+ fn sort_span(&self) -> Span {
+ match self {
+ BufferedDiag::Error(diag) => diag.sort_span,
+ BufferedDiag::NonError(diag) => diag.sort_span,
+ }
+ }
+ }
+
+ pub struct BorrowckDiags<'tcx> {
/// This field keeps track of move errors that are to be reported for given move indices.
///
- /// There are situations where many errors can be reported for a single move out (see #53807)
- /// and we want only the best of those errors.
+ /// There are situations where many errors can be reported for a single move out (see
+ /// #53807) and we want only the best of those errors.
///
/// The `report_use_of_moved_or_uninitialized` function checks this map and replaces the
/// diagnostic (if there is one) if the `Place` of the error being reported is a prefix of
@@ -2409,51 +2418,38 @@ mod error {
/// same primary span come out in a consistent order.
buffered_move_errors:
BTreeMap, (PlaceRef<'tcx>, DiagnosticBuilder<'tcx>)>,
+
buffered_mut_errors: FxIndexMap, usize)>,
- /// Buffer of diagnostics to be reported. Uses `Diagnostic` rather than `DiagnosticBuilder`
- /// because it has a mixture of error diagnostics and non-error diagnostics.
- buffered: Vec,
- /// Set to Some if we emit an error during borrowck
- tainted_by_errors: Option,
+
+ /// Buffer of diagnostics to be reported. A mixture of error and non-error diagnostics.
+ buffered_diags: Vec>,
}
- impl<'tcx> BorrowckErrors<'tcx> {
- pub fn new(tcx: TyCtxt<'tcx>) -> Self {
- BorrowckErrors {
- tcx,
+ impl<'tcx> BorrowckDiags<'tcx> {
+ pub fn new() -> Self {
+ BorrowckDiags {
buffered_move_errors: BTreeMap::new(),
buffered_mut_errors: Default::default(),
- buffered: Default::default(),
- tainted_by_errors: None,
- }
- }
-
- pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_>) {
- if let None = self.tainted_by_errors {
- self.tainted_by_errors = Some(self.tcx.dcx().span_delayed_bug(
- t.span.clone_ignoring_labels(),
- "diagnostic buffered but not emitted",
- ))
+ buffered_diags: Default::default(),
}
- self.buffered.push(t.into_diagnostic());
}
- pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
- self.buffered.push(t.into_diagnostic());
+ pub fn buffer_error(&mut self, t: DiagnosticBuilder<'tcx>) {
+ self.buffered_diags.push(BufferedDiag::Error(t));
}
- pub fn set_tainted_by_errors(&mut self, e: ErrorGuaranteed) {
- self.tainted_by_errors = Some(e);
+ pub fn buffer_non_error(&mut self, t: DiagnosticBuilder<'tcx, ()>) {
+ self.buffered_diags.push(BufferedDiag::NonError(t));
}
}
impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
- pub fn buffer_error(&mut self, t: DiagnosticBuilder<'_>) {
- self.errors.buffer_error(t);
+ pub fn buffer_error(&mut self, t: DiagnosticBuilder<'tcx>) {
+ self.diags.buffer_error(t);
}
- pub fn buffer_non_error_diag(&mut self, t: DiagnosticBuilder<'_, ()>) {
- self.errors.buffer_non_error_diag(t);
+ pub fn buffer_non_error(&mut self, t: DiagnosticBuilder<'tcx, ()>) {
+ self.diags.buffer_non_error(t);
}
pub fn buffer_move_error(
@@ -2462,7 +2458,7 @@ mod error {
place_and_err: (PlaceRef<'tcx>, DiagnosticBuilder<'tcx>),
) -> bool {
if let Some((_, diag)) =
- self.errors.buffered_move_errors.insert(move_out_indices, place_and_err)
+ self.diags.buffered_move_errors.insert(move_out_indices, place_and_err)
{
// Cancel the old diagnostic so we don't ICE
diag.cancel();
@@ -2476,47 +2472,50 @@ mod error {
&mut self,
span: Span,
) -> Option<(DiagnosticBuilder<'tcx>, usize)> {
- self.errors.buffered_mut_errors.remove(&span)
+ self.diags.buffered_mut_errors.remove(&span)
}
pub fn buffer_mut_error(&mut self, span: Span, t: DiagnosticBuilder<'tcx>, count: usize) {
- self.errors.buffered_mut_errors.insert(span, (t, count));
+ self.diags.buffered_mut_errors.insert(span, (t, count));
}
pub fn emit_errors(&mut self) -> Option {
+ let mut res = None;
+
// Buffer any move errors that we collected and de-duplicated.
- for (_, (_, diag)) in std::mem::take(&mut self.errors.buffered_move_errors) {
+ for (_, (_, diag)) in std::mem::take(&mut self.diags.buffered_move_errors) {
// We have already set tainted for this error, so just buffer it.
- self.errors.buffered.push(diag.into_diagnostic());
+ self.diags.buffered_diags.push(BufferedDiag::Error(diag));
}
- for (_, (mut diag, count)) in std::mem::take(&mut self.errors.buffered_mut_errors) {
+ for (_, (mut diag, count)) in std::mem::take(&mut self.diags.buffered_mut_errors) {
if count > 10 {
diag.note(format!("...and {} other attempted mutable borrows", count - 10));
}
- self.errors.buffered.push(diag.into_diagnostic());
+ self.diags.buffered_diags.push(BufferedDiag::Error(diag));
}
- if !self.errors.buffered.is_empty() {
- self.errors.buffered.sort_by_key(|diag| diag.sort_span);
-
- let dcx = self.dcx();
- for diag in self.errors.buffered.drain(..) {
- dcx.emit_diagnostic(diag);
+ if !self.diags.buffered_diags.is_empty() {
+ self.diags.buffered_diags.sort_by_key(|buffered_diag| buffered_diag.sort_span());
+ for buffered_diag in self.diags.buffered_diags.drain(..) {
+ match buffered_diag {
+ BufferedDiag::Error(diag) => res = Some(diag.emit()),
+ BufferedDiag::NonError(diag) => diag.emit(),
+ }
}
}
- self.errors.tainted_by_errors
+ res
}
- pub fn has_buffered_errors(&self) -> bool {
- self.errors.buffered.is_empty()
+ pub(crate) fn has_buffered_diags(&self) -> bool {
+ self.diags.buffered_diags.is_empty()
}
pub fn has_move_error(
&self,
move_out_indices: &[MoveOutIndex],
- ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'cx>)> {
- self.errors.buffered_move_errors.get(move_out_indices)
+ ) -> Option<&(PlaceRef<'tcx>, DiagnosticBuilder<'tcx>)> {
+ self.diags.buffered_move_errors.get(move_out_indices)
}
}
}
diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs
index cc8208e9dc306..7ace013975e1b 100644
--- a/compiler/rustc_borrowck/src/nll.rs
+++ b/compiler/rustc_borrowck/src/nll.rs
@@ -264,7 +264,7 @@ pub(super) fn dump_annotation<'tcx>(
regioncx: &RegionInferenceContext<'tcx>,
closure_region_requirements: &Option>,
opaque_type_values: &FxIndexMap>,
- errors: &mut crate::error::BorrowckErrors<'tcx>,
+ diags: &mut crate::diags::BorrowckDiags<'tcx>,
) {
let tcx = infcx.tcx;
let base_def_id = tcx.typeck_root_def_id(body.source.def_id());
@@ -310,7 +310,7 @@ pub(super) fn dump_annotation<'tcx>(
err.note(format!("Inferred opaque type values:\n{opaque_type_values:#?}"));
}
- errors.buffer_non_error_diag(err);
+ diags.buffer_non_error(err);
}
fn for_each_region_constraint<'tcx>(
diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs
index e321b92603d38..1685624f24772 100644
--- a/compiler/rustc_borrowck/src/session_diagnostics.rs
+++ b/compiler/rustc_borrowck/src/session_diagnostics.rs
@@ -1,4 +1,4 @@
-use rustc_errors::MultiSpan;
+use rustc_errors::{codes::*, MultiSpan};
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
use rustc_middle::ty::{GenericArg, Ty};
use rustc_span::Span;
@@ -6,7 +6,7 @@ use rustc_span::Span;
use crate::diagnostics::RegionName;
#[derive(Diagnostic)]
-#[diag(borrowck_move_unsized, code = "E0161")]
+#[diag(borrowck_move_unsized, code = E0161)]
pub(crate) struct MoveUnsized<'tcx> {
pub ty: Ty<'tcx>,
#[primary_span]
@@ -281,7 +281,7 @@ pub(crate) enum CaptureVarCause {
}
#[derive(Diagnostic)]
-#[diag(borrowck_cannot_move_when_borrowed, code = "E0505")]
+#[diag(borrowck_cannot_move_when_borrowed, code = E0505)]
pub(crate) struct MoveBorrow<'a> {
pub place: &'a str,
pub borrow_place: &'a str,
@@ -294,7 +294,7 @@ pub(crate) struct MoveBorrow<'a> {
}
#[derive(Diagnostic)]
-#[diag(borrowck_opaque_type_non_generic_param, code = "E0792")]
+#[diag(borrowck_opaque_type_non_generic_param, code = E0792)]
pub(crate) struct NonGenericOpaqueTypeParam<'a, 'tcx> {
pub ty: GenericArg<'tcx>,
pub kind: &'a str,
diff --git a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs
index 21d8026e17089..52559f9039b65 100644
--- a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs
+++ b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs
@@ -33,7 +33,7 @@ pub(crate) struct ConstraintConversion<'a, 'tcx> {
/// our special inference variable there, we would mess that up.
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: ty::Region<'tcx>,
- param_env: ty::ParamEnv<'tcx>,
+ known_type_outlives_obligations: &'tcx [ty::PolyTypeOutlivesPredicate<'tcx>],
locations: Locations,
span: Span,
category: ConstraintCategory<'tcx>,
@@ -47,7 +47,7 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
universal_regions: &'a UniversalRegions<'tcx>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: ty::Region<'tcx>,
- param_env: ty::ParamEnv<'tcx>,
+ known_type_outlives_obligations: &'tcx [ty::PolyTypeOutlivesPredicate<'tcx>],
locations: Locations,
span: Span,
category: ConstraintCategory<'tcx>,
@@ -59,7 +59,7 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
universal_regions,
region_bound_pairs,
implicit_region_bound,
- param_env,
+ known_type_outlives_obligations,
locations,
span,
category,
@@ -136,7 +136,11 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
// Extract out various useful fields we'll need below.
let ConstraintConversion {
- tcx, region_bound_pairs, implicit_region_bound, param_env, ..
+ tcx,
+ region_bound_pairs,
+ implicit_region_bound,
+ known_type_outlives_obligations,
+ ..
} = *self;
let ty::OutlivesPredicate(k1, r2) = predicate;
@@ -157,7 +161,7 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
tcx,
region_bound_pairs,
Some(implicit_region_bound),
- param_env,
+ known_type_outlives_obligations,
)
.type_must_outlive(origin, t1, r2, constraint_category);
}
diff --git a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs
index 011b5b760c23a..d518f54fd2533 100644
--- a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs
+++ b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs
@@ -45,12 +45,14 @@ type NormalizedInputsAndOutput<'tcx> = Vec>;
pub(crate) struct CreateResult<'tcx> {
pub(crate) universal_region_relations: Frozen>,
pub(crate) region_bound_pairs: RegionBoundPairs<'tcx>,
+ pub(crate) known_type_outlives_obligations: &'tcx [ty::PolyTypeOutlivesPredicate<'tcx>],
pub(crate) normalized_inputs_and_output: NormalizedInputsAndOutput<'tcx>,
}
pub(crate) fn create<'tcx>(
infcx: &InferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
+ known_type_outlives_obligations: &'tcx [ty::PolyTypeOutlivesPredicate<'tcx>],
implicit_region_bound: ty::Region<'tcx>,
universal_regions: &Rc>,
constraints: &mut MirTypeckRegionConstraints<'tcx>,
@@ -58,6 +60,7 @@ pub(crate) fn create<'tcx>(
UniversalRegionRelationsBuilder {
infcx,
param_env,
+ known_type_outlives_obligations,
implicit_region_bound,
constraints,
universal_regions: universal_regions.clone(),
@@ -175,6 +178,7 @@ impl UniversalRegionRelations<'_> {
struct UniversalRegionRelationsBuilder<'this, 'tcx> {
infcx: &'this InferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
+ known_type_outlives_obligations: &'tcx [ty::PolyTypeOutlivesPredicate<'tcx>],
universal_regions: Rc>,
implicit_region_bound: ty::Region<'tcx>,
constraints: &'this mut MirTypeckRegionConstraints<'tcx>,
@@ -200,7 +204,8 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
let defining_ty_def_id = self.universal_regions.defining_ty.def_id().expect_local();
let span = tcx.def_span(defining_ty_def_id);
- // Insert the facts we know from the predicates. Why? Why not.
+ // Insert the `'a: 'b` we know from the predicates.
+ // This does not consider the type-outlives.
let param_env = self.param_env;
self.add_outlives_bounds(outlives::explicit_outlives_bounds(param_env));
@@ -308,6 +313,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
outlives: self.outlives.freeze(),
inverse_outlives: self.inverse_outlives.freeze(),
}),
+ known_type_outlives_obligations: self.known_type_outlives_obligations,
region_bound_pairs: self.region_bound_pairs,
normalized_inputs_and_output,
}
@@ -322,7 +328,7 @@ impl<'tcx> UniversalRegionRelationsBuilder<'_, 'tcx> {
&self.universal_regions,
&self.region_bound_pairs,
self.implicit_region_bound,
- self.param_env,
+ self.known_type_outlives_obligations,
Locations::All(span),
span,
ConstraintCategory::Internal,
diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs
index cf28e62177fb4..59c4d9a6c78ca 100644
--- a/compiler/rustc_borrowck/src/type_check/mod.rs
+++ b/compiler/rustc_borrowck/src/type_check/mod.rs
@@ -152,9 +152,14 @@ pub(crate) fn type_check<'mir, 'tcx>(
universal_region_relations,
region_bound_pairs,
normalized_inputs_and_output,
+ known_type_outlives_obligations,
} = free_region_relations::create(
infcx,
param_env,
+ // FIXME(-Znext-solver): These are unnormalized. Normalize them.
+ infcx.tcx.arena.alloc_from_iter(
+ param_env.caller_bounds().iter().filter_map(|clause| clause.as_type_outlives_clause()),
+ ),
implicit_region_bound,
universal_regions,
&mut constraints,
@@ -176,6 +181,7 @@ pub(crate) fn type_check<'mir, 'tcx>(
body,
param_env,
®ion_bound_pairs,
+ known_type_outlives_obligations,
implicit_region_bound,
&mut borrowck_context,
);
@@ -850,6 +856,7 @@ struct TypeChecker<'a, 'tcx> {
/// all of the promoted items.
user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
+ known_type_outlives_obligations: &'tcx [ty::PolyTypeOutlivesPredicate<'tcx>],
implicit_region_bound: ty::Region<'tcx>,
reported_errors: FxIndexSet<(Ty<'tcx>, Span)>,
borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
@@ -1000,6 +1007,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
body: &'a Body<'tcx>,
param_env: ty::ParamEnv<'tcx>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
+ known_type_outlives_obligations: &'tcx [ty::PolyTypeOutlivesPredicate<'tcx>],
implicit_region_bound: ty::Region<'tcx>,
borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
) -> Self {
@@ -1010,6 +1018,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
user_type_annotations: &body.user_type_annotations,
param_env,
region_bound_pairs,
+ known_type_outlives_obligations,
implicit_region_bound,
borrowck_context,
reported_errors: Default::default(),
@@ -1099,10 +1108,17 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
#[instrument(skip(self), level = "debug")]
fn check_user_type_annotations(&mut self) {
debug!(?self.user_type_annotations);
+ let tcx = self.tcx();
for user_annotation in self.user_type_annotations {
let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
- self.ascribe_user_type(inferred_ty, annotation, span);
+ if let ty::UserType::TypeOf(def, args) = annotation
+ && let DefKind::InlineConst = tcx.def_kind(def)
+ {
+ self.check_inline_const(inferred_ty, def.expect_local(), args, span);
+ } else {
+ self.ascribe_user_type(inferred_ty, annotation, span);
+ }
}
}
@@ -1120,7 +1136,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
self.borrowck_context.universal_regions,
self.region_bound_pairs,
self.implicit_region_bound,
- self.param_env,
+ self.known_type_outlives_obligations,
locations,
locations.span(self.body),
category,
@@ -1195,6 +1211,36 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
Ok(())
}
+ fn check_inline_const(
+ &mut self,
+ inferred_ty: Ty<'tcx>,
+ def_id: LocalDefId,
+ args: UserArgs<'tcx>,
+ span: Span,
+ ) {
+ assert!(args.user_self_ty.is_none());
+ let tcx = self.tcx();
+ let const_ty = tcx.type_of(def_id).instantiate(tcx, args.args);
+ if let Err(terr) =
+ self.eq_types(const_ty, inferred_ty, Locations::All(span), ConstraintCategory::Boring)
+ {
+ span_bug!(
+ span,
+ "bad inline const pattern: ({:?} = {:?}) {:?}",
+ const_ty,
+ inferred_ty,
+ terr
+ );
+ }
+ let args = self.infcx.resolve_vars_if_possible(args.args);
+ let predicates = self.prove_closure_bounds(tcx, def_id, args, Locations::All(span));
+ self.normalize_and_prove_instantiated_predicates(
+ def_id.to_def_id(),
+ predicates,
+ Locations::All(span),
+ );
+ }
+
fn tcx(&self) -> TyCtxt<'tcx> {
self.infcx.tcx
}
@@ -1851,7 +1897,12 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
let def_id = uv.def;
if tcx.def_kind(def_id) == DefKind::InlineConst {
let def_id = def_id.expect_local();
- let predicates = self.prove_closure_bounds(tcx, def_id, uv.args, location);
+ let predicates = self.prove_closure_bounds(
+ tcx,
+ def_id,
+ uv.args,
+ location.to_locations(),
+ );
self.normalize_and_prove_instantiated_predicates(
def_id.to_def_id(),
predicates,
@@ -2654,9 +2705,15 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
// desugaring. A closure gets desugared to a struct, and
// these extra requirements are basically like where
// clauses on the struct.
- AggregateKind::Closure(def_id, args) | AggregateKind::Coroutine(def_id, args) => {
- (def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), args, location))
- }
+ AggregateKind::Closure(def_id, args) | AggregateKind::Coroutine(def_id, args) => (
+ def_id,
+ self.prove_closure_bounds(
+ tcx,
+ def_id.expect_local(),
+ args,
+ location.to_locations(),
+ ),
+ ),
AggregateKind::Array(_) | AggregateKind::Tuple => {
(CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
@@ -2675,7 +2732,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
def_id: LocalDefId,
args: GenericArgsRef<'tcx>,
- location: Location,
+ locations: Locations,
) -> ty::InstantiatedPredicates<'tcx> {
if let Some(closure_requirements) = &tcx.mir_borrowck(def_id).closure_requirements {
constraint_conversion::ConstraintConversion::new(
@@ -2683,8 +2740,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
self.borrowck_context.universal_regions,
self.region_bound_pairs,
self.implicit_region_bound,
- self.param_env,
- location.to_locations(),
+ self.known_type_outlives_obligations,
+ locations,
DUMMY_SP, // irrelevant; will be overridden.
ConstraintCategory::Boring, // same as above.
self.borrowck_context.constraints,
@@ -2710,7 +2767,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
if let Err(_) = self.eq_args(
typeck_root_args,
parent_args,
- location.to_locations(),
+ locations,
ConstraintCategory::BoringNoLocation,
) {
span_mirbug!(
diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs
index 14ae999427dff..ce3fa1ab32c6a 100644
--- a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs
@@ -19,19 +19,6 @@ pub fn expand_deriving_eq(
) {
let span = cx.with_def_site_ctxt(span);
- let structural_trait_def = TraitDef {
- span,
- path: path_std!(marker::StructuralEq),
- skip_path_as_bound: true, // crucial!
- needs_copy_as_bound_if_packed: false,
- additional_bounds: Vec::new(),
- supports_unions: true,
- methods: Vec::new(),
- associated_types: Vec::new(),
- is_const: false,
- };
- structural_trait_def.expand(cx, mitem, item, push);
-
let trait_def = TraitDef {
span,
path: path_std!(cmp::Eq),
diff --git a/compiler/rustc_builtin_macros/src/errors.rs b/compiler/rustc_builtin_macros/src/errors.rs
index d6dfd0efaf913..eadb48ddd36d8 100644
--- a/compiler/rustc_builtin_macros/src/errors.rs
+++ b/compiler/rustc_builtin_macros/src/errors.rs
@@ -1,6 +1,6 @@
use rustc_errors::{
- AddToDiagnostic, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic, Level,
- MultiSpan, SingleLabelManySpans,
+ codes::*, AddToDiagnostic, DiagCtxt, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic,
+ Level, MultiSpan, SingleLabelManySpans,
};
use rustc_macros::{Diagnostic, Subdiagnostic};
use rustc_span::{symbol::Ident, Span, Symbol};
@@ -269,7 +269,7 @@ pub(crate) struct ConcatIdentsIdentArgs {
}
#[derive(Diagnostic)]
-#[diag(builtin_macros_bad_derive_target, code = "E0774")]
+#[diag(builtin_macros_bad_derive_target, code = E0774)]
pub(crate) struct BadDeriveTarget {
#[primary_span]
#[label]
@@ -283,7 +283,7 @@ pub(crate) struct BadDeriveTarget {
pub(crate) struct TestsNotSupport {}
#[derive(Diagnostic)]
-#[diag(builtin_macros_unexpected_lit, code = "E0777")]
+#[diag(builtin_macros_unexpected_lit, code = E0777)]
pub(crate) struct BadDeriveLit {
#[primary_span]
#[label]
diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs
index eb331ef585301..b66f7111ff006 100644
--- a/compiler/rustc_builtin_macros/src/format.rs
+++ b/compiler/rustc_builtin_macros/src/format.rs
@@ -139,7 +139,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
_ => {
let expr = p.parse_expr()?;
if !args.named_args().is_empty() {
- ecx.dcx().emit_err(errors::PositionalAfterNamed {
+ return Err(ecx.dcx().create_err(errors::PositionalAfterNamed {
span: expr.span,
args: args
.named_args()
@@ -147,7 +147,7 @@ fn parse_args<'a>(ecx: &mut ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<
.filter_map(|a| a.kind.ident().map(|ident| (a, ident)))
.map(|(arg, n)| n.span.to(arg.expr.span))
.collect(),
- });
+ }));
}
args.add(FormatArgument { kind: FormatArgumentKind::Normal, expr });
}
@@ -313,6 +313,8 @@ fn make_format_args(
}
use ArgRef::*;
+ let mut unnamed_arg_after_named_arg = false;
+
let mut lookup_arg = |arg: ArgRef<'_>,
span: Option,
used_as: PositionUsedAs,
@@ -352,6 +354,7 @@ fn make_format_args(
// For the moment capturing variables from format strings expanded from macros is
// disabled (see RFC #2795)
ecx.dcx().emit_err(errors::FormatNoArgNamed { span, name });
+ unnamed_arg_after_named_arg = true;
DummyResult::raw_expr(span, true)
};
Ok(args.add(FormatArgument { kind: FormatArgumentKind::Captured(ident), expr }))
@@ -510,7 +513,8 @@ fn make_format_args(
})
.collect::>();
- if !unused.is_empty() {
+ let has_unused = !unused.is_empty();
+ if has_unused {
// If there's a lot of unused arguments,
// let's check if this format arguments looks like another syntax (printf / shell).
let detect_foreign_fmt = unused.len() > args.explicit_args().len() / 2;
@@ -529,7 +533,7 @@ fn make_format_args(
// Only check for unused named argument names if there are no other errors to avoid causing
// too much noise in output errors, such as when a named argument is entirely unused.
- if invalid_refs.is_empty() && ecx.dcx().has_errors().is_none() {
+ if invalid_refs.is_empty() && !has_unused && !unnamed_arg_after_named_arg {
for &(index, span, used_as) in &numeric_refences_to_named_arg {
let (position_sp_to_replace, position_sp_for_msg) = match used_as {
Placeholder(pspan) => (span, pspan),
diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs
index 3e9b06a5b054b..4d7957ef4ddb0 100644
--- a/compiler/rustc_builtin_macros/src/lib.rs
+++ b/compiler/rustc_builtin_macros/src/lib.rs
@@ -5,17 +5,14 @@
#![feature(rustdoc_internals)]
#![doc(rust_logo)]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
-#![feature(array_windows)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(decl_macro)]
#![feature(if_let_guard)]
-#![feature(is_sorted)]
#![feature(let_chains)]
#![feature(lint_reasons)]
#![feature(proc_macro_internals)]
#![feature(proc_macro_quote)]
-#![recursion_limit = "256"]
extern crate proc_macro;
diff --git a/compiler/rustc_codegen_cranelift/.github/workflows/abi-cafe.yml b/compiler/rustc_codegen_cranelift/.github/workflows/abi-cafe.yml
index bd3b051185b46..e6bf944f5527b 100644
--- a/compiler/rustc_codegen_cranelift/.github/workflows/abi-cafe.yml
+++ b/compiler/rustc_codegen_cranelift/.github/workflows/abi-cafe.yml
@@ -33,14 +33,14 @@ jobs:
TARGET_TRIPLE: x86_64-pc-windows-gnu
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: CPU features
if: matrix.os == 'ubuntu-latest'
run: cat /proc/cpuinfo
- name: Cache cargo target dir
- uses: actions/cache@v3
+ uses: actions/cache@v4
with:
path: build/cg_clif
key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }}
diff --git a/compiler/rustc_codegen_cranelift/.github/workflows/audit.yml b/compiler/rustc_codegen_cranelift/.github/workflows/audit.yml
index 3efdec4155932..b4f8ce0f5329d 100644
--- a/compiler/rustc_codegen_cranelift/.github/workflows/audit.yml
+++ b/compiler/rustc_codegen_cranelift/.github/workflows/audit.yml
@@ -10,7 +10,7 @@ jobs:
audit:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- run: |
sed -i 's/components.*/components = []/' rust-toolchain
echo 'profile = "minimal"' >> rust-toolchain
diff --git a/compiler/rustc_codegen_cranelift/.github/workflows/main.yml b/compiler/rustc_codegen_cranelift/.github/workflows/main.yml
index 9bbb18fc37fca..cf9a105538df4 100644
--- a/compiler/rustc_codegen_cranelift/.github/workflows/main.yml
+++ b/compiler/rustc_codegen_cranelift/.github/workflows/main.yml
@@ -10,7 +10,7 @@ jobs:
timeout-minutes: 10
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Avoid installing rustc-dev
run: |
@@ -64,14 +64,14 @@ jobs:
TARGET_TRIPLE: x86_64-pc-windows-gnu
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: CPU features
if: matrix.os == 'ubuntu-latest'
run: cat /proc/cpuinfo
- name: Cache cargo target dir
- uses: actions/cache@v3
+ uses: actions/cache@v4
with:
path: build/cg_clif
key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }}
@@ -138,7 +138,7 @@ jobs:
shell: bash
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: CPU features
run: cat /proc/cpuinfo
@@ -164,13 +164,13 @@ jobs:
shell: bash
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: CPU features
run: cat /proc/cpuinfo
- name: Cache cargo target dir
- uses: actions/cache@v3
+ uses: actions/cache@v4
with:
path: build/cg_clif
key: ${{ runner.os }}-x86_64-unknown-linux-gnu-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }}
@@ -221,10 +221,10 @@ jobs:
TARGET_TRIPLE: x86_64-pc-windows-gnu
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Cache cargo target dir
- uses: actions/cache@v3
+ uses: actions/cache@v4
with:
path: build/cg_clif
key: ${{ runner.os }}-${{ matrix.env.TARGET_TRIPLE }}-dist-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }}
@@ -276,7 +276,7 @@ jobs:
cancel-in-progress: true
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: Download all built artifacts
uses: actions/download-artifact@v4
diff --git a/compiler/rustc_codegen_cranelift/.github/workflows/rustc.yml b/compiler/rustc_codegen_cranelift/.github/workflows/rustc.yml
index 8085dc58263cc..930d025b73edc 100644
--- a/compiler/rustc_codegen_cranelift/.github/workflows/rustc.yml
+++ b/compiler/rustc_codegen_cranelift/.github/workflows/rustc.yml
@@ -9,13 +9,13 @@ jobs:
timeout-minutes: 60
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: CPU features
run: cat /proc/cpuinfo
- name: Cache cargo target dir
- uses: actions/cache@v3
+ uses: actions/cache@v4
with:
path: build/cg_clif
key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }}
@@ -32,13 +32,13 @@ jobs:
timeout-minutes: 60
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v4
- name: CPU features
run: cat /proc/cpuinfo
- name: Cache cargo target dir
- uses: actions/cache@v3
+ uses: actions/cache@v4
with:
path: build/cg_clif
key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('rust-toolchain', '**/Cargo.lock') }}
diff --git a/compiler/rustc_codegen_cranelift/.vscode/settings.json b/compiler/rustc_codegen_cranelift/.vscode/settings.json
index 834a1362caf32..491646ce59bb3 100644
--- a/compiler/rustc_codegen_cranelift/.vscode/settings.json
+++ b/compiler/rustc_codegen_cranelift/.vscode/settings.json
@@ -1,8 +1,9 @@
{
"editor.formatOnSave": true,
- // source for rustc_* is not included in the rust-src component; disable the errors about this
+ // in case rustc.source is disabled for performance reasons; disable the errors about this
"rust-analyzer.diagnostics.disabled": ["unresolved-extern-crate", "unresolved-macro-call"],
+ "rust-analyzer.rustc.source": "discover",
"rust-analyzer.imports.granularity.enforce": true,
"rust-analyzer.imports.granularity.group": "module",
"rust-analyzer.imports.prefix": "crate",
diff --git a/compiler/rustc_codegen_cranelift/Cargo.lock b/compiler/rustc_codegen_cranelift/Cargo.lock
index 6d6a1200f5028..86bc7d0f067cb 100644
--- a/compiler/rustc_codegen_cranelift/Cargo.lock
+++ b/compiler/rustc_codegen_cranelift/Cargo.lock
@@ -45,18 +45,18 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cranelift-bforest"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7c22542c0b95bd3302f7ed6839869c561f2324bac2fd5e7e99f5cfa65fdc8b92"
+checksum = "d819feeda4c420a18f1e28236ca0ce1177b22bf7c8a44ddee92dfe40de15bcf0"
dependencies = [
"cranelift-entity",
]
[[package]]
name = "cranelift-codegen"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6b3db903ef2e9c8a4de2ea6db5db052c7857282952f9df604aa55d169e6000d8"
+checksum = "e9b8d03d5bdbca7e5f72b0e0a0f69933ed1f09e24be6c075aa6fe3f802b0cc0c"
dependencies = [
"bumpalo",
"cranelift-bforest",
@@ -75,39 +75,39 @@ dependencies = [
[[package]]
name = "cranelift-codegen-meta"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6590feb5a1d6438f974bf6a5ac4dddf69fca14e1f07f3265d880f69e61a94463"
+checksum = "a3fd3664e38e51649b17dc30cfdd561273fe2f590dcd013fb75d9eabc6272dfb"
dependencies = [
"cranelift-codegen-shared",
]
[[package]]
name = "cranelift-codegen-shared"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7239038c56fafe77fddc8788fc8533dd6c474dc5bdc5637216404f41ba807330"
+checksum = "4b031ec5e605828975952622b5a77d49126f20ffe88d33719a0af66b23a0fc36"
[[package]]
name = "cranelift-control"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f7dc9c595341404d381d27a3d950160856b35b402275f0c3990cd1ad683c8053"
+checksum = "fada054d017cf2ed8f7ed2336e0517fc1b19e6825be1790de9eb00c94788362b"
dependencies = [
"arbitrary",
]
[[package]]
name = "cranelift-entity"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "44e3ee532fc4776c69bcedf7e62f9632cbb3f35776fa9a525cdade3195baa3f7"
+checksum = "177b6f94ae8de6348eb45bf977c79ab9e3c40fc3ac8cb7ed8109560ea39bee7d"
[[package]]
name = "cranelift-frontend"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a612c94d09e653662ec37681dc2d6fd2b9856e6df7147be0afc9aabb0abf19df"
+checksum = "ebebd23a69a23e3ddea78e98ff3a2de222e88c8e045d81ef4a72f042e0d79dbd"
dependencies = [
"cranelift-codegen",
"log",
@@ -117,15 +117,15 @@ dependencies = [
[[package]]
name = "cranelift-isle"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85db9830abeb1170b7d29b536ffd55af1d4d26ac8a77570b5d1aca003bf225cc"
+checksum = "1571bfc14df8966d12c6121b5325026591a4b4009e22fea0fe3765ab7cd33b96"
[[package]]
name = "cranelift-jit"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4946271f1055e26544ef8c90fa24776f201566419dfac4b3962c39d5a804ff67"
+checksum = "2f61e236d7622c3c43016e8b0f3ba27136e21ac7de328c7fda902e61db1de851"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -138,14 +138,14 @@ dependencies = [
"region",
"target-lexicon",
"wasmtime-jit-icache-coherence",
- "windows-sys",
+ "windows-sys 0.52.0",
]
[[package]]
name = "cranelift-module"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb7e3bdae2597556e59edeb8ecb62eb32c7e054c4f042d393732902979db69c3"
+checksum = "f30c6820342015c5009070e3e48d1da7b13521399de904663f1c84f5ee839657"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -154,9 +154,9 @@ dependencies = [
[[package]]
name = "cranelift-native"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "301ef0edafeaeda5771a5d2db64ac53e1818ae3111220a185677025fe91db4a1"
+checksum = "35a69c37e0c10b46fe5527f2397ac821046efbf5f7ec112c8b84df25712f465b"
dependencies = [
"cranelift-codegen",
"libc",
@@ -165,9 +165,9 @@ dependencies = [
[[package]]
name = "cranelift-object"
-version = "0.103.0"
+version = "0.104.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "59e0ee3d013728903e0c513c31afa389b559bfd4fe8a44f80335c799e3132a41"
+checksum = "24425a329b4343177d5f1852243841dcec17f929d72c0e7f41262140155e55e7"
dependencies = [
"anyhow",
"cranelift-codegen",
@@ -251,7 +251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c571b676ddfc9a8c12f1f3d3085a7b163966a8fd8098a90640953ce5f6170161"
dependencies = [
"cfg-if",
- "windows-sys",
+ "windows-sys 0.48.0",
]
[[package]]
@@ -374,13 +374,13 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "wasmtime-jit-icache-coherence"
-version = "16.0.0"
+version = "17.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6b6d197fcc34ad32ed440e1f9552fd57d1f377d9699d31dee1b5b457322c1f8a"
+checksum = "bdc26415bb89e9ccd3bdc498fef63aabf665c4c0dd710c107691deb9694955da"
dependencies = [
"cfg-if",
"libc",
- "windows-sys",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -411,7 +411,16 @@ version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
- "windows-targets",
+ "windows-targets 0.48.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.0",
]
[[package]]
@@ -420,13 +429,28 @@ version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
- "windows_aarch64_gnullvm",
- "windows_aarch64_msvc",
- "windows_i686_gnu",
- "windows_i686_msvc",
- "windows_x86_64_gnu",
- "windows_x86_64_gnullvm",
- "windows_x86_64_msvc",
+ "windows_aarch64_gnullvm 0.48.5",
+ "windows_aarch64_msvc 0.48.5",
+ "windows_i686_gnu 0.48.5",
+ "windows_i686_msvc 0.48.5",
+ "windows_x86_64_gnu 0.48.5",
+ "windows_x86_64_gnullvm 0.48.5",
+ "windows_x86_64_msvc 0.48.5",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.0",
+ "windows_aarch64_msvc 0.52.0",
+ "windows_i686_gnu 0.52.0",
+ "windows_i686_msvc 0.52.0",
+ "windows_x86_64_gnu 0.52.0",
+ "windows_x86_64_gnullvm 0.52.0",
+ "windows_x86_64_msvc 0.52.0",
]
[[package]]
@@ -435,38 +459,80 @@ version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea"
+
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef"
+
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313"
+
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a"
+
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd"
+
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e"
+
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04"
diff --git a/compiler/rustc_codegen_cranelift/Cargo.toml b/compiler/rustc_codegen_cranelift/Cargo.toml
index c57e964168f4d..586ce2286f971 100644
--- a/compiler/rustc_codegen_cranelift/Cargo.toml
+++ b/compiler/rustc_codegen_cranelift/Cargo.toml
@@ -8,12 +8,12 @@ crate-type = ["dylib"]
[dependencies]
# These have to be in sync with each other
-cranelift-codegen = { version = "0.103", default-features = false, features = ["std", "unwind", "all-arch"] }
-cranelift-frontend = { version = "0.103" }
-cranelift-module = { version = "0.103" }
-cranelift-native = { version = "0.103" }
-cranelift-jit = { version = "0.103", optional = true }
-cranelift-object = { version = "0.103" }
+cranelift-codegen = { version = "0.104", default-features = false, features = ["std", "unwind", "all-arch"] }
+cranelift-frontend = { version = "0.104" }
+cranelift-module = { version = "0.104" }
+cranelift-native = { version = "0.104" }
+cranelift-jit = { version = "0.104", optional = true }
+cranelift-object = { version = "0.104" }
target-lexicon = "0.12.0"
gimli = { version = "0.28", default-features = false, features = ["write"]}
object = { version = "0.32", default-features = false, features = ["std", "read_core", "write", "archive", "coff", "elf", "macho", "pe"] }
diff --git a/compiler/rustc_codegen_cranelift/Readme.md b/compiler/rustc_codegen_cranelift/Readme.md
index ca6ecdf1d0e88..4f45526196397 100644
--- a/compiler/rustc_codegen_cranelift/Readme.md
+++ b/compiler/rustc_codegen_cranelift/Readme.md
@@ -62,6 +62,27 @@ $ ./test.sh
For more docs on how to build and test see [build_system/usage.txt](build_system/usage.txt) or the help message of `./y.sh`.
+## Platform support
+
+|OS \ architecture|x86\_64|AArch64|Riscv64|s390x (System-Z)|
+|---|---|---|---|---|
+|Linux|✅|✅|✅[^no-rustup]|✅[^no-rustup]|
+|FreeBSD|✅[^no-rustup]|❓|❓|❓|
+|AIX|❌[^xcoff]|N/A|N/A|❌[^xcoff]|
+|Other unixes|❓|❓|❓|❓|
+|macOS|✅|❌[^apple-silicon]|N/A|N/A|
+|Windows|✅[^no-rustup]|❌|N/A|N/A|
+
+✅: Fully supported and tested
+❓: Maybe supported, not tested
+❌: Not supported at all
+
+Not all targets are available as rustup component for nightly. See notes in the platform support matrix.
+
+[^xcoff]: XCOFF object file format is not supported.
+[^apple-silicon]: Tracked in [#1248](https://github.com/rust-lang/rustc_codegen_cranelift/issues/1248).
+[^no-rustup]: Not available as rustup component for nightly. You can build it yourself.
+
## Usage
rustc_codegen_cranelift can be used as a near-drop-in replacement for `cargo build` or `cargo run` for existing projects.
@@ -100,6 +121,8 @@ You need to do this steps to successfully compile and use the cranelift backend
* (Optional) run tests: `rustup run stage2 ./y.sh test`
8. Now you can use your cg_clif build to compile other Rust programs, e.g. you can open any Rust crate and run commands like `$RustCheckoutDir/compiler/rustc_codegen_cranelift/dist/cargo-clif build --release`.
+You can also set `rust-analyzer.rustc.source` to your rust workspace to get rust-analyzer to understand your changes.
+
## Configuration
See the documentation on the `BackendConfig` struct in [config.rs](src/config.rs) for all
diff --git a/compiler/rustc_codegen_cranelift/build_system/tests.rs b/compiler/rustc_codegen_cranelift/build_system/tests.rs
index cb7b2454cd5ed..818f3d6f08d26 100644
--- a/compiler/rustc_codegen_cranelift/build_system/tests.rs
+++ b/compiler/rustc_codegen_cranelift/build_system/tests.rs
@@ -113,8 +113,8 @@ const BASE_SYSROOT_SUITE: &[TestCase] = &[
pub(crate) static RAND_REPO: GitRepo = GitRepo::github(
"rust-random",
"rand",
- "9a02c819cc1e4ec6959ae25eafbb5cf6acb68234",
- "4934f0afb1d1c2ca",
+ "1f4507a8e1cf8050e4ceef95eeda8f64645b6719",
+ "981f8bf489338978",
"rand",
);
@@ -133,8 +133,8 @@ pub(crate) static REGEX: CargoProject = CargoProject::new(®EX_REPO.source_dir
pub(crate) static PORTABLE_SIMD_REPO: GitRepo = GitRepo::github(
"rust-lang",
"portable-simd",
- "4825b2a64d765317066948867e8714674419359b",
- "9e67d07c00f5fb0b",
+ "97007cc2e70df8c97326ce896a79e2f0ce4dd98b",
+ "e54a16035cedf205",
"portable-simd",
);
diff --git a/compiler/rustc_codegen_cranelift/example/mini_core.rs b/compiler/rustc_codegen_cranelift/example/mini_core.rs
index 3607b7cd9448b..a79909ce0c878 100644
--- a/compiler/rustc_codegen_cranelift/example/mini_core.rs
+++ b/compiler/rustc_codegen_cranelift/example/mini_core.rs
@@ -104,9 +104,6 @@ unsafe impl Freeze for &mut T {}
#[lang = "structural_peq"]
pub trait StructuralPartialEq {}
-#[lang = "structural_teq"]
-pub trait StructuralEq {}
-
#[lang = "not"]
pub trait Not {
type Output;
diff --git a/compiler/rustc_codegen_cranelift/patches/0001-portable-simd-Enable-the-exposed_provenance-feature.patch b/compiler/rustc_codegen_cranelift/patches/0001-portable-simd-Enable-the-exposed_provenance-feature.patch
deleted file mode 100644
index b8c0783f52430..0000000000000
--- a/compiler/rustc_codegen_cranelift/patches/0001-portable-simd-Enable-the-exposed_provenance-feature.patch
+++ /dev/null
@@ -1,22 +0,0 @@
-From a101a43b795431ce617e7782afb451f4853afc00 Mon Sep 17 00:00:00 2001
-From: bjorn3 <17426603+bjorn3@users.noreply.github.com>
-Date: Thu, 7 Dec 2023 14:51:35 +0000
-Subject: [PATCH] Enable the exposed_provenance feature
-
----
- crates/core_simd/tests/pointers.rs | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/crates/core_simd/tests/pointers.rs b/crates/core_simd/tests/pointers.rs
-index 0ae8f83..06620d6 100644
---- a/crates/core_simd/tests/pointers.rs
-+++ b/crates/core_simd/tests/pointers.rs
-@@ -1,4 +1,4 @@
--#![feature(portable_simd, strict_provenance)]
-+#![feature(exposed_provenance, portable_simd, strict_provenance)]
-
- use core_simd::simd::{Simd, SimdConstPtr, SimdMutPtr};
-
---
-2.34.1
-
diff --git a/compiler/rustc_codegen_cranelift/patches/0027-coretests-128bit-atomic-operations.patch b/compiler/rustc_codegen_cranelift/patches/0027-coretests-128bit-atomic-operations.patch
index be29ae09bcfc6..271ca12eabbcd 100644
--- a/compiler/rustc_codegen_cranelift/patches/0027-coretests-128bit-atomic-operations.patch
+++ b/compiler/rustc_codegen_cranelift/patches/0027-coretests-128bit-atomic-operations.patch
@@ -21,7 +21,7 @@ index 897a5e9..331f66f 100644
-#![cfg_attr(target_has_atomic = "128", feature(integer_atomics))]
#![cfg_attr(test, feature(cfg_match))]
#![feature(int_roundings)]
- #![feature(slice_group_by)]
+ #![feature(split_array)]
diff --git a/atomic.rs b/atomic.rs
index b735957..ea728b6 100644
--- a/atomic.rs
diff --git a/compiler/rustc_codegen_cranelift/patches/rand-lock.toml b/compiler/rustc_codegen_cranelift/patches/rand-lock.toml
index aacf3653c169e..815b828a68bd6 100644
--- a/compiler/rustc_codegen_cranelift/patches/rand-lock.toml
+++ b/compiler/rustc_codegen_cranelift/patches/rand-lock.toml
@@ -487,6 +487,7 @@ dependencies = [
"rand_pcg",
"rayon",
"serde",
+ "zerocopy",
]
[[package]]
@@ -505,6 +506,7 @@ version = "0.7.0"
dependencies = [
"getrandom",
"serde",
+ "zerocopy",
]
[[package]]
@@ -525,6 +527,7 @@ name = "rand_pcg"
version = "0.4.0"
dependencies = [
"bincode",
+ "rand",
"rand_core",
"serde",
]
@@ -823,3 +826,23 @@ name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "zerocopy"
+version = "0.7.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.7.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.37",
+]
diff --git a/compiler/rustc_codegen_cranelift/patches/stdlib-lock.toml b/compiler/rustc_codegen_cranelift/patches/stdlib-lock.toml
index 8e213f71c3f38..ad63b0768d313 100644
--- a/compiler/rustc_codegen_cranelift/patches/stdlib-lock.toml
+++ b/compiler/rustc_codegen_cranelift/patches/stdlib-lock.toml
@@ -61,9 +61,9 @@ dependencies = [
[[package]]
name = "compiler_builtins"
-version = "0.1.104"
+version = "0.1.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99c3f9035afc33f4358773239573f7d121099856753e1bbd2a6a5207098fc741"
+checksum = "f4ab134a739bafec76aa91ccb15d519a54e569350644a1fea6528d5a0d407e22"
dependencies = [
"cc",
"rustc-std-workspace-core",
diff --git a/compiler/rustc_codegen_cranelift/rust-toolchain b/compiler/rustc_codegen_cranelift/rust-toolchain
index a086c0293601f..ccd7edbc2a917 100644
--- a/compiler/rustc_codegen_cranelift/rust-toolchain
+++ b/compiler/rustc_codegen_cranelift/rust-toolchain
@@ -1,3 +1,3 @@
[toolchain]
-channel = "nightly-2023-12-31"
+channel = "nightly-2024-01-26"
components = ["rust-src", "rustc-dev", "llvm-tools"]
diff --git a/compiler/rustc_codegen_cranelift/src/abi/mod.rs b/compiler/rustc_codegen_cranelift/src/abi/mod.rs
index abd70dd4458f6..0f0d828c8fc3f 100644
--- a/compiler/rustc_codegen_cranelift/src/abi/mod.rs
+++ b/compiler/rustc_codegen_cranelift/src/abi/mod.rs
@@ -56,11 +56,7 @@ pub(crate) fn conv_to_call_conv(sess: &Session, c: Conv, default_call_conv: Call
sess.dcx().fatal("C-cmse-nonsecure-call call conv is not yet implemented");
}
- Conv::Msp430Intr
- | Conv::PtxKernel
- | Conv::AmdGpuKernel
- | Conv::AvrInterrupt
- | Conv::AvrNonBlockingInterrupt => {
+ Conv::Msp430Intr | Conv::PtxKernel | Conv::AvrInterrupt | Conv::AvrNonBlockingInterrupt => {
unreachable!("tried to use {c:?} call conv which only exists on an unsupported target");
}
}
diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs
index e6edc452cfb08..2d9c2ecdbc2be 100644
--- a/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs
+++ b/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs
@@ -13,17 +13,14 @@ use gimli::write::{
};
use gimli::{Encoding, Format, LineEncoding, RunTimeEndian};
use indexmap::IndexSet;
+use rustc_session::Session;
pub(crate) use self::emit::{DebugReloc, DebugRelocName};
pub(crate) use self::unwind::UnwindContext;
use crate::prelude::*;
-pub(crate) fn producer() -> String {
- format!(
- "rustc version {} with cranelift {}",
- rustc_interface::util::rustc_version_str().unwrap_or("unknown version"),
- cranelift_codegen::VERSION,
- )
+pub(crate) fn producer(sess: &Session) -> String {
+ format!("rustc version {} with cranelift {}", sess.cfg_version, cranelift_codegen::VERSION)
}
pub(crate) struct DebugContext {
@@ -67,7 +64,7 @@ impl DebugContext {
let should_remap_filepaths = tcx.sess.should_prefer_remapped_for_codegen();
- let producer = producer();
+ let producer = producer(tcx.sess);
let comp_dir = tcx
.sess
.opts
diff --git a/compiler/rustc_codegen_cranelift/src/driver/aot.rs b/compiler/rustc_codegen_cranelift/src/driver/aot.rs
index e77b0cd0721b2..757082a5fed1c 100644
--- a/compiler/rustc_codegen_cranelift/src/driver/aot.rs
+++ b/compiler/rustc_codegen_cranelift/src/driver/aot.rs
@@ -143,6 +143,7 @@ fn emit_cgu(
debug: Option,
unwind_context: UnwindContext,
global_asm_object_file: Option,
+ producer: &str,
) -> Result {
let mut product = module.finish();
@@ -152,8 +153,14 @@ fn emit_cgu(
unwind_context.emit(&mut product);
- let module_regular =
- emit_module(output_filenames, prof, product.object, ModuleKind::Regular, name.clone())?;
+ let module_regular = emit_module(
+ output_filenames,
+ prof,
+ product.object,
+ ModuleKind::Regular,
+ name.clone(),
+ producer,
+ )?;
Ok(ModuleCodegenResult {
module_regular,
@@ -174,6 +181,7 @@ fn emit_module(
mut object: cranelift_object::object::write::Object<'_>,
kind: ModuleKind,
name: String,
+ producer_str: &str,
) -> Result {
if object.format() == cranelift_object::object::BinaryFormat::Elf {
let comment_section = object.add_section(
@@ -182,7 +190,7 @@ fn emit_module(
cranelift_object::object::SectionKind::OtherString,
);
let mut producer = vec![0];
- producer.extend(crate::debuginfo::producer().as_bytes());
+ producer.extend(producer_str.as_bytes());
producer.push(0);
object.set_section_data(comment_section, producer, 1);
}
@@ -321,6 +329,8 @@ fn module_codegen(
(cgu_name, cx, module, codegened_functions)
});
+ let producer = crate::debuginfo::producer(tcx.sess);
+
OngoingModuleCodegen::Async(std::thread::spawn(move || {
cx.profiler.clone().generic_activity_with_arg("compile functions", &*cgu_name).run(|| {
cranelift_codegen::timing::set_thread_profiler(Box::new(super::MeasuremeProfiler(
@@ -348,6 +358,7 @@ fn module_codegen(
cx.debug_context,
cx.unwind_context,
global_asm_object_file,
+ &producer,
)
});
std::mem::drop(token);
@@ -453,6 +464,7 @@ pub(crate) fn run_aot(
product.object,
ModuleKind::Allocator,
"allocator_shim".to_owned(),
+ &crate::debuginfo::producer(tcx.sess),
) {
Ok(allocator_module) => Some(allocator_module),
Err(err) => tcx.dcx().fatal(err),
@@ -467,7 +479,7 @@ pub(crate) fn run_aot(
let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
let metadata_cgu_name = cgu_name_builder
- .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
+ .build_cgu_name(LOCAL_CRATE, ["crate"], Some("metadata"))
.as_str()
.to_string();
diff --git a/compiler/rustc_codegen_cranelift/src/driver/jit.rs b/compiler/rustc_codegen_cranelift/src/driver/jit.rs
index 50d9f287e74c9..6b2b946db02b6 100644
--- a/compiler/rustc_codegen_cranelift/src/driver/jit.rs
+++ b/compiler/rustc_codegen_cranelift/src/driver/jit.rs
@@ -321,10 +321,9 @@ fn dep_symbol_lookup_fn(
Linkage::NotLinked | Linkage::IncludedFromDylib => {}
Linkage::Static => {
let name = crate_info.crate_name[&cnum];
- sess.dcx()
- .struct_err(format!("Can't load static lib {}", name))
- .note("rustc_codegen_cranelift can only load dylibs in JIT mode.")
- .emit();
+ let mut diag = sess.dcx().struct_err(format!("Can't load static lib {}", name));
+ diag.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
+ diag.emit();
}
Linkage::Dynamic => {
dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
diff --git a/compiler/rustc_codegen_cranelift/src/inline_asm.rs b/compiler/rustc_codegen_cranelift/src/inline_asm.rs
index 6b9cec39d7020..7793b1b70924b 100644
--- a/compiler/rustc_codegen_cranelift/src/inline_asm.rs
+++ b/compiler/rustc_codegen_cranelift/src/inline_asm.rs
@@ -52,7 +52,7 @@ pub(crate) fn codegen_inline_asm_terminator<'tcx>(
}
let operands = operands
- .into_iter()
+ .iter()
.map(|operand| match *operand {
InlineAsmOperand::In { reg, ref value } => CInlineAsmOperand::In {
reg,
@@ -506,10 +506,34 @@ impl<'tcx> InlineAssemblyGenerator<'_, 'tcx> {
if self.options.contains(InlineAsmOptions::ATT_SYNTAX) {
generated_asm.push('%');
}
- self.registers[*operand_idx]
- .unwrap()
- .emit(&mut generated_asm, self.arch, *modifier)
- .unwrap();
+
+ let reg = self.registers[*operand_idx].unwrap();
+ match self.arch {
+ InlineAsmArch::X86_64 => match reg {
+ InlineAsmReg::X86(reg)
+ if reg as u32 >= X86InlineAsmReg::xmm0 as u32
+ && reg as u32 <= X86InlineAsmReg::xmm15 as u32 =>
+ {
+ // rustc emits x0 rather than xmm0
+ let class = match *modifier {
+ None | Some('x') => "xmm",
+ Some('y') => "ymm",
+ Some('z') => "zmm",
+ _ => unreachable!(),
+ };
+ write!(
+ generated_asm,
+ "{class}{}",
+ reg as u32 - X86InlineAsmReg::xmm0 as u32
+ )
+ .unwrap();
+ }
+ _ => reg
+ .emit(&mut generated_asm, InlineAsmArch::X86_64, *modifier)
+ .unwrap(),
+ },
+ _ => reg.emit(&mut generated_asm, self.arch, *modifier).unwrap(),
+ }
}
CInlineAsmOperand::Const { ref value } => {
generated_asm.push_str(value);
@@ -739,7 +763,7 @@ fn call_inline_asm<'tcx>(
},
)
.unwrap();
- let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, &mut fx.bcx.func);
+ let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, fx.bcx.func);
if fx.clif_comments.enabled() {
fx.add_comment(inline_asm_func, asm_name);
}
diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs
index 1345c4614e254..e50c74b87f603 100644
--- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs
+++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs
@@ -35,6 +35,10 @@ pub(crate) fn codegen_llvm_intrinsic_call<'tcx>(
}
match intrinsic {
+ "llvm.prefetch" => {
+ // Nothing to do. This is merely a perf hint.
+ }
+
_ if intrinsic.starts_with("llvm.ctlz.v") => {
intrinsic_args!(fx, args => (a); intrinsic);
diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs
index f6f3b85d3ef81..e66bcbf4e40e5 100644
--- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs
+++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs
@@ -243,6 +243,20 @@ pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>(
}
// FIXME generalize vector types
+ "llvm.aarch64.neon.tbl1.v8i8" => {
+ intrinsic_args!(fx, args => (t, idx); intrinsic);
+
+ let zero = fx.bcx.ins().iconst(types::I8, 0);
+ for i in 0..8 {
+ let idx_lane = idx.value_lane(fx, i).load_scalar(fx);
+ let is_zero =
+ fx.bcx.ins().icmp_imm(IntCC::UnsignedGreaterThanOrEqual, idx_lane, 16);
+ let t_idx = fx.bcx.ins().uextend(fx.pointer_type, idx_lane);
+ let t_lane = t.value_lane_dyn(fx, t_idx).load_scalar(fx);
+ let res = fx.bcx.ins().select(is_zero, zero, t_lane);
+ ret.place_lane(fx, i).to_ptr().store(fx, res, MemFlags::trusted());
+ }
+ }
"llvm.aarch64.neon.tbl1.v16i8" => {
intrinsic_args!(fx, args => (t, idx); intrinsic);
diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs
index 994dc66835cde..2e3e7ce986b36 100644
--- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs
+++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs
@@ -610,230 +610,56 @@ pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>(
// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packus_epi16&ig_expand=4903
intrinsic_args!(fx, args => (a, b); intrinsic);
- assert_eq!(a.layout(), b.layout());
- let layout = a.layout();
-
- let (lane_count, lane_ty) = layout.ty.simd_size_and_type(fx.tcx);
- let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
- assert_eq!(lane_ty, fx.tcx.types.i16);
- assert_eq!(ret_lane_ty, fx.tcx.types.u8);
- assert_eq!(lane_count * 2, ret_lane_count);
-
- let zero = fx.bcx.ins().iconst(types::I16, 0);
- let max_u8 = fx.bcx.ins().iconst(types::I16, 255);
- let ret_lane_layout = fx.layout_of(fx.tcx.types.u8);
-
- for idx in 0..lane_count {
- let lane = a.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, zero);
- let sat = fx.bcx.ins().umin(sat, max_u8);
- let res = fx.bcx.ins().ireduce(types::I8, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, idx).write_cvalue(fx, res_lane);
- }
+ pack_instruction(fx, a, b, ret, PackSize::U8, PackWidth::Sse);
+ }
- for idx in 0..lane_count {
- let lane = b.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, zero);
- let sat = fx.bcx.ins().umin(sat, max_u8);
- let res = fx.bcx.ins().ireduce(types::I8, sat);
+ "llvm.x86.sse2.packsswb.128" => {
+ // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packs_epi16&ig_expand=4848
+ intrinsic_args!(fx, args => (a, b); intrinsic);
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count + idx).write_cvalue(fx, res_lane);
- }
+ pack_instruction(fx, a, b, ret, PackSize::S8, PackWidth::Sse);
}
"llvm.x86.avx2.packuswb" => {
// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_packus_epi16&ig_expand=4906
intrinsic_args!(fx, args => (a, b); intrinsic);
- assert_eq!(a.layout(), b.layout());
- let layout = a.layout();
-
- let (lane_count, lane_ty) = layout.ty.simd_size_and_type(fx.tcx);
- let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
- assert_eq!(lane_ty, fx.tcx.types.i16);
- assert_eq!(ret_lane_ty, fx.tcx.types.u8);
- assert_eq!(lane_count * 2, ret_lane_count);
-
- let zero = fx.bcx.ins().iconst(types::I16, 0);
- let max_u8 = fx.bcx.ins().iconst(types::I16, 255);
- let ret_lane_layout = fx.layout_of(fx.tcx.types.u8);
-
- for idx in 0..lane_count / 2 {
- let lane = a.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, zero);
- let sat = fx.bcx.ins().umin(sat, max_u8);
- let res = fx.bcx.ins().ireduce(types::I8, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, idx).write_cvalue(fx, res_lane);
- }
-
- for idx in 0..lane_count / 2 {
- let lane = b.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, zero);
- let sat = fx.bcx.ins().umin(sat, max_u8);
- let res = fx.bcx.ins().ireduce(types::I8, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count / 2 + idx).write_cvalue(fx, res_lane);
- }
-
- for idx in 0..lane_count / 2 {
- let lane = a.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, zero);
- let sat = fx.bcx.ins().umin(sat, max_u8);
- let res = fx.bcx.ins().ireduce(types::I8, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count / 2 * 2 + idx).write_cvalue(fx, res_lane);
- }
-
- for idx in 0..lane_count / 2 {
- let lane = b.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, zero);
- let sat = fx.bcx.ins().umin(sat, max_u8);
- let res = fx.bcx.ins().ireduce(types::I8, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count / 2 * 3 + idx).write_cvalue(fx, res_lane);
- }
+ pack_instruction(fx, a, b, ret, PackSize::U8, PackWidth::Avx);
}
- "llvm.x86.sse2.packssdw.128" => {
- // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packs_epi32&ig_expand=4889
+ "llvm.x86.avx2.packsswb" => {
+ // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_packs_epi16&ig_expand=4851
intrinsic_args!(fx, args => (a, b); intrinsic);
- assert_eq!(a.layout(), b.layout());
- let layout = a.layout();
-
- let (lane_count, lane_ty) = layout.ty.simd_size_and_type(fx.tcx);
- let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
- assert_eq!(lane_ty, fx.tcx.types.i32);
- assert_eq!(ret_lane_ty, fx.tcx.types.i16);
- assert_eq!(lane_count * 2, ret_lane_count);
-
- let min_i16 = fx.bcx.ins().iconst(types::I32, i32::from(i16::MIN) as u32 as i64);
- let max_i16 = fx.bcx.ins().iconst(types::I32, i32::from(i16::MAX) as u32 as i64);
- let ret_lane_layout = fx.layout_of(fx.tcx.types.i16);
-
- for idx in 0..lane_count {
- let lane = a.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, min_i16);
- let sat = fx.bcx.ins().smin(sat, max_i16);
- let res = fx.bcx.ins().ireduce(types::I16, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, idx).write_cvalue(fx, res_lane);
- }
-
- for idx in 0..lane_count {
- let lane = b.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, min_i16);
- let sat = fx.bcx.ins().smin(sat, max_i16);
- let res = fx.bcx.ins().ireduce(types::I16, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count + idx).write_cvalue(fx, res_lane);
- }
+ pack_instruction(fx, a, b, ret, PackSize::S8, PackWidth::Avx);
}
"llvm.x86.sse41.packusdw" => {
// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packus_epi32&ig_expand=4912
intrinsic_args!(fx, args => (a, b); intrinsic);
- assert_eq!(a.layout(), b.layout());
- let layout = a.layout();
-
- let (lane_count, lane_ty) = layout.ty.simd_size_and_type(fx.tcx);
- let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
- assert_eq!(lane_ty, fx.tcx.types.i32);
- assert_eq!(ret_lane_ty, fx.tcx.types.u16);
- assert_eq!(lane_count * 2, ret_lane_count);
-
- let min_u16 = fx.bcx.ins().iconst(types::I32, i64::from(u16::MIN));
- let max_u16 = fx.bcx.ins().iconst(types::I32, i64::from(u16::MAX));
- let ret_lane_layout = fx.layout_of(fx.tcx.types.u16);
+ pack_instruction(fx, a, b, ret, PackSize::U16, PackWidth::Sse);
+ }
- for idx in 0..lane_count {
- let lane = a.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, min_u16);
- let sat = fx.bcx.ins().smin(sat, max_u16);
- let res = fx.bcx.ins().ireduce(types::I16, sat);
+ "llvm.x86.sse2.packssdw.128" => {
+ // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_packs_epi32&ig_expand=4889
+ intrinsic_args!(fx, args => (a, b); intrinsic);
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, idx).write_cvalue(fx, res_lane);
- }
+ pack_instruction(fx, a, b, ret, PackSize::S16, PackWidth::Sse);
+ }
- for idx in 0..lane_count {
- let lane = b.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, min_u16);
- let sat = fx.bcx.ins().smin(sat, max_u16);
- let res = fx.bcx.ins().ireduce(types::I16, sat);
+ "llvm.x86.avx2.packusdw" => {
+ // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_packus_epi32&ig_expand=4883
+ intrinsic_args!(fx, args => (a, b); intrinsic);
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count + idx).write_cvalue(fx, res_lane);
- }
+ pack_instruction(fx, a, b, ret, PackSize::U16, PackWidth::Avx);
}
"llvm.x86.avx2.packssdw" => {
// https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm256_packs_epi32&ig_expand=4892
intrinsic_args!(fx, args => (a, b); intrinsic);
- assert_eq!(a.layout(), b.layout());
- let layout = a.layout();
-
- let (lane_count, lane_ty) = layout.ty.simd_size_and_type(fx.tcx);
- let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
- assert_eq!(lane_ty, fx.tcx.types.i32);
- assert_eq!(ret_lane_ty, fx.tcx.types.i16);
- assert_eq!(lane_count * 2, ret_lane_count);
-
- let min_i16 = fx.bcx.ins().iconst(types::I32, i32::from(i16::MIN) as u32 as i64);
- let max_i16 = fx.bcx.ins().iconst(types::I32, i32::from(i16::MAX) as u32 as i64);
- let ret_lane_layout = fx.layout_of(fx.tcx.types.i16);
-
- for idx in 0..lane_count / 2 {
- let lane = a.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, min_i16);
- let sat = fx.bcx.ins().smin(sat, max_i16);
- let res = fx.bcx.ins().ireduce(types::I16, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, idx).write_cvalue(fx, res_lane);
- }
-
- for idx in 0..lane_count / 2 {
- let lane = b.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, min_i16);
- let sat = fx.bcx.ins().smin(sat, max_i16);
- let res = fx.bcx.ins().ireduce(types::I16, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count / 2 + idx).write_cvalue(fx, res_lane);
- }
-
- for idx in 0..lane_count / 2 {
- let lane = a.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, min_i16);
- let sat = fx.bcx.ins().smin(sat, max_i16);
- let res = fx.bcx.ins().ireduce(types::I16, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count / 2 * 2 + idx).write_cvalue(fx, res_lane);
- }
-
- for idx in 0..lane_count / 2 {
- let lane = b.value_lane(fx, idx).load_scalar(fx);
- let sat = fx.bcx.ins().smax(lane, min_i16);
- let sat = fx.bcx.ins().smin(sat, max_i16);
- let res = fx.bcx.ins().ireduce(types::I16, sat);
-
- let res_lane = CValue::by_val(res, ret_lane_layout);
- ret.place_lane(fx, lane_count / 2 * 3 + idx).write_cvalue(fx, res_lane);
- }
+ pack_instruction(fx, a, b, ret, PackSize::S16, PackWidth::Avx);
}
"llvm.x86.fma.vfmaddsub.ps"
@@ -1407,3 +1233,115 @@ fn llvm_add_sub<'tcx>(
(cb_out, c)
}
+
+enum PackSize {
+ U8,
+ U16,
+ S8,
+ S16,
+}
+
+impl PackSize {
+ fn ret_clif_type(&self) -> Type {
+ match self {
+ Self::U8 | Self::S8 => types::I8,
+ Self::U16 | Self::S16 => types::I16,
+ }
+ }
+ fn src_clif_type(&self) -> Type {
+ match self {
+ Self::U8 | Self::S8 => types::I16,
+ Self::U16 | Self::S16 => types::I32,
+ }
+ }
+ fn src_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
+ match self {
+ Self::U8 | Self::S8 => tcx.types.i16,
+ Self::U16 | Self::S16 => tcx.types.i32,
+ }
+ }
+ fn ret_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
+ match self {
+ Self::U8 => tcx.types.u8,
+ Self::S8 => tcx.types.i8,
+ Self::U16 => tcx.types.u16,
+ Self::S16 => tcx.types.i16,
+ }
+ }
+ fn max(&self) -> i64 {
+ match self {
+ Self::U8 => u8::MAX as u64 as i64,
+ Self::S8 => i8::MAX as u8 as u64 as i64,
+ Self::U16 => u16::MAX as u64 as i64,
+ Self::S16 => i16::MAX as u64 as u64 as i64,
+ }
+ }
+ fn min(&self) -> i64 {
+ match self {
+ Self::U8 | Self::U16 => 0,
+ Self::S8 => i16::from(i8::MIN) as u16 as i64,
+ Self::S16 => i32::from(i16::MIN) as u32 as i64,
+ }
+ }
+}
+
+enum PackWidth {
+ Sse = 1,
+ Avx = 2,
+}
+impl PackWidth {
+ fn divisor(&self) -> u64 {
+ match self {
+ Self::Sse => 1,
+ Self::Avx => 2,
+ }
+ }
+}
+
+/// Implement an x86 pack instruction with the intrinsic `_mm{,256}pack{us,s}_epi{16,32}`.
+/// Validated for correctness against LLVM, see commit `c8f5d35508e062bd2d95e6c03429bfec831db6d3`.
+fn pack_instruction<'tcx>(
+ fx: &mut FunctionCx<'_, '_, 'tcx>,
+ a: CValue<'tcx>,
+ b: CValue<'tcx>,
+ ret: CPlace<'tcx>,
+ ret_size: PackSize,
+ width: PackWidth,
+) {
+ assert_eq!(a.layout(), b.layout());
+ let layout = a.layout();
+
+ let (src_lane_count, src_lane_ty) = layout.ty.simd_size_and_type(fx.tcx);
+ let (ret_lane_count, ret_lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
+ assert_eq!(src_lane_ty, ret_size.src_ty(fx.tcx));
+ assert_eq!(ret_lane_ty, ret_size.ret_ty(fx.tcx));
+ assert_eq!(src_lane_count * 2, ret_lane_count);
+
+ let min = fx.bcx.ins().iconst(ret_size.src_clif_type(), ret_size.min());
+ let max = fx.bcx.ins().iconst(ret_size.src_clif_type(), ret_size.max());
+ let ret_lane_layout = fx.layout_of(ret_size.ret_ty(fx.tcx));
+
+ let mut round = |source: CValue<'tcx>, source_offset: u64, dest_offset: u64| {
+ let step_amount = src_lane_count / width.divisor();
+ let dest_offset = step_amount * dest_offset;
+ for idx in 0..step_amount {
+ let lane = source.value_lane(fx, step_amount * source_offset + idx).load_scalar(fx);
+ let sat = fx.bcx.ins().smax(lane, min);
+ let sat = match ret_size {
+ PackSize::U8 | PackSize::U16 => fx.bcx.ins().umin(sat, max),
+ PackSize::S8 | PackSize::S16 => fx.bcx.ins().smin(sat, max),
+ };
+ let res = fx.bcx.ins().ireduce(ret_size.ret_clif_type(), sat);
+ let res_lane = CValue::by_val(res, ret_lane_layout);
+ ret.place_lane(fx, dest_offset + idx).write_cvalue(fx, res_lane);
+ }
+ };
+
+ round(a, 0, 0);
+ round(b, 0, 1);
+
+ if let PackWidth::Avx = width {
+ round(a, 1, 2);
+ round(b, 1, 3);
+ }
+}
diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs
index d56d17892d5b6..ebdc744bcd833 100644
--- a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs
+++ b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs
@@ -293,7 +293,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
}
ret.write_cvalue(fx, base);
- let ret_lane = ret.place_lane(fx, idx.try_into().unwrap());
+ let ret_lane = ret.place_lane(fx, idx.into());
ret_lane.write_cvalue(fx, val);
}
@@ -340,7 +340,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
);
}
- let ret_lane = v.value_lane(fx, idx.try_into().unwrap());
+ let ret_lane = v.value_lane(fx, idx.into());
ret.write_cvalue(fx, ret_lane);
}
@@ -822,7 +822,35 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
let (lane_count, lane_ty) = a.layout().ty.simd_size_and_type(fx.tcx);
let lane_layout = fx.layout_of(lane_ty);
- let m = m.load_scalar(fx);
+ let expected_int_bits = lane_count.max(8);
+ let expected_bytes = expected_int_bits / 8 + ((expected_int_bits % 8 > 0) as u64);
+
+ let m = match m.layout().ty.kind() {
+ ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => m.load_scalar(fx),
+ ty::Array(elem, len)
+ if matches!(elem.kind(), ty::Uint(ty::UintTy::U8))
+ && len.try_eval_target_usize(fx.tcx, ty::ParamEnv::reveal_all())
+ == Some(expected_bytes) =>
+ {
+ m.force_stack(fx).0.load(
+ fx,
+ Type::int(expected_int_bits as u16).unwrap(),
+ MemFlags::trusted(),
+ )
+ }
+ _ => {
+ fx.tcx.dcx().span_fatal(
+ span,
+ format!(
+ "invalid monomorphization of `simd_select_bitmask` intrinsic: \
+ cannot accept `{}` as mask, expected `u{}` or `[u8; {}]`",
+ ret.layout().ty,
+ expected_int_bits,
+ expected_bytes
+ ),
+ );
+ }
+ };
for lane in 0..lane_count {
let m_lane = fx.bcx.ins().ushr_imm(m, u64::from(lane) as i64);
diff --git a/compiler/rustc_codegen_cranelift/src/lib.rs b/compiler/rustc_codegen_cranelift/src/lib.rs
index b482f0dd2f0ab..416f87fcc87b3 100644
--- a/compiler/rustc_codegen_cranelift/src/lib.rs
+++ b/compiler/rustc_codegen_cranelift/src/lib.rs
@@ -18,7 +18,6 @@ extern crate rustc_fs_util;
extern crate rustc_hir;
extern crate rustc_incremental;
extern crate rustc_index;
-extern crate rustc_interface;
extern crate rustc_metadata;
extern crate rustc_session;
extern crate rustc_span;
@@ -42,7 +41,7 @@ use rustc_metadata::EncodedMetadata;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
use rustc_session::config::OutputFilenames;
use rustc_session::Session;
-use rustc_span::Symbol;
+use rustc_span::{sym, Symbol};
pub use crate::config::*;
use crate::prelude::*;
@@ -190,8 +189,17 @@ impl CodegenBackend for CraneliftCodegenBackend {
}
}
- fn target_features(&self, _sess: &Session, _allow_unstable: bool) -> Vec {
- vec![] // FIXME necessary for #[cfg(target_feature]
+ fn target_features(&self, sess: &Session, _allow_unstable: bool) -> Vec {
+ // FIXME return the actually used target features. this is necessary for #[cfg(target_feature)]
+ if sess.target.arch == "x86_64" && sess.target.os != "none" {
+ // x86_64 mandates SSE2 support
+ vec![Symbol::intern("fxsr"), sym::sse, Symbol::intern("sse2")]
+ } else if sess.target.arch == "aarch64" && sess.target.os != "none" {
+ // AArch64 mandates Neon support
+ vec![sym::neon]
+ } else {
+ vec![]
+ }
}
fn print_version(&self) {
@@ -305,16 +313,13 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc {
- let builder = cranelift_native::builder_with_options(true).unwrap();
- builder
- }
+ Some("native") => cranelift_native::builder_with_options(true).unwrap(),
Some(value) => {
let mut builder =
cranelift_codegen::isa::lookup(target_triple.clone()).unwrap_or_else(|err| {
sess.dcx().fatal(format!("can't compile for {}: {}", target_triple, err));
});
- if let Err(_) = builder.enable(value) {
+ if builder.enable(value).is_err() {
sess.dcx()
.fatal("the specified target cpu isn't currently supported by Cranelift.");
}
diff --git a/compiler/rustc_codegen_cranelift/src/unsize.rs b/compiler/rustc_codegen_cranelift/src/unsize.rs
index f777e11371f13..acfa461a6f30b 100644
--- a/compiler/rustc_codegen_cranelift/src/unsize.rs
+++ b/compiler/rustc_codegen_cranelift/src/unsize.rs
@@ -28,10 +28,9 @@ pub(crate) fn unsized_info<'tcx>(
.bcx
.ins()
.iconst(fx.pointer_type, len.eval_target_usize(fx.tcx, ParamEnv::reveal_all()) as i64),
- (
- &ty::Dynamic(ref data_a, _, src_dyn_kind),
- &ty::Dynamic(ref data_b, _, target_dyn_kind),
- ) if src_dyn_kind == target_dyn_kind => {
+ (&ty::Dynamic(data_a, _, src_dyn_kind), &ty::Dynamic(data_b, _, target_dyn_kind))
+ if src_dyn_kind == target_dyn_kind =>
+ {
let old_info =
old_info.expect("unsized_info: missing old info for trait upcasting coercion");
if data_a.principal_def_id() == data_b.principal_def_id() {
diff --git a/compiler/rustc_codegen_cranelift/src/vtable.rs b/compiler/rustc_codegen_cranelift/src/vtable.rs
index 41ea0b122de73..d2254d4c15e6f 100644
--- a/compiler/rustc_codegen_cranelift/src/vtable.rs
+++ b/compiler/rustc_codegen_cranelift/src/vtable.rs
@@ -95,7 +95,7 @@ pub(crate) fn get_vtable<'tcx>(
let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
let data_id =
data_id_for_alloc_id(&mut fx.constants_cx, &mut *fx.module, alloc_id, Mutability::Not);
- let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
+ let local_data_id = fx.module.declare_data_in_func(data_id, fx.bcx.func);
if fx.clif_comments.enabled() {
fx.add_comment(local_data_id, format!("vtable: {:?}", alloc_id));
}
diff --git a/compiler/rustc_codegen_gcc/example/mini_core.rs b/compiler/rustc_codegen_gcc/example/mini_core.rs
index db94bc1c86af9..230009741dc41 100644
--- a/compiler/rustc_codegen_gcc/example/mini_core.rs
+++ b/compiler/rustc_codegen_gcc/example/mini_core.rs
@@ -100,9 +100,6 @@ unsafe impl Freeze for &mut T {}
#[lang = "structural_peq"]
pub trait StructuralPartialEq {}
-#[lang = "structural_teq"]
-pub trait StructuralEq {}
-
#[lang = "not"]
pub trait Not {
type Output;
diff --git a/compiler/rustc_codegen_gcc/src/errors.rs b/compiler/rustc_codegen_gcc/src/errors.rs
index e9283b1989453..cc0fbe46dcc11 100644
--- a/compiler/rustc_codegen_gcc/src/errors.rs
+++ b/compiler/rustc_codegen_gcc/src/errors.rs
@@ -35,7 +35,7 @@ pub(crate) enum PossibleFeature<'a> {
struct ExitCode(Option);
impl IntoDiagnosticArg for ExitCode {
- fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
+ fn into_diagnostic_arg(self) -> DiagnosticArgValue {
let ExitCode(exit_code) = self;
match exit_code {
Some(t) => t.into_diagnostic_arg(),
diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs
index 03f8f43ff1643..f8f054db65ede 100644
--- a/compiler/rustc_codegen_gcc/src/lib.rs
+++ b/compiler/rustc_codegen_gcc/src/lib.rs
@@ -408,7 +408,7 @@ pub fn target_features(sess: &Session, allow_unstable: bool, target_info: &Locke
.filter(|_feature| {
target_info.cpu_supports(_feature)
/*
- adx, aes, avx, avx2, avx512bf16, avx512bitalg, avx512bw, avx512cd, avx512dq, avx512er, avx512f, avx512ifma,
+ adx, aes, avx, avx2, avx512bf16, avx512bitalg, avx512bw, avx512cd, avx512dq, avx512er, avx512f, avx512fp16, avx512ifma,
avx512pf, avx512vbmi, avx512vbmi2, avx512vl, avx512vnni, avx512vp2intersect, avx512vpopcntdq,
bmi1, bmi2, cmpxchg16b, ermsb, f16c, fma, fxsr, gfni, lzcnt, movbe, pclmulqdq, popcnt, rdrand, rdseed, rtm,
sha, sse, sse2, sse3, sse4.1, sse4.2, sse4a, ssse3, tbm, vaes, vpclmulqdq, xsave, xsavec, xsaveopt, xsaves
diff --git a/compiler/rustc_codegen_gcc/tests/run/static.rs b/compiler/rustc_codegen_gcc/tests/run/static.rs
index 0b933754c2937..e7c46ae3fcc81 100644
--- a/compiler/rustc_codegen_gcc/tests/run/static.rs
+++ b/compiler/rustc_codegen_gcc/tests/run/static.rs
@@ -61,9 +61,6 @@ mod libc {
#[lang = "structural_peq"]
pub trait StructuralPartialEq {}
-#[lang = "structural_teq"]
-pub trait StructuralEq {}
-
#[lang = "drop_in_place"]
#[allow(unconditional_recursion)]
pub unsafe fn drop_in_place(to_drop: *mut T) {
diff --git a/compiler/rustc_codegen_llvm/messages.ftl b/compiler/rustc_codegen_llvm/messages.ftl
index 7a86ddc7556a0..d5bc04f594da1 100644
--- a/compiler/rustc_codegen_llvm/messages.ftl
+++ b/compiler/rustc_codegen_llvm/messages.ftl
@@ -39,6 +39,9 @@ codegen_llvm_lto_dylib = lto cannot be used for `dylib` crate type without `-Zdy
codegen_llvm_lto_proc_macro = lto cannot be used for `proc-macro` crate type without `-Zdylib-lto`
+codegen_llvm_mismatch_data_layout =
+ data-layout for target `{$rustc_target}`, `{$rustc_layout}`, differs from LLVM target's `{$llvm_target}` default layout, `{$llvm_layout}`
+
codegen_llvm_missing_features =
add the missing features in a `target_feature` attribute
diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs
index 0718bebb31bf8..b5b4f894e4d82 100644
--- a/compiler/rustc_codegen_llvm/src/abi.rs
+++ b/compiler/rustc_codegen_llvm/src/abi.rs
@@ -590,7 +590,6 @@ impl From for llvm::CallConv {
Conv::Cold => llvm::ColdCallConv,
Conv::PreserveMost => llvm::PreserveMost,
Conv::PreserveAll => llvm::PreserveAll,
- Conv::AmdGpuKernel => llvm::AmdGpuKernel,
Conv::AvrInterrupt => llvm::AvrInterrupt,
Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
Conv::ArmAapcs => llvm::ArmAapcsCallConv,
diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs
index 5ef05dfbe4c10..7dfcf1ab50e41 100644
--- a/compiler/rustc_codegen_llvm/src/context.rs
+++ b/compiler/rustc_codegen_llvm/src/context.rs
@@ -34,6 +34,7 @@ use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel};
use smallvec::SmallVec;
use libc::c_uint;
+use std::borrow::Borrow;
use std::cell::{Cell, RefCell};
use std::ffi::CStr;
use std::str;
@@ -155,8 +156,7 @@ pub unsafe fn create_module<'ll>(
}
// Ensure the data-layout values hardcoded remain the defaults.
- if sess.target.is_builtin {
- // tm is disposed by its drop impl
+ {
let tm = crate::back::write::create_informational_target_machine(tcx.sess);
llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, &tm);
@@ -164,33 +164,13 @@ pub unsafe fn create_module<'ll>(
let llvm_data_layout = str::from_utf8(CStr::from_ptr(llvm_data_layout).to_bytes())
.expect("got a non-UTF8 data-layout from LLVM");
- // Unfortunately LLVM target specs change over time, and right now we
- // don't have proper support to work with any more than one
- // `data_layout` than the one that is in the rust-lang/rust repo. If
- // this compiler is configured against a custom LLVM, we may have a
- // differing data layout, even though we should update our own to use
- // that one.
- //
- // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
- // disable this check entirely as we may be configured with something
- // that has a different target layout.
- //
- // Unsure if this will actually cause breakage when rustc is configured
- // as such.
- //
- // FIXME(#34960)
- let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
- let custom_llvm_used = !cfg_llvm_root.trim().is_empty();
-
- if !custom_llvm_used && target_data_layout != llvm_data_layout {
- bug!(
- "data-layout for target `{rustc_target}`, `{rustc_layout}`, \
- differs from LLVM target's `{llvm_target}` default layout, `{llvm_layout}`",
- rustc_target = sess.opts.target_triple,
- rustc_layout = target_data_layout,
- llvm_target = sess.target.llvm_target,
- llvm_layout = llvm_data_layout
- );
+ if target_data_layout != llvm_data_layout {
+ tcx.dcx().emit_err(crate::errors::MismatchedDataLayout {
+ rustc_target: sess.opts.target_triple.to_string().as_str(),
+ rustc_layout: target_data_layout.as_str(),
+ llvm_target: sess.target.llvm_target.borrow(),
+ llvm_layout: llvm_data_layout,
+ });
}
}
@@ -929,6 +909,7 @@ impl<'ll> CodegenCx<'ll, '_> {
ifn!("llvm.is.constant.isize", fn(t_isize) -> i1);
ifn!("llvm.is.constant.f32", fn(t_f32) -> i1);
ifn!("llvm.is.constant.f64", fn(t_f64) -> i1);
+ ifn!("llvm.is.constant.ptr", fn(ptr) -> i1);
ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
ifn!("llvm.eh.typeid.for", fn(ptr) -> t_i32);
diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs
index 6116a6fd222b3..b1ceb1d4dd56d 100644
--- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs
+++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs
@@ -403,6 +403,7 @@ fn codegenned_and_inlined_items(tcx: TyCtxt<'_>) -> DefIdSet {
let mut result = items.clone();
for cgu in cgus {
+ #[allow(rustc::potential_query_instability)]
for item in cgu.items().keys() {
if let mir::mono::MonoItem::Fn(ref instance) = item {
let did = instance.def_id();
diff --git a/compiler/rustc_codegen_llvm/src/errors.rs b/compiler/rustc_codegen_llvm/src/errors.rs
index 697ce6022984b..e839d278bea7c 100644
--- a/compiler/rustc_codegen_llvm/src/errors.rs
+++ b/compiler/rustc_codegen_llvm/src/errors.rs
@@ -102,7 +102,7 @@ pub(crate) struct ParseTargetMachineConfig<'a>(pub LlvmError<'a>);
impl IntoDiagnostic<'_, G> for ParseTargetMachineConfig<'_> {
fn into_diagnostic(self, dcx: &'_ DiagCtxt, level: Level) -> DiagnosticBuilder<'_, G> {
let diag: DiagnosticBuilder<'_, G> = self.0.into_diagnostic(dcx, level);
- let (message, _) = diag.messages().first().expect("`LlvmError` with no message");
+ let (message, _) = diag.messages.first().expect("`LlvmError` with no message");
let message = dcx.eagerly_translate_to_string(message.clone(), diag.args());
DiagnosticBuilder::new(dcx, level, fluent::codegen_llvm_parse_target_machine_config)
@@ -244,3 +244,12 @@ pub(crate) struct CopyBitcode {
pub struct UnknownCompression {
pub algorithm: &'static str,
}
+
+#[derive(Diagnostic)]
+#[diag(codegen_llvm_mismatch_data_layout)]
+pub struct MismatchedDataLayout<'a> {
+ pub rustc_target: &'a str,
+ pub rustc_layout: &'a str,
+ pub llvm_target: &'a str,
+ pub llvm_layout: &'a str,
+}
diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs
index f1a6f7bd8e690..e3e48ecb3aa5f 100644
--- a/compiler/rustc_codegen_llvm/src/intrinsic.rs
+++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs
@@ -119,10 +119,18 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
sym::likely => {
self.call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(true)])
}
- sym::is_val_statically_known => self.call_intrinsic(
- &format!("llvm.is.constant.{:?}", args[0].layout.immediate_llvm_type(self.cx)),
- &[args[0].immediate()],
- ),
+ sym::is_val_statically_known => {
+ let intrinsic_type = args[0].layout.immediate_llvm_type(self.cx);
+ match self.type_kind(intrinsic_type) {
+ TypeKind::Pointer | TypeKind::Integer | TypeKind::Float | TypeKind::Double => {
+ self.call_intrinsic(
+ &format!("llvm.is.constant.{:?}", intrinsic_type),
+ &[args[0].immediate()],
+ )
+ }
+ _ => self.const_bool(false),
+ }
+ }
sym::unlikely => self
.call_intrinsic("llvm.expect.i1", &[args[0].immediate(), self.const_bool(false)]),
kw::Try => {
@@ -1977,10 +1985,9 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
match in_elem.kind() {
ty::RawPtr(p) => {
- let (metadata, check_sized) = p.ty.ptr_metadata_ty(bx.tcx, |ty| {
+ let metadata = p.ty.ptr_metadata_ty(bx.tcx, |ty| {
bx.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), ty)
});
- assert!(!check_sized); // we are in codegen, so we shouldn't see these types
require!(
metadata.is_unit(),
InvalidMonomorphization::CastFatPointer { span, name, ty: in_elem }
@@ -1992,10 +1999,9 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
}
match out_elem.kind() {
ty::RawPtr(p) => {
- let (metadata, check_sized) = p.ty.ptr_metadata_ty(bx.tcx, |ty| {
+ let metadata = p.ty.ptr_metadata_ty(bx.tcx, |ty| {
bx.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), ty)
});
- assert!(!check_sized); // we are in codegen, so we shouldn't see these types
require!(
metadata.is_unit(),
InvalidMonomorphization::CastFatPointer { span, name, ty: out_elem }
diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs
index a81056ed3ad62..f4f29078190a1 100644
--- a/compiler/rustc_codegen_llvm/src/lib.rs
+++ b/compiler/rustc_codegen_llvm/src/lib.rs
@@ -14,9 +14,7 @@
#![feature(iter_intersperse)]
#![feature(let_chains)]
#![feature(min_specialization)]
-#![feature(never_type)]
#![feature(impl_trait_in_assoc_type)]
-#![recursion_limit = "256"]
#![deny(rustc::untranslatable_diagnostic)]
#![deny(rustc::diagnostic_outside_of_impl)]
diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
index ee73c6b4756f0..4ad44a42738b3 100644
--- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
+++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
@@ -106,7 +106,6 @@ pub enum CallConv {
X86_Intr = 83,
AvrNonBlockingInterrupt = 84,
AvrInterrupt = 85,
- AmdGpuKernel = 91,
}
/// LLVMRustLinkage
diff --git a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs
index a1daadce958eb..3e5a43c6e73a6 100644
--- a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs
+++ b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs
@@ -206,7 +206,7 @@ impl fmt::Display for CguReuse {
}
impl IntoDiagnosticArg for CguReuse {
- fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
+ fn into_diagnostic_arg(self) -> DiagnosticArgValue {
DiagnosticArgValue::Str(Cow::Owned(self.to_string()))
}
}
@@ -267,6 +267,7 @@ impl CguReuseTracker {
fn check_expected_reuse(&self, sess: &Session) {
if let Some(ref data) = self.data {
+ #[allow(rustc::potential_query_instability)]
let mut keys = data.expected_reuse.keys().collect::>();
keys.sort_unstable();
for cgu_name in keys {
diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs
index 959653c932653..b29f71bfb9553 100644
--- a/compiler/rustc_codegen_ssa/src/back/link.rs
+++ b/compiler/rustc_codegen_ssa/src/back/link.rs
@@ -52,6 +52,15 @@ use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Output, Stdio};
use std::{env, fmt, fs, io, mem, str};
+#[derive(Default)]
+pub struct SearchPaths(OnceCell>);
+
+impl SearchPaths {
+ pub(super) fn get(&self, sess: &Session) -> &[PathBuf] {
+ self.0.get_or_init(|| archive_search_paths(sess))
+ }
+}
+
pub fn ensure_removed(dcx: &DiagCtxt, path: &Path) {
if let Err(e) = fs::remove_file(path) {
if e.kind() != io::ErrorKind::NotFound {
@@ -673,6 +682,7 @@ fn link_dwarf_object<'a>(
}
// Input rlibs contain .o/.dwo files from dependencies.
+ #[allow(rustc::potential_query_instability)]
let input_rlibs = cg_results
.crate_info
.used_crate_source
@@ -1265,7 +1275,7 @@ fn link_sanitizer_runtime(
let path = find_sanitizer_runtime(sess, &filename);
let rpath = path.to_str().expect("non-utf8 component in path");
linker.args(&["-Wl,-rpath", "-Xlinker", rpath]);
- linker.link_dylib(&filename, false, true);
+ linker.link_dylib_by_name(&filename, false, true);
} else if sess.target.is_like_msvc && flavor == LinkerFlavor::Msvc(Lld::No) && name == "asan" {
// MSVC provides the `/INFERASANLIBS` argument to automatically find the
// compatible ASAN library.
@@ -1273,7 +1283,7 @@ fn link_sanitizer_runtime(
} else {
let filename = format!("librustc{channel}_rt.{name}.a");
let path = find_sanitizer_runtime(sess, &filename).join(&filename);
- linker.link_whole_rlib(&path);
+ linker.link_staticlib_by_path(&path, true);
}
}
@@ -2445,7 +2455,7 @@ fn add_native_libs_from_crate(
archive_builder_builder: &dyn ArchiveBuilderBuilder,
codegen_results: &CodegenResults,
tmpdir: &Path,
- search_paths: &OnceCell>,
+ search_paths: &SearchPaths,
bundled_libs: &FxHashSet,
cnum: CrateNum,
link_static: bool,
@@ -2505,28 +2515,16 @@ fn add_native_libs_from_crate(
if let Some(filename) = lib.filename {
// If rlib contains native libs as archives, they are unpacked to tmpdir.
let path = tmpdir.join(filename.as_str());
- if whole_archive {
- cmd.link_whole_rlib(&path);
- } else {
- cmd.link_rlib(&path);
- }
+ cmd.link_staticlib_by_path(&path, whole_archive);
}
} else {
- if whole_archive {
- cmd.link_whole_staticlib(
- name,
- verbatim,
- search_paths.get_or_init(|| archive_search_paths(sess)),
- );
- } else {
- cmd.link_staticlib(name, verbatim)
- }
+ cmd.link_staticlib_by_name(name, verbatim, whole_archive, search_paths);
}
}
}
NativeLibKind::Dylib { as_needed } => {
if link_dynamic {
- cmd.link_dylib(name, verbatim, as_needed.unwrap_or(true))
+ cmd.link_dylib_by_name(name, verbatim, as_needed.unwrap_or(true))
}
}
NativeLibKind::Unspecified => {
@@ -2534,17 +2532,17 @@ fn add_native_libs_from_crate(
// link kind is unspecified.
if !link_output_kind.can_link_dylib() && !sess.target.crt_static_allows_dylibs {
if link_static {
- cmd.link_staticlib(name, verbatim)
+ cmd.link_staticlib_by_name(name, verbatim, false, search_paths);
}
} else {
if link_dynamic {
- cmd.link_dylib(name, verbatim, true);
+ cmd.link_dylib_by_name(name, verbatim, true);
}
}
}
NativeLibKind::Framework { as_needed } => {
if link_dynamic {
- cmd.link_framework(name, as_needed.unwrap_or(true))
+ cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))
}
}
NativeLibKind::RawDylib => {
@@ -2581,7 +2579,7 @@ fn add_local_native_libraries(
}
}
- let search_paths = OnceCell::new();
+ let search_paths = SearchPaths::default();
// All static and dynamic native library dependencies are linked to the local crate.
let link_static = true;
let link_dynamic = true;
@@ -2623,7 +2621,7 @@ fn add_upstream_rust_crates<'a>(
.find(|(ty, _)| *ty == crate_type)
.expect("failed to find crate type in dependency format list");
- let search_paths = OnceCell::new();
+ let search_paths = SearchPaths::default();
for &cnum in &codegen_results.crate_info.used_crates {
// We may not pass all crates through to the linker. Some crates may appear statically in
// an existing dylib, meaning we'll pick up all the symbols from the dylib.
@@ -2698,7 +2696,7 @@ fn add_upstream_native_libraries(
tmpdir: &Path,
link_output_kind: LinkOutputKind,
) {
- let search_path = OnceCell::new();
+ let search_paths = SearchPaths::default();
for &cnum in &codegen_results.crate_info.used_crates {
// Static libraries are not linked here, they are linked in `add_upstream_rust_crates`.
// FIXME: Merge this function to `add_upstream_rust_crates` so that all native libraries
@@ -2720,7 +2718,7 @@ fn add_upstream_native_libraries(
archive_builder_builder,
codegen_results,
tmpdir,
- &search_path,
+ &search_paths,
&Default::default(),
cnum,
link_static,
@@ -2791,7 +2789,7 @@ fn add_static_crate<'a>(
} else {
fix_windows_verbatim_for_gcc(path)
};
- cmd.link_rlib(&rlib_path);
+ cmd.link_staticlib_by_path(&rlib_path, false);
};
if !are_upstream_rust_objects_already_included(sess)
@@ -2859,13 +2857,24 @@ fn add_dynamic_crate(cmd: &mut dyn Linker, sess: &Session, cratepath: &Path) {
// Just need to tell the linker about where the library lives and
// what its name is
let parent = cratepath.parent();
+ // When producing a dll, the MSVC linker may not actually emit a
+ // `foo.lib` file if the dll doesn't actually export any symbols, so we
+ // check to see if the file is there and just omit linking to it if it's
+ // not present.
+ if sess.target.is_like_msvc && !cratepath.with_extension("dll.lib").exists() {
+ return;
+ }
if let Some(dir) = parent {
cmd.include_path(&rehome_sysroot_lib_dir(sess, dir));
}
- let stem = cratepath.file_stem().unwrap().to_str().unwrap();
+ // "/name.dll -> name.dll" on windows-msvc
+ // "/name.dll -> name" on windows-gnu
+ // "/libname. -> name" elsewhere
+ let stem = if sess.target.is_like_msvc { cratepath.file_name() } else { cratepath.file_stem() };
+ let stem = stem.unwrap().to_str().unwrap();
// Convert library file-stem into a cc -l argument.
let prefix = if stem.starts_with("lib") && !sess.target.is_like_windows { 3 } else { 0 };
- cmd.link_rust_dylib(&stem[prefix..], parent.unwrap_or_else(|| Path::new("")));
+ cmd.link_dylib_by_name(&stem[prefix..], false, true);
}
fn relevant_lib(sess: &Session, lib: &NativeLib) -> bool {
diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs
index 90f5027c26494..9f06f398288f2 100644
--- a/compiler/rustc_codegen_ssa/src/back/linker.rs
+++ b/compiler/rustc_codegen_ssa/src/back/linker.rs
@@ -1,5 +1,6 @@
use super::command::Command;
use super::symbol_export;
+use crate::back::link::SearchPaths;
use crate::errors;
use rustc_span::symbol::sym;
@@ -166,13 +167,18 @@ pub fn get_linker<'a>(
pub trait Linker {
fn cmd(&mut self) -> &mut Command;
fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path);
- fn link_dylib(&mut self, lib: &str, verbatim: bool, as_needed: bool);
- fn link_rust_dylib(&mut self, lib: &str, path: &Path);
- fn link_framework(&mut self, framework: &str, as_needed: bool);
- fn link_staticlib(&mut self, lib: &str, verbatim: bool);
- fn link_rlib(&mut self, lib: &Path);
- fn link_whole_rlib(&mut self, lib: &Path);
- fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, search_path: &[PathBuf]);
+ fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, as_needed: bool);
+ fn link_framework_by_name(&mut self, _name: &str, _verbatim: bool, _as_needed: bool) {
+ bug!("framework linked with unsupported linker")
+ }
+ fn link_staticlib_by_name(
+ &mut self,
+ name: &str,
+ verbatim: bool,
+ whole_archive: bool,
+ search_paths: &SearchPaths,
+ );
+ fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool);
fn include_path(&mut self, path: &Path);
fn framework_path(&mut self, path: &Path);
fn output_filename(&mut self, path: &Path);
@@ -432,8 +438,8 @@ impl<'a> Linker for GccLinker<'a> {
}
}
- fn link_dylib(&mut self, lib: &str, verbatim: bool, as_needed: bool) {
- if self.sess.target.os == "illumos" && lib == "c" {
+ fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, as_needed: bool) {
+ if self.sess.target.os == "illumos" && name == "c" {
// libc will be added via late_link_args on illumos so that it will
// appear last in the library search order.
// FIXME: This should be replaced by a more complete and generic
@@ -454,7 +460,7 @@ impl<'a> Linker for GccLinker<'a> {
}
}
self.hint_dynamic();
- self.cmd.arg(format!("-l{}{lib}", if verbatim && self.is_gnu { ":" } else { "" },));
+ self.cmd.arg(format!("-l{}{name}", if verbatim && self.is_gnu { ":" } else { "" },));
if !as_needed {
if self.sess.target.is_like_osx {
// See above FIXME comment
@@ -463,14 +469,56 @@ impl<'a> Linker for GccLinker<'a> {
}
}
}
- fn link_staticlib(&mut self, lib: &str, verbatim: bool) {
+
+ fn link_framework_by_name(&mut self, name: &str, _verbatim: bool, as_needed: bool) {
+ self.hint_dynamic();
+ if !as_needed {
+ // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
+ // flag but we have no way to detect that here.
+ // self.cmd.arg("-needed_framework").arg(name);
+ self.sess.dcx().emit_warn(errors::Ld64UnimplementedModifier);
+ }
+ self.cmd.arg("-framework").arg(name);
+ }
+
+ fn link_staticlib_by_name(
+ &mut self,
+ name: &str,
+ verbatim: bool,
+ whole_archive: bool,
+ search_paths: &SearchPaths,
+ ) {
self.hint_static();
- self.cmd.arg(format!("-l{}{lib}", if verbatim && self.is_gnu { ":" } else { "" },));
+ let colon = if verbatim && self.is_gnu { ":" } else { "" };
+ if !whole_archive {
+ self.cmd.arg(format!("-l{colon}{name}"));
+ } else if self.sess.target.is_like_osx {
+ // -force_load is the macOS equivalent of --whole-archive, but it
+ // involves passing the full path to the library to link.
+ self.linker_arg("-force_load");
+ let search_paths = search_paths.get(self.sess);
+ self.linker_arg(find_native_static_library(name, verbatim, search_paths, self.sess));
+ } else {
+ self.linker_arg("--whole-archive");
+ self.cmd.arg(format!("-l{colon}{name}"));
+ self.linker_arg("--no-whole-archive");
+ }
}
- fn link_rlib(&mut self, lib: &Path) {
+
+ fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
self.hint_static();
- self.cmd.arg(lib);
+ if !whole_archive {
+ self.cmd.arg(path);
+ } else if self.sess.target.is_like_osx {
+ self.linker_arg("-force_load");
+ self.linker_arg(path);
+ } else {
+ self.linker_arg("--whole-archive");
+ self.linker_arg(path);
+ self.linker_arg("--no-whole-archive");
+ }
}
+
fn include_path(&mut self, path: &Path) {
self.cmd.arg("-L").arg(path);
}
@@ -493,55 +541,6 @@ impl<'a> Linker for GccLinker<'a> {
self.linker_args(&["-z", "norelro"]);
}
- fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
- self.hint_dynamic();
- self.cmd.arg(format!("-l{lib}"));
- }
-
- fn link_framework(&mut self, framework: &str, as_needed: bool) {
- self.hint_dynamic();
- if !as_needed {
- // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
- // flag but we have no way to detect that here.
- // self.cmd.arg("-needed_framework").arg(framework);
- self.sess.dcx().emit_warn(errors::Ld64UnimplementedModifier);
- }
- self.cmd.arg("-framework").arg(framework);
- }
-
- // Here we explicitly ask that the entire archive is included into the
- // result artifact. For more details see #15460, but the gist is that
- // the linker will strip away any unused objects in the archive if we
- // don't otherwise explicitly reference them. This can occur for
- // libraries which are just providing bindings, libraries with generic
- // functions, etc.
- fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, search_path: &[PathBuf]) {
- self.hint_static();
- let target = &self.sess.target;
- if !target.is_like_osx {
- self.linker_arg("--whole-archive");
- self.cmd.arg(format!("-l{}{lib}", if verbatim && self.is_gnu { ":" } else { "" },));
- self.linker_arg("--no-whole-archive");
- } else {
- // -force_load is the macOS equivalent of --whole-archive, but it
- // involves passing the full path to the library to link.
- self.linker_arg("-force_load");
- let lib = find_native_static_library(lib, verbatim, search_path, self.sess);
- self.linker_arg(&lib);
- }
- }
-
- fn link_whole_rlib(&mut self, lib: &Path) {
- self.hint_static();
- if self.sess.target.is_like_osx {
- self.linker_arg("-force_load");
- self.linker_arg(&lib);
- } else {
- self.linker_args(&[OsString::from("--whole-archive"), lib.into()]);
- self.linker_arg("--no-whole-archive");
- }
- }
-
fn gc_sections(&mut self, keep_metadata: bool) {
// The dead_strip option to the linker specifies that functions and data
// unreachable by the entry point will be removed. This is quite useful
@@ -821,9 +820,32 @@ impl<'a> Linker for MsvcLinker<'a> {
}
}
- fn link_rlib(&mut self, lib: &Path) {
- self.cmd.arg(lib);
+ fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, _as_needed: bool) {
+ self.cmd.arg(format!("{}{}", name, if verbatim { "" } else { ".lib" }));
+ }
+
+ fn link_staticlib_by_name(
+ &mut self,
+ name: &str,
+ verbatim: bool,
+ whole_archive: bool,
+ _search_paths: &SearchPaths,
+ ) {
+ let prefix = if whole_archive { "/WHOLEARCHIVE:" } else { "" };
+ let suffix = if verbatim { "" } else { ".lib" };
+ self.cmd.arg(format!("{prefix}{name}{suffix}"));
+ }
+
+ fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
+ if !whole_archive {
+ self.cmd.arg(path);
+ } else {
+ let mut arg = OsString::from("/WHOLEARCHIVE:");
+ arg.push(path);
+ self.cmd.arg(arg);
+ }
}
+
fn add_object(&mut self, path: &Path) {
self.cmd.arg(path);
}
@@ -845,25 +867,6 @@ impl<'a> Linker for MsvcLinker<'a> {
self.cmd.arg("/OPT:NOREF,NOICF");
}
- fn link_dylib(&mut self, lib: &str, verbatim: bool, _as_needed: bool) {
- self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
- }
-
- fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
- // When producing a dll, the MSVC linker may not actually emit a
- // `foo.lib` file if the dll doesn't actually export any symbols, so we
- // check to see if the file is there and just omit linking to it if it's
- // not present.
- let name = format!("{lib}.dll.lib");
- if path.join(&name).exists() {
- self.cmd.arg(name);
- }
- }
-
- fn link_staticlib(&mut self, lib: &str, verbatim: bool) {
- self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
- }
-
fn full_relro(&mut self) {
// noop
}
@@ -899,18 +902,7 @@ impl<'a> Linker for MsvcLinker<'a> {
fn framework_path(&mut self, _path: &Path) {
bug!("frameworks are not supported on windows")
}
- fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
- bug!("frameworks are not supported on windows")
- }
- fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, _search_path: &[PathBuf]) {
- self.cmd.arg(format!("/WHOLEARCHIVE:{}{}", lib, if verbatim { "" } else { ".lib" }));
- }
- fn link_whole_rlib(&mut self, path: &Path) {
- let mut arg = OsString::from("/WHOLEARCHIVE:");
- arg.push(path);
- self.cmd.arg(arg);
- }
fn optimize(&mut self) {
// Needs more investigation of `/OPT` arguments
}
@@ -1057,43 +1049,35 @@ impl<'a> Linker for EmLinker<'a> {
fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
- fn include_path(&mut self, path: &Path) {
- self.cmd.arg("-L").arg(path);
- }
-
- fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
- self.cmd.arg("-l").arg(lib);
+ fn link_dylib_by_name(&mut self, name: &str, _verbatim: bool, _as_needed: bool) {
+ // Emscripten always links statically
+ self.cmd.arg("-l").arg(name);
}
- fn output_filename(&mut self, path: &Path) {
- self.cmd.arg("-o").arg(path);
+ fn link_staticlib_by_name(
+ &mut self,
+ name: &str,
+ _verbatim: bool,
+ _whole_archive: bool,
+ _search_paths: &SearchPaths,
+ ) {
+ self.cmd.arg("-l").arg(name);
}
- fn add_object(&mut self, path: &Path) {
+ fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
self.cmd.arg(path);
}
- fn link_dylib(&mut self, lib: &str, verbatim: bool, _as_needed: bool) {
- // Emscripten always links statically
- self.link_staticlib(lib, verbatim);
- }
-
- fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, _search_path: &[PathBuf]) {
- // not supported?
- self.link_staticlib(lib, verbatim);
- }
-
- fn link_whole_rlib(&mut self, lib: &Path) {
- // not supported?
- self.link_rlib(lib);
+ fn include_path(&mut self, path: &Path) {
+ self.cmd.arg("-L").arg(path);
}
- fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
- self.link_dylib(lib, false, true);
+ fn output_filename(&mut self, path: &Path) {
+ self.cmd.arg("-o").arg(path);
}
- fn link_rlib(&mut self, lib: &Path) {
- self.add_object(lib);
+ fn add_object(&mut self, path: &Path) {
+ self.cmd.arg(path);
}
fn full_relro(&mut self) {
@@ -1112,10 +1096,6 @@ impl<'a> Linker for EmLinker<'a> {
bug!("frameworks are not supported on Emscripten")
}
- fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
- bug!("frameworks are not supported on Emscripten")
- }
-
fn gc_sections(&mut self, _keep_metadata: bool) {
// noop
}
@@ -1249,16 +1229,30 @@ impl<'a> Linker for WasmLd<'a> {
}
}
- fn link_dylib(&mut self, lib: &str, _verbatim: bool, _as_needed: bool) {
- self.cmd.arg("-l").arg(lib);
+ fn link_dylib_by_name(&mut self, name: &str, _verbatim: bool, _as_needed: bool) {
+ self.cmd.arg("-l").arg(name);
}
- fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
- self.cmd.arg("-l").arg(lib);
+ fn link_staticlib_by_name(
+ &mut self,
+ name: &str,
+ _verbatim: bool,
+ whole_archive: bool,
+ _search_paths: &SearchPaths,
+ ) {
+ if !whole_archive {
+ self.cmd.arg("-l").arg(name);
+ } else {
+ self.cmd.arg("--whole-archive").arg("-l").arg(name).arg("--no-whole-archive");
+ }
}
- fn link_rlib(&mut self, lib: &Path) {
- self.cmd.arg(lib);
+ fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
+ if !whole_archive {
+ self.cmd.arg(path);
+ } else {
+ self.cmd.arg("--whole-archive").arg(path).arg("--no-whole-archive");
+ }
}
fn include_path(&mut self, path: &Path) {
@@ -1283,22 +1277,6 @@ impl<'a> Linker for WasmLd<'a> {
fn no_relro(&mut self) {}
- fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
- self.cmd.arg("-l").arg(lib);
- }
-
- fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
- panic!("frameworks not supported")
- }
-
- fn link_whole_staticlib(&mut self, lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
- self.cmd.arg("--whole-archive").arg("-l").arg(lib).arg("--no-whole-archive");
- }
-
- fn link_whole_rlib(&mut self, lib: &Path) {
- self.cmd.arg("--whole-archive").arg(lib).arg("--no-whole-archive");
- }
-
fn gc_sections(&mut self, _keep_metadata: bool) {
self.cmd.arg("--gc-sections");
}
@@ -1398,17 +1376,40 @@ pub struct L4Bender<'a> {
}
impl<'a> Linker for L4Bender<'a> {
- fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
+ fn cmd(&mut self) -> &mut Command {
+ &mut self.cmd
+ }
+
+ fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
+
+ fn link_dylib_by_name(&mut self, _name: &str, _verbatim: bool, _as_needed: bool) {
bug!("dylibs are not supported on L4Re");
}
- fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
+
+ fn link_staticlib_by_name(
+ &mut self,
+ name: &str,
+ _verbatim: bool,
+ whole_archive: bool,
+ _search_paths: &SearchPaths,
+ ) {
self.hint_static();
- self.cmd.arg(format!("-PC{lib}"));
+ if !whole_archive {
+ self.cmd.arg(format!("-PC{name}"));
+ } else {
+ self.cmd.arg("--whole-archive").arg(format!("-l{name}")).arg("--no-whole-archive");
+ }
}
- fn link_rlib(&mut self, lib: &Path) {
+
+ fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
self.hint_static();
- self.cmd.arg(lib);
+ if !whole_archive {
+ self.cmd.arg(path);
+ } else {
+ self.cmd.arg("--whole-archive").arg(path).arg("--no-whole-archive");
+ }
}
+
fn include_path(&mut self, path: &Path) {
self.cmd.arg("-L").arg(path);
}
@@ -1436,31 +1437,6 @@ impl<'a> Linker for L4Bender<'a> {
self.cmd.arg("-z").arg("norelro");
}
- fn cmd(&mut self) -> &mut Command {
- &mut self.cmd
- }
-
- fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
-
- fn link_rust_dylib(&mut self, _: &str, _: &Path) {
- panic!("Rust dylibs not supported");
- }
-
- fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
- bug!("frameworks not supported on L4Re");
- }
-
- fn link_whole_staticlib(&mut self, lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
- self.hint_static();
- self.cmd.arg("--whole-archive").arg(format!("-l{lib}"));
- self.cmd.arg("--no-whole-archive");
- }
-
- fn link_whole_rlib(&mut self, lib: &Path) {
- self.hint_static();
- self.cmd.arg("--whole-archive").arg(lib).arg("--no-whole-archive");
- }
-
fn gc_sections(&mut self, keep_metadata: bool) {
if !keep_metadata {
self.cmd.arg("--gc-sections");
@@ -1571,19 +1547,56 @@ impl<'a> AixLinker<'a> {
}
impl<'a> Linker for AixLinker<'a> {
- fn link_dylib(&mut self, lib: &str, _verbatim: bool, _as_needed: bool) {
+ fn cmd(&mut self) -> &mut Command {
+ &mut self.cmd
+ }
+
+ fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
+ match output_kind {
+ LinkOutputKind::DynamicDylib => {
+ self.hint_dynamic();
+ self.build_dylib(out_filename);
+ }
+ LinkOutputKind::StaticDylib => {
+ self.hint_static();
+ self.build_dylib(out_filename);
+ }
+ _ => {}
+ }
+ }
+
+ fn link_dylib_by_name(&mut self, name: &str, _verbatim: bool, _as_needed: bool) {
self.hint_dynamic();
- self.cmd.arg(format!("-l{lib}"));
+ self.cmd.arg(format!("-l{name}"));
}
- fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
+ fn link_staticlib_by_name(
+ &mut self,
+ name: &str,
+ verbatim: bool,
+ whole_archive: bool,
+ search_paths: &SearchPaths,
+ ) {
self.hint_static();
- self.cmd.arg(format!("-l{lib}"));
+ if !whole_archive {
+ self.cmd.arg(format!("-l{name}"));
+ } else {
+ let mut arg = OsString::from("-bkeepfile:");
+ let search_path = search_paths.get(self.sess);
+ arg.push(find_native_static_library(name, verbatim, search_path, self.sess));
+ self.cmd.arg(arg);
+ }
}
- fn link_rlib(&mut self, lib: &Path) {
+ fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
self.hint_static();
- self.cmd.arg(lib);
+ if !whole_archive {
+ self.cmd.arg(path);
+ } else {
+ let mut arg = OsString::from("-bkeepfile:");
+ arg.push(path);
+ self.cmd.arg(arg);
+ }
}
fn include_path(&mut self, path: &Path) {
@@ -1608,44 +1621,6 @@ impl<'a> Linker for AixLinker<'a> {
fn no_relro(&mut self) {}
- fn cmd(&mut self) -> &mut Command {
- &mut self.cmd
- }
-
- fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
- match output_kind {
- LinkOutputKind::DynamicDylib => {
- self.hint_dynamic();
- self.build_dylib(out_filename);
- }
- LinkOutputKind::StaticDylib => {
- self.hint_static();
- self.build_dylib(out_filename);
- }
- _ => {}
- }
- }
-
- fn link_rust_dylib(&mut self, lib: &str, _: &Path) {
- self.hint_dynamic();
- self.cmd.arg(format!("-l{lib}"));
- }
-
- fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
- bug!("frameworks not supported on AIX");
- }
-
- fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, search_path: &[PathBuf]) {
- self.hint_static();
- let lib = find_native_static_library(lib, verbatim, search_path, self.sess);
- self.cmd.arg(format!("-bkeepfile:{}", lib.to_str().unwrap()));
- }
-
- fn link_whole_rlib(&mut self, lib: &Path) {
- self.hint_static();
- self.cmd.arg(format!("-bkeepfile:{}", lib.to_str().unwrap()));
- }
-
fn gc_sections(&mut self, _keep_metadata: bool) {
self.cmd.arg("-bgc");
}
@@ -1810,11 +1785,21 @@ impl<'a> Linker for PtxLinker<'a> {
fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
- fn link_rlib(&mut self, path: &Path) {
- self.cmd.arg("--rlib").arg(path);
+ fn link_dylib_by_name(&mut self, _name: &str, _verbatim: bool, _as_needed: bool) {
+ panic!("external dylibs not supported")
+ }
+
+ fn link_staticlib_by_name(
+ &mut self,
+ _name: &str,
+ _verbatim: bool,
+ _whole_archive: bool,
+ _search_paths: &SearchPaths,
+ ) {
+ panic!("staticlibs not supported")
}
- fn link_whole_rlib(&mut self, path: &Path) {
+ fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
self.cmd.arg("--rlib").arg(path);
}
@@ -1844,30 +1829,10 @@ impl<'a> Linker for PtxLinker<'a> {
self.cmd.arg("-o").arg(path);
}
- fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
- panic!("external dylibs not supported")
- }
-
- fn link_rust_dylib(&mut self, _lib: &str, _path: &Path) {
- panic!("external dylibs not supported")
- }
-
- fn link_staticlib(&mut self, _lib: &str, _verbatim: bool) {
- panic!("staticlibs not supported")
- }
-
- fn link_whole_staticlib(&mut self, _lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
- panic!("staticlibs not supported")
- }
-
fn framework_path(&mut self, _path: &Path) {
panic!("frameworks not supported")
}
- fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
- panic!("frameworks not supported")
- }
-
fn full_relro(&mut self) {}
fn partial_relro(&mut self) {}
@@ -1907,11 +1872,21 @@ impl<'a> Linker for BpfLinker<'a> {
fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
- fn link_rlib(&mut self, path: &Path) {
- self.cmd.arg(path);
+ fn link_dylib_by_name(&mut self, _name: &str, _verbatim: bool, _as_needed: bool) {
+ panic!("external dylibs not supported")
}
- fn link_whole_rlib(&mut self, path: &Path) {
+ fn link_staticlib_by_name(
+ &mut self,
+ _name: &str,
+ _verbatim: bool,
+ _whole_archive: bool,
+ _search_paths: &SearchPaths,
+ ) {
+ panic!("staticlibs not supported")
+ }
+
+ fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
self.cmd.arg(path);
}
@@ -1942,30 +1917,10 @@ impl<'a> Linker for BpfLinker<'a> {
self.cmd.arg("-o").arg(path);
}
- fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
- panic!("external dylibs not supported")
- }
-
- fn link_rust_dylib(&mut self, _lib: &str, _path: &Path) {
- panic!("external dylibs not supported")
- }
-
- fn link_staticlib(&mut self, _lib: &str, _verbatim: bool) {
- panic!("staticlibs not supported")
- }
-
- fn link_whole_staticlib(&mut self, _lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
- panic!("staticlibs not supported")
- }
-
fn framework_path(&mut self, _path: &Path) {
panic!("frameworks not supported")
}
- fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
- panic!("frameworks not supported")
- }
-
fn full_relro(&mut self) {}
fn partial_relro(&mut self) {}
diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs
index 5d497d4a1883a..4211f875dd01a 100644
--- a/compiler/rustc_codegen_ssa/src/back/write.rs
+++ b/compiler/rustc_codegen_ssa/src/back/write.rs
@@ -14,8 +14,11 @@ use rustc_data_structures::memmap::Mmap;
use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
use rustc_data_structures::sync::Lrc;
use rustc_errors::emitter::Emitter;
-use rustc_errors::{translation::Translate, DiagCtxt, FatalError, Level};
-use rustc_errors::{DiagnosticBuilder, DiagnosticMessage, Style};
+use rustc_errors::translation::Translate;
+use rustc_errors::{
+ DiagCtxt, DiagnosticArgName, DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage, ErrCode,
+ FatalError, FluentBundle, Level, Style,
+};
use rustc_fs_util::link_or_copy;
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc_incremental::{
@@ -36,7 +39,6 @@ use rustc_target::spec::{MergeFunctions, SanitizerSet};
use crate::errors::ErrorCreatingRemarkDir;
use std::any::Any;
-use std::borrow::Cow;
use std::fs;
use std::io;
use std::marker::PhantomData;
@@ -995,12 +997,10 @@ pub(crate) enum Message {
/// process another codegen unit.
pub struct CguMessage;
-type DiagnosticArgName<'source> = Cow<'source, str>;
-
struct Diagnostic {
msgs: Vec<(DiagnosticMessage, Style)>,
- args: FxHashMap, rustc_errors::DiagnosticArgValue<'static>>,
- code: Option,
+ args: FxHashMap,
+ code: Option,
lvl: Level,
}
@@ -1800,23 +1800,23 @@ impl SharedEmitter {
}
impl Translate for SharedEmitter {
- fn fluent_bundle(&self) -> Option<&Lrc> {
+ fn fluent_bundle(&self) -> Option<&Lrc> {
None
}
- fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle {
+ fn fallback_fluent_bundle(&self) -> &FluentBundle {
panic!("shared emitter attempted to translate a diagnostic");
}
}
impl Emitter for SharedEmitter {
fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
- let args: FxHashMap, rustc_errors::DiagnosticArgValue<'_>> =
+ let args: FxHashMap =
diag.args().map(|(name, arg)| (name.clone(), arg.clone())).collect();
drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
msgs: diag.messages.clone(),
args: args.clone(),
- code: diag.code.clone(),
+ code: diag.code,
lvl: diag.level(),
})));
for child in &diag.children {
diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs
index cca239a43b342..47b1b0801193a 100644
--- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs
+++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs
@@ -1,6 +1,6 @@
use rustc_ast::{ast, attr, MetaItemKind, NestedMetaItem};
use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr};
-use rustc_errors::struct_span_code_err;
+use rustc_errors::{codes::*, struct_span_code_err};
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
diff --git a/compiler/rustc_codegen_ssa/src/errors.rs b/compiler/rustc_codegen_ssa/src/errors.rs
index f90e1906caf0a..06ea5b9e8f4ab 100644
--- a/compiler/rustc_codegen_ssa/src/errors.rs
+++ b/compiler/rustc_codegen_ssa/src/errors.rs
@@ -4,7 +4,7 @@ use crate::assert_module_sources::CguReuse;
use crate::back::command::Command;
use crate::fluent_generated as fluent;
use rustc_errors::{
- DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic,
+ codes::*, DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, EmissionGuarantee, IntoDiagnostic,
IntoDiagnosticArg, Level,
};
use rustc_macros::Diagnostic;
@@ -147,7 +147,7 @@ impl<'a> CopyPath<'a> {
struct DebugArgPath<'a>(pub &'a Path);
impl IntoDiagnosticArg for DebugArgPath<'_> {
- fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
+ fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue {
DiagnosticArgValue::Str(Cow::Owned(format!("{:?}", self.0)))
}
}
@@ -612,7 +612,7 @@ pub struct UnknownAtomicOperation;
#[derive(Diagnostic)]
pub enum InvalidMonomorphization<'tcx> {
- #[diag(codegen_ssa_invalid_monomorphization_basic_integer_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_basic_integer_type, code = E0511)]
BasicIntegerType {
#[primary_span]
span: Span,
@@ -620,7 +620,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_basic_float_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_basic_float_type, code = E0511)]
BasicFloatType {
#[primary_span]
span: Span,
@@ -628,14 +628,14 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_float_to_int_unchecked, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_float_to_int_unchecked, code = E0511)]
FloatToIntUnchecked {
#[primary_span]
span: Span,
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_floating_point_vector, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_floating_point_vector, code = E0511)]
FloatingPointVector {
#[primary_span]
span: Span,
@@ -644,7 +644,7 @@ pub enum InvalidMonomorphization<'tcx> {
in_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_floating_point_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_floating_point_type, code = E0511)]
FloatingPointType {
#[primary_span]
span: Span,
@@ -652,14 +652,14 @@ pub enum InvalidMonomorphization<'tcx> {
in_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_unrecognized_intrinsic, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_unrecognized_intrinsic, code = E0511)]
UnrecognizedIntrinsic {
#[primary_span]
span: Span,
name: Symbol,
},
- #[diag(codegen_ssa_invalid_monomorphization_simd_argument, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_simd_argument, code = E0511)]
SimdArgument {
#[primary_span]
span: Span,
@@ -667,7 +667,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_simd_input, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_simd_input, code = E0511)]
SimdInput {
#[primary_span]
span: Span,
@@ -675,7 +675,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_simd_first, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_simd_first, code = E0511)]
SimdFirst {
#[primary_span]
span: Span,
@@ -683,7 +683,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_simd_second, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_simd_second, code = E0511)]
SimdSecond {
#[primary_span]
span: Span,
@@ -691,7 +691,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_simd_third, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_simd_third, code = E0511)]
SimdThird {
#[primary_span]
span: Span,
@@ -699,7 +699,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_simd_return, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_simd_return, code = E0511)]
SimdReturn {
#[primary_span]
span: Span,
@@ -707,7 +707,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_invalid_bitmask, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_invalid_bitmask, code = E0511)]
InvalidBitmask {
#[primary_span]
span: Span,
@@ -717,7 +717,7 @@ pub enum InvalidMonomorphization<'tcx> {
expected_bytes: u64,
},
- #[diag(codegen_ssa_invalid_monomorphization_return_length_input_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_return_length_input_type, code = E0511)]
ReturnLengthInputType {
#[primary_span]
span: Span,
@@ -728,7 +728,7 @@ pub enum InvalidMonomorphization<'tcx> {
out_len: u64,
},
- #[diag(codegen_ssa_invalid_monomorphization_second_argument_length, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_second_argument_length, code = E0511)]
SecondArgumentLength {
#[primary_span]
span: Span,
@@ -739,7 +739,7 @@ pub enum InvalidMonomorphization<'tcx> {
out_len: u64,
},
- #[diag(codegen_ssa_invalid_monomorphization_third_argument_length, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_third_argument_length, code = E0511)]
ThirdArgumentLength {
#[primary_span]
span: Span,
@@ -750,7 +750,7 @@ pub enum InvalidMonomorphization<'tcx> {
out_len: u64,
},
- #[diag(codegen_ssa_invalid_monomorphization_return_integer_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_return_integer_type, code = E0511)]
ReturnIntegerType {
#[primary_span]
span: Span,
@@ -759,7 +759,7 @@ pub enum InvalidMonomorphization<'tcx> {
out_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_simd_shuffle, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_simd_shuffle, code = E0511)]
SimdShuffle {
#[primary_span]
span: Span,
@@ -767,7 +767,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_return_length, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_return_length, code = E0511)]
ReturnLength {
#[primary_span]
span: Span,
@@ -777,7 +777,7 @@ pub enum InvalidMonomorphization<'tcx> {
out_len: u64,
},
- #[diag(codegen_ssa_invalid_monomorphization_return_element, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_return_element, code = E0511)]
ReturnElement {
#[primary_span]
span: Span,
@@ -788,7 +788,7 @@ pub enum InvalidMonomorphization<'tcx> {
out_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_shuffle_index_not_constant, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_shuffle_index_not_constant, code = E0511)]
ShuffleIndexNotConstant {
#[primary_span]
span: Span,
@@ -796,7 +796,7 @@ pub enum InvalidMonomorphization<'tcx> {
arg_idx: u64,
},
- #[diag(codegen_ssa_invalid_monomorphization_shuffle_index_out_of_bounds, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_shuffle_index_out_of_bounds, code = E0511)]
ShuffleIndexOutOfBounds {
#[primary_span]
span: Span,
@@ -805,7 +805,7 @@ pub enum InvalidMonomorphization<'tcx> {
total_len: u128,
},
- #[diag(codegen_ssa_invalid_monomorphization_inserted_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_inserted_type, code = E0511)]
InsertedType {
#[primary_span]
span: Span,
@@ -815,7 +815,7 @@ pub enum InvalidMonomorphization<'tcx> {
out_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_return_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_return_type, code = E0511)]
ReturnType {
#[primary_span]
span: Span,
@@ -825,7 +825,7 @@ pub enum InvalidMonomorphization<'tcx> {
ret_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_expected_return_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_expected_return_type, code = E0511)]
ExpectedReturnType {
#[primary_span]
span: Span,
@@ -834,7 +834,7 @@ pub enum InvalidMonomorphization<'tcx> {
ret_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_mismatched_lengths, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_mismatched_lengths, code = E0511)]
MismatchedLengths {
#[primary_span]
span: Span,
@@ -843,7 +843,7 @@ pub enum InvalidMonomorphization<'tcx> {
v_len: u64,
},
- #[diag(codegen_ssa_invalid_monomorphization_mask_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_mask_type, code = E0511)]
MaskType {
#[primary_span]
span: Span,
@@ -851,7 +851,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_vector_argument, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_vector_argument, code = E0511)]
VectorArgument {
#[primary_span]
span: Span,
@@ -860,7 +860,7 @@ pub enum InvalidMonomorphization<'tcx> {
in_elem: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_cannot_return, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_cannot_return, code = E0511)]
CannotReturn {
#[primary_span]
span: Span,
@@ -870,7 +870,7 @@ pub enum InvalidMonomorphization<'tcx> {
expected_bytes: u64,
},
- #[diag(codegen_ssa_invalid_monomorphization_expected_element_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_expected_element_type, code = E0511)]
ExpectedElementType {
#[primary_span]
span: Span,
@@ -882,7 +882,7 @@ pub enum InvalidMonomorphization<'tcx> {
mutability: ExpectedPointerMutability,
},
- #[diag(codegen_ssa_invalid_monomorphization_third_arg_element_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_third_arg_element_type, code = E0511)]
ThirdArgElementType {
#[primary_span]
span: Span,
@@ -891,7 +891,7 @@ pub enum InvalidMonomorphization<'tcx> {
third_arg: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_unsupported_symbol_of_size, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_unsupported_symbol_of_size, code = E0511)]
UnsupportedSymbolOfSize {
#[primary_span]
span: Span,
@@ -903,7 +903,7 @@ pub enum InvalidMonomorphization<'tcx> {
ret_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_unsupported_symbol, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_unsupported_symbol, code = E0511)]
UnsupportedSymbol {
#[primary_span]
span: Span,
@@ -914,7 +914,7 @@ pub enum InvalidMonomorphization<'tcx> {
ret_ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_cast_fat_pointer, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_cast_fat_pointer, code = E0511)]
CastFatPointer {
#[primary_span]
span: Span,
@@ -922,7 +922,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_expected_pointer, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_expected_pointer, code = E0511)]
ExpectedPointer {
#[primary_span]
span: Span,
@@ -930,7 +930,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_expected_usize, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_expected_usize, code = E0511)]
ExpectedUsize {
#[primary_span]
span: Span,
@@ -938,7 +938,7 @@ pub enum InvalidMonomorphization<'tcx> {
ty: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_unsupported_cast, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_unsupported_cast, code = E0511)]
UnsupportedCast {
#[primary_span]
span: Span,
@@ -949,7 +949,7 @@ pub enum InvalidMonomorphization<'tcx> {
out_elem: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_unsupported_operation, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_unsupported_operation, code = E0511)]
UnsupportedOperation {
#[primary_span]
span: Span,
@@ -958,7 +958,7 @@ pub enum InvalidMonomorphization<'tcx> {
in_elem: Ty<'tcx>,
},
- #[diag(codegen_ssa_invalid_monomorphization_expected_vector_element_type, code = "E0511")]
+ #[diag(codegen_ssa_invalid_monomorphization_expected_vector_element_type, code = E0511)]
ExpectedVectorElementType {
#[primary_span]
span: Span,
@@ -974,7 +974,7 @@ pub enum ExpectedPointerMutability {
}
impl IntoDiagnosticArg for ExpectedPointerMutability {
- fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
+ fn into_diagnostic_arg(self) -> DiagnosticArgValue {
match self {
ExpectedPointerMutability::Mut => DiagnosticArgValue::Str(Cow::Borrowed("*mut")),
ExpectedPointerMutability::Not => DiagnosticArgValue::Str(Cow::Borrowed("*_")),
diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs
index 8f5421823a384..fc833a3863e40 100644
--- a/compiler/rustc_codegen_ssa/src/lib.rs
+++ b/compiler/rustc_codegen_ssa/src/lib.rs
@@ -7,10 +7,8 @@
#![feature(if_let_guard)]
#![feature(let_chains)]
#![feature(negative_impls)]
-#![feature(never_type)]
#![feature(strict_provenance)]
#![feature(try_blocks)]
-#![recursion_limit = "256"]
//! This crate contains codegen code that is used by all codegen backends (LLVM and others).
//! The backend-agnostic functions of this crate use functions defined in various traits that
diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs
index e8d0430c9d955..62af21396ab4b 100644
--- a/compiler/rustc_const_eval/src/const_eval/error.rs
+++ b/compiler/rustc_const_eval/src/const_eval/error.rs
@@ -1,6 +1,8 @@
use std::mem;
-use rustc_errors::{DiagnosticArgValue, DiagnosticMessage, IntoDiagnostic, IntoDiagnosticArg};
+use rustc_errors::{
+ DiagnosticArgName, DiagnosticArgValue, DiagnosticMessage, IntoDiagnostic, IntoDiagnosticArg,
+};
use rustc_hir::CRATE_HIR_ID;
use rustc_middle::mir::AssertKind;
use rustc_middle::query::TyCtxtAt;
@@ -32,10 +34,7 @@ impl MachineStopType for ConstEvalErrKind {
AssertFailure(x) => x.diagnostic_message(),
}
}
- fn add_args(
- self: Box,
- adder: &mut dyn FnMut(std::borrow::Cow<'static, str>, DiagnosticArgValue<'static>),
- ) {
+ fn add_args(self: Box, adder: &mut dyn FnMut(DiagnosticArgName, DiagnosticArgValue)) {
use ConstEvalErrKind::*;
match *self {
ConstAccessesStatic | ModifiedGlobal => {}
@@ -50,9 +49,7 @@ impl MachineStopType for ConstEvalErrKind {
}
}
-// The errors become `MachineStop` with plain strings when being raised.
-// `ConstEvalErr` (in `librustc_middle/mir/interpret/error.rs`) knows to
-// handle these.
+/// The errors become [`InterpError::MachineStop`] when being raised.
impl<'tcx> Into> for ConstEvalErrKind {
fn into(self) -> InterpErrorInfo<'tcx> {
err_machine_stop!(self).into()
diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs
index 707bb8d893336..12544f5b02955 100644
--- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs
+++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs
@@ -138,7 +138,7 @@ pub(crate) fn const_to_valtree_inner<'tcx>(
}
// Trait objects are not allowed in type level constants, as we have no concept for
// resolving their backing type, even if we can do that at const eval time. We may
- // hypothetically be able to allow `dyn StructuralEq` trait objects in the future,
+ // hypothetically be able to allow `dyn StructuralPartialEq` trait objects in the future,
// but it is unclear if this is useful.
ty::Dynamic(..) => Err(ValTreeCreationError::NonSupportedType),
diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs
index 064d97a49d75a..4d2b1ba3eec89 100644
--- a/compiler/rustc_const_eval/src/errors.rs
+++ b/compiler/rustc_const_eval/src/errors.rs
@@ -1,8 +1,8 @@
use std::borrow::Cow;
use rustc_errors::{
- DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage, EmissionGuarantee,
- IntoDiagnostic, Level,
+ codes::*, DiagCtxt, DiagnosticArgValue, DiagnosticBuilder, DiagnosticMessage,
+ EmissionGuarantee, IntoDiagnostic, Level,
};
use rustc_hir::ConstContext;
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
@@ -55,14 +55,14 @@ pub(crate) struct UnstableInStable {
}
#[derive(Diagnostic)]
-#[diag(const_eval_thread_local_access, code = "E0625")]
+#[diag(const_eval_thread_local_access, code = E0625)]
pub(crate) struct NonConstOpErr {
#[primary_span]
pub span: Span,
}
#[derive(Diagnostic)]
-#[diag(const_eval_static_access, code = "E0013")]
+#[diag(const_eval_static_access, code = E0013)]
#[help]
pub(crate) struct StaticAccessErr {
#[primary_span]
@@ -98,7 +98,7 @@ pub(crate) struct PanicNonStrErr {
}
#[derive(Diagnostic)]
-#[diag(const_eval_mut_deref, code = "E0658")]
+#[diag(const_eval_mut_deref, code = E0658)]
pub(crate) struct MutDerefErr {
#[primary_span]
pub span: Span,
@@ -106,7 +106,7 @@ pub(crate) struct MutDerefErr {
}
#[derive(Diagnostic)]
-#[diag(const_eval_transient_mut_borrow, code = "E0658")]
+#[diag(const_eval_transient_mut_borrow, code = E0658)]
pub(crate) struct TransientMutBorrowErr {
#[primary_span]
pub span: Span,
@@ -114,7 +114,7 @@ pub(crate) struct TransientMutBorrowErr {
}
#[derive(Diagnostic)]
-#[diag(const_eval_transient_mut_raw, code = "E0658")]
+#[diag(const_eval_transient_mut_raw, code = E0658)]
pub(crate) struct TransientMutRawErr {
#[primary_span]
pub span: Span,
@@ -146,7 +146,7 @@ pub(crate) struct UnstableConstFn {
}
#[derive(Diagnostic)]
-#[diag(const_eval_unallowed_mutable_refs, code = "E0764")]
+#[diag(const_eval_unallowed_mutable_refs, code = E0764)]
pub(crate) struct UnallowedMutableRefs {
#[primary_span]
pub span: Span,
@@ -156,7 +156,7 @@ pub(crate) struct UnallowedMutableRefs {
}
#[derive(Diagnostic)]
-#[diag(const_eval_unallowed_mutable_raw, code = "E0764")]
+#[diag(const_eval_unallowed_mutable_raw, code = E0764)]
pub(crate) struct UnallowedMutableRaw {
#[primary_span]
pub span: Span,
@@ -165,7 +165,7 @@ pub(crate) struct UnallowedMutableRaw {
pub teach: Option<()>,
}
#[derive(Diagnostic)]
-#[diag(const_eval_non_const_fmt_macro_call, code = "E0015")]
+#[diag(const_eval_non_const_fmt_macro_call, code = E0015)]
pub(crate) struct NonConstFmtMacroCall {
#[primary_span]
pub span: Span,
@@ -173,7 +173,7 @@ pub(crate) struct NonConstFmtMacroCall {
}
#[derive(Diagnostic)]
-#[diag(const_eval_non_const_fn_call, code = "E0015")]
+#[diag(const_eval_non_const_fn_call, code = E0015)]
pub(crate) struct NonConstFnCall {
#[primary_span]
pub span: Span,
@@ -190,7 +190,7 @@ pub(crate) struct UnallowedOpInConstContext {
}
#[derive(Diagnostic)]
-#[diag(const_eval_unallowed_heap_allocations, code = "E0010")]
+#[diag(const_eval_unallowed_heap_allocations, code = E0010)]
pub(crate) struct UnallowedHeapAllocations {
#[primary_span]
#[label]
@@ -201,7 +201,7 @@ pub(crate) struct UnallowedHeapAllocations {
}
#[derive(Diagnostic)]
-#[diag(const_eval_unallowed_inline_asm, code = "E0015")]
+#[diag(const_eval_unallowed_inline_asm, code = E0015)]
pub(crate) struct UnallowedInlineAsm {
#[primary_span]
pub span: Span,
@@ -209,7 +209,7 @@ pub(crate) struct UnallowedInlineAsm {
}
#[derive(Diagnostic)]
-#[diag(const_eval_interior_mutable_data_refer, code = "E0492")]
+#[diag(const_eval_interior_mutable_data_refer, code = E0492)]
pub(crate) struct InteriorMutableDataRefer {
#[primary_span]
#[label]
@@ -274,7 +274,7 @@ pub struct RawBytesNote {
// FIXME(fee1-dead) do not use stringly typed `ConstContext`
#[derive(Diagnostic)]
-#[diag(const_eval_match_eq_non_const, code = "E0015")]
+#[diag(const_eval_match_eq_non_const, code = E0015)]
#[note]
pub struct NonConstMatchEq<'tcx> {
#[primary_span]
@@ -284,7 +284,7 @@ pub struct NonConstMatchEq<'tcx> {
}
#[derive(Diagnostic)]
-#[diag(const_eval_for_loop_into_iter_non_const, code = "E0015")]
+#[diag(const_eval_for_loop_into_iter_non_const, code = E0015)]
pub struct NonConstForLoopIntoIter<'tcx> {
#[primary_span]
pub span: Span,
@@ -293,7 +293,7 @@ pub struct NonConstForLoopIntoIter<'tcx> {
}
#[derive(Diagnostic)]
-#[diag(const_eval_question_branch_non_const, code = "E0015")]
+#[diag(const_eval_question_branch_non_const, code = E0015)]
pub struct NonConstQuestionBranch<'tcx> {
#[primary_span]
pub span: Span,
@@ -302,7 +302,7 @@ pub struct NonConstQuestionBranch<'tcx> {
}
#[derive(Diagnostic)]
-#[diag(const_eval_question_from_residual_non_const, code = "E0015")]
+#[diag(const_eval_question_from_residual_non_const, code = E0015)]
pub struct NonConstQuestionFromResidual<'tcx> {
#[primary_span]
pub span: Span,
@@ -311,7 +311,7 @@ pub struct NonConstQuestionFromResidual<'tcx> {
}
#[derive(Diagnostic)]
-#[diag(const_eval_try_block_from_output_non_const, code = "E0015")]
+#[diag(const_eval_try_block_from_output_non_const, code = E0015)]
pub struct NonConstTryBlockFromOutput<'tcx> {
#[primary_span]
pub span: Span,
@@ -320,7 +320,7 @@ pub struct NonConstTryBlockFromOutput<'tcx> {
}
#[derive(Diagnostic)]
-#[diag(const_eval_await_non_const, code = "E0015")]
+#[diag(const_eval_await_non_const, code = E0015)]
pub struct NonConstAwait<'tcx> {
#[primary_span]
pub span: Span,
@@ -329,7 +329,7 @@ pub struct NonConstAwait<'tcx> {
}
#[derive(Diagnostic)]
-#[diag(const_eval_closure_non_const, code = "E0015")]
+#[diag(const_eval_closure_non_const, code = E0015)]
pub struct NonConstClosure {
#[primary_span]
pub span: Span,
@@ -362,7 +362,7 @@ pub struct ConsiderDereferencing {
}
#[derive(Diagnostic)]
-#[diag(const_eval_operator_non_const, code = "E0015")]
+#[diag(const_eval_operator_non_const, code = E0015)]
pub struct NonConstOperator {
#[primary_span]
pub span: Span,
@@ -372,7 +372,7 @@ pub struct NonConstOperator {
}
#[derive(Diagnostic)]
-#[diag(const_eval_deref_coercion_non_const, code = "E0015")]
+#[diag(const_eval_deref_coercion_non_const, code = E0015)]
#[note]
pub struct NonConstDerefCoercion<'tcx> {
#[primary_span]
@@ -385,7 +385,7 @@ pub struct NonConstDerefCoercion<'tcx> {
}
#[derive(Diagnostic)]
-#[diag(const_eval_live_drop, code = "E0493")]
+#[diag(const_eval_live_drop, code = E0493)]
pub struct LiveDrop<'tcx> {
#[primary_span]
#[label]
@@ -397,7 +397,7 @@ pub struct LiveDrop<'tcx> {
}
#[derive(Diagnostic)]
-#[diag(const_eval_error, code = "E0080")]
+#[diag(const_eval_error, code = E0080)]
pub struct ConstEvalError {
#[primary_span]
pub span: Span,
@@ -423,7 +423,7 @@ pub struct NullaryIntrinsicError {
}
#[derive(Diagnostic)]
-#[diag(const_eval_undefined_behavior, code = "E0080")]
+#[diag(const_eval_undefined_behavior, code = E0080)]
pub struct UndefinedBehavior {
#[primary_span]
pub span: Span,
@@ -906,7 +906,7 @@ impl ReportErrorExt for ResourceExhaustionInfo {
}
impl rustc_errors::IntoDiagnosticArg for InternKind {
- fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> {
+ fn into_diagnostic_arg(self) -> DiagnosticArgValue {
DiagnosticArgValue::Str(Cow::Borrowed(match self {
InternKind::Static(Mutability::Not) => "static",
InternKind::Static(Mutability::Mut) => "static_mut",
diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs
index 3afd14eb57435..38ad8cbf3a691 100644
--- a/compiler/rustc_const_eval/src/interpret/memory.rs
+++ b/compiler/rustc_const_eval/src/interpret/memory.rs
@@ -396,7 +396,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
/// to the allocation it points to. Supports both shared and mutable references, as the actual
/// checking is offloaded to a helper closure.
///
- /// If this returns `None`, the size is 0; it can however return `Some` even for size 0.
+ /// Returns `None` if and only if the size is 0.
fn check_and_deref_ptr(
&self,
ptr: Pointer