rust/compiler/rustc_hir_analysis/src/lib.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

223 lines
7.4 KiB
Rust
Raw Normal View History

2014-11-26 11:11:29 +00:00
/*!
2012-11-29 00:20:41 +00:00
2019-02-08 13:53:55 +00:00
# typeck
2012-11-29 00:20:41 +00:00
The type checker is responsible for:
1. Determining the type of each expression.
2. Resolving methods and traits.
3. Guaranteeing that most type rules are met. ("Most?", you say, "why most?"
Well, dear reader, read on.)
2012-11-29 00:20:41 +00:00
The main entry point is [`check_crate()`]. Type checking operates in
several major phases:
2012-11-29 00:20:41 +00:00
1. The collect phase first passes over all items and determines their
type, without examining their "innards".
2. Variance inference then runs to compute the variance of each parameter.
3. Coherence checks for overlapping or orphaned impls.
4. Finally, the check phase then checks function bodies and so forth.
Within the check phase, we check each function body one at a time
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the
documentation for the [`check`] module.
2012-11-29 00:20:41 +00:00
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation.
2012-11-29 00:20:41 +00:00
- collect: computes the types of each top-level item and enters them into
the `tcx.types` table for later use.
2012-11-29 00:20:41 +00:00
- coherence: enforces coherence rules, builds some tables.
- variance: variance inference
- outlives: outlives inference
2012-11-29 00:20:41 +00:00
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
2012-11-29 00:20:41 +00:00
module specifies the constraints, and the infer module solves them.
## Note
2014-11-26 11:11:29 +00:00
This API is completely unstable and subject to change.
2012-11-29 00:20:41 +00:00
*/
#![allow(rustc::diagnostic_outside_of_impl)]
2022-02-26 10:43:47 +00:00
#![allow(rustc::potential_query_instability)]
#![allow(rustc::untranslatable_diagnostic)]
2020-09-23 19:51:56 +00:00
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2023-11-13 12:39:17 +00:00
#![doc(rust_logo)]
#![feature(rustdoc_internals)]
#![allow(internal_features)]
2022-02-26 10:43:47 +00:00
#![feature(control_flow_enum)]
2024-01-29 22:59:09 +00:00
#![feature(generic_nonzero)]
2021-08-16 15:29:49 +00:00
#![feature(if_let_guard)]
#![feature(is_sorted)]
2022-04-13 14:49:03 +00:00
#![feature(iter_intersperse)]
#![feature(let_chains)]
#![feature(never_type)]
#![feature(lazy_cell)]
2022-02-26 10:43:47 +00:00
#![feature(slice_partition_dedup)]
#![feature(try_blocks)]
#[macro_use]
2020-08-14 06:05:01 +00:00
extern crate tracing;
#[macro_use]
2020-03-29 14:41:09 +00:00
extern crate rustc_middle;
2014-11-26 11:11:29 +00:00
2020-08-03 00:19:33 +00:00
// These are used by Clippy.
pub mod check;
pub mod astconv;
2022-12-27 00:39:36 +00:00
pub mod autoderef;
mod bounds;
mod check_unused;
mod coherence;
// FIXME: This module shouldn't be public.
pub mod collect;
mod constrained_generic_params;
mod errors;
Add initial implementation of HIR-based WF checking for diagnostics During well-formed checking, we walk through all types 'nested' in generic arguments. For example, WF-checking `Option<MyStruct<u8>>` will cause us to check `MyStruct<u8>` and `u8`. However, this is done on a `rustc_middle::ty::Ty`, which has no span information. As a result, any errors that occur will have a very general span (e.g. the definintion of an associated item). This becomes a problem when macros are involved. In general, an associated type like `type MyType = Option<MyStruct<u8>>;` may have completely different spans for each nested type in the HIR. Using the span of the entire associated item might end up pointing to a macro invocation, even though a user-provided span is available in one of the nested types. This PR adds a framework for HIR-based well formed checking. This check is only run during error reporting, and is used to obtain a more precise span for an existing error. This is accomplished by individually checking each 'nested' type in the HIR for the type, allowing us to find the most-specific type (and span) that produces a given error. The majority of the changes are to the error-reporting code. However, some of the general trait code is modified to pass through more information. Since this has no soundness implications, I've implemented a minimal version to begin with, which can be extended over time. In particular, this only works for HIR items with a corresponding `DefId` (e.g. it will not work for WF-checking performed within function bodies).
2021-04-04 20:55:39 +00:00
pub mod hir_wf_check;
mod impl_wf_check;
mod outlives;
pub mod structured_errors;
mod variance;
use rustc_errors::ErrorGuaranteed;
use rustc_hir as hir;
2024-03-15 01:19:29 +00:00
use rustc_hir::def::DefKind;
2020-03-29 14:41:09 +00:00
use rustc_middle::middle;
use rustc_middle::query::Providers;
2024-03-15 01:19:29 +00:00
use rustc_middle::ty::{Ty, TyCtxt};
2020-03-29 14:41:09 +00:00
use rustc_middle::util;
use rustc_session::parse::feature_err;
2024-03-15 01:19:29 +00:00
use rustc_span::{symbol::sym, Span};
use rustc_target::spec::abi::Abi;
use rustc_trait_selection::traits;
rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
2019-12-01 15:08:58 +00:00
fn require_c_abi_if_c_variadic(tcx: TyCtxt<'_>, decl: &hir::FnDecl<'_>, abi: Abi, span: Span) {
2024-01-13 07:05:07 +00:00
const CONVENTIONS_UNSTABLE: &str =
"`C`, `cdecl`, `system`, `aapcs`, `win64`, `sysv64` or `efiapi`";
const CONVENTIONS_STABLE: &str = "`C` or `cdecl`";
const UNSTABLE_EXPLAIN: &str =
2022-10-23 23:11:25 +00:00
"using calling conventions other than `C` or `cdecl` for varargs functions is unstable";
if !decl.c_variadic || matches!(abi, Abi::C { .. } | Abi::Cdecl { .. }) {
return;
}
let extended_abi_support = tcx.features().extended_varargs_abi_support;
let conventions = match (extended_abi_support, abi.supports_varargs()) {
// User enabled additional ABI support for varargs and function ABI matches those ones.
(true, true) => return,
// Using this ABI would be ok, if the feature for additional ABI support was enabled.
// Return CONVENTIONS_STABLE, because we want the other error to look the same.
(false, true) => {
feature_err(&tcx.sess, sym::extended_varargs_abi_support, span, UNSTABLE_EXPLAIN)
.emit();
CONVENTIONS_STABLE
rustc_target: add "unwind" payloads to `Abi` ### Overview This commit begins the implementation work for RFC 2945. For more information, see the rendered RFC [1] and tracking issue [2]. A boolean `unwind` payload is added to the `C`, `System`, `Stdcall`, and `Thiscall` variants, marking whether unwinding across FFI boundaries is acceptable. The cases where each of these variants' `unwind` member is true correspond with the `C-unwind`, `system-unwind`, `stdcall-unwind`, and `thiscall-unwind` ABI strings introduced in RFC 2945 [3]. ### Feature Gate and Unstable Book This commit adds a `c_unwind` feature gate for the new ABI strings. Tests for this feature gate are included in `src/test/ui/c-unwind/`, which ensure that this feature gate works correctly for each of the new ABIs. A new language features entry in the unstable book is added as well. ### Further Work To Be Done This commit does not proceed to implement the new unwinding ABIs, and is intentionally scoped specifically to *defining* the ABIs and their feature flag. ### One Note on Test Churn This will lead to some test churn, in re-blessing hash tests, as the deleted comment in `src/librustc_target/spec/abi.rs` mentioned, because we can no longer guarantee the ordering of the `Abi` variants. While this is a downside, this decision was made bearing in mind that RFC 2945 states the following, in the "Other `unwind` Strings" section [3]: > More unwind variants of existing ABI strings may be introduced, > with the same semantics, without an additional RFC. Adding a new variant for each of these cases, rather than specifying a payload for a given ABI, would quickly become untenable, and make working with the `Abi` enum prone to mistakes. This approach encodes the unwinding information *into* a given ABI, to account for the future possibility of other `-unwind` ABI strings. ### Ignore Directives `ignore-*` directives are used in two of our `*-unwind` ABI test cases. Specifically, the `stdcall-unwind` and `thiscall-unwind` test cases ignore architectures that do not support `stdcall` and `thiscall`, respectively. These directives are cribbed from `src/test/ui/c-variadic/variadic-ffi-1.rs` for `stdcall`, and `src/test/ui/extern/extern-thiscall.rs` for `thiscall`. This would otherwise fail on some targets, see: https://github.com/rust-lang-ci/rust/commit/fcf697f90206e9c87b39d494f94ab35d976bfc60 ### Footnotes [1]: https://github.com/rust-lang/rfcs/blob/master/text/2945-c-unwind-abi.md [2]: https://github.com/rust-lang/rust/issues/74990 [3]: https://github.com/rust-lang/rfcs/blob/master/text/2945-c-unwind-abi.md#other-unwind-abi-strings
2020-08-27 15:49:18 +00:00
}
(false, false) => CONVENTIONS_STABLE,
(true, false) => CONVENTIONS_UNSTABLE,
};
tcx.dcx().emit_err(errors::VariadicFunctionCompatibleConvention { span, conventions });
}
pub fn provide(providers: &mut Providers) {
collect::provide(providers);
coherence::provide(providers);
check::provide(providers);
2022-01-30 16:14:54 +00:00
check_unused::provide(providers);
variance::provide(providers);
outlives::provide(providers);
Add initial implementation of HIR-based WF checking for diagnostics During well-formed checking, we walk through all types 'nested' in generic arguments. For example, WF-checking `Option<MyStruct<u8>>` will cause us to check `MyStruct<u8>` and `u8`. However, this is done on a `rustc_middle::ty::Ty`, which has no span information. As a result, any errors that occur will have a very general span (e.g. the definintion of an associated item). This becomes a problem when macros are involved. In general, an associated type like `type MyType = Option<MyStruct<u8>>;` may have completely different spans for each nested type in the HIR. Using the span of the entire associated item might end up pointing to a macro invocation, even though a user-provided span is available in one of the nested types. This PR adds a framework for HIR-based well formed checking. This check is only run during error reporting, and is used to obtain a more precise span for an existing error. This is accomplished by individually checking each 'nested' type in the HIR for the type, allowing us to find the most-specific type (and span) that produces a given error. The majority of the changes are to the error-reporting code. However, some of the general trait code is modified to pass through more information. Since this has no soundness implications, I've implemented a minimal version to begin with, which can be extended over time. In particular, this only works for HIR items with a corresponding `DefId` (e.g. it will not work for WF-checking performed within function bodies).
2021-04-04 20:55:39 +00:00
hir_wf_check::provide(providers);
}
pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> {
let _prof_timer = tcx.sess.timer("type_check_crate");
2018-05-19 17:50:58 +00:00
2019-01-26 14:26:49 +00:00
if tcx.features().rustc_attrs {
tcx.sess.time("outlives_testing", || outlives::test::test_inferred_outlives(tcx))?;
2019-01-26 14:26:49 +00:00
}
tcx.sess.time("coherence_checking", || {
tcx.hir().par_for_each_module(|module| {
let _ = tcx.ensure().check_mod_type_wf(module);
});
2024-01-23 15:23:22 +00:00
for &trait_def_id in tcx.all_local_trait_impls(()).keys() {
let _ = tcx.ensure().coherent_trait(trait_def_id);
2024-01-23 15:23:22 +00:00
}
// these queries are executed for side-effects (error reporting):
let _ = tcx.ensure().crate_inherent_impls(());
let _ = tcx.ensure().crate_inherent_impls_overlap_check(());
});
2013-03-21 10:28:58 +00:00
if tcx.features().rustc_attrs {
tcx.sess.time("variance_testing", || variance::test::test_variance(tcx))?;
}
if tcx.features().rustc_attrs {
collect::test_opaque_hidden_types(tcx)?;
}
// 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| {
let def_kind = tcx.def_kind(item_def_id);
match def_kind {
DefKind::Static { .. } => tcx.ensure().eval_static_initializer(item_def_id),
DefKind::Const => tcx.ensure().const_eval_poly(item_def_id.into()),
_ => (),
}
});
2023-09-01 22:25:54 +00:00
// Freeze definitions as we don't add new ones at this point. This improves performance by
// allowing lock-free access to them.
tcx.untracked().definitions.freeze();
// FIXME: Remove this when we implement creating `DefId`s
// 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| {
let def_kind = tcx.def_kind(item_def_id);
if !matches!(def_kind, DefKind::AnonConst) {
tcx.ensure().typeck(item_def_id);
}
});
tcx.ensure().check_unused_traits(());
Ok(())
2012-11-29 00:20:41 +00:00
}
/// A quasi-deprecated helper used in rustdoc and clippy to get
/// the type from a HIR node.
pub fn hir_ty_to_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
// In case there are any projections, etc., find the "environment"
// def-ID that will be used to determine the traits/predicates in
// scope. This is derived from the enclosing item-like thing.
let env_def_id = tcx.hir().get_parent_item(hir_ty.hir_id);
2024-03-15 01:19:29 +00:00
collect::ItemCtxt::new(tcx, env_def_id.def_id).to_ty(hir_ty)
}