about summary refs log tree commit diff
path: root/compiler/rustc_query_impl/src
diff options
context:
space:
mode:
authorMatthew Kelly <matthew.kelly2@gmail.com>2022-08-31 19:39:39 -0400
committerMatthew Kelly <matthew.kelly2@gmail.com>2022-08-31 19:39:39 -0400
commiteda2a401457ba645a32bdc5b9e7e90214e3e4e24 (patch)
tree76c4a12cb26666f03aa37a81abe27782def16f1d /compiler/rustc_query_impl/src
parent4a443dfb8227d407ff3f0542cb6e688833708ba9 (diff)
parent9243168fa5615ec8ebe9164c6bc2fdcccffd08b6 (diff)
Merge remote-tracking branch 'origin/master' into mpk/add-long-error-message-for-E0311
Diffstat (limited to 'compiler/rustc_query_impl/src')
-rw-r--r--compiler/rustc_query_impl/src/lib.rs5
-rw-r--r--compiler/rustc_query_impl/src/on_disk_cache.rs34
-rw-r--r--compiler/rustc_query_impl/src/plumbing.rs182
-rw-r--r--compiler/rustc_query_impl/src/profiling_support.rs4
4 files changed, 133 insertions, 92 deletions
diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs
index eda61df7700..8ea09880694 100644
--- a/compiler/rustc_query_impl/src/lib.rs
+++ b/compiler/rustc_query_impl/src/lib.rs
@@ -7,13 +7,14 @@
 #![feature(rustc_attrs)]
 #![recursion_limit = "256"]
 #![allow(rustc::potential_query_instability)]
+#![deny(rustc::untranslatable_diagnostic)]
+#![deny(rustc::diagnostic_outside_of_impl)]
 
 #[macro_use]
 extern crate rustc_macros;
 #[macro_use]
 extern crate rustc_middle;
 
-use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
 use rustc_data_structures::sync::AtomicU64;
 use rustc_middle::arena::Arena;
 use rustc_middle::dep_graph::{self, DepKindStruct, SerializedDepNodeIndex};
@@ -53,7 +54,7 @@ fn describe_as_module(def_id: LocalDefId, tcx: TyCtxt<'_>) -> String {
     }
 }
 
-rustc_query_append! { [define_queries!][<'tcx>] }
+rustc_query_append! { define_queries! }
 
 impl<'tcx> Queries<'tcx> {
     // Force codegen in the dyn-trait transformation in this crate.
diff --git a/compiler/rustc_query_impl/src/on_disk_cache.rs b/compiler/rustc_query_impl/src/on_disk_cache.rs
index 6711dd3d5c5..5ef95911f56 100644
--- a/compiler/rustc_query_impl/src/on_disk_cache.rs
+++ b/compiler/rustc_query_impl/src/on_disk_cache.rs
@@ -42,6 +42,7 @@ const TAG_EXPN_DATA: u8 = 1;
 // Tags for encoding Symbol's
 const SYMBOL_STR: u8 = 0;
 const SYMBOL_OFFSET: u8 = 1;
+const SYMBOL_PREINTERNED: u8 = 2;
 
 /// Provides an interface to incremental compilation data cached from the
 /// previous compilation session. This data will eventually include the results
@@ -745,6 +746,10 @@ impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Symbol {
 
                 sym
             }
+            SYMBOL_PREINTERNED => {
+                let symbol_index = d.read_u32();
+                Symbol::new_from_decoded(symbol_index)
+            }
             _ => unreachable!(),
         }
     }
@@ -939,17 +944,24 @@ impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for Span {
 // copy&paste impl from rustc_metadata
 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for Symbol {
     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx>) {
-        match s.symbol_table.entry(*self) {
-            Entry::Vacant(o) => {
-                s.encoder.emit_u8(SYMBOL_STR);
-                let pos = s.encoder.position();
-                o.insert(pos);
-                s.emit_str(self.as_str());
-            }
-            Entry::Occupied(o) => {
-                let x = o.get().clone();
-                s.emit_u8(SYMBOL_OFFSET);
-                s.emit_usize(x);
+        // if symbol preinterned, emit tag and symbol index
+        if self.is_preinterned() {
+            s.encoder.emit_u8(SYMBOL_PREINTERNED);
+            s.encoder.emit_u32(self.as_u32());
+        } else {
+            // otherwise write it as string or as offset to it
+            match s.symbol_table.entry(*self) {
+                Entry::Vacant(o) => {
+                    s.encoder.emit_u8(SYMBOL_STR);
+                    let pos = s.encoder.position();
+                    o.insert(pos);
+                    s.emit_str(self.as_str());
+                }
+                Entry::Occupied(o) => {
+                    let x = o.get().clone();
+                    s.emit_u8(SYMBOL_OFFSET);
+                    s.emit_usize(x);
+                }
             }
         }
     }
diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs
index 339683cf689..eab627c5d4c 100644
--- a/compiler/rustc_query_impl/src/plumbing.rs
+++ b/compiler/rustc_query_impl/src/plumbing.rs
@@ -2,13 +2,18 @@
 //! generate the actual methods on tcx which find and execute the provider,
 //! manage the caches, and so forth.
 
+use crate::keys::Key;
 use crate::{on_disk_cache, Queries};
-use rustc_middle::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
+use rustc_middle::dep_graph::{self, DepKind, DepNodeIndex, SerializedDepNodeIndex};
 use rustc_middle::ty::tls::{self, ImplicitCtxt};
-use rustc_middle::ty::TyCtxt;
+use rustc_middle::ty::{self, TyCtxt};
 use rustc_query_system::dep_graph::HasDepContext;
-use rustc_query_system::query::{QueryContext, QueryJobId, QueryMap, QuerySideEffects};
+use rustc_query_system::ich::StableHashingContext;
+use rustc_query_system::query::{
+    QueryContext, QueryJobId, QueryMap, QuerySideEffects, QueryStackFrame,
+};
 
+use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
 use rustc_data_structures::sync::Lock;
 use rustc_data_structures::thin_vec::ThinVec;
 use rustc_errors::{Diagnostic, Handler};
@@ -91,6 +96,7 @@ impl QueryContext for QueryCtxt<'_> {
     fn start_query<R>(
         &self,
         token: QueryJobId,
+        depth_limit: bool,
         diagnostics: Option<&Lock<ThinVec<Diagnostic>>>,
         compute: impl FnOnce() -> R,
     ) -> R {
@@ -98,12 +104,16 @@ impl QueryContext for QueryCtxt<'_> {
         // as `self`, so we use `with_related_context` to relate the 'tcx lifetimes
         // when accessing the `ImplicitCtxt`.
         tls::with_related_context(**self, move |current_icx| {
+            if depth_limit && !self.recursion_limit().value_within_limit(current_icx.query_depth) {
+                self.depth_limit_error();
+            }
+
             // Update the `ImplicitCtxt` to point to our new query job.
             let new_icx = ImplicitCtxt {
                 tcx: **self,
                 query: Some(token),
                 diagnostics,
-                layout_depth: current_icx.layout_depth,
+                query_depth: current_icx.query_depth + depth_limit as usize,
                 task_deps: current_icx.task_deps,
             };
 
@@ -205,6 +215,18 @@ macro_rules! is_eval_always {
     };
 }
 
+macro_rules! depth_limit {
+    ([]) => {{
+        false
+    }};
+    ([(depth_limit) $($rest:tt)*]) => {{
+        true
+    }};
+    ([$other:tt $($modifiers:tt)*]) => {
+        depth_limit!([$($modifiers)*])
+    };
+}
+
 macro_rules! hash_result {
     ([]) => {{
         Some(dep_graph::hash_result)
@@ -233,12 +255,58 @@ macro_rules! get_provider {
     };
 }
 
+pub(crate) fn create_query_frame<
+    'tcx,
+    K: Copy + Key + for<'a> HashStable<StableHashingContext<'a>>,
+>(
+    tcx: QueryCtxt<'tcx>,
+    do_describe: fn(QueryCtxt<'tcx>, K) -> String,
+    key: K,
+    kind: DepKind,
+    name: &'static str,
+) -> QueryStackFrame {
+    // Disable visible paths printing for performance reasons.
+    // Showing visible path instead of any path is not that important in production.
+    let description = ty::print::with_no_visible_paths!(
+        // Force filename-line mode to avoid invoking `type_of` query.
+        ty::print::with_forced_impl_filename_line!(do_describe(tcx, key))
+    );
+    let description =
+        if tcx.sess.verbose() { format!("{} [{}]", description, name) } else { description };
+    let span = if kind == dep_graph::DepKind::def_span {
+        // The `def_span` query is used to calculate `default_span`,
+        // so exit to avoid infinite recursion.
+        None
+    } else {
+        Some(key.default_span(*tcx))
+    };
+    let def_kind = if kind == dep_graph::DepKind::opt_def_kind {
+        // Try to avoid infinite recursion.
+        None
+    } else {
+        key.key_as_def_id()
+            .and_then(|def_id| def_id.as_local())
+            .and_then(|def_id| tcx.opt_def_kind(def_id))
+    };
+    let hash = || {
+        tcx.with_stable_hashing_context(|mut hcx| {
+            let mut hasher = StableHasher::new();
+            std::mem::discriminant(&kind).hash_stable(&mut hcx, &mut hasher);
+            key.hash_stable(&mut hcx, &mut hasher);
+            hasher.finish::<u64>()
+        })
+    };
+
+    QueryStackFrame::new(name, description, span, def_kind, hash)
+}
+
+// NOTE: `$V` isn't used here, but we still need to match on it so it can be passed to other macros
+// invoked by `rustc_query_append`.
 macro_rules! define_queries {
-    (<$tcx:tt>
+    (
      $($(#[$attr:meta])*
         [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => {
         define_queries_struct! {
-            tcx: $tcx,
             input: ($(([$($modifiers)*] [$($attr)*] [$name]))*)
         }
 
@@ -247,47 +315,10 @@ macro_rules! define_queries {
 
             // Create an eponymous constructor for each query.
             $(#[allow(nonstandard_style)] $(#[$attr])*
-            pub fn $name<$tcx>(tcx: QueryCtxt<$tcx>, key: query_keys::$name<$tcx>) -> QueryStackFrame {
+            pub fn $name<'tcx>(tcx: QueryCtxt<'tcx>, key: <queries::$name<'tcx> as QueryConfig>::Key) -> QueryStackFrame {
                 let kind = dep_graph::DepKind::$name;
                 let name = stringify!($name);
-                // Disable visible paths printing for performance reasons.
-                // Showing visible path instead of any path is not that important in production.
-                let description = ty::print::with_no_visible_paths!(
-                    // Force filename-line mode to avoid invoking `type_of` query.
-                    ty::print::with_forced_impl_filename_line!(
-                        queries::$name::describe(tcx, key)
-                    )
-                );
-                let description = if tcx.sess.verbose() {
-                    format!("{} [{}]", description, name)
-                } else {
-                    description
-                };
-                let span = if kind == dep_graph::DepKind::def_span {
-                    // The `def_span` query is used to calculate `default_span`,
-                    // so exit to avoid infinite recursion.
-                    None
-                } else {
-                    Some(key.default_span(*tcx))
-                };
-                let def_kind = if kind == dep_graph::DepKind::opt_def_kind {
-                    // Try to avoid infinite recursion.
-                    None
-                } else {
-                    key.key_as_def_id()
-                        .and_then(|def_id| def_id.as_local())
-                        .and_then(|def_id| tcx.opt_def_kind(def_id))
-                };
-                let hash = || {
-                    tcx.with_stable_hashing_context(|mut hcx|{
-                        let mut hasher = StableHasher::new();
-                        std::mem::discriminant(&kind).hash_stable(&mut hcx, &mut hasher);
-                        key.hash_stable(&mut hcx, &mut hasher);
-                        hasher.finish::<u64>()
-                    })
-                };
-
-                QueryStackFrame::new(name, description, span, def_kind, hash)
+                $crate::plumbing::create_query_frame(tcx, queries::$name::describe, key, kind, name)
             })*
         }
 
@@ -295,32 +326,32 @@ macro_rules! define_queries {
         mod queries {
             use std::marker::PhantomData;
 
-            $(pub struct $name<$tcx> {
-                data: PhantomData<&$tcx ()>
+            $(pub struct $name<'tcx> {
+                data: PhantomData<&'tcx ()>
             })*
         }
 
-        $(impl<$tcx> QueryConfig for queries::$name<$tcx> {
-            type Key = query_keys::$name<$tcx>;
-            type Value = query_values::$name<$tcx>;
-            type Stored = query_stored::$name<$tcx>;
+        $(impl<'tcx> QueryConfig for queries::$name<'tcx> {
+            type Key = query_keys::$name<'tcx>;
+            type Value = query_values::$name<'tcx>;
+            type Stored = query_stored::$name<'tcx>;
             const NAME: &'static str = stringify!($name);
         }
 
-        impl<$tcx> QueryDescription<QueryCtxt<$tcx>> for queries::$name<$tcx> {
-            rustc_query_description! { $name<$tcx> }
+        impl<'tcx> QueryDescription<QueryCtxt<'tcx>> for queries::$name<'tcx> {
+            rustc_query_description! { $name }
 
-            type Cache = query_storage::$name<$tcx>;
+            type Cache = query_storage::$name<'tcx>;
 
             #[inline(always)]
-            fn query_state<'a>(tcx: QueryCtxt<$tcx>) -> &'a QueryState<Self::Key>
-                where QueryCtxt<$tcx>: 'a
+            fn query_state<'a>(tcx: QueryCtxt<'tcx>) -> &'a QueryState<Self::Key>
+                where QueryCtxt<'tcx>: 'a
             {
                 &tcx.queries.$name
             }
 
             #[inline(always)]
-            fn query_cache<'a>(tcx: QueryCtxt<$tcx>) -> &'a Self::Cache
+            fn query_cache<'a>(tcx: QueryCtxt<'tcx>) -> &'a Self::Cache
                 where 'tcx:'a
             {
                 &tcx.query_caches.$name
@@ -328,13 +359,14 @@ macro_rules! define_queries {
 
             #[inline]
             fn make_vtable(tcx: QueryCtxt<'tcx>, key: &Self::Key) ->
-                QueryVTable<QueryCtxt<$tcx>, Self::Key, Self::Value>
+                QueryVTable<QueryCtxt<'tcx>, Self::Key, Self::Value>
             {
                 let compute = get_provider!([$($modifiers)*][tcx, $name, key]);
                 let cache_on_disk = Self::cache_on_disk(tcx.tcx, key);
                 QueryVTable {
                     anon: is_anon!([$($modifiers)*]),
                     eval_always: is_eval_always!([$($modifiers)*]),
+                    depth_limit: depth_limit!([$($modifiers)*]),
                     dep_kind: dep_graph::DepKind::$name,
                     hash_result: hash_result!([$($modifiers)*]),
                     handle_cycle_error: |tcx, mut error| handle_cycle_error!([$($modifiers)*][tcx, error]),
@@ -349,7 +381,6 @@ macro_rules! define_queries {
         mod query_callbacks {
             use super::*;
             use rustc_middle::dep_graph::DepNode;
-            use rustc_middle::ty::query::query_keys;
             use rustc_query_system::dep_graph::DepNodeParams;
             use rustc_query_system::query::{force_query, QueryDescription};
             use rustc_query_system::dep_graph::FingerprintStyle;
@@ -411,7 +442,7 @@ macro_rules! define_queries {
                 let is_eval_always = is_eval_always!([$($modifiers)*]);
 
                 let fingerprint_style =
-                    <query_keys::$name<'_> as DepNodeParams<TyCtxt<'_>>>::fingerprint_style();
+                    <<queries::$name<'_> as QueryConfig>::Key as DepNodeParams<TyCtxt<'_>>>::fingerprint_style();
 
                 if is_anon || !fingerprint_style.reconstructible() {
                     return DepKindStruct {
@@ -424,8 +455,8 @@ macro_rules! define_queries {
                 }
 
                 #[inline(always)]
-                fn recover<'tcx>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> Option<query_keys::$name<'tcx>> {
-                    <query_keys::$name<'_> as DepNodeParams<TyCtxt<'_>>>::recover(tcx, &dep_node)
+                fn recover<'tcx>(tcx: TyCtxt<'tcx>, dep_node: DepNode) -> Option<<queries::$name<'tcx> as QueryConfig>::Key> {
+                    <<queries::$name<'_> as QueryConfig>::Key as DepNodeParams<TyCtxt<'_>>>::recover(tcx, &dep_node)
                 }
 
                 fn force_from_dep_node(tcx: TyCtxt<'_>, dep_node: DepNode) -> bool {
@@ -465,28 +496,25 @@ macro_rules! define_queries {
     }
 }
 
-// FIXME(eddyb) this macro (and others?) use `$tcx` and `'tcx` interchangeably.
-// We should either not take `$tcx` at all and use `'tcx` everywhere, or use
-// `$tcx` everywhere (even if that isn't necessary due to lack of hygiene).
 macro_rules! define_queries_struct {
-    (tcx: $tcx:tt,
+    (
      input: ($(([$($modifiers:tt)*] [$($attr:tt)*] [$name:ident]))*)) => {
-        pub struct Queries<$tcx> {
+        pub struct Queries<'tcx> {
             local_providers: Box<Providers>,
             extern_providers: Box<ExternProviders>,
 
-            pub on_disk_cache: Option<OnDiskCache<$tcx>>,
+            pub on_disk_cache: Option<OnDiskCache<'tcx>>,
 
             jobs: AtomicU64,
 
-            $($(#[$attr])*  $name: QueryState<query_keys::$name<$tcx>>,)*
+            $($(#[$attr])*  $name: QueryState<<queries::$name<'tcx> as QueryConfig>::Key>,)*
         }
 
-        impl<$tcx> Queries<$tcx> {
+        impl<'tcx> Queries<'tcx> {
             pub fn new(
                 local_providers: Providers,
                 extern_providers: ExternProviders,
-                on_disk_cache: Option<OnDiskCache<$tcx>>,
+                on_disk_cache: Option<OnDiskCache<'tcx>>,
             ) -> Self {
                 Queries {
                     local_providers: Box::new(local_providers),
@@ -498,8 +526,8 @@ macro_rules! define_queries_struct {
             }
 
             pub(crate) fn try_collect_active_jobs(
-                &$tcx self,
-                tcx: TyCtxt<$tcx>,
+                &'tcx self,
+                tcx: TyCtxt<'tcx>,
             ) -> Option<QueryMap> {
                 let tcx = QueryCtxt { tcx, queries: self };
                 let mut jobs = QueryMap::default();
@@ -532,13 +560,13 @@ macro_rules! define_queries_struct {
             #[tracing::instrument(level = "trace", skip(self, tcx))]
             fn $name(
                 &'tcx self,
-                tcx: TyCtxt<$tcx>,
+                tcx: TyCtxt<'tcx>,
                 span: Span,
-                key: query_keys::$name<$tcx>,
+                key: <queries::$name<'tcx> as QueryConfig>::Key,
                 mode: QueryMode,
-            ) -> Option<query_stored::$name<$tcx>> {
+            ) -> Option<query_stored::$name<'tcx>> {
                 let qcx = QueryCtxt { tcx, queries: self };
-                get_query::<queries::$name<$tcx>, _>(qcx, span, key, mode)
+                get_query::<queries::$name<'tcx>, _>(qcx, span, key, mode)
             })*
         }
     };
diff --git a/compiler/rustc_query_impl/src/profiling_support.rs b/compiler/rustc_query_impl/src/profiling_support.rs
index 551f094209e..260af0d5408 100644
--- a/compiler/rustc_query_impl/src/profiling_support.rs
+++ b/compiler/rustc_query_impl/src/profiling_support.rs
@@ -306,7 +306,7 @@ pub fn alloc_self_profile_query_strings(tcx: TyCtxt<'_>) {
     let mut string_cache = QueryKeyStringCache::new();
 
     macro_rules! alloc_once {
-        (<$tcx:tt>
+        (
             $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident($K:ty) -> $V:ty,)*
         ) => {
             $({
@@ -320,5 +320,5 @@ pub fn alloc_self_profile_query_strings(tcx: TyCtxt<'_>) {
         }
     }
 
-    rustc_query_append! { [alloc_once!][<'tcx>] }
+    rustc_query_append! { alloc_once! }
 }