Skip to content

Commit

Permalink
Auto merge of rust-lang#116052 - oli-obk:ceci_nest_pas_une_query, r=W…
Browse files Browse the repository at this point in the history
…affleLapkin

Add a way to decouple the implementation and the declaration of a TyCtxt method.

properly addresses rust-lang#115819

accepted MCP: rust-lang/compiler-team#395
  • Loading branch information
bors committed Sep 23, 2023
2 parents 2d08657 + 4ed4913 commit bf98263
Show file tree
Hide file tree
Showing 24 changed files with 143 additions and 72 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_gcc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ use rustc_errors::{DiagnosticMessage, ErrorGuaranteed, Handler, SubdiagnosticMes
use rustc_fluent_macro::fluent_messages;
use rustc_metadata::EncodedMetadata;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
use rustc_middle::query::Providers;
use rustc_middle::util::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_session::config::{Lto, OptLevel, OutputFilenames};
use rustc_session::Session;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ use rustc_errors::{DiagnosticMessage, ErrorGuaranteed, FatalError, Handler, Subd
use rustc_fluent_macro::fluent_messages;
use rustc_metadata::EncodedMetadata;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
use rustc_middle::query::Providers;
use rustc_middle::ty::TyCtxt;
use rustc_middle::util::Providers;
use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
use rustc_session::Session;
use rustc_span::symbol::Symbol;
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_codegen_ssa/src/back/symbol_export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ use rustc_middle::middle::exported_symbols::{
metadata_symbol_name, ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
};
use rustc_middle::query::LocalCrate;
use rustc_middle::query::{ExternProviders, Providers};
use rustc_middle::ty::Instance;
use rustc_middle::ty::{self, SymbolName, TyCtxt};
use rustc_middle::ty::{GenericArgKind, GenericArgsRef};
use rustc_middle::util::Providers;
use rustc_session::config::{CrateType, OomStrategy};
use rustc_target::spec::SanitizerSet;

Expand Down Expand Up @@ -457,11 +457,9 @@ pub fn provide(providers: &mut Providers) {
providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
providers.upstream_drop_glue_for = upstream_drop_glue_for_provider;
providers.wasm_import_module_map = wasm_import_module_map;
}

pub fn provide_extern(providers: &mut ExternProviders) {
providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
providers.extern_queries.upstream_monomorphizations_for =
upstream_monomorphizations_for_provider;
}

fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
Expand Down
6 changes: 1 addition & 5 deletions compiler/rustc_codegen_ssa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use rustc_middle::dep_graph::WorkProduct;
use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
use rustc_middle::middle::dependency_format::Dependencies;
use rustc_middle::middle::exported_symbols::SymbolExportKind;
use rustc_middle::query::{ExternProviders, Providers};
use rustc_middle::util::Providers;
use rustc_serialize::opaque::{FileEncoder, MemDecoder};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use rustc_session::config::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT};
Expand Down Expand Up @@ -190,10 +190,6 @@ pub fn provide(providers: &mut Providers) {
crate::codegen_attrs::provide(providers);
}

pub fn provide_extern(providers: &mut ExternProviders) {
crate::back::symbol_export::provide_extern(providers);
}

/// Checks if the given filename ends with the `.rcgu.o` extension that `rustc`
/// uses for the object files it generates.
pub fn looks_like_rust_object_file(filename: &str) -> bool {
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_codegen_ssa/src/traits/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ use rustc_data_structures::sync::{DynSend, DynSync};
use rustc_errors::ErrorGuaranteed;
use rustc_metadata::EncodedMetadata;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
use rustc_middle::query::{ExternProviders, Providers};
use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, LayoutOf, TyAndLayout};
use rustc_middle::ty::{Ty, TyCtxt};
use rustc_middle::util::Providers;
use rustc_session::{
config::{self, OutputFilenames, PrintRequest},
cstore::MetadataLoaderDyn,
Expand Down Expand Up @@ -85,7 +85,6 @@ pub trait CodegenBackend {
}

fn provide(&self, _providers: &mut Providers) {}
fn provide_extern(&self, _providers: &mut ExternProviders) {}
fn codegen_crate<'tcx>(
&self,
tcx: TyCtxt<'tcx>,
Expand Down
7 changes: 4 additions & 3 deletions compiler/rustc_const_eval/src/const_eval/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::errors::MaxNumNodesInConstErr;
use crate::interpret::{intern_const_alloc_recursive, InternKind, InterpCx, Scalar};
use rustc_middle::mir;
use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId};
use rustc_middle::query::TyCtxtAt;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{source_map::DUMMY_SP, symbol::Symbol};

Expand Down Expand Up @@ -86,17 +87,17 @@ pub(crate) fn eval_to_valtree<'tcx>(

#[instrument(skip(tcx), level = "debug")]
pub(crate) fn try_destructure_mir_constant_for_diagnostics<'tcx>(
tcx: TyCtxt<'tcx>,
tcx: TyCtxtAt<'tcx>,
val: mir::ConstValue<'tcx>,
ty: Ty<'tcx>,
) -> Option<mir::DestructuredConstant<'tcx>> {
let param_env = ty::ParamEnv::reveal_all();
let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, CanAccessStatics::No);
let ecx = mk_eval_cx(tcx.tcx, tcx.span, param_env, CanAccessStatics::No);
let op = ecx.const_val_to_op(val, ty, None).ok()?;

// We go to `usize` as we cannot allocate anything bigger anyway.
let (field_count, variant, down) = match ty.kind() {
ty::Array(_, len) => (len.eval_target_usize(tcx, param_env) as usize, None, op),
ty::Array(_, len) => (len.eval_target_usize(tcx.tcx, param_env) as usize, None, op),
ty::Adt(def, _) if def.variants().is_empty() => {
return None;
}
Expand Down
7 changes: 3 additions & 4 deletions compiler/rustc_const_eval/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,7 @@ pub use errors::ReportErrorExt;

use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage};
use rustc_fluent_macro::fluent_messages;
use rustc_middle::query::Providers;
use rustc_middle::ty;
use rustc_middle::{ty, util::Providers};

fluent_messages! { "../messages.ftl" }

Expand All @@ -52,8 +51,8 @@ pub fn provide(providers: &mut Providers) {
let (param_env, raw) = param_env_and_value.into_parts();
const_eval::eval_to_valtree(tcx, param_env, raw)
};
providers.try_destructure_mir_constant_for_diagnostics =
|tcx, (cv, ty)| const_eval::try_destructure_mir_constant_for_diagnostics(tcx, cv, ty);
providers.hooks.try_destructure_mir_constant_for_diagnostics =
const_eval::try_destructure_mir_constant_for_diagnostics;
providers.valtree_to_const_val = |tcx, (ty, valtree)| {
const_eval::valtree_to_const_value(tcx, ty::ParamEnv::empty().and(ty), valtree)
};
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_interface/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use rustc_data_structures::sync::Lrc;
use rustc_errors::registry::Registry;
use rustc_errors::{ErrorGuaranteed, Handler};
use rustc_lint::LintStore;
use rustc_middle::query::{ExternProviders, Providers};
use rustc_middle::util::Providers;
use rustc_middle::{bug, ty};
use rustc_parse::maybe_new_parser_from_source_str;
use rustc_query_impl::QueryCtxt;
Expand Down Expand Up @@ -37,7 +37,7 @@ pub struct Compiler {
pub(crate) sess: Lrc<Session>,
codegen_backend: Lrc<dyn CodegenBackend>,
pub(crate) register_lints: Option<Box<dyn Fn(&Session, &mut LintStore) + Send + Sync>>,
pub(crate) override_queries: Option<fn(&Session, &mut Providers, &mut ExternProviders)>,
pub(crate) override_queries: Option<fn(&Session, &mut Providers)>,
}

impl Compiler {
Expand Down Expand Up @@ -271,7 +271,7 @@ pub struct Config {
/// the list of queries.
///
/// The second parameter is local providers and the third parameter is external providers.
pub override_queries: Option<fn(&Session, &mut Providers, &mut ExternProviders)>,
pub override_queries: Option<fn(&Session, &mut Providers)>,

/// This is a callback from the driver that is called to create a codegen backend.
pub make_codegen_backend:
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_interface/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub mod util;

pub use callbacks::setup_callbacks;
pub use interface::{run_compiler, Config};
pub use passes::{DEFAULT_EXTERN_QUERY_PROVIDERS, DEFAULT_QUERY_PROVIDERS};
pub use passes::DEFAULT_QUERY_PROVIDERS;
pub use queries::Queries;

#[cfg(test)]
Expand Down
23 changes: 7 additions & 16 deletions compiler/rustc_interface/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ use rustc_lint::{unerased_lint_store, BufferedEarlyLint, EarlyCheckNode, LintSto
use rustc_metadata::creader::CStore;
use rustc_middle::arena::Arena;
use rustc_middle::dep_graph::DepGraph;
use rustc_middle::query::{ExternProviders, Providers};
use rustc_middle::ty::{self, GlobalCtxt, RegisteredTools, TyCtxt};
use rustc_middle::util::Providers;
use rustc_mir_build as mir_build;
use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str, validate_attr};
use rustc_passes::{self, abi_test, hir_stats, layout_test};
Expand Down Expand Up @@ -675,13 +675,6 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
*providers
});

pub static DEFAULT_EXTERN_QUERY_PROVIDERS: LazyLock<ExternProviders> = LazyLock::new(|| {
let mut extern_providers = ExternProviders::default();
rustc_metadata::provide_extern(&mut extern_providers);
rustc_codegen_ssa::provide_extern(&mut extern_providers);
extern_providers
});

pub fn create_global_ctxt<'tcx>(
compiler: &'tcx Compiler,
crate_types: Vec<CrateType>,
Expand All @@ -702,14 +695,11 @@ pub fn create_global_ctxt<'tcx>(
let query_result_on_disk_cache = rustc_incremental::load_query_result_cache(sess);

let codegen_backend = compiler.codegen_backend();
let mut local_providers = *DEFAULT_QUERY_PROVIDERS;
codegen_backend.provide(&mut local_providers);

let mut extern_providers = *DEFAULT_EXTERN_QUERY_PROVIDERS;
codegen_backend.provide_extern(&mut extern_providers);
let mut providers = *DEFAULT_QUERY_PROVIDERS;
codegen_backend.provide(&mut providers);

if let Some(callback) = compiler.override_queries {
callback(sess, &mut local_providers, &mut extern_providers);
callback(sess, &mut providers);
}

let incremental = dep_graph.is_fully_enabled();
Expand All @@ -727,11 +717,12 @@ pub fn create_global_ctxt<'tcx>(
dep_graph,
rustc_query_impl::query_callbacks(arena),
rustc_query_impl::query_system(
local_providers,
extern_providers,
providers.queries,
providers.extern_queries,
query_result_on_disk_cache,
incremental,
),
providers.hooks,
)
})
})
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ extern crate rustc_middle;
#[macro_use]
extern crate tracing;

pub use rmeta::{provide, provide_extern};
pub use rmeta::provide;
use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage};
use rustc_fluent_macro::fluent_messages;

Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ use std::sync::atomic::Ordering;
use std::{io, iter, mem};

pub(super) use cstore_impl::provide;
pub use cstore_impl::provide_extern;
use rustc_span::hygiene::HygieneDecodeContext;

mod cstore_impl;
Expand Down
10 changes: 6 additions & 4 deletions compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ use rustc_middle::arena::ArenaAllocatable;
use rustc_middle::metadata::ModChild;
use rustc_middle::middle::exported_symbols::ExportedSymbol;
use rustc_middle::middle::stability::DeprecationEntry;
use rustc_middle::query::ExternProviders;
use rustc_middle::query::LocalCrate;
use rustc_middle::query::{ExternProviders, Providers};
use rustc_middle::ty::fast_reject::SimplifiedType;
use rustc_middle::ty::{self, TyCtxt};
use rustc_middle::util::Providers;
use rustc_session::cstore::CrateStore;
use rustc_session::{Session, StableCrateId};
use rustc_span::hygiene::{ExpnHash, ExpnId};
Expand Down Expand Up @@ -147,7 +148,7 @@ macro_rules! provide_one {
macro_rules! provide {
($tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
$($name:ident => { $($compute:tt)* })*) => {
pub fn provide_extern(providers: &mut ExternProviders) {
fn provide_extern(providers: &mut ExternProviders) {
$(provide_one! {
$tcx, $def_id, $other, $cdata, $name => { $($compute)* }
})*
Expand Down Expand Up @@ -385,7 +386,7 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) {
// FIXME(#44234) - almost all of these queries have no sub-queries and
// therefore no actual inputs, they're just reading tables calculated in
// resolve! Does this work? Unsure! That's what the issue is about
*providers = Providers {
providers.queries = rustc_middle::query::Providers {
allocator_kind: |tcx, ()| CStore::from_tcx(tcx).allocator_kind(),
alloc_error_handler_kind: |tcx, ()| CStore::from_tcx(tcx).alloc_error_handler_kind(),
is_private_dep: |_tcx, LocalCrate| false,
Expand Down Expand Up @@ -513,8 +514,9 @@ pub(in crate::rmeta) fn provide(providers: &mut Providers) {
tcx.untracked().cstore.freeze();
tcx.arena.alloc_from_iter(CStore::from_tcx(tcx).iter_crate_data().map(|(cnum, _)| cnum))
},
..*providers
..providers.queries
};
provide_extern(&mut providers.extern_queries);
}

impl CStore {
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_metadata/src/rmeta/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault;
use rustc_middle::mir;
use rustc_middle::query::Providers;
use rustc_middle::ty::fast_reject::SimplifiedType;
use rustc_middle::ty::{self, ReprOptions, Ty, UnusedGenericParams};
use rustc_middle::ty::{DeducedParamAttrs, GeneratorDiagnosticData, ParameterizedOverTcx, TyCtxt};
use rustc_middle::util::Providers;
use rustc_serialize::opaque::FileEncoder;
use rustc_session::config::SymbolManglingVersion;
use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib};
Expand All @@ -38,7 +38,6 @@ use rustc_target::spec::{PanicStrategy, TargetTriple};
use std::marker::PhantomData;
use std::num::NonZeroUsize;

pub use decoder::provide_extern;
use decoder::DecodeContext;
pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
use encoder::EncodeContext;
Expand Down
65 changes: 65 additions & 0 deletions compiler/rustc_middle/src/hooks/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use crate::mir;
use crate::query::TyCtxtAt;
use crate::ty::{Ty, TyCtxt};
use rustc_span::DUMMY_SP;

macro_rules! declare_hooks {
($($(#[$attr:meta])*hook $name:ident($($arg:ident: $K:ty),*) -> $V:ty;)*) => {

impl<'tcx> TyCtxt<'tcx> {
$(
$(#[$attr])*
#[inline(always)]
#[must_use]
pub fn $name(self, $($arg: $K,)*) -> $V
{
self.at(DUMMY_SP).$name($($arg,)*)
}
)*
}

impl<'tcx> TyCtxtAt<'tcx> {
$(
$(#[$attr])*
#[inline(always)]
#[must_use]
#[instrument(level = "debug", skip(self), ret)]
pub fn $name(self, $($arg: $K,)*) -> $V
{
(self.tcx.hooks.$name)(self, $($arg,)*)
}
)*
}

pub struct Providers {
$(pub $name: for<'tcx> fn(
TyCtxtAt<'tcx>,
$($arg: $K,)*
) -> $V,)*
}

impl Default for Providers {
fn default() -> Self {
Providers {
$($name: |_, $($arg,)*| bug!(
"`tcx.{}{:?}` cannot be called as `{}` was never assigned to a provider function.\n",
stringify!($name),
($($arg,)*),
stringify!($name),
),)*
}
}
}

impl Copy for Providers {}
impl Clone for Providers {
fn clone(&self) -> Self { *self }
}
};
}

declare_hooks! {
/// Tries to destructure an `mir::Const` ADT or array into its variant index
/// and its field values. This should only be used for pretty printing.
hook try_destructure_mir_constant_for_diagnostics(val: mir::ConstValue<'tcx>, ty: Ty<'tcx>) -> Option<mir::DestructuredConstant<'tcx>>;
}
1 change: 1 addition & 0 deletions compiler/rustc_middle/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ mod macros;
pub mod arena;
pub mod error;
pub mod hir;
pub mod hooks;
pub mod infer;
pub mod lint;
pub mod metadata;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1691,7 +1691,7 @@ fn pretty_print_const_value_tcx<'tcx>(
(_, ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) if !ty.has_non_region_param() => {
let ct = tcx.lift(ct).unwrap();
let ty = tcx.lift(ty).unwrap();
if let Some(contents) = tcx.try_destructure_mir_constant_for_diagnostics((ct, ty)) {
if let Some(contents) = tcx.try_destructure_mir_constant_for_diagnostics(ct, ty) {
let fields: Vec<(ConstValue<'_>, Ty<'_>)> = contents.fields.to_vec();
match *ty.kind() {
ty::Array(..) => {
Expand Down
Loading

0 comments on commit bf98263

Please sign in to comment.