Merge pull request #4197 from rust-lang/rustup-2025-02-19

Automatic Rustup
This commit is contained in:
Ben Kimock 2025-02-19 05:39:15 +00:00 committed by GitHub
commit e2ba35a451
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
953 changed files with 15017 additions and 7103 deletions

2
.gitmodules vendored
View file

@ -29,7 +29,7 @@
[submodule "src/llvm-project"]
path = src/llvm-project
url = https://github.com/rust-lang/llvm-project.git
branch = rustc/19.1-2024-12-03
branch = rustc/20.1-2025-02-13
shallow = true
[submodule "src/doc/embedded-book"]
path = src/doc/embedded-book

View file

@ -61,19 +61,6 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "ammonia"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ab99eae5ee58501ab236beb6f20f6ca39be615267b014899c89b2f0bc18a459"
dependencies = [
"html5ever",
"maplit",
"once_cell",
"tendril",
"url",
]
[[package]]
name = "android-tzdata"
version = "0.1.1"
@ -513,16 +500,6 @@ dependencies = [
"anstyle",
"clap_lex",
"strsim",
"terminal_size",
]
[[package]]
name = "clap_complete"
version = "4.5.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33a7e468e750fa4b6be660e8b5651ad47372e8fb114030b594c2d75d48c5ffd0"
dependencies = [
"clap",
]
[[package]]
@ -1084,18 +1061,6 @@ version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "elasticlunr-rs"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41e83863a500656dfa214fee6682de9c5b9f03de6860fec531235ed2ae9f6571"
dependencies = [
"regex",
"serde",
"serde_derive",
"serde_json",
]
[[package]]
name = "elsa"
version = "1.11.0"
@ -1159,13 +1124,6 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "error_index_generator"
version = "0.0.0"
dependencies = [
"mdbook",
]
[[package]]
name = "expect-test"
version = "1.5.1"
@ -1517,22 +1475,6 @@ dependencies = [
"serde",
]
[[package]]
name = "handlebars"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d6b224b95c1e668ac0270325ad563b2eef1469fbbb8959bc7c692c844b813d9"
dependencies = [
"derive_builder",
"log",
"num-order",
"pest",
"pest_derive",
"serde",
"serde_json",
"thiserror 2.0.11",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
@ -2189,12 +2131,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]]
name = "markup5ever"
version = "0.12.1"
@ -2228,34 +2164,6 @@ dependencies = [
"digest",
]
[[package]]
name = "mdbook"
version = "0.4.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe1f98b8d66e537d2f0ba06e7dec4f44001deec539a2d18bfc102d6a86189148"
dependencies = [
"ammonia",
"anyhow",
"chrono",
"clap",
"clap_complete",
"elasticlunr-rs",
"env_logger",
"handlebars",
"log",
"memchr",
"once_cell",
"opener",
"pulldown-cmark 0.10.3",
"regex",
"serde",
"serde_json",
"shlex",
"tempfile",
"toml 0.5.11",
"topological-sort",
]
[[package]]
name = "measureme"
version = "11.0.1"
@ -2303,9 +2211,9 @@ dependencies = [
[[package]]
name = "minifier"
version = "0.3.4"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cf47565b1430f5fe6c81d3afcb4b835271348d7eb35294a4d592e38dd09ea22"
checksum = "9bfdc64e2f805f3d12965f10522000bae36e88d2cfea44112331f467d4f4bf68"
[[package]]
name = "minimal-lexical"
@ -2483,21 +2391,6 @@ dependencies = [
"num-traits",
]
[[package]]
name = "num-modular"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17bb261bf36fa7d83f4c294f834e91256769097b3cb505d44831e0a179ac647f"
[[package]]
name = "num-order"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "537b596b97c40fcf8056d153049eb22f481c17ebce72a513ec9286e4986d1bb6"
dependencies = [
"num-modular",
]
[[package]]
name = "num-rational"
version = "0.4.2"
@ -2718,51 +2611,6 @@ dependencies = [
"libc",
]
[[package]]
name = "pest"
version = "2.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b7cafe60d6cf8e62e1b9b2ea516a089c008945bb5a275416789e7db0bc199dc"
dependencies = [
"memchr",
"thiserror 2.0.11",
"ucd-trie",
]
[[package]]
name = "pest_derive"
version = "2.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "816518421cfc6887a0d62bf441b6ffb4536fcc926395a69e1a85852d4363f57e"
dependencies = [
"pest",
"pest_generator",
]
[[package]]
name = "pest_generator"
version = "2.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d1396fd3a870fc7838768d171b4616d5c91f6cc25e377b673d714567d99377b"
dependencies = [
"pest",
"pest_meta",
"proc-macro2",
"quote",
"syn 2.0.96",
]
[[package]]
name = "pest_meta"
version = "2.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1e58089ea25d717bfd31fb534e4f3afcc2cc569c70de3e239778991ea3b7dea"
dependencies = [
"once_cell",
"pest",
"sha2",
]
[[package]]
name = "phf"
version = "0.11.3"
@ -2921,18 +2769,6 @@ dependencies = [
"unicase",
]
[[package]]
name = "pulldown-cmark"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76979bea66e7875e7509c4ec5300112b316af87fa7a252ca91c448b32dfe3993"
dependencies = [
"bitflags",
"memchr",
"pulldown-cmark-escape 0.10.1",
"unicase",
]
[[package]]
name = "pulldown-cmark"
version = "0.11.3"
@ -2941,16 +2777,10 @@ checksum = "679341d22c78c6c649893cbd6c3278dcbe9fc4faa62fea3a9296ae2b50c14625"
dependencies = [
"bitflags",
"memchr",
"pulldown-cmark-escape 0.11.0",
"pulldown-cmark-escape",
"unicase",
]
[[package]]
name = "pulldown-cmark-escape"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd348ff538bc9caeda7ee8cad2d1d48236a1f443c1fa3913c6a02fe0043b1dd3"
[[package]]
name = "pulldown-cmark-escape"
version = "0.11.0"
@ -3317,6 +3147,7 @@ dependencies = [
"rand 0.8.5",
"rand_xoshiro",
"rustc_data_structures",
"rustc_hashes",
"rustc_index",
"rustc_macros",
"rustc_serialize",
@ -3544,6 +3375,7 @@ dependencies = [
"rustc_errors",
"rustc_fluent_macro",
"rustc_fs_util",
"rustc_hashes",
"rustc_hir",
"rustc_index",
"rustc_llvm",
@ -3586,6 +3418,7 @@ dependencies = [
"rustc_errors",
"rustc_fluent_macro",
"rustc_fs_util",
"rustc_hashes",
"rustc_hir",
"rustc_hir_pretty",
"rustc_incremental",
@ -3658,6 +3491,7 @@ dependencies = [
"rustc-stable-hash",
"rustc_arena",
"rustc_graphviz",
"rustc_hashes",
"rustc_index",
"rustc_macros",
"rustc_serialize",
@ -3768,6 +3602,7 @@ dependencies = [
"rustc_error_codes",
"rustc_error_messages",
"rustc_fluent_macro",
"rustc_hashes",
"rustc_hir",
"rustc_index",
"rustc_lexer",
@ -3840,6 +3675,13 @@ version = "0.0.0"
name = "rustc_graphviz"
version = "0.0.0"
[[package]]
name = "rustc_hashes"
version = "0.0.0"
dependencies = [
"rustc-stable-hash",
]
[[package]]
name = "rustc_hir"
version = "0.0.0"
@ -3849,6 +3691,7 @@ dependencies = [
"rustc_arena",
"rustc_ast",
"rustc_data_structures",
"rustc_hashes",
"rustc_index",
"rustc_macros",
"rustc_serialize",
@ -4169,6 +4012,7 @@ dependencies = [
"rustc_feature",
"rustc_fluent_macro",
"rustc_graphviz",
"rustc_hashes",
"rustc_hir",
"rustc_hir_pretty",
"rustc_index",
@ -4405,6 +4249,7 @@ dependencies = [
"measureme",
"rustc_data_structures",
"rustc_errors",
"rustc_hashes",
"rustc_hir",
"rustc_index",
"rustc_middle",
@ -4428,6 +4273,7 @@ dependencies = [
"rustc_errors",
"rustc_feature",
"rustc_fluent_macro",
"rustc_hashes",
"rustc_hir",
"rustc_index",
"rustc_macros",
@ -4488,6 +4334,7 @@ name = "rustc_serialize"
version = "0.0.0"
dependencies = [
"indexmap",
"rustc_hashes",
"rustc_macros",
"smallvec",
"tempfile",
@ -4508,6 +4355,7 @@ dependencies = [
"rustc_feature",
"rustc_fluent_macro",
"rustc_fs_util",
"rustc_hashes",
"rustc_hir",
"rustc_lint_defs",
"rustc_macros",
@ -4549,6 +4397,7 @@ dependencies = [
"md-5",
"rustc_arena",
"rustc_data_structures",
"rustc_hashes",
"rustc_index",
"rustc_macros",
"rustc_serialize",
@ -4568,6 +4417,7 @@ dependencies = [
"rustc_abi",
"rustc_data_structures",
"rustc_errors",
"rustc_hashes",
"rustc_hir",
"rustc_middle",
"rustc_session",
@ -4663,6 +4513,7 @@ dependencies = [
"rustc_data_structures",
"rustc_errors",
"rustc_fluent_macro",
"rustc_hashes",
"rustc_hir",
"rustc_index",
"rustc_infer",
@ -5289,16 +5140,6 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "terminal_size"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5352447f921fda68cf61b4101566c0bdb5104eff6804d0678e5227580ab6a4e9"
dependencies = [
"rustix",
"windows-sys 0.59.0",
]
[[package]]
name = "termize"
version = "0.1.1"
@ -5539,12 +5380,6 @@ dependencies = [
"winnow",
]
[[package]]
name = "topological-sort"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d"
[[package]]
name = "tracing"
version = "0.1.37"
@ -5665,12 +5500,6 @@ dependencies = [
"regex-lite",
]
[[package]]
name = "ucd-trie"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
[[package]]
name = "ui_test"
version = "0.26.5"

View file

@ -13,7 +13,6 @@ members = [
"src/tools/clippy/clippy_dev",
"src/tools/compiletest",
"src/tools/run-make-support",
"src/tools/error_index_generator",
"src/tools/linkchecker",
"src/tools/lint-docs",
"src/tools/miropt-test-tools",

View file

@ -34,7 +34,8 @@ Libraries
---------
- [Panics in the standard library now have a leading `library/` in their path](https://github.com/rust-lang/rust/pull/132390)
- [`std::env::home_dir()` on Windows now ignores the non-standard `$HOME` environment variable](https://github.com/rust-lang/rust/pull/132515)
It will be un-deprecated in a subsequent release.
It will be un-deprecated in a subsequent release.
- [Add `AsyncFn*` to the prelude in all editions.](https://github.com/rust-lang/rust/pull/132611)
<a id="1.85.0-Stabilized-APIs"></a>
@ -98,15 +99,18 @@ Rustdoc
Compatibility Notes
-------------------
- [`rustc` no longer treats the `test` cfg as a well known check-cfg](https://github.com/rust-lang/rust/pull/131729), instead it is up to the build systems and users of `--check-cfg`[^check-cfg] to set it as a well known cfg using `--check-cfg=cfg(test)`.
This is done to enable build systems like Cargo to set it conditionally, as not all source files are suitable for unit tests.
[Cargo (for now) unconditionally sets the `test` cfg as a well known cfg](https://github.com/rust-lang/cargo/pull/14963).
[^check-cfg]: https://doc.rust-lang.org/nightly/rustc/check-cfg.html
[^check-cfg]: https://doc.rust-lang.org/nightly/rustc/check-cfg.html
- [Disable potentially incorrect type inference if there are trivial and non-trivial where-clauses](https://github.com/rust-lang/rust/pull/132325)
- `std::env::home_dir()` has been deprecated for years, because it can give surprising results in some Windows configurations if the `HOME` environment variable is set (which is not the normal configuration on Windows). We had previously avoided changing its behavior, out of concern for compatibility with code depending on this non-standard configuration. Given how long this function has been deprecated, we're now fixing its behavior as a bugfix. A subsequent release will remove the deprecation for this function.
- [Make `core::ffi::c_char` signedness more closely match that of the platform-default `char`](https://github.com/rust-lang/rust/pull/132975)
This changed `c_char` from an `i8` to `u8` or vice versa on many Tier 2 and 3
targets (mostly Arm and RISC-V embedded targets). The new definition may
result in compilation failures but fixes compatibility issues with C.
The `libc` crate matches this change as of its 0.2.169 release.
- [When compiling a nested `macro_rules` macro from an external crate, the content of the inner `macro_rules` is now built with the edition of the external crate, not the local crate.](https://github.com/rust-lang/rust/pull/133274)
- [Increase `sparcv9-sun-solaris` and `x86_64-pc-solaris` Solaris baseline to 11.4.](https://github.com/rust-lang/rust/pull/133293)

View file

@ -9,6 +9,7 @@ bitflags = "2.4.1"
rand = { version = "0.8.4", default-features = false, optional = true }
rand_xoshiro = { version = "0.6.0", optional = true }
rustc_data_structures = { path = "../rustc_data_structures", optional = true }
rustc_hashes = { path = "../rustc_hashes" }
rustc_index = { path = "../rustc_index", default-features = false }
rustc_macros = { path = "../rustc_macros", optional = true }
rustc_serialize = { path = "../rustc_serialize", optional = true }

View file

@ -2,6 +2,7 @@ use std::fmt::{self, Write};
use std::ops::{Bound, Deref};
use std::{cmp, iter};
use rustc_hashes::Hash64;
use rustc_index::Idx;
use tracing::debug;
@ -133,7 +134,7 @@ impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
size,
max_repr_align: None,
unadjusted_abi_align: align.abi,
randomization_seed: combined_seed,
randomization_seed: Hash64::new(combined_seed),
}
}
@ -226,7 +227,7 @@ impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
size: Size::ZERO,
max_repr_align: None,
unadjusted_abi_align: dl.i8_align.abi,
randomization_seed: 0,
randomization_seed: Hash64::ZERO,
}
}
@ -1058,7 +1059,7 @@ impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
// unsizable tail fields are excluded so that we use the same seed for the sized and unsized layouts.
let field_seed = fields_excluding_tail
.iter()
.fold(0u64, |acc, f| acc.wrapping_add(f.randomization_seed));
.fold(Hash64::ZERO, |acc, f| acc.wrapping_add(f.randomization_seed));
if optimize_field_order && fields.len() > 1 {
// If `-Z randomize-layout` was enabled for the type definition we can shuffle
@ -1072,7 +1073,7 @@ impl<Cx: HasDataLayout> LayoutCalculator<Cx> {
// `ReprOptions.field_shuffle_seed` is a deterministic seed we can use to randomize field
// ordering.
let mut rng = rand_xoshiro::Xoshiro128StarStar::seed_from_u64(
field_seed.wrapping_add(repr.field_shuffle_seed),
field_seed.wrapping_add(repr.field_shuffle_seed).as_u64(),
);
// Shuffle the ordering of the fields.

View file

@ -50,6 +50,7 @@ use std::str::FromStr;
use bitflags::bitflags;
#[cfg(feature = "nightly")]
use rustc_data_structures::stable_hasher::StableOrd;
use rustc_hashes::Hash64;
use rustc_index::{Idx, IndexSlice, IndexVec};
#[cfg(feature = "nightly")]
use rustc_macros::{Decodable_Generic, Encodable_Generic, HashStable_Generic};
@ -140,7 +141,7 @@ pub struct ReprOptions {
/// hash without loss, but it does pay the price of being larger.
/// Everything's a tradeoff, a 64-bit seed should be sufficient for our
/// purposes (primarily `-Z randomize-layout`)
pub field_shuffle_seed: u64,
pub field_shuffle_seed: Hash64,
}
impl ReprOptions {
@ -1727,7 +1728,7 @@ pub struct LayoutData<FieldIdx: Idx, VariantIdx: Idx> {
/// transmuted to `Foo<U>` we aim to create probalistically distinct seeds so that Foo can choose
/// to reorder its fields based on that information. The current implementation is a conservative
/// approximation of this goal.
pub randomization_seed: u64,
pub randomization_seed: Hash64,
}
impl<FieldIdx: Idx, VariantIdx: Idx> LayoutData<FieldIdx, VariantIdx> {
@ -1781,7 +1782,7 @@ impl<FieldIdx: Idx, VariantIdx: Idx> LayoutData<FieldIdx, VariantIdx> {
align,
max_repr_align: None,
unadjusted_abi_align: align.abi,
randomization_seed,
randomization_seed: Hash64::new(randomization_seed),
}
}
}

View file

@ -203,10 +203,8 @@ impl HasTokens for Nonterminal {
Nonterminal::NtStmt(stmt) => stmt.tokens(),
Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => expr.tokens(),
Nonterminal::NtPat(pat) => pat.tokens(),
Nonterminal::NtTy(ty) => ty.tokens(),
Nonterminal::NtMeta(attr_item) => attr_item.tokens(),
Nonterminal::NtPath(path) => path.tokens(),
Nonterminal::NtVis(vis) => vis.tokens(),
Nonterminal::NtBlock(block) => block.tokens(),
}
}
@ -216,10 +214,8 @@ impl HasTokens for Nonterminal {
Nonterminal::NtStmt(stmt) => stmt.tokens_mut(),
Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => expr.tokens_mut(),
Nonterminal::NtPat(pat) => pat.tokens_mut(),
Nonterminal::NtTy(ty) => ty.tokens_mut(),
Nonterminal::NtMeta(attr_item) => attr_item.tokens_mut(),
Nonterminal::NtPath(path) => path.tokens_mut(),
Nonterminal::NtVis(vis) => vis.tokens_mut(),
Nonterminal::NtBlock(block) => block.tokens_mut(),
}
}

View file

@ -907,7 +907,6 @@ fn visit_nonterminal<T: MutVisitor>(vis: &mut T, nt: &mut token::Nonterminal) {
}),
token::NtPat(pat) => vis.visit_pat(pat),
token::NtExpr(expr) => vis.visit_expr(expr),
token::NtTy(ty) => vis.visit_ty(ty),
token::NtLiteral(expr) => vis.visit_expr(expr),
token::NtMeta(item) => {
let AttrItem { unsafety: _, path, args, tokens } = item.deref_mut();
@ -916,7 +915,6 @@ fn visit_nonterminal<T: MutVisitor>(vis: &mut T, nt: &mut token::Nonterminal) {
visit_lazy_tts(vis, tokens);
}
token::NtPath(path) => vis.visit_path(path),
token::NtVis(visib) => vis.visit_vis(visib),
}
}

View file

@ -84,7 +84,9 @@ pub enum MetaVarKind {
// This field is needed for `Token::can_begin_string_literal`.
can_begin_string_literal: bool,
},
Ty,
Ty {
is_path: bool,
},
Ident,
Lifetime,
Literal,
@ -104,7 +106,7 @@ impl fmt::Display for MetaVarKind {
MetaVarKind::Pat(PatParam { inferred: false }) => sym::pat_param,
MetaVarKind::Expr { kind: Expr2021 { inferred: true } | Expr, .. } => sym::expr,
MetaVarKind::Expr { kind: Expr2021 { inferred: false }, .. } => sym::expr_2021,
MetaVarKind::Ty => sym::ty,
MetaVarKind::Ty { .. } => sym::ty,
MetaVarKind::Ident => sym::ident,
MetaVarKind::Lifetime => sym::lifetime,
MetaVarKind::Literal => sym::literal,
@ -659,7 +661,6 @@ impl Token {
| NtMeta(..)
| NtPat(..)
| NtPath(..)
| NtTy(..)
),
OpenDelim(Delimiter::Invisible(InvisibleOrigin::MetaVar(
MetaVarKind::Expr { .. } |
@ -667,7 +668,7 @@ impl Token {
MetaVarKind::Meta |
MetaVarKind::Pat(_) |
MetaVarKind::Path |
MetaVarKind::Ty
MetaVarKind::Ty { .. }
))) => true,
_ => false,
}
@ -688,9 +689,9 @@ impl Token {
Lifetime(..) | // lifetime bound in trait object
Lt | BinOp(Shl) | // associated path
PathSep => true, // global path
Interpolated(ref nt) => matches!(&**nt, NtTy(..) | NtPath(..)),
Interpolated(ref nt) => matches!(&**nt, NtPath(..)),
OpenDelim(Delimiter::Invisible(InvisibleOrigin::MetaVar(
MetaVarKind::Ty |
MetaVarKind::Ty { .. } |
MetaVarKind::Path
))) => true,
// For anonymous structs or unions, which only appear in specific positions
@ -969,6 +970,15 @@ impl Token {
}
}
/// Is this an invisible open delimiter at the start of a token sequence
/// from an expanded metavar?
pub fn is_metavar_seq(&self) -> Option<MetaVarKind> {
match self.kind {
OpenDelim(Delimiter::Invisible(InvisibleOrigin::MetaVar(kind))) => Some(kind),
_ => None,
}
}
pub fn glue(&self, joint: &Token) -> Option<Token> {
let kind = match self.kind {
Eq => match joint.kind {
@ -1067,12 +1077,10 @@ pub enum Nonterminal {
NtStmt(P<ast::Stmt>),
NtPat(P<ast::Pat>),
NtExpr(P<ast::Expr>),
NtTy(P<ast::Ty>),
NtLiteral(P<ast::Expr>),
/// Stuff inside brackets for attributes
NtMeta(P<ast::AttrItem>),
NtPath(P<ast::Path>),
NtVis(P<ast::Visibility>),
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, HashStable_Generic)]
@ -1166,10 +1174,8 @@ impl Nonterminal {
NtStmt(stmt) => stmt.span,
NtPat(pat) => pat.span,
NtExpr(expr) | NtLiteral(expr) => expr.span,
NtTy(ty) => ty.span,
NtMeta(attr_item) => attr_item.span(),
NtPath(path) => path.span,
NtVis(vis) => vis.span,
}
}
@ -1181,10 +1187,8 @@ impl Nonterminal {
NtPat(..) => "pattern",
NtExpr(..) => "expression",
NtLiteral(..) => "literal",
NtTy(..) => "type",
NtMeta(..) => "attribute",
NtPath(..) => "path",
NtVis(..) => "visibility",
}
}
}
@ -1207,11 +1211,9 @@ impl fmt::Debug for Nonterminal {
NtStmt(..) => f.pad("NtStmt(..)"),
NtPat(..) => f.pad("NtPat(..)"),
NtExpr(..) => f.pad("NtExpr(..)"),
NtTy(..) => f.pad("NtTy(..)"),
NtLiteral(..) => f.pad("NtLiteral(..)"),
NtMeta(..) => f.pad("NtMeta(..)"),
NtPath(..) => f.pad("NtPath(..)"),
NtVis(..) => f.pad("NtVis(..)"),
}
}
}

View file

@ -469,10 +469,8 @@ impl TokenStream {
}
Nonterminal::NtStmt(stmt) => TokenStream::from_ast(stmt),
Nonterminal::NtPat(pat) => TokenStream::from_ast(pat),
Nonterminal::NtTy(ty) => TokenStream::from_ast(ty),
Nonterminal::NtMeta(attr) => TokenStream::from_ast(attr),
Nonterminal::NtPath(path) => TokenStream::from_ast(path),
Nonterminal::NtVis(vis) => TokenStream::from_ast(vis),
Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => TokenStream::from_ast(expr),
}
}

View file

@ -407,7 +407,7 @@ fn compute_hir_hash(
.iter_enumerated()
.filter_map(|(def_id, info)| {
let info = info.as_owner()?;
let def_path_hash = tcx.hir().def_path_hash(def_id);
let def_path_hash = tcx.hir_def_path_hash(def_id);
Some((def_path_hash, info))
})
.collect();
@ -497,7 +497,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
"adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
node_id,
def_kind,
self.tcx.hir().def_key(self.local_def_id(node_id)),
self.tcx.hir_def_key(self.local_def_id(node_id)),
);
let def_id = self.tcx.at(span).create_def(parent, name, def_kind).def_id();

View file

@ -14,16 +14,15 @@ use rustc_errors::codes::*;
use rustc_errors::{Applicability, Diag, MultiSpan, struct_span_code_err};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::intravisit::{Map, Visitor, walk_block, walk_expr};
use rustc_hir::intravisit::{Visitor, walk_block, walk_expr};
use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, LangItem, PatField};
use rustc_middle::bug;
use rustc_middle::hir::nested_filter::OnlyBodies;
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::{
self, AggregateKind, BindingForm, BorrowKind, ClearCrossCrate, ConstraintCategory,
FakeBorrowKind, FakeReadCause, LocalDecl, LocalInfo, LocalKind, Location, MutBorrowKind,
Operand, Place, PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator,
TerminatorKind, VarBindingForm, VarDebugInfoContents,
Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement, StatementKind,
Terminator, TerminatorKind, VarBindingForm, VarDebugInfoContents,
};
use rustc_middle::ty::print::PrintTraitRefExt as _;
use rustc_middle::ty::{
@ -348,13 +347,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
expr: Option<&'hir hir::Expr<'hir>>,
pat: Option<&'hir hir::Pat<'hir>>,
parent_pat: Option<&'hir hir::Pat<'hir>>,
hir: rustc_middle::hir::map::Map<'hir>,
tcx: TyCtxt<'hir>,
}
impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
type NestedFilter = OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.hir
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
@ -386,8 +385,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
hir::intravisit::walk_pat(self, p);
}
}
let tcx = self.infcx.tcx;
let hir = self.infcx.tcx.hir();
if let Some(body) = hir.maybe_body_owned_by(self.mir_def_id()) {
if let Some(body) = tcx.hir_maybe_body_owned_by(self.mir_def_id()) {
let expr = body.value;
let place = &self.move_data.move_paths[mpi].place;
let span = place.as_local().map(|local| self.body.local_decls[local].source_info.span);
@ -396,7 +396,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
expr: None,
pat: None,
parent_pat: None,
hir,
tcx,
};
finder.visit_expr(expr);
if let Some(span) = span
@ -782,9 +782,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// We use the statements were the binding was initialized, and inspect the HIR to look
// for the branching codepaths that aren't covered, to point at them.
let map = self.infcx.tcx.hir();
let body = map.body_owned_by(self.mir_def_id());
let mut visitor = ConditionVisitor { tcx: self.infcx.tcx, spans, name, errors: vec![] };
let tcx = self.infcx.tcx;
let body = tcx.hir_body_owned_by(self.mir_def_id());
let mut visitor = ConditionVisitor { tcx, spans, name, errors: vec![] };
visitor.visit_body(&body);
let spans = visitor.spans;
@ -1082,7 +1082,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
] {
for (destination, sp) in elements {
if let Ok(hir_id) = destination.target_id
&& let hir::Node::Expr(expr) = tcx.hir().hir_node(hir_id)
&& let hir::Node::Expr(expr) = tcx.hir_node(hir_id)
&& !matches!(
sp.desugaring_kind(),
Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
@ -1437,7 +1437,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let Some(hir_generics) = tcx
.typeck_root_def_id(self.mir_def_id().to_def_id())
.as_local()
.and_then(|def_id| tcx.hir().get_generics(def_id))
.and_then(|def_id| tcx.hir_get_generics(def_id))
else {
return;
};
@ -1889,7 +1889,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
let tcx = self.infcx.tcx;
let hir = tcx.hir();
let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
struct FindUselessClone<'tcx> {
@ -1917,7 +1916,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
let body = hir.body(body_id).value;
let body = tcx.hir_body(body_id).value;
expr_finder.visit_expr(body);
struct Holds<'tcx> {
@ -2106,7 +2105,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let tcx = self.infcx.tcx;
let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
let mut expr_finder = FindExprBySpan::new(span, tcx);
expr_finder.visit_expr(tcx.hir().body(body_id).value);
expr_finder.visit_expr(tcx.hir_body(body_id).value);
expr_finder.result
}
@ -2258,7 +2257,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
) {
let issue_span = issued_spans.args_or_use();
let tcx = self.infcx.tcx;
let hir = tcx.hir();
let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
let typeck_results = tcx.typeck(self.mir_def_id());
@ -2346,7 +2344,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
pat_span: None,
head: None,
};
finder.visit_expr(hir.body(body_id).value);
finder.visit_expr(tcx.hir_body(body_id).value);
if let Some(body_expr) = finder.body_expr
&& let Some(loop_span) = finder.loop_span
@ -2445,7 +2443,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
) {
let &UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return };
let tcx = self.infcx.tcx;
let hir = tcx.hir();
// Get the type of the local that we are trying to borrow
let local = borrowed_place.local;
@ -2454,10 +2451,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// Get the body the error happens in
let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
let body_expr = hir.body(body_id).value;
let body_expr = tcx.hir_body(body_id).value;
struct ClosureFinder<'hir> {
hir: rustc_middle::hir::map::Map<'hir>,
tcx: TyCtxt<'hir>,
borrow_span: Span,
res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
/// The path expression with the `borrow_span` span
@ -2466,8 +2463,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
type NestedFilter = OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.hir
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
@ -2493,7 +2490,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// Find the closure that most tightly wraps `capture_kind_span`
let mut finder =
ClosureFinder { hir, borrow_span: capture_kind_span, res: None, error_path: None };
ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
finder.visit_expr(body_expr);
let Some((closure_expr, closure)) = finder.res else { return };
@ -2524,7 +2521,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// Find the first argument with a matching type, get its name
let Some((_, this_name)) =
params.iter().zip(hir.body_param_names(closure.body)).find(|(param_ty, name)| {
params.iter().zip(tcx.hir_body_param_names(closure.body)).find(|(param_ty, name)| {
// FIXME: also support deref for stuff like `Rc` arguments
param_ty.peel_refs() == local_ty && name != &Ident::empty()
})
@ -2558,7 +2555,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
finder.visit_expr(hir.body(closure.body).value);
finder.visit_expr(tcx.hir_body(closure.body).value);
spans = finder.spans;
} else {
@ -3211,7 +3208,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if let Some(scope) = self.body.source_scopes.get(source_info.scope)
&& let ClearCrossCrate::Set(scope_data) = &scope.local_data
&& let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
&& let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir().body(id).value.kind
&& let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
{
for stmt in block.stmts {
let mut visitor = NestedStatementVisitor {
@ -4180,7 +4177,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
let is_closure = self.infcx.tcx.is_closure_like(did.to_def_id());
let fn_hir_id = self.infcx.tcx.local_def_id_to_hir_id(did);
let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(fn_hir_id)?;
// We need to work out which arguments to highlight. We do this by looking
// at the return type, where there are three cases:

View file

@ -75,10 +75,10 @@ impl<'tcx> BorrowExplanation<'tcx> {
if let Some(span) = borrow_span {
let def_id = body.source.def_id();
if let Some(node) = tcx.hir().get_if_local(def_id)
if let Some(node) = tcx.hir_get_if_local(def_id)
&& let Some(body_id) = node.body_id()
{
let body = tcx.hir().body(body_id);
let body = tcx.hir_body(body_id);
let mut expr_finder = FindExprBySpan::new(span, tcx);
expr_finder.visit_expr(body.value);
if let Some(mut expr) = expr_finder.result {
@ -256,8 +256,8 @@ impl<'tcx> BorrowExplanation<'tcx> {
impl<'hir> rustc_hir::intravisit::Visitor<'hir> for FindLetExpr<'hir> {
type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
if let hir::ExprKind::If(cond, _conseq, _alt)
@ -308,9 +308,9 @@ impl<'tcx> BorrowExplanation<'tcx> {
suggest_rewrite_if_let(tcx, expr, &pat, init, conseq, alt, err);
} else if let Some((old, new)) = multiple_borrow_span
&& let def_id = body.source.def_id()
&& let Some(node) = tcx.hir().get_if_local(def_id)
&& let Some(node) = tcx.hir_get_if_local(def_id)
&& let Some(body_id) = node.body_id()
&& let hir_body = tcx.hir().body(body_id)
&& let hir_body = tcx.hir_body(body_id)
&& let mut expr_finder = (FindLetExpr { span: old, result: None, tcx })
&& let Some((let_expr_span, let_expr_pat, let_expr_init)) = {
expr_finder.visit_expr(hir_body.value);

View file

@ -13,10 +13,9 @@ use rustc_infer::infer::{
};
use rustc_infer::traits::SelectionError;
use rustc_middle::bug;
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::{
AggregateKind, CallSource, ConstOperand, ConstraintCategory, FakeReadCause, Local, LocalInfo,
LocalKind, Location, Operand, Place, PlaceRef, ProjectionElem, Rvalue, Statement,
LocalKind, Location, Operand, Place, PlaceRef, PlaceTy, ProjectionElem, Rvalue, Statement,
StatementKind, Terminator, TerminatorKind, find_self_call,
};
use rustc_middle::ty::print::Print;
@ -1220,7 +1219,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.tcx
.typeck_root_def_id(self.mir_def_id().to_def_id())
.as_local()
.and_then(|def_id| self.infcx.tcx.hir().get_generics(def_id))
.and_then(|def_id| self.infcx.tcx.hir_get_generics(def_id))
&& let spans = hir_generics
.predicates
.iter()

View file

@ -7,7 +7,7 @@ use rustc_hir::intravisit::Visitor;
use rustc_hir::{self as hir, CaptureBy, ExprKind, HirId, Node};
use rustc_middle::bug;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_mir_dataflow::move_paths::{LookupResult, MovePathIndex};
use rustc_span::{BytePos, ExpnKind, MacroKind, Span};
use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
@ -347,7 +347,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// Find the closure that captured the binding.
let mut expr_finder = FindExprBySpan::new(args_span, tcx);
expr_finder.include_closures = true;
expr_finder.visit_expr(tcx.hir().body(body_id).value);
expr_finder.visit_expr(tcx.hir_body(body_id).value);
let Some(closure_expr) = expr_finder.result else { return };
let ExprKind::Closure(closure) = closure_expr.kind else { return };
// We'll only suggest cloning the binding if it's a `move` closure.
@ -357,7 +357,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let use_span = use_spans.var_or_use();
let mut expr_finder = FindExprBySpan::new(use_span, tcx);
expr_finder.include_closures = true;
expr_finder.visit_expr(tcx.hir().body(body_id).value);
expr_finder.visit_expr(tcx.hir_body(body_id).value);
let Some(use_expr) = expr_finder.result else { return };
let parent = tcx.parent_hir_node(use_expr.hir_id);
if let Node::Expr(expr) = parent
@ -690,7 +690,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
/// make it bind by reference instead (if possible)
struct BindingFinder<'tcx> {
typeck_results: &'tcx ty::TypeckResults<'tcx>,
hir: rustc_middle::hir::map::Map<'tcx>,
tcx: TyCtxt<'tcx>,
/// Input: the span of the pattern we're finding bindings in
pat_span: Span,
/// Input: the spans of the bindings we're providing suggestions for
@ -709,8 +709,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
impl<'tcx> Visitor<'tcx> for BindingFinder<'tcx> {
type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.hir
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
@ -777,12 +777,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
let Some(pat_span) = pat_span else { return };
let hir = self.infcx.tcx.hir();
let Some(body) = hir.maybe_body_owned_by(self.mir_def_id()) else { return };
let tcx = self.infcx.tcx;
let Some(body) = tcx.hir_maybe_body_owned_by(self.mir_def_id()) else { return };
let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
let mut finder = BindingFinder {
typeck_results,
hir,
tcx,
pat_span,
binding_spans,
found_pat: false,

View file

@ -648,10 +648,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
}
}
let hir_map = self.infcx.tcx.hir();
let def_id = self.body.source.def_id();
let Some(local_def_id) = def_id.as_local() else { return };
let Some(body) = hir_map.maybe_body_owned_by(local_def_id) else { return };
let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(local_def_id) else { return };
let mut v = SuggestIndexOperatorAlternativeVisitor {
assign_span: span,
@ -749,7 +748,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// `fn foo(&x: &i32)` -> `fn foo(&(mut x): &i32)`
let def_id = self.body.source.def_id();
if let Some(local_def_id) = def_id.as_local()
&& let Some(body) = self.infcx.tcx.hir().maybe_body_owned_by(local_def_id)
&& let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(local_def_id)
&& let Some(hir_id) = (BindingFinder { span: pat_span }).visit_body(&body).break_value()
&& let node = self.infcx.tcx.hir_node(hir_id)
&& let hir::Node::LetStmt(hir::LetStmt {
@ -856,7 +855,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
use hir::ExprKind::{AddrOf, Block, Call, MethodCall};
use hir::{BorrowKind, Expr};
let hir_map = self.infcx.tcx.hir();
let tcx = self.infcx.tcx;
struct Finder {
span: Span,
}
@ -871,7 +870,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
}
}
if let Some(body) = hir_map.maybe_body_owned_by(self.mir_def_id())
if let Some(body) = tcx.hir_maybe_body_owned_by(self.mir_def_id())
&& let Block(block, _) = body.value.kind
{
// `span` corresponds to the expression being iterated, find the `for`-loop desugared
@ -884,17 +883,15 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
MethodCall(path_segment, _, _, span) => {
// We have `for _ in iter.read_only_iter()`, try to
// suggest `for _ in iter.mutable_iter()` instead.
let opt_suggestions = self
.infcx
.tcx
let opt_suggestions = tcx
.typeck(path_segment.hir_id.owner.def_id)
.type_dependent_def_id(expr.hir_id)
.and_then(|def_id| self.infcx.tcx.impl_of_method(def_id))
.map(|def_id| self.infcx.tcx.associated_items(def_id))
.and_then(|def_id| tcx.impl_of_method(def_id))
.map(|def_id| tcx.associated_items(def_id))
.map(|assoc_items| {
assoc_items
.in_definition_order()
.map(|assoc_item_def| assoc_item_def.ident(self.infcx.tcx))
.map(|assoc_item_def| assoc_item_def.ident(tcx))
.filter(|&ident| {
let original_method_ident = path_segment.ident;
original_method_ident != ident
@ -936,12 +933,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
fn expected_fn_found_fn_mut_call(&self, err: &mut Diag<'_>, sp: Span, act: &str) {
err.span_label(sp, format!("cannot {act}"));
let hir = self.infcx.tcx.hir();
let tcx = self.infcx.tcx;
let hir = tcx.hir();
let closure_id = self.mir_hir_id();
let closure_span = self.infcx.tcx.def_span(self.mir_def_id());
let fn_call_id = self.infcx.tcx.parent_hir_id(closure_id);
let node = self.infcx.tcx.hir_node(fn_call_id);
let def_id = hir.enclosing_body_owner(fn_call_id);
let closure_span = tcx.def_span(self.mir_def_id());
let fn_call_id = tcx.parent_hir_id(closure_id);
let node = tcx.hir_node(fn_call_id);
let def_id = tcx.hir_enclosing_body_owner(fn_call_id);
let mut look_at_return = true;
// If the HIR node is a function or method call gets the def ID
@ -951,7 +949,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
return None;
};
let typeck_results = self.infcx.tcx.typeck(def_id);
let typeck_results = tcx.typeck(def_id);
match kind {
hir::ExprKind::Call(expr, args) => {
@ -980,7 +978,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.map(|(pos, _)| pos)
.next();
let arg = match hir.get_if_local(callee_def_id) {
let arg = match tcx.hir_get_if_local(callee_def_id) {
Some(
hir::Node::Item(hir::Item {
ident, kind: hir::ItemKind::Fn { sig, .. }, ..
@ -1022,7 +1020,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if look_at_return && hir.get_fn_id_for_return_block(closure_id).is_some() {
// ...otherwise we are probably in the tail expression of the function, point at the
// return type.
match self.infcx.tcx.hir_node_by_def_id(hir.get_parent_item(fn_call_id).def_id) {
match tcx.hir_node_by_def_id(hir.get_parent_item(fn_call_id).def_id) {
hir::Node::Item(hir::Item {
ident, kind: hir::ItemKind::Fn { sig, .. }, ..
})
@ -1050,9 +1048,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
fn suggest_using_iter_mut(&self, err: &mut Diag<'_>) {
let source = self.body.source;
let hir = self.infcx.tcx.hir();
if let InstanceKind::Item(def_id) = source.instance
&& let Some(Node::Expr(hir::Expr { hir_id, kind, .. })) = hir.get_if_local(def_id)
&& let Some(Node::Expr(hir::Expr { hir_id, kind, .. })) =
self.infcx.tcx.hir_get_if_local(def_id)
&& let ExprKind::Closure(hir::Closure { kind: hir::ClosureKind::Closure, .. }) = kind
&& let Node::Expr(expr) = self.infcx.tcx.parent_hir_node(*hir_id)
{
@ -1274,7 +1272,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}) => {
let def_id = self.body.source.def_id();
let hir_id = if let Some(local_def_id) = def_id.as_local()
&& let Some(body) = self.infcx.tcx.hir().maybe_body_owned_by(local_def_id)
&& let Some(body) = self.infcx.tcx.hir_maybe_body_owned_by(local_def_id)
{
BindingFinder { span: err_label_span }.visit_body(&body).break_value()
} else {

View file

@ -219,7 +219,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
lower_bound: RegionVid,
) {
let mut suggestions = vec![];
let hir = self.infcx.tcx.hir();
let tcx = self.infcx.tcx;
// find generic associated types in the given region 'lower_bound'
let gat_id_and_generics = self
@ -228,12 +228,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.map(|placeholder| {
if let Some(id) = placeholder.bound.kind.get_id()
&& let Some(placeholder_id) = id.as_local()
&& let gat_hir_id = self.infcx.tcx.local_def_id_to_hir_id(placeholder_id)
&& let Some(generics_impl) = self
.infcx
.tcx
.parent_hir_node(self.infcx.tcx.parent_hir_id(gat_hir_id))
.generics()
&& let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
&& let Some(generics_impl) =
tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
{
Some((gat_hir_id, generics_impl))
} else {
@ -254,7 +251,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
};
if bound_generic_params
.iter()
.rfind(|bgp| self.infcx.tcx.local_def_id_to_hir_id(bgp.def_id) == *gat_hir_id)
.rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == *gat_hir_id)
.is_some()
{
for bound in *bounds {
@ -270,7 +267,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
return;
};
diag.span_note(*trait_span, fluent::borrowck_limitations_implies_static);
let Some(generics_fn) = hir.get_generics(self.body.source.def_id().expect_local())
let Some(generics_fn) = tcx.hir_get_generics(self.body.source.def_id().expect_local())
else {
return;
};
@ -1162,7 +1159,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if ocx.select_all_or_error().is_empty() && count > 0 {
diag.span_suggestion_verbose(
tcx.hir().body(*body).value.peel_blocks().span.shrink_to_lo(),
tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
fluent::borrowck_dereference_suggestion,
"*".repeat(count),
Applicability::MachineApplicable,
@ -1172,8 +1169,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
#[allow(rustc::diagnostic_outside_of_impl)]
fn suggest_move_on_borrowing_closure(&self, diag: &mut Diag<'_>) {
let map = self.infcx.tcx.hir();
let body = map.body_owned_by(self.mir_def_id());
let body = self.infcx.tcx.hir_body_owned_by(self.mir_def_id());
let expr = &body.value.peel_blocks();
let mut closure_span = None::<rustc_span::Span>;
match expr.kind {

View file

@ -424,7 +424,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
&self,
argument_index: usize,
) -> Option<&hir::Ty<'tcx>> {
let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(self.mir_hir_id())?;
let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(self.mir_hir_id())?;
let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
match argument_hir_ty.kind {
// This indicates a variable with no type annotation, like

View file

@ -33,7 +33,6 @@ use rustc_index::{IndexSlice, IndexVec};
use rustc_infer::infer::{
InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin, TyCtxtInferExt,
};
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::*;
use rustc_middle::query::Providers;
use rustc_middle::ty::fold::fold_regions;
@ -188,7 +187,7 @@ fn do_mir_borrowck<'tcx>(
.iterate_to_fixpoint(tcx, body, Some("borrowck"))
.into_results_cursor(body);
let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(def).is_fn_or_closure();
let locals_are_invalidated_at_exit = tcx.hir_body_owner_kind(def).is_fn_or_closure();
let borrow_set = BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &move_data);
// Compute non-lexical lifetimes.

View file

@ -1267,6 +1267,11 @@ impl<'tcx> RegionInferenceContext<'tcx> {
let sub_region_scc = self.constraint_sccs.scc(sub_region);
let sup_region_scc = self.constraint_sccs.scc(sup_region);
if sub_region_scc == sup_region_scc {
debug!("{sup_region:?}: {sub_region:?} holds trivially; they are in the same SCC");
return true;
}
// If we are checking that `'sup: 'sub`, and `'sub` contains
// some placeholder that `'sup` cannot name, then this is only
// true if `'sup` outlives static.

View file

@ -19,7 +19,6 @@ use rustc_infer::infer::{
BoundRegion, BoundRegionConversionTime, InferCtxt, NllRegionVariableOrigin,
};
use rustc_infer::traits::PredicateObligations;
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
use rustc_middle::mir::*;
use rustc_middle::traits::query::NoSolution;

View file

@ -21,6 +21,7 @@ use std::iter;
use rustc_data_structures::fx::FxIndexMap;
use rustc_errors::Diag;
use rustc_hir::BodyOwnerKind;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::lang_items::LangItem;
use rustc_index::IndexVec;
@ -576,7 +577,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> {
let tcx = self.infcx.tcx;
let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.to_def_id());
match tcx.hir().body_owner_kind(self.mir_def) {
match tcx.hir_body_owner_kind(self.mir_def) {
BodyOwnerKind::Closure | BodyOwnerKind::Fn => {
let defining_ty = tcx.type_of(self.mir_def).instantiate_identity();
@ -603,7 +604,10 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> {
BodyOwnerKind::Const { .. } | BodyOwnerKind::Static(..) => {
let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id);
if self.mir_def.to_def_id() == typeck_root_def_id {
if self.mir_def.to_def_id() == typeck_root_def_id
// Do not ICE when checking default_field_values consts with lifetimes (#135649)
&& DefKind::Field != tcx.def_kind(tcx.parent(typeck_root_def_id))
{
let args =
self.infcx.replace_free_regions_with_nll_infer_vars(FR, identity_args);
DefiningTy::Const(self.mir_def.to_def_id(), args)

View file

@ -65,7 +65,7 @@ pub(super) fn add_locals_header_comment(fx: &mut FunctionCx<'_, '_, '_>) {
if fx.clif_comments.enabled() {
fx.add_global_comment(String::new());
fx.add_global_comment(
"kind local ty size align (abi,pref)".to_string(),
"kind local ty size align (abi)".to_string(),
);
}
}
@ -84,14 +84,13 @@ pub(super) fn add_local_place_comments<'tcx>(
let (kind, extra) = place.debug_comment();
fx.add_global_comment(format!(
"{:<5} {:5} {:30} {:4}b {}, {}{}{}",
"{:<5} {:5} {:30} {:4}b {}{}{}",
kind,
format!("{:?}", local),
format!("{:?}", ty),
size.bytes(),
align.abi.bytes(),
align.pref.bytes(),
if extra.is_empty() { "" } else { " " },
if extra.is_empty() { "" } else { " " },
extra,
));
}

View file

@ -272,7 +272,7 @@ fn data_id_for_static(
.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty))
.unwrap()
.align
.pref
.abi
.bytes();
let linkage = if import_linkage == rustc_middle::mir::mono::Linkage::ExternalWeak

View file

@ -124,7 +124,7 @@ pub(crate) fn run_jit(tcx: TyCtxt<'_>, codegen_mode: CodegenMode, jit_args: Vec<
crate::constant::codegen_static(tcx, &mut jit_module, def_id);
}
MonoItem::GlobalAsm(item_id) => {
let item = tcx.hir().item(item_id);
let item = tcx.hir_item(item_id);
tcx.dcx().span_fatal(item.span, "Global asm is not supported in JIT mode");
}
}

View file

@ -15,7 +15,7 @@ use rustc_target::asm::InlineAsmArch;
use crate::prelude::*;
pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String, item_id: ItemId) {
let item = tcx.hir().item(item_id);
let item = tcx.hir_item(item_id);
if let rustc_hir::ItemKind::GlobalAsm(asm) = item.kind {
let is_x86 =
matches!(tcx.sess.asm_arch.unwrap(), InlineAsmArch::X86 | InlineAsmArch::X86_64);

View file

@ -25,6 +25,7 @@ rustc_data_structures = { path = "../rustc_data_structures" }
rustc_errors = { path = "../rustc_errors" }
rustc_fluent_macro = { path = "../rustc_fluent_macro" }
rustc_fs_util = { path = "../rustc_fs_util" }
rustc_hashes = { path = "../rustc_hashes" }
rustc_hir = { path = "../rustc_hir" }
rustc_index = { path = "../rustc_index" }
rustc_llvm = { path = "../rustc_llvm" }

View file

@ -2,19 +2,18 @@ use std::borrow::Borrow;
use std::cmp;
use libc::c_uint;
use rustc_abi as abi;
pub(crate) use rustc_abi::ExternAbi;
use rustc_abi::{HasDataLayout, Primitive, Reg, RegKind, Size};
use rustc_abi::{BackendRepr, HasDataLayout, Primitive, Reg, RegKind, Size};
use rustc_codegen_ssa::MemFlags;
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue};
use rustc_codegen_ssa::traits::*;
use rustc_middle::ty::Ty;
use rustc_middle::ty::layout::LayoutOf;
pub(crate) use rustc_middle::ty::layout::{WIDE_PTR_ADDR, WIDE_PTR_EXTRA};
use rustc_middle::{bug, ty};
use rustc_session::config;
pub(crate) use rustc_target::callconv::*;
use rustc_target::callconv::{
ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, CastTarget, Conv, FnAbi, PassMode,
};
use rustc_target::spec::SanitizerSet;
use smallvec::SmallVec;
@ -458,7 +457,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
match &self.ret.mode {
PassMode::Direct(attrs) => {
attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
if let abi::BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
if let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr {
apply_range_attr(llvm::AttributePlace::ReturnValue, scalar);
}
}
@ -499,7 +498,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
}
PassMode::Direct(attrs) => {
let i = apply(attrs);
if let abi::BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
apply_range_attr(llvm::AttributePlace::Argument(i), scalar);
}
}
@ -514,9 +513,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
PassMode::Pair(a, b) => {
let i = apply(a);
let ii = apply(b);
if let abi::BackendRepr::ScalarPair(scalar_a, scalar_b) =
arg.layout.backend_repr
{
if let BackendRepr::ScalarPair(scalar_a, scalar_b) = arg.layout.backend_repr {
apply_range_attr(llvm::AttributePlace::Argument(i), scalar_a);
apply_range_attr(llvm::AttributePlace::Argument(ii), scalar_b);
}
@ -576,7 +573,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
}
if bx.cx.sess().opts.optimize != config::OptLevel::No
&& llvm_util::get_version() < (19, 0, 0)
&& let abi::BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr
&& let BackendRepr::Scalar(scalar) = self.ret.layout.backend_repr
&& matches!(scalar.primitive(), Primitive::Int(..))
// If the value is a boolean, the range is 0..2 and that ultimately
// become 0..0 when the type becomes i1, which would be rejected

View file

@ -7,7 +7,8 @@ use rustc_abi::{AddressSpace, HasDataLayout};
use rustc_ast::Mutability;
use rustc_codegen_ssa::common::TypeKind;
use rustc_codegen_ssa::traits::*;
use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher};
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_hashes::Hash128;
use rustc_hir::def_id::DefId;
use rustc_middle::bug;
use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar};

View file

@ -87,7 +87,7 @@ pub(crate) fn get_or_insert_gdb_debug_scripts_section_global<'ll>(
pub(crate) fn needs_gdb_debug_scripts_section(cx: &CodegenCx<'_, '_>) -> bool {
let omit_gdb_pretty_printer_section =
attr::contains_name(cx.tcx.hir().krate_attrs(), sym::omit_gdb_pretty_printer_section);
attr::contains_name(cx.tcx.hir_krate_attrs(), sym::omit_gdb_pretty_printer_section);
// To ensure the section `__rustc_debug_gdb_scripts_section__` will not create
// ODR violations at link time, this section will not be emitted for rlibs since

View file

@ -11,7 +11,9 @@ use rustc_codegen_ssa::traits::*;
use rustc_hir::def::{CtorKind, DefKind};
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_middle::bug;
use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf, TyAndLayout};
use rustc_middle::ty::layout::{
HasTypingEnv, LayoutOf, TyAndLayout, WIDE_PTR_ADDR, WIDE_PTR_EXTRA,
};
use rustc_middle::ty::{
self, AdtKind, CoroutineArgsExt, ExistentialTraitRef, Instance, Ty, TyCtxt, Visibility,
};
@ -34,12 +36,12 @@ use crate::common::{AsCCharPtr, CodegenCx};
use crate::debuginfo::dwarf_const;
use crate::debuginfo::metadata::type_map::build_type_with_children;
use crate::debuginfo::utils::{WidePtrKind, wide_pointer_kind};
use crate::llvm;
use crate::llvm::debuginfo::{
DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType, DebugEmissionKind,
DebugNameTableKind,
};
use crate::value::Value;
use crate::{abi, llvm};
impl PartialEq for llvm::Metadata {
fn eq(&self, other: &Self) -> bool {
@ -211,16 +213,16 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>(
};
let layout = cx.layout_of(layout_type);
let addr_field = layout.field(cx, abi::WIDE_PTR_ADDR);
let extra_field = layout.field(cx, abi::WIDE_PTR_EXTRA);
let addr_field = layout.field(cx, WIDE_PTR_ADDR);
let extra_field = layout.field(cx, WIDE_PTR_EXTRA);
let (addr_field_name, extra_field_name) = match wide_pointer_kind {
WidePtrKind::Dyn => ("pointer", "vtable"),
WidePtrKind::Slice => ("data_ptr", "length"),
};
assert_eq!(abi::WIDE_PTR_ADDR, 0);
assert_eq!(abi::WIDE_PTR_EXTRA, 1);
assert_eq!(WIDE_PTR_ADDR, 0);
assert_eq!(WIDE_PTR_EXTRA, 1);
// The data pointer type is a regular, thin pointer, regardless of whether this
// is a slice or a trait object.
@ -242,7 +244,7 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>(
owner,
addr_field_name,
(addr_field.size, addr_field.align.abi),
layout.fields.offset(abi::WIDE_PTR_ADDR),
layout.fields.offset(WIDE_PTR_ADDR),
DIFlags::FlagZero,
data_ptr_type_di_node,
None,
@ -252,7 +254,7 @@ fn build_pointer_or_reference_di_node<'ll, 'tcx>(
owner,
extra_field_name,
(extra_field.size, extra_field.align.abi),
layout.fields.offset(abi::WIDE_PTR_EXTRA),
layout.fields.offset(WIDE_PTR_EXTRA),
DIFlags::FlagZero,
type_di_node(cx, extra_field.ty),
None,

View file

@ -22,6 +22,7 @@ use rustc_session::config::{self, DebugInfo};
use rustc_span::{
BytePos, Pos, SourceFile, SourceFileAndLine, SourceFileHash, Span, StableSourceFileId, Symbol,
};
use rustc_target::callconv::FnAbi;
use rustc_target::spec::DebuginfoKind;
use smallvec::SmallVec;
use tracing::debug;
@ -29,7 +30,6 @@ use tracing::debug;
use self::metadata::{UNKNOWN_COLUMN_NUMBER, UNKNOWN_LINE_NUMBER, file_metadata, type_di_node};
use self::namespace::mangled_name_of_instance;
use self::utils::{DIB, create_DIArray, is_node_local_to_unit};
use crate::abi::FnAbi;
use crate::builder::Builder;
use crate::common::{AsCCharPtr, CodegenCx};
use crate::llvm;

View file

@ -16,10 +16,11 @@ use rustc_codegen_ssa::traits::TypeMembershipCodegenMethods;
use rustc_data_structures::fx::FxIndexSet;
use rustc_middle::ty::{Instance, Ty};
use rustc_sanitizers::{cfi, kcfi};
use rustc_target::callconv::FnAbi;
use smallvec::SmallVec;
use tracing::debug;
use crate::abi::{FnAbi, FnAbiLlvmExt};
use crate::abi::FnAbiLlvmExt;
use crate::common::AsCCharPtr;
use crate::context::{CodegenCx, SimpleCx};
use crate::llvm::AttributePlace::Function;

View file

@ -1,7 +1,7 @@
use std::assert_matches::assert_matches;
use std::cmp::Ordering;
use rustc_abi::{self as abi, Align, Float, HasDataLayout, Primitive, Size};
use rustc_abi::{Align, BackendRepr, ExternAbi, Float, HasDataLayout, Primitive, Size};
use rustc_codegen_ssa::base::{compare_simd_types, wants_msvc_seh, wants_wasm_eh};
use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
use rustc_codegen_ssa::errors::{ExpectedPointerMutability, InvalidMonomorphization};
@ -14,10 +14,11 @@ use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf};
use rustc_middle::ty::{self, GenericArgsRef, Ty};
use rustc_middle::{bug, span_bug};
use rustc_span::{Span, Symbol, sym};
use rustc_target::callconv::{FnAbi, PassMode};
use rustc_target::spec::{HasTargetSpec, PanicStrategy};
use tracing::debug;
use crate::abi::{ExternAbi, FnAbi, FnAbiLlvmExt, LlvmType, PassMode};
use crate::abi::{FnAbiLlvmExt, LlvmType};
use crate::builder::Builder;
use crate::context::CodegenCx;
use crate::llvm::{self, Metadata};
@ -257,7 +258,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
}
sym::va_arg => {
match fn_abi.ret.layout.backend_repr {
abi::BackendRepr::Scalar(scalar) => {
BackendRepr::Scalar(scalar) => {
match scalar.primitive() {
Primitive::Int(..) => {
if self.cx().size_of(ret_ty).bytes() < 4 {
@ -470,7 +471,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
}
sym::raw_eq => {
use abi::BackendRepr::*;
use BackendRepr::*;
let tp_ty = fn_args.type_at(0);
let layout = self.layout_of(tp_ty).layout;
let use_integer_compare = match layout.backend_repr() {
@ -582,8 +583,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
}
let llret_ty = if ret_ty.is_simd()
&& let abi::BackendRepr::Memory { .. } =
self.layout_of(ret_ty).layout.backend_repr
&& let BackendRepr::Memory { .. } = self.layout_of(ret_ty).layout.backend_repr
{
let (size, elem_ty) = ret_ty.simd_size_and_type(self.tcx());
let elem_ll_ty = match elem_ty.kind() {

View file

@ -25,6 +25,7 @@ rustc_data_structures = { path = "../rustc_data_structures" }
rustc_errors = { path = "../rustc_errors" }
rustc_fluent_macro = { path = "../rustc_fluent_macro" }
rustc_fs_util = { path = "../rustc_fs_util" }
rustc_hashes = { path = "../rustc_hashes" }
rustc_hir = { path = "../rustc_hir" }
rustc_hir_pretty = { path = "../rustc_hir_pretty" }
rustc_incremental = { path = "../rustc_incremental" }

View file

@ -15,7 +15,8 @@ use std::fmt::Write;
use rustc_abi::Integer;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher};
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_hashes::Hash64;
use rustc_hir::def_id::DefId;
use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData};
use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, Mutability};

View file

@ -1,7 +1,7 @@
use rustc_abi::Primitive::{Int, Pointer};
use rustc_abi::{Align, BackendRepr, FieldsShape, Size, TagEncoding, VariantIdx, Variants};
use rustc_middle::mir::PlaceTy;
use rustc_middle::mir::interpret::Scalar;
use rustc_middle::mir::tcx::PlaceTy;
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
use rustc_middle::ty::{self, Ty};
use rustc_middle::{bug, mir};

View file

@ -35,7 +35,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
cx.codegen_static(def_id);
}
MonoItem::GlobalAsm(item_id) => {
let item = cx.tcx().hir().item(item_id);
let item = cx.tcx().hir_item(item_id);
if let hir::ItemKind::GlobalAsm(asm) = item.kind {
let operands: Vec<_> = asm
.operands

View file

@ -31,7 +31,7 @@ pub struct ConstCx<'mir, 'tcx> {
impl<'mir, 'tcx> ConstCx<'mir, 'tcx> {
pub fn new(tcx: TyCtxt<'tcx>, body: &'mir mir::Body<'tcx>) -> Self {
let typing_env = body.typing_env(tcx);
let const_kind = tcx.hir().body_const_context(body.source.def_id().expect_local());
let const_kind = tcx.hir_body_const_context(body.source.def_id().expect_local());
ConstCx { body, tcx, typing_env, const_kind }
}

View file

@ -18,6 +18,7 @@ rustc-rayon = { version = "0.5.1", features = ["indexmap"] }
rustc-stable-hash = { version = "0.1.0", features = ["nightly"] }
rustc_arena = { path = "../rustc_arena" }
rustc_graphviz = { path = "../rustc_graphviz" }
rustc_hashes = { path = "../rustc_hashes" }
rustc_index = { path = "../rustc_index", package = "rustc_index" }
rustc_macros = { path = "../rustc_macros" }
rustc_serialize = { path = "../rustc_serialize" }

View file

@ -1,10 +1,9 @@
use std::hash::{Hash, Hasher};
use rustc_hashes::Hash64;
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use crate::stable_hasher::{
FromStableHash, Hash64, StableHasherHash, impl_stable_traits_for_trivial_type,
};
use crate::stable_hasher::{FromStableHash, StableHasherHash, impl_stable_traits_for_trivial_type};
#[cfg(test)]
mod tests;

View file

@ -92,7 +92,10 @@ impl<'a, T: Ord> Ord for Interned<'a, T> {
}
}
impl<'a, T> Hash for Interned<'a, T> {
impl<'a, T> Hash for Interned<'a, T>
where
T: Hash,
{
#[inline]
fn hash<H: Hasher>(&self, s: &mut H) {
// Pointer hashing is sufficient, due to the uniqueness constraint.

View file

@ -84,7 +84,6 @@ pub mod vec_cache;
pub mod work_queue;
mod atomic_ref;
mod hashes;
/// This calls the passed function while ensuring it won't be inlined into the caller.
#[inline(never)]

View file

@ -10,12 +10,11 @@ use smallvec::SmallVec;
#[cfg(test)]
mod tests;
use rustc_hashes::{Hash64, Hash128};
pub use rustc_stable_hash::{
FromStableHash, SipHasher128Hash as StableHasherHash, StableSipHasher128 as StableHasher,
};
pub use crate::hashes::{Hash64, Hash128};
/// Something that implements `HashStable<CTX>` can be hashed in a way that is
/// stable across multiple compilation sessions.
///

View file

@ -1,7 +1,8 @@
use std::ptr;
use rustc_hashes::Hash128;
use super::*;
use crate::hashes::Hash128;
use crate::stable_hasher::{HashStable, StableHasher};
/// A tag type used in [`TaggedRef`] tests.

View file

@ -164,8 +164,7 @@ impl<'tcx> pprust_hir::PpAnn for HirTypedAnn<'tcx> {
if let pprust_hir::AnnNode::Expr(expr) = node {
let typeck_results = self.maybe_typeck_results.get().or_else(|| {
self.tcx
.hir()
.maybe_body_owned_by(expr.hir_id.owner.def_id)
.hir_maybe_body_owned_by(expr.hir_id.owner.def_id)
.map(|body_id| self.tcx.typeck_body(body_id.id()))
});
@ -273,7 +272,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
let attrs = |id| hir_map.attrs(id);
pprust_hir::print_crate(
sm,
hir_map.root_module(),
tcx.hir_root_module(),
src_name,
src,
&attrs,
@ -294,7 +293,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
}
HirTree => {
debug!("pretty printing HIR tree");
format!("{:#?}", ex.tcx().hir().krate())
format!("{:#?}", ex.tcx().hir_crate(()))
}
Mir => {
let mut out = Vec::new();
@ -317,7 +316,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
rustc_hir_analysis::check_crate(tcx);
tcx.dcx().abort_if_errors();
debug!("pretty printing THIR tree");
for did in tcx.hir().body_owners() {
for did in tcx.hir_body_owners() {
let _ = writeln!(out, "{:?}:\n{}\n", did, thir_tree(tcx, did));
}
out
@ -328,7 +327,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
rustc_hir_analysis::check_crate(tcx);
tcx.dcx().abort_if_errors();
debug!("pretty printing THIR flat");
for did in tcx.hir().body_owners() {
for did in tcx.hir_body_owners() {
let _ = writeln!(out, "{:?}:\n{}\n", did, thir_flat(tcx, did));
}
out

View file

@ -6,6 +6,15 @@ use std::{fmt, mem, ptr, slice};
use rustc_interface::util::{DEFAULT_STACK_SIZE, STACK_SIZE};
/// Signals that represent that we have a bug, and our prompt termination has
/// been ordered.
#[rustfmt::skip]
const KILL_SIGNALS: [(libc::c_int, &str); 3] = [
(libc::SIGILL, "SIGILL"),
(libc::SIGBUS, "SIGBUS"),
(libc::SIGSEGV, "SIGSEGV")
];
unsafe extern "C" {
fn backtrace_symbols_fd(buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int);
}
@ -39,8 +48,19 @@ macro raw_errln($tokens:tt) {
/// # Safety
///
/// Caller must ensure that this function is not re-entered.
unsafe extern "C" fn print_stack_trace(_: libc::c_int) {
unsafe extern "C" fn print_stack_trace(signum: libc::c_int) {
const MAX_FRAMES: usize = 256;
let signame = {
let mut signame = "<unknown>";
for sig in KILL_SIGNALS {
if sig.0 == signum {
signame = sig.1;
}
}
signame
};
let stack = unsafe {
// Reserve data segment so we don't have to malloc in a signal handler, which might fail
// in incredibly undesirable and unexpected ways due to e.g. the allocator deadlocking
@ -54,7 +74,8 @@ unsafe extern "C" fn print_stack_trace(_: libc::c_int) {
};
// Just a stack trace is cryptic. Explain what we're doing.
raw_errln!("error: rustc interrupted by SIGSEGV, printing backtrace\n");
raw_errln!("error: rustc interrupted by {signame}, printing backtrace\n");
let mut written = 1;
let mut consumed = 0;
// Begin elaborating return addrs into symbols and writing them directly to stderr
@ -94,7 +115,7 @@ unsafe extern "C" fn print_stack_trace(_: libc::c_int) {
written += rem.len() + 1;
let random_depth = || 8 * 16; // chosen by random diceroll (2d20)
if cyclic || stack.len() > random_depth() {
if (cyclic || stack.len() > random_depth()) && signum == libc::SIGSEGV {
// technically speculation, but assert it with confidence anyway.
// rustc only arrived in this signal handler because bad things happened
// and this message is for explaining it's not the programmer's fault
@ -106,17 +127,22 @@ unsafe extern "C" fn print_stack_trace(_: libc::c_int) {
written += 1;
}
raw_errln!("note: we would appreciate a report at https://github.com/rust-lang/rust");
// get the current stack size WITHOUT blocking and double it
let new_size = STACK_SIZE.get().copied().unwrap_or(DEFAULT_STACK_SIZE) * 2;
raw_errln!("help: you can increase rustc's stack size by setting RUST_MIN_STACK={new_size}");
written += 2;
written += 1;
if signum == libc::SIGSEGV {
// get the current stack size WITHOUT blocking and double it
let new_size = STACK_SIZE.get().copied().unwrap_or(DEFAULT_STACK_SIZE) * 2;
raw_errln!(
"help: you can increase rustc's stack size by setting RUST_MIN_STACK={new_size}"
);
written += 1;
}
if written > 24 {
// We probably just scrolled the earlier "we got SIGSEGV" message off the terminal
raw_errln!("note: backtrace dumped due to SIGSEGV! resuming signal");
// We probably just scrolled the earlier "interrupted by {signame}" message off the terminal
raw_errln!("note: backtrace dumped due to {signame}! resuming signal");
};
}
/// When SIGSEGV is delivered to the process, print a stack trace and then exit.
/// When one of the KILL signals is delivered to the process, print a stack trace and then exit.
pub(super) fn install() {
unsafe {
let alt_stack_size: usize = min_sigstack_size() + 64 * 1024;
@ -129,7 +155,9 @@ pub(super) fn install() {
sa.sa_sigaction = print_stack_trace as libc::sighandler_t;
sa.sa_flags = libc::SA_NODEFER | libc::SA_RESETHAND | libc::SA_ONSTACK;
libc::sigemptyset(&mut sa.sa_mask);
libc::sigaction(libc::SIGSEGV, &sa, ptr::null_mut());
for (signum, _signame) in KILL_SIGNALS {
libc::sigaction(signum, &sa, ptr::null_mut());
}
}
}

View file

@ -0,0 +1,46 @@
A trait implementation returns a reference without an
explicit lifetime linking it to `self`.
It commonly arises in generic trait implementations
requiring explicit lifetime bounds.
Erroneous code example:
```compile_fail,E0803
trait DataAccess<T> {
fn get_ref(&self) -> T;
}
struct Container<'a> {
value: &'a f64,
}
// Attempting to implement reference return
impl<'a> DataAccess<&f64> for Container<'a> {
fn get_ref(&self) -> &f64 { // Error: Lifetime mismatch
self.value
}
}
```
The trait method returns &f64 requiring an independent lifetime
The struct Container<'a> carries lifetime parameter 'a
The compiler cannot verify if the returned reference satisfies 'a constraints
Solution
Explicitly bind lifetimes to clarify constraints:
```
// Modified trait with explicit lifetime binding
trait DataAccess<'a, T> {
fn get_ref(&'a self) -> T;
}
struct Container<'a> {
value: &'a f64,
}
// Correct implementation (bound lifetimes)
impl<'a> DataAccess<'a, &'a f64> for Container<'a> {
fn get_ref(&'a self) -> &'a f64 {
self.value
}
}
```

View file

@ -546,6 +546,7 @@ E0799: 0799,
E0800: 0800,
E0801: 0801,
E0802: 0802,
E0803: 0803,
);
)
}

View file

@ -14,6 +14,7 @@ rustc_data_structures = { path = "../rustc_data_structures" }
rustc_error_codes = { path = "../rustc_error_codes" }
rustc_error_messages = { path = "../rustc_error_messages" }
rustc_fluent_macro = { path = "../rustc_fluent_macro" }
rustc_hashes = { path = "../rustc_hashes" }
rustc_hir = { path = "../rustc_hir" }
rustc_index = { path = "../rustc_index" }
rustc_lexer = { path = "../rustc_lexer" }

View file

@ -58,12 +58,13 @@ pub use emitter::ColorConfig;
use emitter::{DynEmitter, Emitter, is_case_difference, is_different};
use rustc_data_structures::AtomicRef;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
use rustc_data_structures::stable_hasher::{Hash128, StableHasher};
use rustc_data_structures::stable_hasher::StableHasher;
use rustc_data_structures::sync::{DynSend, Lock};
pub use rustc_error_messages::{
DiagMessage, FluentBundle, LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel,
SubdiagMessage, fallback_fluent_bundle, fluent_bundle,
};
use rustc_hashes::Hash128;
use rustc_lint_defs::LintExpectationId;
pub use rustc_lint_defs::{Applicability, listify, pluralize};
use rustc_macros::{Decodable, Encodable};

View file

@ -1,10 +1,13 @@
use std::mem;
use std::sync::Arc;
use rustc_ast::ExprKind;
use rustc_ast::mut_visit::{self, MutVisitor};
use rustc_ast::token::{self, Delimiter, IdentIsRaw, Lit, LitKind, Nonterminal, Token, TokenKind};
use rustc_ast::token::{
self, Delimiter, IdentIsRaw, InvisibleOrigin, Lit, LitKind, MetaVarKind, Nonterminal, Token,
TokenKind,
};
use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree};
use rustc_ast::{ExprKind, TyKind};
use rustc_data_structures::fx::FxHashMap;
use rustc_errors::{Diag, DiagCtxtHandle, PResult, pluralize};
use rustc_parse::lexer::nfc_normalize;
@ -274,6 +277,33 @@ pub(super) fn transcribe<'a>(
// some of the unnecessary whitespace.
let ident = MacroRulesNormalizedIdent::new(original_ident);
if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) {
// We wrap the tokens in invisible delimiters, unless they are already wrapped
// in invisible delimiters with the same `MetaVarKind`. Because some proc
// macros can't multiple layers of invisible delimiters of the same
// `MetaVarKind`. This loses some span info, though it hopefully won't matter.
let mut mk_delimited = |mv_kind, mut stream: TokenStream| {
if stream.len() == 1 {
let tree = stream.iter().next().unwrap();
if let TokenTree::Delimited(_, _, delim, inner) = tree
&& let Delimiter::Invisible(InvisibleOrigin::MetaVar(mvk)) = delim
&& mv_kind == *mvk
{
stream = inner.clone();
}
}
// Emit as a token stream within `Delimiter::Invisible` to maintain
// parsing priorities.
marker.visit_span(&mut sp);
// Both the open delim and close delim get the same span, which covers the
// `$foo` in the decl macro RHS.
TokenTree::Delimited(
DelimSpan::from_single(sp),
DelimSpacing::new(Spacing::Alone, Spacing::Alone),
Delimiter::Invisible(InvisibleOrigin::MetaVar(mv_kind)),
stream,
)
};
let tt = match cur_matched {
MatchedSingle(ParseNtResult::Tt(tt)) => {
// `tt`s are emitted into the output stream directly as "raw tokens",
@ -292,6 +322,13 @@ pub(super) fn transcribe<'a>(
let kind = token::NtLifetime(*ident, *is_raw);
TokenTree::token_alone(kind, sp)
}
MatchedSingle(ParseNtResult::Ty(ty)) => {
let is_path = matches!(&ty.kind, TyKind::Path(None, _path));
mk_delimited(MetaVarKind::Ty { is_path }, TokenStream::from_ast(ty))
}
MatchedSingle(ParseNtResult::Vis(vis)) => {
mk_delimited(MetaVarKind::Vis, TokenStream::from_ast(vis))
}
MatchedSingle(ParseNtResult::Nt(nt)) => {
// Other variables are emitted into the output stream as groups with
// `Delimiter::Invisible` to maintain parsing priorities.

View file

@ -1149,7 +1149,7 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
"the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
),
rustc_attr!(
TEST, pattern_complexity, CrateLevel, template!(NameValueStr: "N"),
TEST, pattern_complexity_limit, CrateLevel, template!(NameValueStr: "N"),
ErrorFollowing, EncodeCrossCrate::No,
),
];

View file

@ -227,7 +227,7 @@ declare_features! (
/// Allows using `#[omit_gdb_pretty_printer_section]`.
(internal, omit_gdb_pretty_printer_section, "1.5.0", None),
/// Set the maximum pattern complexity allowed (not limited by default).
(internal, pattern_complexity, "1.78.0", None),
(internal, pattern_complexity_limit, "1.78.0", None),
/// Allows using pattern types.
(internal, pattern_types, "1.79.0", Some(123646)),
/// Allows using `#[prelude_import]` on glob `use` items.

View file

@ -0,0 +1,9 @@
[package]
name = "rustc_hashes"
version = "0.0.0"
edition = "2021"
[dependencies]
# tidy-alphabetical-start
rustc-stable-hash = { version = "0.1.0" }
# tidy-alphabetical-end

View file

@ -1,6 +1,8 @@
//! rustc encodes a lot of hashes. If hashes are stored as `u64` or `u128`, a `derive(Encodable)`
//! will apply varint encoding to the hashes, which is less efficient than directly encoding the 8
//! or 16 bytes of the hash.
//! or 16 bytes of the hash. And if that hash depends on the `StableCrateHash` (which most in rustc
//! do), the varint encoding will make the number of bytes encoded fluctuate between compiler
//! versions.
//!
//! The types in this module represent 64-bit or 128-bit hashes produced by a `StableHasher`.
//! `Hash64` and `Hash128` expose some utility functions to encourage users to not extract the inner
@ -14,10 +16,9 @@
use std::fmt;
use std::ops::BitXorAssign;
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use crate::stable_hasher::{FromStableHash, StableHasherHash};
use rustc_stable_hash::{FromStableHash, SipHasher128Hash as StableHasherHash};
/// A `u64` but encoded with a fixed size; for hashes this encoding is more compact than `u64`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Hash64 {
inner: u64,
@ -35,6 +36,11 @@ impl Hash64 {
pub fn as_u64(self) -> u64 {
self.inner
}
#[inline]
pub fn wrapping_add(self, other: Self) -> Self {
Self { inner: self.inner.wrapping_add(other.inner) }
}
}
impl BitXorAssign<u64> for Hash64 {
@ -44,20 +50,6 @@ impl BitXorAssign<u64> for Hash64 {
}
}
impl<S: Encoder> Encodable<S> for Hash64 {
#[inline]
fn encode(&self, s: &mut S) {
s.emit_raw_bytes(&self.inner.to_le_bytes());
}
}
impl<D: Decoder> Decodable<D> for Hash64 {
#[inline]
fn decode(d: &mut D) -> Self {
Self { inner: u64::from_le_bytes(d.read_raw_bytes(8).try_into().unwrap()) }
}
}
impl FromStableHash for Hash64 {
type Hash = StableHasherHash;
@ -79,6 +71,7 @@ impl fmt::LowerHex for Hash64 {
}
}
/// A `u128` but encoded with a fixed size; for hashes this encoding is more compact than `u128`.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct Hash128 {
inner: u128,
@ -95,6 +88,11 @@ impl std::hash::Hash for Hash128 {
}
impl Hash128 {
#[inline]
pub fn new(n: u128) -> Self {
Self { inner: n }
}
#[inline]
pub fn truncate(self) -> Hash64 {
Hash64 { inner: self.inner as u64 }
@ -111,20 +109,6 @@ impl Hash128 {
}
}
impl<S: Encoder> Encodable<S> for Hash128 {
#[inline]
fn encode(&self, s: &mut S) {
s.emit_raw_bytes(&self.inner.to_le_bytes());
}
}
impl<D: Decoder> Decodable<D> for Hash128 {
#[inline]
fn decode(d: &mut D) -> Self {
Self { inner: u128::from_le_bytes(d.read_raw_bytes(16).try_into().unwrap()) }
}
}
impl FromStableHash for Hash128 {
type Hash = StableHasherHash;

View file

@ -10,6 +10,7 @@ rustc_abi = { path = "../rustc_abi" }
rustc_arena = { path = "../rustc_arena" }
rustc_ast = { path = "../rustc_ast" }
rustc_data_structures = { path = "../rustc_data_structures" }
rustc_hashes = { path = "../rustc_hashes" }
rustc_index = { path = "../rustc_index" }
rustc_macros = { path = "../rustc_macros" }
rustc_serialize = { path = "../rustc_serialize" }

View file

@ -1,4 +1,4 @@
use rustc_data_structures::stable_hasher::Hash64;
use rustc_hashes::Hash64;
use rustc_span::def_id::DefIndex;
#[derive(Clone, Default)]

View file

@ -7,8 +7,9 @@
use std::fmt::{self, Write};
use std::hash::Hash;
use rustc_data_structures::stable_hasher::{Hash64, StableHasher};
use rustc_data_structures::stable_hasher::StableHasher;
use rustc_data_structures::unord::UnordMap;
use rustc_hashes::Hash64;
use rustc_index::IndexVec;
use rustc_macros::{Decodable, Encodable};
use rustc_span::{Symbol, kw, sym};

View file

@ -18,8 +18,8 @@
//! within one another.
//! - Example: Examine each expression to look for its type and do some check or other.
//! - How: Implement `intravisit::Visitor` and override the `NestedFilter` type to
//! `nested_filter::OnlyBodies` (and implement `nested_visit_map`), and use
//! `tcx.hir().visit_all_item_likes_in_crate(&mut visitor)`. Within your
//! `nested_filter::OnlyBodies` (and implement `maybe_tcx`), and use
//! `tcx.hir_visit_all_item_likes_in_crate(&mut visitor)`. Within your
//! `intravisit::Visitor` impl, implement methods like `visit_expr()` (don't forget to invoke
//! `intravisit::walk_expr()` to keep walking the subparts).
//! - Pro: Visitor methods for any kind of HIR node, not just item-like things.
@ -30,8 +30,8 @@
//! - Example: Lifetime resolution, which wants to bring lifetimes declared on the
//! impl into scope while visiting the impl-items, and then back out again.
//! - How: Implement `intravisit::Visitor` and override the `NestedFilter` type to
//! `nested_filter::All` (and implement `nested_visit_map`). Walk your crate with
//! `tcx.hir().walk_toplevel_module(visitor)` invoked on `tcx.hir().krate()`.
//! `nested_filter::All` (and implement `maybe_tcx`). Walk your crate with
//! `tcx.hir_walk_toplevel_module(visitor)`.
//! - Pro: Visitor methods for any kind of HIR node, not just item-like things.
//! - Pro: Preserves nesting information
//! - Con: Does not integrate well into dependency tracking.
@ -106,45 +106,43 @@ impl<'a> FnKind<'a> {
}
}
/// An abstract representation of the HIR `rustc_middle::hir::map::Map`.
pub trait Map<'hir> {
/// HIR things retrievable from `TyCtxt`, avoiding an explicit dependence on
/// `TyCtxt`. The only impls are for `!` (where these functions are never
/// called) and `TyCtxt` (in `rustc_middle`).
pub trait HirTyCtxt<'hir> {
/// Retrieves the `Node` corresponding to `id`.
fn hir_node(&self, hir_id: HirId) -> Node<'hir>;
fn hir_node_by_def_id(&self, def_id: LocalDefId) -> Node<'hir>;
fn body(&self, id: BodyId) -> &'hir Body<'hir>;
fn item(&self, id: ItemId) -> &'hir Item<'hir>;
fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir>;
fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir>;
fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir>;
fn hir_body(&self, id: BodyId) -> &'hir Body<'hir>;
fn hir_item(&self, id: ItemId) -> &'hir Item<'hir>;
fn hir_trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir>;
fn hir_impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir>;
fn hir_foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir>;
}
// Used when no map is actually available, forcing manual implementation of nested visitors.
impl<'hir> Map<'hir> for ! {
// Used when no tcx is actually available, forcing manual implementation of nested visitors.
impl<'hir> HirTyCtxt<'hir> for ! {
fn hir_node(&self, _: HirId) -> Node<'hir> {
*self;
unreachable!();
}
fn hir_node_by_def_id(&self, _: LocalDefId) -> Node<'hir> {
*self;
fn hir_body(&self, _: BodyId) -> &'hir Body<'hir> {
unreachable!();
}
fn body(&self, _: BodyId) -> &'hir Body<'hir> {
*self;
fn hir_item(&self, _: ItemId) -> &'hir Item<'hir> {
unreachable!();
}
fn item(&self, _: ItemId) -> &'hir Item<'hir> {
*self;
fn hir_trait_item(&self, _: TraitItemId) -> &'hir TraitItem<'hir> {
unreachable!();
}
fn trait_item(&self, _: TraitItemId) -> &'hir TraitItem<'hir> {
*self;
fn hir_impl_item(&self, _: ImplItemId) -> &'hir ImplItem<'hir> {
unreachable!();
}
fn impl_item(&self, _: ImplItemId) -> &'hir ImplItem<'hir> {
*self;
}
fn foreign_item(&self, _: ForeignItemId) -> &'hir ForeignItem<'hir> {
*self;
fn hir_foreign_item(&self, _: ForeignItemId) -> &'hir ForeignItem<'hir> {
unreachable!();
}
}
pub mod nested_filter {
use super::Map;
use super::HirTyCtxt;
/// Specifies what nested things a visitor wants to visit. By "nested
/// things", we are referring to bits of HIR that are not directly embedded
@ -159,7 +157,7 @@ pub mod nested_filter {
/// See the comments at [`rustc_hir::intravisit`] for more details on the overall
/// visit strategy.
pub trait NestedFilter<'hir> {
type Map: Map<'hir>;
type MaybeTyCtxt: HirTyCtxt<'hir>;
/// Whether the visitor visits nested "item-like" things.
/// E.g., item, impl-item.
@ -175,10 +173,10 @@ pub mod nested_filter {
///
/// Use this if you are only walking some particular kind of tree
/// (i.e., a type, or fn signature) and you don't want to thread a
/// HIR map around.
/// `tcx` around.
pub struct None(());
impl NestedFilter<'_> for None {
type Map = !;
type MaybeTyCtxt = !;
const INTER: bool = false;
const INTRA: bool = false;
}
@ -195,7 +193,7 @@ use nested_filter::NestedFilter;
/// (this is why the module is called `intravisit`, to distinguish it
/// from the AST's `visit` module, which acts differently). If you
/// simply want to visit all items in the crate in some order, you
/// should call `tcx.hir().visit_all_item_likes_in_crate`. Otherwise, see the comment
/// should call `tcx.hir_visit_all_item_likes_in_crate`. Otherwise, see the comment
/// on `visit_nested_item` for details on how to visit nested items.
///
/// If you want to ensure that your code handles every variant
@ -203,18 +201,18 @@ use nested_filter::NestedFilter;
/// to monitor future changes to `Visitor` in case a new method with a
/// new default implementation gets introduced.)
pub trait Visitor<'v>: Sized {
// this type should not be overridden, it exists for convenient usage as `Self::Map`
type Map: Map<'v> = <Self::NestedFilter as NestedFilter<'v>>::Map;
// This type should not be overridden, it exists for convenient usage as `Self::MaybeTyCtxt`.
type MaybeTyCtxt: HirTyCtxt<'v> = <Self::NestedFilter as NestedFilter<'v>>::MaybeTyCtxt;
///////////////////////////////////////////////////////////////////////////
// Nested items.
/// Override this type to control which nested HIR are visited; see
/// [`NestedFilter`] for details. If you override this type, you
/// must also override [`nested_visit_map`](Self::nested_visit_map).
/// must also override [`maybe_tcx`](Self::maybe_tcx).
///
/// **If for some reason you want the nested behavior, but don't
/// have a `Map` at your disposal:** then override the
/// have a `tcx` at your disposal:** then override the
/// `visit_nested_XXX` methods. If a new `visit_nested_XXX` variant is
/// added in the future, it will cause a panic which can be detected
/// and fixed appropriately.
@ -226,9 +224,9 @@ pub trait Visitor<'v>: Sized {
/// If `type NestedFilter` is set to visit nested items, this method
/// must also be overridden to provide a map to retrieve nested items.
fn nested_visit_map(&mut self) -> Self::Map {
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
panic!(
"nested_visit_map must be implemented or consider using \
"maybe_tcx must be implemented or consider using \
`type NestedFilter = nested_filter::None` (the default)"
);
}
@ -240,10 +238,10 @@ pub trait Visitor<'v>: Sized {
/// "deep" visit patterns described at
/// [`rustc_hir::intravisit`]. The only reason to override
/// this method is if you want a nested pattern but cannot supply a
/// [`Map`]; see `nested_visit_map` for advice.
/// `TyCtxt`; see `maybe_tcx` for advice.
fn visit_nested_item(&mut self, id: ItemId) -> Self::Result {
if Self::NestedFilter::INTER {
let item = self.nested_visit_map().item(id);
let item = self.maybe_tcx().hir_item(id);
try_visit!(self.visit_item(item));
}
Self::Result::output()
@ -254,7 +252,7 @@ pub trait Visitor<'v>: Sized {
/// method.
fn visit_nested_trait_item(&mut self, id: TraitItemId) -> Self::Result {
if Self::NestedFilter::INTER {
let item = self.nested_visit_map().trait_item(id);
let item = self.maybe_tcx().hir_trait_item(id);
try_visit!(self.visit_trait_item(item));
}
Self::Result::output()
@ -265,7 +263,7 @@ pub trait Visitor<'v>: Sized {
/// method.
fn visit_nested_impl_item(&mut self, id: ImplItemId) -> Self::Result {
if Self::NestedFilter::INTER {
let item = self.nested_visit_map().impl_item(id);
let item = self.maybe_tcx().hir_impl_item(id);
try_visit!(self.visit_impl_item(item));
}
Self::Result::output()
@ -276,7 +274,7 @@ pub trait Visitor<'v>: Sized {
/// method.
fn visit_nested_foreign_item(&mut self, id: ForeignItemId) -> Self::Result {
if Self::NestedFilter::INTER {
let item = self.nested_visit_map().foreign_item(id);
let item = self.maybe_tcx().hir_foreign_item(id);
try_visit!(self.visit_foreign_item(item));
}
Self::Result::output()
@ -287,7 +285,7 @@ pub trait Visitor<'v>: Sized {
/// `Self::NestedFilter`.
fn visit_nested_body(&mut self, id: BodyId) -> Self::Result {
if Self::NestedFilter::INTRA {
let body = self.nested_visit_map().body(id);
let body = self.maybe_tcx().hir_body(id);
try_visit!(self.visit_body(body));
}
Self::Result::output()

View file

@ -1,6 +1,6 @@
#![allow(rustc::symbol_intern_string_literal)]
use rustc_data_structures::stable_hasher::Hash64;
use rustc_hashes::Hash64;
use rustc_span::def_id::{DefPathHash, StableCrateId};
use rustc_span::edition::Edition;
use rustc_span::{Symbol, create_session_globals_then};

View file

@ -387,6 +387,8 @@ hir_analysis_must_implement_not_function_span_note = required by this annotation
hir_analysis_must_implement_one_of_attribute = the `#[rustc_must_implement_one_of]` attribute must be used with at least 2 args
hir_analysis_no_variant_named = no variant named `{$ident}` found for enum `{$ty}`
hir_analysis_not_supported_delegation = {$descr}
.label = callee defined here

View file

@ -1,100 +0,0 @@
//! Bounds are restrictions applied to some types after they've been lowered from the HIR to the
//! [`rustc_middle::ty`] form.
use rustc_hir::LangItem;
use rustc_middle::ty::{self, Ty, TyCtxt, Upcast};
use rustc_span::Span;
/// Collects together a list of type bounds. These lists of bounds occur in many places
/// in Rust's syntax:
///
/// ```text
/// trait Foo: Bar + Baz { }
/// ^^^^^^^^^ supertrait list bounding the `Self` type parameter
///
/// fn foo<T: Bar + Baz>() { }
/// ^^^^^^^^^ bounding the type parameter `T`
///
/// impl dyn Bar + Baz
/// ^^^^^^^^^ bounding the type-erased dynamic type
/// ```
///
/// Our representation is a bit mixed here -- in some cases, we
/// include the self type (e.g., `trait_bounds`) but in others we do not
#[derive(Default, PartialEq, Eq, Clone, Debug)]
pub(crate) struct Bounds<'tcx> {
clauses: Vec<(ty::Clause<'tcx>, Span)>,
}
impl<'tcx> Bounds<'tcx> {
pub(crate) fn push_region_bound(
&mut self,
tcx: TyCtxt<'tcx>,
region: ty::PolyTypeOutlivesPredicate<'tcx>,
span: Span,
) {
self.clauses
.push((region.map_bound(|p| ty::ClauseKind::TypeOutlives(p)).upcast(tcx), span));
}
pub(crate) fn push_trait_bound(
&mut self,
tcx: TyCtxt<'tcx>,
bound_trait_ref: ty::PolyTraitRef<'tcx>,
span: Span,
polarity: ty::PredicatePolarity,
) {
let clause = (
bound_trait_ref
.map_bound(|trait_ref| {
ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
})
.upcast(tcx),
span,
);
// FIXME(-Znext-solver): We can likely remove this hack once the new trait solver lands.
if tcx.is_lang_item(bound_trait_ref.def_id(), LangItem::Sized) {
self.clauses.insert(0, clause);
} else {
self.clauses.push(clause);
}
}
pub(crate) fn push_projection_bound(
&mut self,
tcx: TyCtxt<'tcx>,
projection: ty::PolyProjectionPredicate<'tcx>,
span: Span,
) {
self.clauses.push((
projection.map_bound(|proj| ty::ClauseKind::Projection(proj)).upcast(tcx),
span,
));
}
pub(crate) fn push_sized(&mut self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) {
let sized_def_id = tcx.require_lang_item(LangItem::Sized, Some(span));
let trait_ref = ty::TraitRef::new(tcx, sized_def_id, [ty]);
// Preferable to put this obligation first, since we report better errors for sized ambiguity.
self.clauses.insert(0, (trait_ref.upcast(tcx), span));
}
/// Push a `const` or `~const` bound as a `HostEffect` predicate.
pub(crate) fn push_const_bound(
&mut self,
tcx: TyCtxt<'tcx>,
bound_trait_ref: ty::PolyTraitRef<'tcx>,
constness: ty::BoundConstness,
span: Span,
) {
if tcx.is_const_trait(bound_trait_ref.def_id()) {
self.clauses.push((bound_trait_ref.to_host_effect_clause(tcx, constness), span));
} else {
tcx.dcx().span_delayed_bug(span, "tried to lower {host:?} bound for non-const trait");
}
}
pub(crate) fn clauses(&self) -> impl Iterator<Item = (ty::Clause<'tcx>, Span)> + '_ {
self.clauses.iter().cloned()
}
}

View file

@ -124,7 +124,7 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b
for field in &def.non_enum_variant().fields {
if !allowed_union_or_unsafe_field(tcx, field.ty(tcx, args), typing_env, span) {
let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
// We are currently checking the type this field came from, so it must be local.
Some(Node::Field(field)) => (field.span, field.ty.span),
_ => unreachable!("mir field has to correspond to hir field"),
@ -435,8 +435,8 @@ fn best_definition_site_of_opaque<'tcx>(
impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
type NestedFilter = nested_filter::All;
type Result = ControlFlow<(Span, LocalDefId)>;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
if let hir::ExprKind::Closure(closure) = ex.kind {
@ -484,7 +484,7 @@ fn best_definition_site_of_opaque<'tcx>(
hir::OpaqueTyOrigin::TyAlias { in_assoc_ty: false, .. } => {
let scope = tcx.hir().get_defining_scope(tcx.local_def_id_to_hir_id(opaque_def_id));
let found = if scope == hir::CRATE_HIR_ID {
tcx.hir().walk_toplevel_module(&mut locator)
tcx.hir_walk_toplevel_module(&mut locator)
} else {
match tcx.hir_node(scope) {
Node::Item(it) => locator.visit_item(it),
@ -880,7 +880,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) {
.emit();
}
let item = tcx.hir().foreign_item(item.id);
let item = tcx.hir_foreign_item(item.id);
match &item.kind {
hir::ForeignItemKind::Fn(sig, _, _) => {
require_c_abi_if_c_variadic(tcx, sig.decl, abi, item.span);
@ -1494,7 +1494,7 @@ fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
// In the case the discriminant is both a duplicate and overflowed, let the user know
if let hir::Node::AnonConst(expr) =
tcx.hir_node_by_def_id(discr_def_id.expect_local())
&& let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind
&& let hir::ExprKind::Lit(lit) = &tcx.hir_body(expr.body).value.kind
&& let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node
&& *lit_value != dis.val
{

View file

@ -501,7 +501,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id);
let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
let return_span = tcx.hir_fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
let cause = ObligationCause::new(
return_span,
impl_m_def_id,
@ -658,11 +658,10 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
"method `{}` has an incompatible return type for trait",
trait_m.name
);
let hir = tcx.hir();
infcx.err_ctxt().note_type_err(
&mut diag,
&cause,
hir.get_if_local(impl_m.def_id)
tcx.hir_get_if_local(impl_m.def_id)
.and_then(|node| node.fn_decl())
.map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
@ -1034,8 +1033,7 @@ fn report_trait_method_mismatch<'tcx>(
// argument pattern and type.
let (sig, body) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
let span = tcx
.hir()
.body_param_names(body)
.hir_body_param_names(body)
.zip(sig.decl.inputs.iter())
.map(|(param, ty)| param.span.to(ty.span))
.next()
@ -1123,15 +1121,14 @@ fn check_region_bounds_on_impl_item<'tcx>(
// the moment, give a kind of vague error message.
if trait_params != impl_params {
let span = tcx
.hir()
.get_generics(impl_m.def_id.expect_local())
.hir_get_generics(impl_m.def_id.expect_local())
.expect("expected impl item to have generics or else we can't compare them")
.span;
let mut generics_span = None;
let mut bounds_span = vec![];
let mut where_span = None;
if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
if let Some(trait_node) = tcx.hir_get_if_local(trait_m.def_id)
&& let Some(trait_generics) = trait_node.generics()
{
generics_span = Some(trait_generics.span);
@ -1146,7 +1143,7 @@ fn check_region_bounds_on_impl_item<'tcx>(
}
}
}
if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
if let Some(impl_node) = tcx.hir_get_if_local(impl_m.def_id)
&& let Some(impl_generics) = impl_node.generics()
{
let mut impl_bounds = 0;
@ -2107,18 +2104,21 @@ pub(super) fn check_type_bounds<'tcx>(
ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
};
let mut obligations: Vec<_> = tcx
.explicit_item_bounds(trait_ty.def_id)
.iter_instantiated_copied(tcx, rebased_args)
.map(|(concrete_ty_bound, span)| {
debug!(?concrete_ty_bound);
traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
})
.collect();
let mut obligations: Vec<_> = util::elaborate(
tcx,
tcx.explicit_item_bounds(trait_ty.def_id).iter_instantiated_copied(tcx, rebased_args).map(
|(concrete_ty_bound, span)| {
debug!(?concrete_ty_bound);
traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
},
),
)
.collect();
// Only in a const implementation do we need to check that the `~const` item bounds hold.
if tcx.is_conditionally_const(impl_ty_def_id) {
obligations.extend(
obligations.extend(util::elaborate(
tcx,
tcx.explicit_implied_const_bounds(trait_ty.def_id)
.iter_instantiated_copied(tcx, rebased_args)
.map(|(c, span)| {
@ -2129,7 +2129,7 @@ pub(super) fn check_type_bounds<'tcx>(
c.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
)
}),
);
));
}
debug!(item_bounds=?obligations);
@ -2137,26 +2137,19 @@ pub(super) fn check_type_bounds<'tcx>(
// to its definition type. This should be the param-env we use to *prove* the
// predicate too, but we don't do that because of performance issues.
// See <https://github.com/rust-lang/rust/pull/117542#issue-1976337685>.
let trait_projection_ty = Ty::new_projection_from_args(tcx, trait_ty.def_id, rebased_args);
let impl_identity_ty = tcx.type_of(impl_ty.def_id).instantiate_identity();
let normalize_param_env = param_env_with_gat_bounds(tcx, impl_ty, impl_trait_ref);
for mut obligation in util::elaborate(tcx, obligations) {
let normalized_predicate = if infcx.next_trait_solver() {
obligation.predicate.fold_with(&mut ReplaceTy {
tcx,
from: trait_projection_ty,
to: impl_identity_ty,
})
} else {
ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate)
};
debug!(?normalized_predicate);
obligation.predicate = normalized_predicate;
ocx.register_obligation(obligation);
for obligation in &mut obligations {
match ocx.deeply_normalize(&normalize_cause, normalize_param_env, obligation.predicate) {
Ok(pred) => obligation.predicate = pred,
Err(e) => {
return Err(infcx.err_ctxt().report_fulfillment_errors(e));
}
}
}
// Check that all obligations are satisfied by the implementation's
// version.
ocx.register_obligations(obligations);
let errors = ocx.select_all_or_error();
if !errors.is_empty() {
let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
@ -2168,22 +2161,6 @@ pub(super) fn check_type_bounds<'tcx>(
ocx.resolve_regions_and_report_errors(impl_ty_def_id, param_env, assumed_wf_types)
}
struct ReplaceTy<'tcx> {
tcx: TyCtxt<'tcx>,
from: Ty<'tcx>,
to: Ty<'tcx>,
}
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceTy<'tcx> {
fn cx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
if self.from == ty { self.to } else { ty.super_fold_with(self) }
}
}
/// Install projection predicates that allow GATs to project to their own
/// definition types. This is not allowed in general in cases of default
/// associated types in trait definitions, or when specialization is involved,

View file

@ -96,7 +96,7 @@ pub(crate) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
// This opaque also needs to be from the impl method -- otherwise,
// it's a refinement to a TAIT.
if !tcx.hir().get_if_local(impl_opaque.def_id).is_some_and(|node| {
if !tcx.hir_get_if_local(impl_opaque.def_id).is_some_and(|node| {
matches!(
node.expect_opaque_ty().origin,
hir::OpaqueTyOrigin::AsyncFn { parent, .. } | hir::OpaqueTyOrigin::FnReturn { parent, .. }
@ -327,7 +327,7 @@ fn report_mismatched_rpitit_signature<'tcx>(
hir::FnRetTy::Return(ty) => (ty.span, ty.span, "", ""),
};
let trait_return_span =
tcx.hir().get_if_local(trait_m_def_id).map(|node| match node.fn_decl().unwrap().output {
tcx.hir_get_if_local(trait_m_def_id).map(|node| match node.fn_decl().unwrap().output {
hir::FnRetTy::DefaultReturn(_) => tcx.def_span(trait_m_def_id),
hir::FnRetTy::Return(ty) => ty.span,
});

View file

@ -129,7 +129,7 @@ fn get_owner_return_paths(
let hir_id = tcx.local_def_id_to_hir_id(def_id);
let parent_id = tcx.hir().get_parent_item(hir_id).def_id;
tcx.hir_node_by_def_id(parent_id).body_id().map(|body_id| {
let body = tcx.hir().body(body_id);
let body = tcx.hir_body(body_id);
let mut visitor = ReturnsVisitor::default();
visitor.visit_body(body);
(parent_id, visitor)

View file

@ -424,7 +424,7 @@ fn resolve_expr<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, expr: &'tcx hi
// that share the parent environment. We handle const blocks in
// `visit_inline_const`.
hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
let body = visitor.tcx.hir().body(body);
let body = visitor.tcx.hir_body(body);
visitor.visit_body(body);
}
hir::ExprKind::AssignOp(_, left_expr, right_expr) => {
@ -844,7 +844,7 @@ impl<'tcx> Visitor<'tcx> for ScopeResolutionVisitor<'tcx> {
fn visit_body(&mut self, body: &hir::Body<'tcx>) {
let body_id = body.id();
let owner_id = self.tcx.hir().body_owner_def_id(body_id);
let owner_id = self.tcx.hir_body_owner_def_id(body_id);
debug!(
"visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})",
@ -855,7 +855,7 @@ impl<'tcx> Visitor<'tcx> for ScopeResolutionVisitor<'tcx> {
);
self.enter_body(body.value.hir_id, |this| {
if this.tcx.hir().body_owner_kind(owner_id).is_fn_or_closure() {
if this.tcx.hir_body_owner_kind(owner_id).is_fn_or_closure() {
// The arguments and `self` are parented to the fn.
this.cx.var_parent = this.cx.parent.take();
for param in body.params {
@ -906,7 +906,7 @@ impl<'tcx> Visitor<'tcx> for ScopeResolutionVisitor<'tcx> {
resolve_local(self, Some(l.pat), l.init)
}
fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
let body = self.tcx.hir().body(c.body);
let body = self.tcx.hir_body(c.body);
self.visit_body(body);
}
}
@ -924,7 +924,7 @@ pub(crate) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree {
return tcx.region_scope_tree(typeck_root_def_id);
}
let scope_tree = if let Some(body) = tcx.hir().maybe_body_owned_by(def_id.expect_local()) {
let scope_tree = if let Some(body) = tcx.hir_maybe_body_owned_by(def_id.expect_local()) {
let mut visitor = ScopeResolutionVisitor {
tcx,
scope_tree: ScopeTree::default(),

View file

@ -1163,7 +1163,7 @@ fn check_type_defn<'tcx>(
// be refactored to check the instantiate-ability of the code better.
if let Some(def_id) = def_id.as_local()
&& let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
&& let expr = &tcx.hir().body(anon.body).value
&& let expr = &tcx.hir_body(anon.body).value
&& let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
&& let Res::Def(DefKind::ConstParam, _def_id) = path.res
{
@ -1710,7 +1710,7 @@ fn check_sized_if_body<'tcx>(
maybe_span: Option<Span>,
) {
let tcx = wfcx.tcx();
if let Some(body) = tcx.hir().maybe_body_owned_by(def_id) {
if let Some(body) = tcx.hir_maybe_body_owned_by(def_id) {
let span = maybe_span.unwrap_or(body.value.span);
wfcx.register_bound(

View file

@ -13,11 +13,11 @@ pub(crate) fn provide(providers: &mut Providers) {
fn check_unused_traits(tcx: TyCtxt<'_>, (): ()) {
let mut used_trait_imports = UnordSet::<LocalDefId>::default();
// FIXME: Use `tcx.hir().par_body_owners()` when we implement creating `DefId`s
// FIXME: Use `tcx.hir_par_body_owners()` when we implement creating `DefId`s
// for anon constants during their parents' typeck.
// Doing so at current will produce queries cycle errors because it may typeck
// on anon constants directly.
for item_def_id in tcx.hir().body_owners() {
for item_def_id in tcx.hir_body_owners() {
let imports = tcx.used_trait_imports(item_def_id);
debug!("GatherVisitor: item_def_id={:?} with imports {:#?}", item_def_id, imports);
used_trait_imports.extend_unord(imports.items().copied());

View file

@ -679,7 +679,7 @@ fn infringing_fields_error<'tcx>(
suggest_constraining_type_params(
tcx,
tcx.hir().get_generics(impl_did).expect("impls always have generics"),
tcx.hir_get_generics(impl_did).expect("impls always have generics"),
&mut err,
bounds
.iter()

View file

@ -25,7 +25,7 @@ pub(crate) fn crate_inherent_impls(
let mut collect = InherentCollect { tcx, impls_map: Default::default() };
let mut res = Ok(());
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
res = res.and(collect.check_item(id));
}
@ -113,7 +113,7 @@ impl<'tcx> InherentCollect<'tcx> {
ty: Ty<'tcx>,
) -> Result<(), ErrorGuaranteed> {
let items = self.tcx.associated_item_def_ids(impl_def_id);
if !self.tcx.hir().rustc_coherence_is_core() {
if !self.tcx.hir_rustc_coherence_is_core() {
if self.tcx.features().rustc_attrs() {
for &impl_item in items {
if !self.tcx.has_attr(impl_item, sym::rustc_allow_incoherent_impl) {

View file

@ -18,7 +18,7 @@ pub(crate) fn crate_inherent_impls_overlap_check(
) -> Result<(), ErrorGuaranteed> {
let mut inherent_overlap_checker = InherentOverlapChecker { tcx };
let mut res = Ok(());
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
res = res.and(inherent_overlap_checker.check_item(id));
}
res

View file

@ -277,8 +277,8 @@ fn reject_placeholder_type_signatures_in_item<'tcx>(
impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
@ -669,7 +669,7 @@ fn get_new_lifetime_name<'tcx>(
#[instrument(level = "debug", skip_all)]
fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
let it = tcx.hir().item(item_id);
let it = tcx.hir_item(item_id);
debug!(item = %it.ident, id = %it.hir_id());
let def_id = item_id.owner_id.def_id;
let icx = ItemCtxt::new(tcx, def_id);
@ -683,7 +683,7 @@ fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
| hir::ItemKind::GlobalAsm(_) => {}
hir::ItemKind::ForeignMod { items, .. } => {
for item in *items {
let item = tcx.hir().foreign_item(item.id);
let item = tcx.hir_foreign_item(item.id);
tcx.ensure_ok().generics_of(item.owner_id);
tcx.ensure_ok().type_of(item.owner_id);
tcx.ensure_ok().predicates_of(item.owner_id);
@ -790,7 +790,7 @@ fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
}
fn lower_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
let trait_item = tcx.hir().trait_item(trait_item_id);
let trait_item = tcx.hir_trait_item(trait_item_id);
let def_id = trait_item_id.owner_id;
tcx.ensure_ok().generics_of(def_id);
let icx = ItemCtxt::new(tcx, def_id.def_id);
@ -865,7 +865,7 @@ fn lower_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
tcx.ensure_ok().generics_of(def_id);
tcx.ensure_ok().type_of(def_id);
tcx.ensure_ok().predicates_of(def_id);
let impl_item = tcx.hir().impl_item(impl_item_id);
let impl_item = tcx.hir_impl_item(impl_item_id);
let icx = ItemCtxt::new(tcx, def_id.def_id);
match impl_item.kind {
hir::ImplItemKind::Fn(..) => {
@ -1769,7 +1769,7 @@ fn coroutine_for_closure(tcx: TyCtxt<'_>, def_id: LocalDefId) -> DefId {
..
}),
..
} = tcx.hir().body(body).value
} = tcx.hir_body(body).value
else {
bug!()
};

View file

@ -52,7 +52,7 @@ pub(crate) fn predicates_and_item_bounds(tcx: TyCtxt<'_>) {
}
pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
for iid in tcx.hir().items() {
for iid in tcx.hir_free_items() {
let did = iid.owner_id.def_id;
if tcx.has_attr(did, sym::rustc_dump_def_parents) {
struct AnonConstFinder<'tcx> {
@ -63,8 +63,8 @@ pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
impl<'tcx> intravisit::Visitor<'tcx> for AnonConstFinder<'tcx> {
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_anon_const(&mut self, c: &'tcx rustc_hir::AnonConst) {
@ -77,7 +77,7 @@ pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
// the `rustc_dump_def_parents` attribute to the anon const so it would not be possible
// to see what its def parent is.
let mut anon_ct_finder = AnonConstFinder { tcx, anon_consts: vec![] };
intravisit::walk_item(&mut anon_ct_finder, tcx.hir().item(iid));
intravisit::walk_item(&mut anon_ct_finder, tcx.hir_item(iid));
for did in [did].into_iter().chain(anon_ct_finder.anon_consts) {
let span = tcx.def_span(did);
@ -99,14 +99,14 @@ pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
}
pub(crate) fn vtables<'tcx>(tcx: TyCtxt<'tcx>) {
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
let def_id = id.owner_id.def_id;
let Some(attr) = tcx.get_attr(def_id, sym::rustc_dump_vtable) else {
continue;
};
let vtable_entries = match tcx.hir().item(id).kind {
let vtable_entries = match tcx.hir_item(id).kind {
hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
let trait_ref = tcx.impl_trait_ref(def_id).unwrap().instantiate_identity();
if trait_ref.has_non_region_param() {

View file

@ -13,7 +13,6 @@ use tracing::{debug, instrument};
use super::ItemCtxt;
use super::predicates_of::assert_only_contains_predicates_from;
use crate::bounds::Bounds;
use crate::hir_ty_lowering::{HirTyLowerer, PredicateFilter};
/// For associated types we include both bounds written on the type
@ -38,7 +37,7 @@ fn associated_type_bounds<'tcx>(
);
let icx = ItemCtxt::new(tcx, assoc_item_def_id);
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds, ty::List::empty(), filter);
// Associated types are implicitly sized unless a `?Sized` bound is found
match filter {
@ -68,7 +67,7 @@ fn associated_type_bounds<'tcx>(
)
});
let all_bounds = tcx.arena.alloc_from_iter(bounds.clauses().chain(bounds_from_parent));
let all_bounds = tcx.arena.alloc_from_iter(bounds.into_iter().chain(bounds_from_parent));
debug!(
"associated_type_bounds({}) = {:?}",
tcx.def_path_str(assoc_item_def_id.to_def_id()),
@ -327,7 +326,7 @@ fn opaque_type_bounds<'tcx>(
) -> &'tcx [(ty::Clause<'tcx>, Span)] {
ty::print::with_reduced_queries!({
let icx = ItemCtxt::new(tcx, opaque_def_id);
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
icx.lowerer().lower_bounds(item_ty, hir_bounds, &mut bounds, ty::List::empty(), filter);
// Opaque types are implicitly sized unless a `?Sized` bound is found
match filter {
@ -343,7 +342,7 @@ fn opaque_type_bounds<'tcx>(
}
debug!(?bounds);
tcx.arena.alloc_from_iter(bounds.clauses())
tcx.arena.alloc_slice(&bounds)
})
}

View file

@ -13,7 +13,6 @@ use rustc_span::{DUMMY_SP, Ident, Span};
use tracing::{debug, instrument, trace};
use super::item_bounds::explicit_item_bounds_with_filter;
use crate::bounds::Bounds;
use crate::collect::ItemCtxt;
use crate::constrained_generic_params as cgp;
use crate::delegation::inherit_predicates_for_delegation_item;
@ -178,7 +177,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
// on a trait we must also consider the bounds that follow the trait's name,
// like `trait Foo: A + B + C`.
if let Some(self_bounds) = is_trait {
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
icx.lowerer().lower_bounds(
tcx.types.self_param,
self_bounds,
@ -186,7 +185,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
ty::List::empty(),
PredicateFilter::All,
);
predicates.extend(bounds.clauses());
predicates.extend(bounds);
}
// In default impls, we can assume that the self type implements
@ -209,7 +208,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
GenericParamKind::Lifetime { .. } => (),
GenericParamKind::Type { .. } => {
let param_ty = icx.lowerer().lower_ty_param(param.hir_id);
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
// Params are implicitly sized unless a `?Sized` bound is found
icx.lowerer().add_sized_bound(
&mut bounds,
@ -219,7 +218,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
param.span,
);
trace!(?bounds);
predicates.extend(bounds.clauses());
predicates.extend(bounds);
trace!(?predicates);
}
hir::GenericParamKind::Const { .. } => {
@ -264,7 +263,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
}
}
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
icx.lowerer().lower_bounds(
ty,
bound_pred.bounds,
@ -272,7 +271,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
bound_vars,
PredicateFilter::All,
);
predicates.extend(bounds.clauses());
predicates.extend(bounds);
}
hir::WherePredicateKind::RegionPredicate(region_pred) => {
@ -436,7 +435,7 @@ fn const_evaluatable_predicates_of<'tcx>(
self_ty.instantiate_identity().visit_with(&mut collector);
}
if let Some(_) = tcx.hir().fn_sig_by_hir_id(hir_id) {
if let Some(_) = tcx.hir_fn_sig_by_hir_id(hir_id) {
debug!("visit fn sig");
let fn_sig = tcx.fn_sig(def_id);
let fn_sig = fn_sig.instantiate_identity();
@ -627,7 +626,7 @@ pub(super) fn implied_predicates_with_filter<'tcx>(
let icx = ItemCtxt::new(tcx, trait_def_id);
let self_param_ty = tcx.types.self_param;
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
icx.lowerer().lower_bounds(self_param_ty, superbounds, &mut bounds, ty::List::empty(), filter);
let where_bounds_that_match =
@ -635,7 +634,7 @@ pub(super) fn implied_predicates_with_filter<'tcx>(
// Combine the two lists to form the complete set of superbounds:
let implied_bounds =
&*tcx.arena.alloc_from_iter(bounds.clauses().chain(where_bounds_that_match));
&*tcx.arena.alloc_from_iter(bounds.into_iter().chain(where_bounds_that_match));
debug!(?implied_bounds);
// Now require that immediate supertraits are lowered, which will, in
@ -826,7 +825,7 @@ pub(super) fn type_param_predicates<'tcx>(
// `where T: Foo`.
let param_id = tcx.local_def_id_to_hir_id(def_id);
let param_owner = tcx.hir().ty_param_owner(def_id);
let param_owner = tcx.hir_ty_param_owner(def_id);
// Don't look for bounds where the type parameter isn't in scope.
let parent = if item_def_id == param_owner {
@ -904,7 +903,7 @@ impl<'tcx> ItemCtxt<'tcx> {
param_def_id: LocalDefId,
filter: PredicateFilter,
) -> Vec<(ty::Clause<'tcx>, Span)> {
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
for predicate in hir_generics.predicates {
let hir_id = predicate.hir_id;
@ -938,7 +937,7 @@ impl<'tcx> ItemCtxt<'tcx> {
);
}
bounds.clauses().collect()
bounds
}
}
@ -1007,7 +1006,7 @@ pub(super) fn const_conditions<'tcx>(
};
let icx = ItemCtxt::new(tcx, def_id);
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
for pred in generics.predicates {
match pred.kind {
@ -1027,12 +1026,12 @@ pub(super) fn const_conditions<'tcx>(
}
if let Some((def_id, supertraits)) = trait_def_id_and_supertraits {
bounds.push_const_bound(
tcx,
ty::Binder::dummy(ty::TraitRef::identity(tcx, def_id.to_def_id())),
ty::BoundConstness::Maybe,
// We've checked above that the trait is conditionally const.
bounds.push((
ty::Binder::dummy(ty::TraitRef::identity(tcx, def_id.to_def_id()))
.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
DUMMY_SP,
);
));
icx.lowerer().lower_bounds(
tcx.types.self_param,
@ -1045,7 +1044,7 @@ pub(super) fn const_conditions<'tcx>(
ty::ConstConditions {
parent: has_parent.then(|| tcx.local_parent(def_id).to_def_id()),
predicates: tcx.arena.alloc_from_iter(bounds.clauses().map(|(clause, span)| {
predicates: tcx.arena.alloc_from_iter(bounds.into_iter().map(|(clause, span)| {
(
clause.kind().map_bound(|clause| match clause {
ty::ClauseKind::HostEffect(ty::HostEffectPredicate {

View file

@ -422,12 +422,12 @@ enum NonLifetimeBinderAllowed {
impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_nested_body(&mut self, body: hir::BodyId) {
let body = self.tcx.hir().body(body);
let body = self.tcx.hir_body(body);
self.with(Scope::Body { id: body.id(), s: self.scope }, |this| {
this.visit_body(body);
});
@ -1049,7 +1049,7 @@ fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: LocalDefId) -> ObjectL
match param.source {
hir::GenericParamSource::Generics => {
let parent_def_id = tcx.local_parent(param_def_id);
let generics = tcx.hir().get_generics(parent_def_id).unwrap();
let generics = tcx.hir_get_generics(parent_def_id).unwrap();
let param_hir_id = tcx.local_def_id_to_hir_id(param_def_id);
let param = generics.params.iter().find(|p| p.hir_id == param_hir_id).unwrap();
@ -1250,7 +1250,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin
&& let hir::LifetimeName::Param(param_id) = lifetime_ref.res
&& let Some(generics) =
self.tcx.hir().get_generics(self.tcx.local_parent(param_id))
self.tcx.hir_get_generics(self.tcx.local_parent(param_id))
&& let Some(param) = generics.params.iter().find(|p| p.def_id == param_id)
&& param.is_elided_lifetime()
&& !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async()
@ -1264,7 +1264,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
);
if let Some(generics) =
self.tcx.hir().get_generics(lifetime_ref.hir_id.owner.def_id)
self.tcx.hir_get_generics(lifetime_ref.hir_id.owner.def_id)
{
let new_param_sugg =
if let Some(span) = generics.span_for_lifetime_suggestion() {
@ -1340,7 +1340,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
};
def = ResolvedArg::Error(guar);
} else if let Some(body_id) = outermost_body {
let fn_id = self.tcx.hir().body_owner(body_id);
let fn_id = self.tcx.hir_body_owner(body_id);
match self.tcx.hir_node(fn_id) {
Node::Item(hir::Item { owner_id, kind: hir::ItemKind::Fn { .. }, .. })
| Node::TraitItem(hir::TraitItem {
@ -2265,8 +2265,8 @@ fn is_late_bound_map(
tcx: TyCtxt<'_>,
owner_id: hir::OwnerId,
) -> Option<&FxIndexSet<hir::ItemLocalId>> {
let sig = tcx.hir().fn_sig_by_hir_id(owner_id.into())?;
let generics = tcx.hir().get_generics(owner_id.def_id)?;
let sig = tcx.hir_fn_sig_by_hir_id(owner_id.into())?;
let generics = tcx.hir_get_generics(owner_id.def_id)?;
let mut late_bound = FxIndexSet::default();

View file

@ -451,7 +451,7 @@ fn infer_placeholder_type<'tcx>(
);
} else {
with_forced_trimmed_paths!(err.span_note(
tcx.hir().body(body_id).value.span,
tcx.hir_body(body_id).value.span,
format!("however, the inferred type `{ty}` cannot be named"),
));
}
@ -494,7 +494,7 @@ fn infer_placeholder_type<'tcx>(
);
} else {
with_forced_trimmed_paths!(diag.span_note(
tcx.hir().body(body_id).value.span,
tcx.hir_body(body_id).value.span,
format!("however, the inferred type `{ty}` cannot be named"),
));
}

View file

@ -89,7 +89,7 @@ pub(super) fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: Local
debug!(?scope);
if scope == hir::CRATE_HIR_ID {
tcx.hir().walk_toplevel_module(&mut locator);
tcx.hir_walk_toplevel_module(&mut locator);
} else {
trace!("scope={:#?}", tcx.hir_node(scope));
match tcx.hir_node(scope) {
@ -298,8 +298,8 @@ impl TaitConstraintLocator<'_> {
impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let hir::ExprKind::Closure(closure) = ex.kind {
@ -441,8 +441,8 @@ impl RpitConstraintChecker<'_> {
impl<'tcx> intravisit::Visitor<'tcx> for RpitConstraintChecker<'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let hir::ExprKind::Closure(closure) = ex.kind {

View file

@ -1417,6 +1417,15 @@ pub(crate) struct CrossCrateTraitsDefined {
pub traits: String,
}
#[derive(Diagnostic)]
#[diag(hir_analysis_no_variant_named, code = E0599)]
pub struct NoVariantNamed<'tcx> {
#[primary_span]
pub span: Span,
pub ident: Ident,
pub ty: Ty<'tcx>,
}
// FIXME(fmease): Deduplicate:
#[derive(Diagnostic)]

View file

@ -451,7 +451,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
)
});
let fn_sig = self.tcx.hir().get_if_local(self.def_id).and_then(hir::Node::fn_sig);
let fn_sig = self.tcx.hir_get_if_local(self.def_id).and_then(hir::Node::fn_sig);
let is_used_in_input = |def_id| {
fn_sig.is_some_and(|fn_sig| {
fn_sig.decl.inputs.iter().any(|ty| match ty.kind {

View file

@ -8,7 +8,7 @@ use rustc_hir::HirId;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_middle::bug;
use rustc_middle::ty::{self as ty, IsSuggestable, Ty, TyCtxt};
use rustc_middle::ty::{self as ty, IsSuggestable, Ty, TyCtxt, Upcast};
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, kw, sym};
use rustc_trait_selection::traits;
use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor};
@ -16,7 +16,6 @@ use smallvec::SmallVec;
use tracing::{debug, instrument};
use super::errors::GenericsArgsErrExtend;
use crate::bounds::Bounds;
use crate::errors;
use crate::hir_ty_lowering::{
AssocItemQSelf, FeedConstTy, HirTyLowerer, PredicateFilter, RegionInferReason,
@ -28,7 +27,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
/// Doesn't add the bound if the HIR bounds contain any of `Sized`, `?Sized` or `!Sized`.
pub(crate) fn add_sized_bound(
&self,
bounds: &mut Bounds<'tcx>,
bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
self_ty: Ty<'tcx>,
hir_bounds: &'tcx [hir::GenericBound<'tcx>],
self_ty_where_predicates: Option<(LocalDefId, &'tcx [hir::WherePredicate<'tcx>])>,
@ -113,10 +112,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
if seen_sized_unbound || seen_negative_sized_bound || seen_positive_sized_bound {
// There was in fact a `?Sized`, `!Sized` or explicit `Sized` bound;
// we don't need to do anything.
} else if sized_def_id.is_some() {
} else if let Some(sized_def_id) = sized_def_id {
// There was no `?Sized`, `!Sized` or explicit `Sized` bound;
// add `Sized` if it's available.
bounds.push_sized(tcx, self_ty, span);
let trait_ref = ty::TraitRef::new(tcx, sized_def_id, [self_ty]);
// Preferable to put this obligation first, since we report better errors for sized ambiguity.
bounds.insert(0, (trait_ref.upcast(tcx), span));
}
}
@ -146,7 +147,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
&self,
param_ty: Ty<'tcx>,
hir_bounds: I,
bounds: &mut Bounds<'tcx>,
bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
predicate_filter: PredicateFilter,
) where
@ -189,14 +190,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
}
let region = self.lower_lifetime(lifetime, RegionInferReason::OutlivesBound);
bounds.push_region_bound(
self.tcx(),
ty::Binder::bind_with_vars(
ty::OutlivesPredicate(param_ty, region),
bound_vars,
),
lifetime.ident.span,
let bound = ty::Binder::bind_with_vars(
ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region)),
bound_vars,
);
bounds.push((bound.upcast(self.tcx()), lifetime.ident.span));
}
hir::GenericBound::Use(..) => {
// We don't actually lower `use` into the type layer.
@ -219,7 +217,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
hir_ref_id: hir::HirId,
trait_ref: ty::PolyTraitRef<'tcx>,
constraint: &hir::AssocItemConstraint<'tcx>,
bounds: &mut Bounds<'tcx>,
bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
duplicates: &mut FxIndexMap<DefId, Span>,
path_span: Span,
predicate_filter: PredicateFilter,
@ -389,14 +387,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
PredicateFilter::All
| PredicateFilter::SelfOnly
| PredicateFilter::SelfAndAssociatedTypeBounds => {
bounds.push_projection_bound(
tcx,
projection_term.map_bound(|projection_term| ty::ProjectionPredicate {
let bound = projection_term.map_bound(|projection_term| {
ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_term,
term,
}),
constraint.span,
);
})
});
bounds.push((bound.upcast(tcx), constraint.span));
}
// SelfTraitThatDefines is only interested in trait predicates.
PredicateFilter::SelfTraitThatDefines(_) => {}

View file

@ -17,7 +17,6 @@ use smallvec::{SmallVec, smallvec};
use tracing::{debug, instrument};
use super::HirTyLowerer;
use crate::bounds::Bounds;
use crate::hir_ty_lowering::{
GenericArgCountMismatch, GenericArgCountResult, PredicateFilter, RegionInferReason,
};
@ -36,7 +35,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
let tcx = self.tcx();
let dummy_self = tcx.types.trait_object_dummy_self;
let mut user_written_bounds = Bounds::default();
let mut user_written_bounds = Vec::new();
let mut potential_assoc_types = Vec::new();
for trait_bound in hir_bounds.iter() {
if let hir::BoundPolarity::Maybe(_) = trait_bound.modifiers.polarity {
@ -60,15 +59,17 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
}
let (trait_bounds, mut projection_bounds) =
traits::expand_trait_aliases(tcx, user_written_bounds.clauses());
traits::expand_trait_aliases(tcx, user_written_bounds.iter().copied());
let (regular_traits, mut auto_traits): (Vec<_>, Vec<_>) = trait_bounds
.into_iter()
.partition(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
// We don't support empty trait objects.
if regular_traits.is_empty() && auto_traits.is_empty() {
let guar =
self.report_trait_object_with_no_traits_error(span, user_written_bounds.clauses());
let guar = self.report_trait_object_with_no_traits_error(
span,
user_written_bounds.iter().copied(),
);
return Ty::new_error(tcx, guar);
}
// We don't support >1 principal
@ -84,7 +85,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
// Check that there are no gross dyn-compatibility violations;
// most importantly, that the supertraits don't contain `Self`,
// to avoid ICEs.
for (clause, span) in user_written_bounds.clauses() {
for (clause, span) in user_written_bounds {
if let Some(trait_pred) = clause.as_trait_clause() {
let violations =
hir_ty_lowering_dyn_compatibility_violations(tcx, trait_pred.def_id());

View file

@ -225,7 +225,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
&& let item_def_id =
tcx.hir().get_parent_item(tcx.local_def_id_to_hir_id(ty_param_def_id))
// FIXME: ...which obviously won't have any generics.
&& let Some(generics) = tcx.hir().get_generics(item_def_id.def_id)
&& let Some(generics) = tcx.hir_get_generics(item_def_id.def_id)
{
// FIXME: Suggest adding supertrait bounds if we have a `Self` type param.
// FIXME(trait_alias): Suggest adding `Self: Trait` to

View file

@ -70,7 +70,7 @@ fn generic_arg_mismatch_err(
}
Res::Def(DefKind::TyParam, src_def_id) => {
if let Some(param_local_id) = param.def_id.as_local() {
let param_name = tcx.hir().ty_param_name(param_local_id);
let param_name = tcx.hir_ty_param_name(param_local_id);
let param_type = tcx.type_of(param.def_id).instantiate_identity();
if param_type.is_suggestable(tcx, false) {
err.span_suggestion(
@ -110,7 +110,7 @@ fn generic_arg_mismatch_err(
err.help(format!("`{}` is a function item, not a type", tcx.item_name(id)));
err.help("function item types cannot be named directly");
} else if let hir::ConstArgKind::Anon(anon) = cnst.kind
&& let body = tcx.hir().body(anon.body)
&& let body = tcx.hir_body(anon.body)
&& let rustc_hir::ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) =
body.value.kind
&& let Res::Def(DefKind::Fn { .. }, id) = path.res

View file

@ -49,11 +49,13 @@ use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw};
use rustc_trait_selection::infer::InferCtxtExt;
use rustc_trait_selection::traits::wf::object_region_bounds;
use rustc_trait_selection::traits::{self, ObligationCtxt};
use rustc_type_ir::Upcast;
use tracing::{debug, instrument};
use crate::bounds::Bounds;
use crate::check::check_abi_fn_ptr;
use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation, InvalidBaseType};
use crate::errors::{
AmbiguousLifetimeBound, BadReturnTypeNotation, InvalidBaseType, NoVariantNamed,
};
use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
use crate::middle::resolve_bound_vars as rbv;
@ -217,7 +219,7 @@ impl AssocItemQSelf {
fn to_string(&self, tcx: TyCtxt<'_>) -> String {
match *self {
Self::Trait(def_id) => tcx.def_path_str(def_id),
Self::TyParam(def_id, _) => tcx.hir().ty_param_name(def_id).to_string(),
Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
Self::SelfTyAlias => kw::SelfUpper.to_string(),
}
}
@ -342,8 +344,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
}
rbv::ResolvedArg::EarlyBound(def_id) => {
let name = tcx.hir().ty_param_name(def_id);
let item_def_id = tcx.hir().ty_param_owner(def_id);
let name = tcx.hir_ty_param_name(def_id);
let item_def_id = tcx.hir_ty_param_owner(def_id);
let generics = tcx.generics_of(item_def_id);
let index = generics.param_def_id_to_index[&def_id.to_def_id()];
ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
@ -691,7 +693,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
constness: hir::BoundConstness,
polarity: hir::BoundPolarity,
self_ty: Ty<'tcx>,
bounds: &mut Bounds<'tcx>,
bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
predicate_filter: PredicateFilter,
) -> GenericArgCountResult {
let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
@ -720,6 +722,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
bound_vars,
);
debug!(?poly_trait_ref);
let polarity = match polarity {
rustc_ast::BoundPolarity::Positive => ty::PredicatePolarity::Positive,
rustc_ast::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
@ -741,6 +745,26 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
}
};
// We deal with const conditions later.
match predicate_filter {
PredicateFilter::All
| PredicateFilter::SelfOnly
| PredicateFilter::SelfTraitThatDefines(..)
| PredicateFilter::SelfAndAssociatedTypeBounds => {
let bound = poly_trait_ref.map_bound(|trait_ref| {
ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
});
let bound = (bound.upcast(tcx), span);
// FIXME(-Znext-solver): We can likely remove this hack once the new trait solver lands.
if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
bounds.insert(0, bound);
} else {
bounds.push(bound);
}
}
PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
}
if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
&& !self.tcx().is_const_trait(trait_def_id)
{
@ -765,58 +789,53 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
suggestion_pre,
suggestion,
});
}
match predicate_filter {
// This is only concerned with trait predicates.
PredicateFilter::SelfTraitThatDefines(..) => {
bounds.push_trait_bound(tcx, poly_trait_ref, span, polarity);
}
PredicateFilter::All
| PredicateFilter::SelfOnly
| PredicateFilter::SelfAndAssociatedTypeBounds => {
debug!(?poly_trait_ref);
bounds.push_trait_bound(tcx, poly_trait_ref, span, polarity);
match constness {
hir::BoundConstness::Always(span) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push_const_bound(
tcx,
poly_trait_ref,
ty::BoundConstness::Const,
span,
);
} else {
match predicate_filter {
// This is only concerned with trait predicates.
PredicateFilter::SelfTraitThatDefines(..) => {}
PredicateFilter::All
| PredicateFilter::SelfOnly
| PredicateFilter::SelfAndAssociatedTypeBounds => {
match constness {
hir::BoundConstness::Always(span) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((
poly_trait_ref
.to_host_effect_clause(tcx, ty::BoundConstness::Const),
span,
));
}
}
hir::BoundConstness::Maybe(_) => {
// We don't emit a const bound here, since that would mean that we
// unconditionally need to prove a `HostEffect` predicate, even when
// the predicates are being instantiated in a non-const context. This
// is instead handled in the `const_conditions` query.
}
hir::BoundConstness::Never => {}
}
hir::BoundConstness::Maybe(_) => {
// We don't emit a const bound here, since that would mean that we
// unconditionally need to prove a `HostEffect` predicate, even when
// the predicates are being instantiated in a non-const context. This
// is instead handled in the `const_conditions` query.
}
// On the flip side, when filtering `ConstIfConst` bounds, we only need to convert
// `~const` bounds. All other predicates are handled in their respective queries.
//
// Note that like `PredicateFilter::SelfOnly`, we don't need to do any filtering
// here because we only call this on self bounds, and deal with the recursive case
// in `lower_assoc_item_constraint`.
PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
match constness {
hir::BoundConstness::Maybe(span) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((
poly_trait_ref
.to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
span,
));
}
}
hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
}
hir::BoundConstness::Never => {}
}
}
// On the flip side, when filtering `ConstIfConst` bounds, we only need to convert
// `~const` bounds. All other predicates are handled in their respective queries.
//
// Note that like `PredicateFilter::SelfOnly`, we don't need to do any filtering
// here because we only call this on self bounds, and deal with the recursive case
// in `lower_assoc_item_constraint`.
PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => match constness {
hir::BoundConstness::Maybe(span) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push_const_bound(
tcx,
poly_trait_ref,
ty::BoundConstness::Maybe,
span,
);
}
}
hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
},
}
let mut dup_constraints = FxIndexMap::default();
@ -1188,14 +1207,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
let msg = format!("expected type, found variant `{assoc_ident}`");
self.dcx().span_err(span, msg)
} else if qself_ty.is_enum() {
let mut err = struct_span_code_err!(
self.dcx(),
assoc_ident.span,
E0599,
"no variant named `{}` found for enum `{}`",
assoc_ident,
qself_ty,
);
let mut err = self.dcx().create_err(NoVariantNamed {
span: assoc_ident.span,
ident: assoc_ident,
ty: qself_ty,
});
let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
if let Some(variant_name) = find_best_match_for_name(
@ -1976,7 +1992,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
if let Some(hir::Node::Item(&hir::Item {
kind: hir::ItemKind::Impl(impl_),
..
})) = tcx.hir().get_if_local(def_id)
})) = tcx.hir_get_if_local(def_id)
{
err.span_note(impl_.self_ty.span, "not a concrete type");
}
@ -2053,10 +2069,10 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
Ty::new_bound(tcx, debruijn, br)
}
Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
let item_def_id = tcx.hir().ty_param_owner(def_id);
let item_def_id = tcx.hir_ty_param_owner(def_id);
let generics = tcx.generics_of(item_def_id);
let index = generics.param_def_id_to_index[&def_id.to_def_id()];
Ty::new_param(tcx, index, tcx.hir().ty_param_name(def_id))
Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
}
Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
arg => bug!("unexpected bound var resolution for {hir_id:?}: {arg:?}"),
@ -2213,7 +2229,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
fn lower_anon_const(&self, anon: &AnonConst) -> Const<'tcx> {
let tcx = self.tcx();
let expr = &tcx.hir().body(anon.body).value;
let expr = &tcx.hir_body(anon.body).value;
debug!(?expr);
let ty = tcx
@ -2382,7 +2398,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
// Impl trait in bindings lower as an infer var with additional
// set of type bounds.
let self_ty = self.ty_infer(None, hir_ty.span);
let mut bounds = Bounds::default();
let mut bounds = Vec::new();
self.lower_bounds(
self_ty,
hir_bounds.iter(),
@ -2390,11 +2406,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
ty::List::empty(),
PredicateFilter::All,
);
self.register_trait_ascription_bounds(
bounds.clauses().collect(),
hir_ty.hir_id,
hir_ty.span,
);
self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
self_ty
}
// If we encounter a type relative path with RTN generics, then it must have

View file

@ -22,8 +22,6 @@ fn diagnostic_hir_wf_check<'tcx>(
tcx: TyCtxt<'tcx>,
(predicate, loc): (ty::Predicate<'tcx>, WellFormedLoc),
) -> Option<ObligationCause<'tcx>> {
let hir = tcx.hir();
let def_id = match loc {
WellFormedLoc::Ty(def_id) => def_id,
WellFormedLoc::Param { function, param_idx: _ } => function,
@ -187,7 +185,7 @@ fn diagnostic_hir_wf_check<'tcx>(
ref node => bug!("Unexpected node {:?}", node),
},
WellFormedLoc::Param { function: _, param_idx } => {
let fn_decl = hir.fn_decl_by_hir_id(hir_id).unwrap();
let fn_decl = tcx.hir_fn_decl_by_hir_id(hir_id).unwrap();
// Get return type
if param_idx as usize == fn_decl.inputs.len() {
match fn_decl.output {

View file

@ -80,7 +80,6 @@ This API is completely unstable and subject to change.
pub mod check;
pub mod autoderef;
mod bounds;
mod check_unused;
mod coherence;
mod collect;
@ -93,6 +92,7 @@ mod impl_wf_check;
mod outlives;
mod variance;
pub use errors::NoVariantNamed;
use rustc_abi::ExternAbi;
use rustc_hir as hir;
use rustc_hir::def::DefKind;
@ -184,7 +184,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) {
// what we are intending to discard, to help future type-based refactoring.
type R = Result<(), ErrorGuaranteed>;
tcx.hir().par_for_each_module(|module| {
tcx.par_hir_for_each_module(|module| {
let _: R = tcx.ensure_ok().check_mod_type_wf(module);
});
@ -209,7 +209,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) {
// Make sure we evaluate all static and (non-associated) const items, even if unused.
// If any of these fail to evaluate, we do not want this crate to pass compilation.
tcx.hir().par_body_owners(|item_def_id| {
tcx.par_hir_body_owners(|item_def_id| {
let def_kind = tcx.def_kind(item_def_id);
match def_kind {
DefKind::Static { .. } => tcx.ensure_ok().eval_static_initializer(item_def_id),
@ -227,7 +227,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) {
// for anon constants during their parents' typeck.
// Typeck all body owners in parallel will produce queries
// cycle errors because it may typeck on anon constants directly.
tcx.hir().par_body_owners(|item_def_id| {
tcx.par_hir_body_owners(|item_def_id| {
let def_kind = tcx.def_kind(item_def_id);
if !matches!(def_kind, DefKind::AnonConst) {
tcx.ensure_ok().typeck(item_def_id);

View file

@ -3,7 +3,7 @@ use rustc_middle::ty::{self, TyCtxt};
use rustc_span::sym;
pub(crate) fn inferred_outlives(tcx: TyCtxt<'_>) {
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
if !tcx.has_attr(id.owner_id, sym::rustc_outlives) {
continue;
}

View file

@ -28,7 +28,7 @@ pub(super) fn infer_predicates(
let mut predicates_added = false;
// Visit all the crates and infer predicates
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
let item_did = id.owner_id;
debug!("InferVisitor::visit_item(item={:?})", item_did);

View file

@ -25,8 +25,8 @@ use rustc_span::source_map::SourceMap;
use rustc_span::{FileName, Ident, Span, Symbol, kw};
use {rustc_ast as ast, rustc_hir as hir};
pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: HirId) -> String {
to_string(&map, |s| s.print_node(map.hir_node(hir_id)))
pub fn id_to_string(cx: &dyn rustc_hir::intravisit::HirTyCtxt<'_>, hir_id: HirId) -> String {
to_string(&cx, |s| s.print_node(cx.hir_node(hir_id)))
}
pub enum AnnNode<'a> {
@ -55,15 +55,15 @@ pub trait PpAnn {
fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
}
impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
impl PpAnn for &dyn rustc_hir::intravisit::HirTyCtxt<'_> {
fn nested(&self, state: &mut State<'_>, nested: Nested) {
match nested {
Nested::Item(id) => state.print_item(self.item(id)),
Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
Nested::Body(id) => state.print_expr(self.body(id).value),
Nested::BodyParamPat(id, i) => state.print_pat(self.body(id).params[i].pat),
Nested::Item(id) => state.print_item(self.hir_item(id)),
Nested::TraitItem(id) => state.print_trait_item(self.hir_trait_item(id)),
Nested::ImplItem(id) => state.print_impl_item(self.hir_impl_item(id)),
Nested::ForeignItem(id) => state.print_foreign_item(self.hir_foreign_item(id)),
Nested::Body(id) => state.print_expr(self.hir_body(id).value),
Nested::BodyParamPat(id, i) => state.print_pat(self.hir_body(id).params[i].pat),
}
}
}

View file

@ -213,10 +213,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
arm_ty: Ty<'tcx>,
prior_arm: Option<(Option<hir::HirId>, Ty<'tcx>, Span)>,
) {
let hir = self.tcx.hir();
// First, check that we're actually in the tail of a function.
let Some(body) = hir.maybe_body_owned_by(self.body_id) else {
let Some(body) = self.tcx.hir_maybe_body_owned_by(self.body_id) else {
return;
};
let hir::ExprKind::Block(block, _) = body.value.kind else {

View file

@ -708,8 +708,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&& let Res::Local(_) = path.res
&& let [segment] = &path.segments
{
for id in self.tcx.hir().items() {
if let Some(node) = self.tcx.hir().get_if_local(id.owner_id.into())
for id in self.tcx.hir_free_items() {
if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
&& let hir::Node::Item(item) = node
&& let hir::ItemKind::Fn { .. } = item.kind
&& item.ident.name == segment.ident.name
@ -860,7 +860,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
return;
}
let host = match self.tcx.hir().body_const_context(self.body_id) {
let host = match self.tcx.hir_body_const_context(self.body_id) {
Some(hir::ConstContext::Const { .. } | hir::ConstContext::Static(_)) => {
ty::BoundConstness::Const
}

View file

@ -35,12 +35,8 @@ pub(super) fn check_fn<'a, 'tcx>(
params_can_be_unsized: bool,
) -> Option<CoroutineTypes<'tcx>> {
let fn_id = fcx.tcx.local_def_id_to_hir_id(fn_def_id);
let tcx = fcx.tcx;
let hir = tcx.hir();
let declared_ret_ty = fn_sig.output();
let ret_ty =
fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(
declared_ret_ty,
@ -69,7 +65,7 @@ pub(super) fn check_fn<'a, 'tcx>(
});
// Add formal parameters.
let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
let inputs_hir = tcx.hir_fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
let inputs_fn = fn_sig.inputs().iter().copied();
for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
// We checked the root's signature during wfcheck, but not the child.

View file

@ -51,7 +51,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let tcx = self.tcx;
let body = tcx.hir().body(closure.body);
let body = tcx.hir_body(closure.body);
let expr_def_id = closure.def_id;
// It's always helpful for inference if we know the kind of

View file

@ -1891,7 +1891,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
..
}) = parent
&& !matches!(fcx.tcx.hir().body(body).value.kind, hir::ExprKind::Block(..))
&& !matches!(fcx.tcx.hir_body(body).value.kind, hir::ExprKind::Block(..))
{
fcx.suggest_missing_semicolon(&mut err, expr, expected, true);
}
@ -1943,7 +1943,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
if due_to_block
&& let Some(expr) = expression
&& let Some(parent_fn_decl) =
fcx.tcx.hir().fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_id))
fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_id))
{
fcx.suggest_missing_break_or_return_expr(
&mut err,

View file

@ -293,8 +293,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
expr: &hir::Expr<'_>,
source: TypeMismatchSource<'tcx>,
) -> bool {
let hir = self.tcx.hir();
let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else {
return false;
};
@ -334,7 +332,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
let mut expr_finder = FindExprs { hir_id: local_hir_id, uses: init.into_iter().collect() };
let body = hir.body_owned_by(self.body_id);
let body = self.tcx.hir_body_owned_by(self.body_id);
expr_finder.visit_expr(body.value);
// Replaces all of the variables in the given type with a fresh inference variable.
@ -727,7 +725,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
ident,
kind: hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..),
..
})) = self.tcx.hir().get_if_local(*def_id)
})) = self.tcx.hir_get_if_local(*def_id)
{
primary_span = ty.span;
secondary_span = ident.span;
@ -1173,7 +1171,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Some(hir::Node::Item(hir::Item {
kind: hir::ItemKind::Impl(hir::Impl { self_ty, .. }),
..
})) = self.tcx.hir().get_if_local(*alias_to)
})) = self.tcx.hir_get_if_local(*alias_to)
{
err.span_label(self_ty.span, "this is the type of the `Self` literal");
}

View file

@ -19,6 +19,7 @@ use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::Visitor;
use rustc_hir::lang_items::LangItem;
use rustc_hir::{ExprKind, HirId, QPath};
use rustc_hir_analysis::NoVariantNamed;
use rustc_hir_analysis::hir_ty_lowering::{FeedConstTy, HirTyLowerer as _};
use rustc_infer::infer;
use rustc_infer::infer::{DefineOpaqueTypes, InferOk};
@ -1150,13 +1151,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// We are inside a function body, so reporting "return statement
// outside of function body" needs an explanation.
let encl_body_owner_id = self.tcx.hir().enclosing_body_owner(expr.hir_id);
let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id);
// If this didn't hold, we would not have to report an error in
// the first place.
assert_ne!(encl_item_id.def_id, encl_body_owner_id);
let encl_body = self.tcx.hir().body_owned_by(encl_body_owner_id);
let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id);
err.encl_body_span = Some(encl_body.value.span);
err.encl_fn_span = Some(*encl_fn_span);
@ -1801,7 +1802,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
block: &'tcx hir::ConstBlock,
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let body = self.tcx.hir().body(block.body);
let body = self.tcx.hir_body(block.body);
// Create a new function context.
let def_id = block.def_id;
@ -3229,7 +3230,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
None => return,
};
let param_span = self.tcx.hir().span(param_hir_id);
let param_name = self.tcx.hir().ty_param_name(param_def_id.expect_local());
let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local());
err.span_label(param_span, format!("type parameter '{param_name}' declared here"));
}
@ -3837,15 +3838,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.iter_enumerated()
.find(|(_, v)| v.ident(self.tcx).normalize_to_macros_2_0() == ident)
else {
type_error_struct!(
self.dcx(),
ident.span,
container,
E0599,
"no variant named `{ident}` found for enum `{container}`",
)
.with_span_label(field.span, "variant not found")
.emit();
self.dcx()
.create_err(NoVariantNamed { span: ident.span, ident, ty: container })
.with_span_label(field.span, "variant not found")
.emit_unless(container.references_error());
break;
};
let Some(&subfield) = fields.next() else {

Some files were not shown because too many files have changed in this diff Show more