diff --git a/RELEASES.md b/RELEASES.md index 10a400fda5c32..424e12ceec054 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -62,9 +62,9 @@ Stabilized APIs - [`::unchecked_shl`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unchecked_shl) - [`::unchecked_shr`](https://doc.rust-lang.org/stable/std/primitive.usize.html#method.unchecked_shr) - [`<[T]>::as_array`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_array) -- [`<[T]>::as_array_mut`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_mut_array) +- [`<[T]>::as_mut_array`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_mut_array) - [`<*const [T]>::as_array`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.as_array) -- [`<*mut [T]>::as_array_mut`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.as_mut_array) +- [`<*mut [T]>::as_mut_array`](https://doc.rust-lang.org/stable/std/primitive.pointer.html#method.as_mut_array) - [`VecDeque::pop_front_if`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.pop_front_if) - [`VecDeque::pop_back_if`](https://doc.rust-lang.org/stable/std/collections/struct.VecDeque.html#method.pop_back_if) - [`Duration::from_nanos_u128`](https://doc.rust-lang.org/stable/std/time/struct.Duration.html#method.from_nanos_u128) diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 7688df2d3a55d..a51aa90355bcd 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -431,8 +431,6 @@ impl ToInternal for Level { } } -pub(crate) struct FreeFunctions; - pub(crate) struct Rustc<'a, 'b> { ecx: &'a mut ExtCtxt<'b>, def_site: Span, @@ -461,13 +459,28 @@ impl<'a, 'b> Rustc<'a, 'b> { } impl server::Types for Rustc<'_, '_> { - type FreeFunctions = FreeFunctions; type TokenStream = TokenStream; type Span = Span; type Symbol = Symbol; } -impl server::FreeFunctions for Rustc<'_, '_> { +impl server::Server for Rustc<'_, '_> { + fn globals(&mut self) -> ExpnGlobals { + ExpnGlobals { + def_site: self.def_site, + call_site: self.call_site, + mixed_site: self.mixed_site, + } + } + + fn intern_symbol(string: &str) -> Self::Symbol { + Symbol::intern(string) + } + + fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) { + f(symbol.as_str()) + } + fn injected_env_var(&mut self, var: &str) -> Option { self.ecx.sess.opts.logical_env.get(var).cloned() } @@ -552,14 +565,20 @@ impl server::FreeFunctions for Rustc<'_, '_> { } diag.emit(); } -} -impl server::TokenStream for Rustc<'_, '_> { - fn is_empty(&mut self, stream: &Self::TokenStream) -> bool { + fn ts_drop(&mut self, stream: Self::TokenStream) { + drop(stream); + } + + fn ts_clone(&mut self, stream: &Self::TokenStream) -> Self::TokenStream { + stream.clone() + } + + fn ts_is_empty(&mut self, stream: &Self::TokenStream) -> bool { stream.is_empty() } - fn from_str(&mut self, src: &str) -> Self::TokenStream { + fn ts_from_str(&mut self, src: &str) -> Self::TokenStream { unwrap_or_emit_fatal(source_str_to_stream( self.psess(), FileName::proc_macro_source_code(src), @@ -568,11 +587,11 @@ impl server::TokenStream for Rustc<'_, '_> { )) } - fn to_string(&mut self, stream: &Self::TokenStream) -> String { + fn ts_to_string(&mut self, stream: &Self::TokenStream) -> String { pprust::tts_to_string(stream) } - fn expand_expr(&mut self, stream: &Self::TokenStream) -> Result { + fn ts_expand_expr(&mut self, stream: &Self::TokenStream) -> Result { // Parse the expression from our tokenstream. let expr: PResult<'_, _> = try { let mut p = Parser::new(self.psess(), stream.clone(), Some("proc_macro expand expr")); @@ -633,14 +652,14 @@ impl server::TokenStream for Rustc<'_, '_> { } } - fn from_token_tree( + fn ts_from_token_tree( &mut self, tree: TokenTree, ) -> Self::TokenStream { Self::TokenStream::new((tree, &mut *self).to_internal().into_iter().collect::>()) } - fn concat_trees( + fn ts_concat_trees( &mut self, base: Option, trees: Vec>, @@ -654,7 +673,7 @@ impl server::TokenStream for Rustc<'_, '_> { stream } - fn concat_streams( + fn ts_concat_streams( &mut self, base: Option, streams: Vec, @@ -666,16 +685,14 @@ impl server::TokenStream for Rustc<'_, '_> { stream } - fn into_trees( + fn ts_into_trees( &mut self, stream: Self::TokenStream, ) -> Vec> { FromInternal::from_internal((stream, self)) } -} -impl server::Span for Rustc<'_, '_> { - fn debug(&mut self, span: Self::Span) -> String { + fn span_debug(&mut self, span: Self::Span) -> String { if self.ecx.ecfg.span_debug { format!("{span:?}") } else { @@ -683,7 +700,7 @@ impl server::Span for Rustc<'_, '_> { } } - fn file(&mut self, span: Self::Span) -> String { + fn span_file(&mut self, span: Self::Span) -> String { self.psess() .source_map() .lookup_char_pos(span.lo()) @@ -693,7 +710,7 @@ impl server::Span for Rustc<'_, '_> { .to_string() } - fn local_file(&mut self, span: Self::Span) -> Option { + fn span_local_file(&mut self, span: Self::Span) -> Option { self.psess() .source_map() .lookup_char_pos(span.lo()) @@ -708,15 +725,15 @@ impl server::Span for Rustc<'_, '_> { }) } - fn parent(&mut self, span: Self::Span) -> Option { + fn span_parent(&mut self, span: Self::Span) -> Option { span.parent_callsite() } - fn source(&mut self, span: Self::Span) -> Self::Span { + fn span_source(&mut self, span: Self::Span) -> Self::Span { span.source_callsite() } - fn byte_range(&mut self, span: Self::Span) -> Range { + fn span_byte_range(&mut self, span: Self::Span) -> Range { let source_map = self.psess().source_map(); let relative_start_pos = source_map.lookup_byte_offset(span.lo()).pos; @@ -724,25 +741,25 @@ impl server::Span for Rustc<'_, '_> { Range { start: relative_start_pos.0 as usize, end: relative_end_pos.0 as usize } } - fn start(&mut self, span: Self::Span) -> Self::Span { + fn span_start(&mut self, span: Self::Span) -> Self::Span { span.shrink_to_lo() } - fn end(&mut self, span: Self::Span) -> Self::Span { + fn span_end(&mut self, span: Self::Span) -> Self::Span { span.shrink_to_hi() } - fn line(&mut self, span: Self::Span) -> usize { + fn span_line(&mut self, span: Self::Span) -> usize { let loc = self.psess().source_map().lookup_char_pos(span.lo()); loc.line } - fn column(&mut self, span: Self::Span) -> usize { + fn span_column(&mut self, span: Self::Span) -> usize { let loc = self.psess().source_map().lookup_char_pos(span.lo()); loc.col.to_usize() + 1 } - fn join(&mut self, first: Self::Span, second: Self::Span) -> Option { + fn span_join(&mut self, first: Self::Span, second: Self::Span) -> Option { let self_loc = self.psess().source_map().lookup_char_pos(first.lo()); let other_loc = self.psess().source_map().lookup_char_pos(second.lo()); @@ -753,7 +770,7 @@ impl server::Span for Rustc<'_, '_> { Some(first.to(second)) } - fn subspan( + fn span_subspan( &mut self, span: Self::Span, start: Bound, @@ -789,11 +806,11 @@ impl server::Span for Rustc<'_, '_> { Some(span.with_lo(new_lo).with_hi(new_hi)) } - fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span { + fn span_resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span { span.with_ctxt(at.ctxt()) } - fn source_text(&mut self, span: Self::Span) -> Option { + fn span_source_text(&mut self, span: Self::Span) -> Option { self.psess().source_map().span_to_snippet(span).ok() } @@ -821,11 +838,11 @@ impl server::Span for Rustc<'_, '_> { /// span from the metadata of `my_proc_macro` (which we have access to, /// since we've loaded `my_proc_macro` from disk in order to execute it). /// In this way, we have obtained a span pointing into `my_proc_macro` - fn save_span(&mut self, span: Self::Span) -> usize { + fn span_save_span(&mut self, span: Self::Span) -> usize { self.psess().save_proc_macro_span(span) } - fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span { + fn span_recover_proc_macro_span(&mut self, id: usize) -> Self::Span { let (resolver, krate, def_site) = (&*self.ecx.resolver, self.krate, self.def_site); *self.rebased_spans.entry(id).or_insert_with(|| { // FIXME: `SyntaxContext` for spans from proc macro crates is lost during encoding, @@ -833,29 +850,9 @@ impl server::Span for Rustc<'_, '_> { resolver.get_proc_macro_quoted_span(krate, id).with_ctxt(def_site.ctxt()) }) } -} -impl server::Symbol for Rustc<'_, '_> { - fn normalize_and_validate_ident(&mut self, string: &str) -> Result { + fn symbol_normalize_and_validate_ident(&mut self, string: &str) -> Result { let sym = nfc_normalize(string); if rustc_lexer::is_ident(sym.as_str()) { Ok(sym) } else { Err(()) } } } - -impl server::Server for Rustc<'_, '_> { - fn globals(&mut self) -> ExpnGlobals { - ExpnGlobals { - def_site: self.def_site, - call_site: self.call_site, - mixed_site: self.mixed_site, - } - } - - fn intern_symbol(string: &str) -> Self::Symbol { - Symbol::intern(string) - } - - fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) { - f(symbol.as_str()) - } -} diff --git a/compiler/rustc_interface/src/callbacks.rs b/compiler/rustc_interface/src/callbacks.rs index 7c6b7157f71a5..3d8d5d59b118b 100644 --- a/compiler/rustc_interface/src/callbacks.rs +++ b/compiler/rustc_interface/src/callbacks.rs @@ -72,7 +72,7 @@ fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) -> pub fn dep_kind_debug(kind: DepKind, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { tls::with_opt(|opt_tcx| { if let Some(tcx) = opt_tcx { - write!(f, "{}", tcx.dep_kind_info(kind).name) + write!(f, "{}", tcx.dep_kind_vtable(kind).name) } else { default_dep_kind_debug(kind, f) } diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 3228a0499accc..60b45f7391b59 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -992,7 +992,7 @@ pub fn create_and_enter_global_ctxt FnOnce(TyCtxt<'tcx>) -> T>( hir_arena, untracked, dep_graph, - rustc_query_impl::query_callbacks(arena), + rustc_query_impl::make_dep_kind_vtables(arena), rustc_query_impl::query_system( providers.queries, providers.extern_queries, diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index 0bdc1bfd45eef..0f254aaa9fa0a 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -104,7 +104,7 @@ macro_rules! arena_types { [decode] is_late_bound_map: rustc_data_structures::fx::FxIndexSet, [decode] impl_source: rustc_middle::traits::ImplSource<'tcx, ()>, - [] dep_kind: rustc_middle::dep_graph::DepKindStruct<'tcx>, + [] dep_kind_vtable: rustc_middle::dep_graph::DepKindVTable<'tcx>, [decode] trait_impl_trait_tys: rustc_data_structures::unord::UnordMap< diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index 049e868879e96..f28ba10d52e27 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -18,7 +18,7 @@ pub use rustc_query_system::dep_graph::{ pub type DepGraph = rustc_query_system::dep_graph::DepGraph; -pub type DepKindStruct<'tcx> = rustc_query_system::dep_graph::DepKindStruct>; +pub type DepKindVTable<'tcx> = rustc_query_system::dep_graph::DepKindVTable>; pub struct DepsType; @@ -79,8 +79,8 @@ impl<'tcx> DepContext for TyCtxt<'tcx> { } #[inline] - fn dep_kind_info(&self, dk: DepKind) -> &DepKindStruct<'tcx> { - &self.query_kinds[dk.as_usize()] + fn dep_kind_vtable(&self, dk: DepKind) -> &DepKindVTable<'tcx> { + &self.dep_kind_vtables[dk.as_usize()] } fn with_reduced_queries(self, f: impl FnOnce() -> T) -> T { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 5ba5a3c3d4dc4..f015d0edc56c8 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -59,7 +59,7 @@ use rustc_type_ir::{ use tracing::{debug, instrument}; use crate::arena::Arena; -use crate::dep_graph::{DepGraph, DepKindStruct}; +use crate::dep_graph::{DepGraph, DepKindVTable}; use crate::infer::canonical::{CanonicalParamEnvCache, CanonicalVarKind, CanonicalVarKinds}; use crate::lint::lint_level; use crate::metadata::ModChild; @@ -1580,7 +1580,7 @@ pub struct GlobalCtxt<'tcx> { untracked: Untracked, pub query_system: QuerySystem<'tcx>, - pub(crate) query_kinds: &'tcx [DepKindStruct<'tcx>], + pub(crate) dep_kind_vtables: &'tcx [DepKindVTable<'tcx>], // Internal caches for metadata decoding. No need to track deps on this. pub ty_rcache: Lock>>, @@ -1801,7 +1801,7 @@ impl<'tcx> TyCtxt<'tcx> { hir_arena: &'tcx WorkerLocal>, untracked: Untracked, dep_graph: DepGraph, - query_kinds: &'tcx [DepKindStruct<'tcx>], + dep_kind_vtables: &'tcx [DepKindVTable<'tcx>], query_system: QuerySystem<'tcx>, hooks: crate::hooks::Providers, current_gcx: CurrentGcx, @@ -1831,7 +1831,7 @@ impl<'tcx> TyCtxt<'tcx> { consts: common_consts, untracked, query_system, - query_kinds, + dep_kind_vtables, ty_rcache: Default::default(), selection_cache: Default::default(), evaluation_cache: Default::default(), diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index c9abc4bdcdfc3..57027e937a4a9 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -9,7 +9,7 @@ use rustc_data_structures::stable_hasher::HashStable; use rustc_data_structures::sync::AtomicU64; use rustc_middle::arena::Arena; -use rustc_middle::dep_graph::{self, DepKind, DepKindStruct, DepNodeIndex}; +use rustc_middle::dep_graph::{self, DepKind, DepKindVTable, DepNodeIndex}; use rustc_middle::query::erase::{Erase, erase, restore}; use rustc_middle::query::on_disk_cache::{CacheEncoder, EncodedDepNodeIndex, OnDiskCache}; use rustc_middle::query::plumbing::{DynamicQuery, QuerySystem, QuerySystemFns}; diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 7479a992e2973..246152f5390c6 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -12,7 +12,7 @@ use rustc_hir::limit::Limit; use rustc_index::Idx; use rustc_middle::bug; use rustc_middle::dep_graph::{ - self, DepContext, DepKind, DepKindStruct, DepNode, DepNodeIndex, SerializedDepNodeIndex, + self, DepContext, DepKind, DepKindVTable, DepNode, DepNodeIndex, SerializedDepNodeIndex, dep_kinds, }; use rustc_middle::query::Key; @@ -489,14 +489,17 @@ where } } -pub(crate) fn query_callback<'tcx, Q>(is_anon: bool, is_eval_always: bool) -> DepKindStruct<'tcx> +pub(crate) fn make_dep_kind_vtable_for_query<'tcx, Q>( + is_anon: bool, + is_eval_always: bool, +) -> DepKindVTable<'tcx> where Q: QueryConfigRestored<'tcx>, { let fingerprint_style = >>::Key::fingerprint_style(); if is_anon || !fingerprint_style.reconstructible() { - return DepKindStruct { + return DepKindVTable { is_anon, is_eval_always, fingerprint_style, @@ -506,7 +509,7 @@ where }; } - DepKindStruct { + DepKindVTable { is_anon, is_eval_always, fingerprint_style, @@ -811,15 +814,19 @@ macro_rules! define_queries { for<'tcx> fn(TyCtxt<'tcx>) ] = &[$(query_impl::$name::query_key_hash_verify),*]; - #[allow(nonstandard_style)] - mod query_callbacks { + /// Module containing a named function for each dep kind (including queries) + /// that creates a `DepKindVTable`. + /// + /// Consumed via `make_dep_kind_array!` to create a list of vtables. + #[expect(non_snake_case)] + mod _dep_kind_vtable_ctors { use super::*; use rustc_middle::bug; use rustc_query_system::dep_graph::FingerprintStyle; // We use this for most things when incr. comp. is turned off. - pub(crate) fn Null<'tcx>() -> DepKindStruct<'tcx> { - DepKindStruct { + pub(crate) fn Null<'tcx>() -> DepKindVTable<'tcx> { + DepKindVTable { is_anon: false, is_eval_always: false, fingerprint_style: FingerprintStyle::Unit, @@ -830,8 +837,8 @@ macro_rules! define_queries { } // We use this for the forever-red node. - pub(crate) fn Red<'tcx>() -> DepKindStruct<'tcx> { - DepKindStruct { + pub(crate) fn Red<'tcx>() -> DepKindVTable<'tcx> { + DepKindVTable { is_anon: false, is_eval_always: false, fingerprint_style: FingerprintStyle::Unit, @@ -841,8 +848,8 @@ macro_rules! define_queries { } } - pub(crate) fn SideEffect<'tcx>() -> DepKindStruct<'tcx> { - DepKindStruct { + pub(crate) fn SideEffect<'tcx>() -> DepKindVTable<'tcx> { + DepKindVTable { is_anon: false, is_eval_always: false, fingerprint_style: FingerprintStyle::Unit, @@ -855,8 +862,8 @@ macro_rules! define_queries { } } - pub(crate) fn AnonZeroDeps<'tcx>() -> DepKindStruct<'tcx> { - DepKindStruct { + pub(crate) fn AnonZeroDeps<'tcx>() -> DepKindVTable<'tcx> { + DepKindVTable { is_anon: true, is_eval_always: false, fingerprint_style: FingerprintStyle::Opaque, @@ -866,8 +873,8 @@ macro_rules! define_queries { } } - pub(crate) fn TraitSelect<'tcx>() -> DepKindStruct<'tcx> { - DepKindStruct { + pub(crate) fn TraitSelect<'tcx>() -> DepKindVTable<'tcx> { + DepKindVTable { is_anon: true, is_eval_always: false, fingerprint_style: FingerprintStyle::Unit, @@ -877,8 +884,8 @@ macro_rules! define_queries { } } - pub(crate) fn CompileCodegenUnit<'tcx>() -> DepKindStruct<'tcx> { - DepKindStruct { + pub(crate) fn CompileCodegenUnit<'tcx>() -> DepKindVTable<'tcx> { + DepKindVTable { is_anon: false, is_eval_always: false, fingerprint_style: FingerprintStyle::Opaque, @@ -888,8 +895,8 @@ macro_rules! define_queries { } } - pub(crate) fn CompileMonoItem<'tcx>() -> DepKindStruct<'tcx> { - DepKindStruct { + pub(crate) fn CompileMonoItem<'tcx>() -> DepKindVTable<'tcx> { + DepKindVTable { is_anon: false, is_eval_always: false, fingerprint_style: FingerprintStyle::Opaque, @@ -899,8 +906,8 @@ macro_rules! define_queries { } } - pub(crate) fn Metadata<'tcx>() -> DepKindStruct<'tcx> { - DepKindStruct { + pub(crate) fn Metadata<'tcx>() -> DepKindVTable<'tcx> { + DepKindVTable { is_anon: false, is_eval_always: false, fingerprint_style: FingerprintStyle::Unit, @@ -910,16 +917,17 @@ macro_rules! define_queries { } } - $(pub(crate) fn $name<'tcx>()-> DepKindStruct<'tcx> { - $crate::plumbing::query_callback::>( + $(pub(crate) fn $name<'tcx>() -> DepKindVTable<'tcx> { + use $crate::query_impl::$name::QueryType; + $crate::plumbing::make_dep_kind_vtable_for_query::>( is_anon!([$($modifiers)*]), is_eval_always!([$($modifiers)*]), ) })* } - pub fn query_callbacks<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindStruct<'tcx>] { - arena.alloc_from_iter(rustc_middle::make_dep_kind_array!(query_callbacks)) + pub fn make_dep_kind_vtables<'tcx>(arena: &'tcx Arena<'tcx>) -> &'tcx [DepKindVTable<'tcx>] { + arena.alloc_from_iter(rustc_middle::make_dep_kind_array!(_dep_kind_vtable_ctors)) } } } diff --git a/compiler/rustc_query_system/src/dep_graph/dep_node.rs b/compiler/rustc_query_system/src/dep_graph/dep_node.rs index bdd1d5f3e88a9..72bdcd2d534d9 100644 --- a/compiler/rustc_query_system/src/dep_graph/dep_node.rs +++ b/compiler/rustc_query_system/src/dep_graph/dep_node.rs @@ -221,12 +221,12 @@ where } } -/// This struct stores metadata about each DepKind. +/// This struct stores function pointers and other metadata for a particular DepKind. /// /// Information is retrieved by indexing the `DEP_KINDS` array using the integer value /// of the `DepKind`. Overall, this allows to implement `DepContext` using this manual /// jump table instead of large matches. -pub struct DepKindStruct { +pub struct DepKindVTable { /// Anonymous queries cannot be replayed from one compiler invocation to the next. /// When their result is needed, it is recomputed. They are useful for fine-grained /// dependency tracking, and caching within one compiler invocation. diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index 8b9e4fe1bf29b..874b41cbf3b1c 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -7,7 +7,7 @@ mod serialized; use std::panic; -pub use dep_node::{DepKind, DepKindStruct, DepNode, DepNodeParams, WorkProductId}; +pub use dep_node::{DepKind, DepKindVTable, DepNode, DepNodeParams, WorkProductId}; pub(crate) use graph::DepGraphData; pub use graph::{DepGraph, DepNodeIndex, TaskDepsRef, WorkProduct, WorkProductMap, hash_result}; pub use query::DepGraphQuery; @@ -35,21 +35,21 @@ pub trait DepContext: Copy { /// Access the compiler session. fn sess(&self) -> &Session; - fn dep_kind_info(&self, dep_node: DepKind) -> &DepKindStruct; + fn dep_kind_vtable(&self, dep_node: DepKind) -> &DepKindVTable; #[inline(always)] fn fingerprint_style(self, kind: DepKind) -> FingerprintStyle { - let data = self.dep_kind_info(kind); - if data.is_anon { + let vtable = self.dep_kind_vtable(kind); + if vtable.is_anon { return FingerprintStyle::Opaque; } - data.fingerprint_style + vtable.fingerprint_style } #[inline(always)] /// Return whether this kind always require evaluation. fn is_eval_always(self, kind: DepKind) -> bool { - self.dep_kind_info(kind).is_eval_always + self.dep_kind_vtable(kind).is_eval_always } /// Try to force a dep node to execute and see if it's green. @@ -65,9 +65,10 @@ pub trait DepContext: Copy { prev_index: SerializedDepNodeIndex, frame: &MarkFrame<'_>, ) -> bool { - let cb = self.dep_kind_info(dep_node.kind); - if let Some(f) = cb.force_from_dep_node { - match panic::catch_unwind(panic::AssertUnwindSafe(|| f(self, dep_node, prev_index))) { + if let Some(force_fn) = self.dep_kind_vtable(dep_node.kind).force_from_dep_node { + match panic::catch_unwind(panic::AssertUnwindSafe(|| { + force_fn(self, dep_node, prev_index) + })) { Err(value) => { if !value.is::() { print_markframe_trace(self.dep_graph(), frame); @@ -83,9 +84,8 @@ pub trait DepContext: Copy { /// Load data from the on-disk cache. fn try_load_from_on_disk_cache(self, dep_node: DepNode) { - let cb = self.dep_kind_info(dep_node.kind); - if let Some(f) = cb.try_load_from_on_disk_cache { - f(self, dep_node) + if let Some(try_load_fn) = self.dep_kind_vtable(dep_node.kind).try_load_from_on_disk_cache { + try_load_fn(self, dep_node) } } diff --git a/compiler/rustc_query_system/src/query/job.rs b/compiler/rustc_query_system/src/query/job.rs index 79d08d33c0b1c..0431151c74c95 100644 --- a/compiler/rustc_query_system/src/query/job.rs +++ b/compiler/rustc_query_system/src/query/job.rs @@ -626,7 +626,7 @@ pub fn print_query_stack( file, "#{} [{}] {}", count_total, - qcx.dep_context().dep_kind_info(query_info.query.dep_kind).name, + qcx.dep_context().dep_kind_vtable(query_info.query.dep_kind).name, query_info.query.description ); } diff --git a/library/Cargo.lock b/library/Cargo.lock index f6c14bc58a044..ee2e7550c3700 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -358,6 +358,13 @@ dependencies = [ "rustc-std-workspace-core", ] +[[package]] +name = "std_detect_tests" +version = "0.0.0" +dependencies = [ + "std_detect", +] + [[package]] name = "sysroot" version = "0.0.0" diff --git a/library/Cargo.toml b/library/Cargo.toml index b26e5f41c9313..dc3f757130f4b 100644 --- a/library/Cargo.toml +++ b/library/Cargo.toml @@ -7,6 +7,7 @@ members = [ "sysroot", "coretests", "alloctests", + "std_detect_tests", ] exclude = [ diff --git a/library/proc_macro/src/bridge/client.rs b/library/proc_macro/src/bridge/client.rs index bdaa865a998d6..0d87a727ae40b 100644 --- a/library/proc_macro/src/bridge/client.rs +++ b/library/proc_macro/src/bridge/client.rs @@ -6,93 +6,66 @@ use std::sync::atomic::AtomicU32; use super::*; -macro_rules! define_client_handles { - ( - 'owned: $($oty:ident,)* - 'interned: $($ity:ident,)* - ) => { - #[repr(C)] - #[allow(non_snake_case)] - pub(super) struct HandleCounters { - $(pub(super) $oty: AtomicU32,)* - $(pub(super) $ity: AtomicU32,)* - } +#[repr(C)] +pub(super) struct HandleCounters { + pub(super) token_stream: AtomicU32, + pub(super) span: AtomicU32, +} - static COUNTERS: HandleCounters = HandleCounters { - $($oty: AtomicU32::new(1),)* - $($ity: AtomicU32::new(1),)* - }; +static COUNTERS: HandleCounters = + HandleCounters { token_stream: AtomicU32::new(1), span: AtomicU32::new(1) }; - $( - pub(crate) struct $oty { - handle: handle::Handle, - } +pub(crate) struct TokenStream { + handle: handle::Handle, +} - impl !Send for $oty {} - impl !Sync for $oty {} +impl !Send for TokenStream {} +impl !Sync for TokenStream {} - // Forward `Drop::drop` to the inherent `drop` method. - impl Drop for $oty { - fn drop(&mut self) { - $oty { - handle: self.handle, - }.drop(); - } - } - - impl Encode for $oty { - fn encode(self, w: &mut Writer, s: &mut S) { - mem::ManuallyDrop::new(self).handle.encode(w, s); - } - } +// Forward `Drop::drop` to the inherent `drop` method. +impl Drop for TokenStream { + fn drop(&mut self) { + Methods::ts_drop(TokenStream { handle: self.handle }); + } +} - impl Encode for &$oty { - fn encode(self, w: &mut Writer, s: &mut S) { - self.handle.encode(w, s); - } - } +impl Encode for TokenStream { + fn encode(self, w: &mut Writer, s: &mut S) { + mem::ManuallyDrop::new(self).handle.encode(w, s); + } +} - impl Encode for &mut $oty { - fn encode(self, w: &mut Writer, s: &mut S) { - self.handle.encode(w, s); - } - } +impl Encode for &TokenStream { + fn encode(self, w: &mut Writer, s: &mut S) { + self.handle.encode(w, s); + } +} - impl Decode<'_, '_, S> for $oty { - fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { - $oty { - handle: handle::Handle::decode(r, s), - } - } - } - )* +impl Decode<'_, '_, S> for TokenStream { + fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { + TokenStream { handle: handle::Handle::decode(r, s) } + } +} - $( - #[derive(Copy, Clone, PartialEq, Eq, Hash)] - pub(crate) struct $ity { - handle: handle::Handle, - } +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +pub(crate) struct Span { + handle: handle::Handle, +} - impl !Send for $ity {} - impl !Sync for $ity {} +impl !Send for Span {} +impl !Sync for Span {} - impl Encode for $ity { - fn encode(self, w: &mut Writer, s: &mut S) { - self.handle.encode(w, s); - } - } +impl Encode for Span { + fn encode(self, w: &mut Writer, s: &mut S) { + self.handle.encode(w, s); + } +} - impl Decode<'_, '_, S> for $ity { - fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { - $ity { - handle: handle::Handle::decode(r, s), - } - } - } - )* +impl Decode<'_, '_, S> for Span { + fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { + Span { handle: handle::Handle::decode(r, s) } } } -with_api_handle_types!(define_client_handles); // FIXME(eddyb) generate these impls by pattern-matching on the // names of methods - also could use the presence of `fn drop` @@ -102,7 +75,7 @@ with_api_handle_types!(define_client_handles); impl Clone for TokenStream { fn clone(&self) -> Self { - self.clone() + Methods::ts_clone(self) } } @@ -122,23 +95,27 @@ impl Span { impl fmt::Debug for Span { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.debug()) + f.write_str(&Methods::span_debug(*self)) } } +pub(crate) use super::Methods; pub(crate) use super::symbol::Symbol; macro_rules! define_client_side { - ($($name:ident { - $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* - }),* $(,)?) => { - $(impl $name { + ( + Methods { + $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* + }, + $($name:ident),* $(,)? + ) => { + impl Methods { $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)? { Bridge::with(|bridge| { let mut buf = bridge.cached_buffer.take(); buf.clear(); - api_tags::Method::$name(api_tags::$name::$method).encode(&mut buf, &mut ()); + api_tags::Method::$method.encode(&mut buf, &mut ()); $($arg.encode(&mut buf, &mut ());)* buf = bridge.dispatch.call(buf); @@ -150,7 +127,7 @@ macro_rules! define_client_side { r.unwrap_or_else(|e| panic::resume_unwind(e.into())) }) })* - })* + } } } with_api!(self, self, define_client_side); diff --git a/library/proc_macro/src/bridge/handle.rs b/library/proc_macro/src/bridge/handle.rs index 8c53bb609f60c..f0c01e39de32d 100644 --- a/library/proc_macro/src/bridge/handle.rs +++ b/library/proc_macro/src/bridge/handle.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use std::hash::Hash; use std::num::NonZero; -use std::ops::{Index, IndexMut}; +use std::ops::Index; use std::sync::atomic::{AtomicU32, Ordering}; use super::fxhash::FxHashMap; @@ -47,12 +47,6 @@ impl Index for OwnedStore { } } -impl IndexMut for OwnedStore { - fn index_mut(&mut self, h: Handle) -> &mut T { - self.data.get_mut(&h).expect("use-after-free in `proc_macro` handle") - } -} - /// Like `OwnedStore`, but avoids storing any value more than once. pub(super) struct InternedStore { owned: OwnedStore, diff --git a/library/proc_macro/src/bridge/mod.rs b/library/proc_macro/src/bridge/mod.rs index b0ee9c0cc3027..6f7c8726f9253 100644 --- a/library/proc_macro/src/bridge/mod.rs +++ b/library/proc_macro/src/bridge/mod.rs @@ -21,14 +21,15 @@ use crate::{Delimiter, Level, Spacing}; /// `with_api!(MySelf, my_self, my_macro)` expands to: /// ```rust,ignore (pseudo-code) /// my_macro! { -/// // ... -/// Literal { +/// Methods { /// // ... -/// fn character(ch: char) -> MySelf::Literal; +/// fn lit_character(ch: char) -> MySelf::Literal; /// // ... -/// fn span(my_self: &MySelf::Literal) -> MySelf::Span; -/// fn set_span(my_self: &mut MySelf::Literal, span: MySelf::Span); +/// fn lit_span(my_self: &MySelf::Literal) -> MySelf::Span; +/// fn lit_set_span(my_self: &mut MySelf::Literal, span: MySelf::Span); /// }, +/// Literal, +/// Span, /// // ... /// } /// ``` @@ -48,77 +49,62 @@ use crate::{Delimiter, Level, Spacing}; macro_rules! with_api { ($S:ident, $self:ident, $m:ident) => { $m! { - FreeFunctions { - fn drop($self: $S::FreeFunctions); + Methods { fn injected_env_var(var: &str) -> Option; fn track_env_var(var: &str, value: Option<&str>); fn track_path(path: &str); fn literal_from_str(s: &str) -> Result, ()>; fn emit_diagnostic(diagnostic: Diagnostic<$S::Span>); - }, - TokenStream { - fn drop($self: $S::TokenStream); - fn clone($self: &$S::TokenStream) -> $S::TokenStream; - fn is_empty($self: &$S::TokenStream) -> bool; - fn expand_expr($self: &$S::TokenStream) -> Result<$S::TokenStream, ()>; - fn from_str(src: &str) -> $S::TokenStream; - fn to_string($self: &$S::TokenStream) -> String; - fn from_token_tree( + + fn ts_drop(stream: $S::TokenStream); + fn ts_clone(stream: &$S::TokenStream) -> $S::TokenStream; + fn ts_is_empty(stream: &$S::TokenStream) -> bool; + fn ts_expand_expr(stream: &$S::TokenStream) -> Result<$S::TokenStream, ()>; + fn ts_from_str(src: &str) -> $S::TokenStream; + fn ts_to_string(stream: &$S::TokenStream) -> String; + fn ts_from_token_tree( tree: TokenTree<$S::TokenStream, $S::Span, $S::Symbol>, ) -> $S::TokenStream; - fn concat_trees( + fn ts_concat_trees( base: Option<$S::TokenStream>, trees: Vec>, ) -> $S::TokenStream; - fn concat_streams( + fn ts_concat_streams( base: Option<$S::TokenStream>, streams: Vec<$S::TokenStream>, ) -> $S::TokenStream; - fn into_trees( - $self: $S::TokenStream + fn ts_into_trees( + stream: $S::TokenStream ) -> Vec>; - }, - Span { - fn debug($self: $S::Span) -> String; - fn parent($self: $S::Span) -> Option<$S::Span>; - fn source($self: $S::Span) -> $S::Span; - fn byte_range($self: $S::Span) -> Range; - fn start($self: $S::Span) -> $S::Span; - fn end($self: $S::Span) -> $S::Span; - fn line($self: $S::Span) -> usize; - fn column($self: $S::Span) -> usize; - fn file($self: $S::Span) -> String; - fn local_file($self: $S::Span) -> Option; - fn join($self: $S::Span, other: $S::Span) -> Option<$S::Span>; - fn subspan($self: $S::Span, start: Bound, end: Bound) -> Option<$S::Span>; - fn resolved_at($self: $S::Span, at: $S::Span) -> $S::Span; - fn source_text($self: $S::Span) -> Option; - fn save_span($self: $S::Span) -> usize; - fn recover_proc_macro_span(id: usize) -> $S::Span; - }, - Symbol { - fn normalize_and_validate_ident(string: &str) -> Result<$S::Symbol, ()>; - }, - } - }; -} -// Similar to `with_api`, but only lists the types requiring handles, and they -// are divided into the two storage categories. -macro_rules! with_api_handle_types { - ($m:ident) => { - $m! { - 'owned: - FreeFunctions, + fn span_debug(span: $S::Span) -> String; + fn span_parent(span: $S::Span) -> Option<$S::Span>; + fn span_source(span: $S::Span) -> $S::Span; + fn span_byte_range(span: $S::Span) -> Range; + fn span_start(span: $S::Span) -> $S::Span; + fn span_end(span: $S::Span) -> $S::Span; + fn span_line(span: $S::Span) -> usize; + fn span_column(span: $S::Span) -> usize; + fn span_file(span: $S::Span) -> String; + fn span_local_file(span: $S::Span) -> Option; + fn span_join(span: $S::Span, other: $S::Span) -> Option<$S::Span>; + fn span_subspan(span: $S::Span, start: Bound, end: Bound) -> Option<$S::Span>; + fn span_resolved_at(span: $S::Span, at: $S::Span) -> $S::Span; + fn span_source_text(span: $S::Span) -> Option; + fn span_save_span(span: $S::Span) -> usize; + fn span_recover_proc_macro_span(id: usize) -> $S::Span; + + fn symbol_normalize_and_validate_ident(string: &str) -> Result<$S::Symbol, ()>; + }, TokenStream, - - 'interned: Span, - // Symbol is handled manually + Symbol, } }; } +pub(crate) struct Methods; + #[allow(unsafe_code)] mod arena; #[allow(unsafe_code)] @@ -171,20 +157,16 @@ mod api_tags { use super::rpc::{Decode, Encode, Reader, Writer}; macro_rules! declare_tags { - ($($name:ident { - $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* - }),* $(,)?) => { - $( - pub(super) enum $name { - $($method),* - } - rpc_encode_decode!(enum $name { $($method),* }); - )* - + ( + Methods { + $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* + }, + $($name:ident),* $(,)? + ) => { pub(super) enum Method { - $($name($name)),* + $($method),* } - rpc_encode_decode!(enum Method { $($name(m)),* }); + rpc_encode_decode!(enum Method { $($method),* }); } } with_api!(self, self, declare_tags); diff --git a/library/proc_macro/src/bridge/server.rs b/library/proc_macro/src/bridge/server.rs index e9ef26c07f24f..b79de99844533 100644 --- a/library/proc_macro/src/bridge/server.rs +++ b/library/proc_macro/src/bridge/server.rs @@ -5,108 +5,66 @@ use std::marker::PhantomData; use super::*; -macro_rules! define_server_handles { - ( - 'owned: $($oty:ident,)* - 'interned: $($ity:ident,)* - ) => { - #[allow(non_snake_case)] - pub(super) struct HandleStore { - $($oty: handle::OwnedStore,)* - $($ity: handle::InternedStore,)* - } +pub(super) struct HandleStore { + token_stream: handle::OwnedStore>, + span: handle::InternedStore>, +} - impl HandleStore { - fn new(handle_counters: &'static client::HandleCounters) -> Self { - HandleStore { - $($oty: handle::OwnedStore::new(&handle_counters.$oty),)* - $($ity: handle::InternedStore::new(&handle_counters.$ity),)* - } - } +impl HandleStore { + fn new(handle_counters: &'static client::HandleCounters) -> Self { + HandleStore { + token_stream: handle::OwnedStore::new(&handle_counters.token_stream), + span: handle::InternedStore::new(&handle_counters.span), } + } +} - $( - impl Encode>> for Marked { - fn encode(self, w: &mut Writer, s: &mut HandleStore>) { - s.$oty.alloc(self).encode(w, s); - } - } - - impl Decode<'_, '_, HandleStore>> - for Marked - { - fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { - s.$oty.take(handle::Handle::decode(r, &mut ())) - } - } +impl Encode> for Marked { + fn encode(self, w: &mut Writer, s: &mut HandleStore) { + s.token_stream.alloc(self).encode(w, s); + } +} - impl<'s, S: Types> Decode<'_, 's, HandleStore>> - for &'s Marked - { - fn decode(r: &mut Reader<'_>, s: &'s mut HandleStore>) -> Self { - &s.$oty[handle::Handle::decode(r, &mut ())] - } - } +impl Decode<'_, '_, HandleStore> for Marked { + fn decode(r: &mut Reader<'_>, s: &mut HandleStore) -> Self { + s.token_stream.take(handle::Handle::decode(r, &mut ())) + } +} - impl<'s, S: Types> Decode<'_, 's, HandleStore>> - for &'s mut Marked - { - fn decode( - r: &mut Reader<'_>, - s: &'s mut HandleStore> - ) -> Self { - &mut s.$oty[handle::Handle::decode(r, &mut ())] - } - } - )* +impl<'s, S: Types> Decode<'_, 's, HandleStore> + for &'s Marked +{ + fn decode(r: &mut Reader<'_>, s: &'s mut HandleStore) -> Self { + &s.token_stream[handle::Handle::decode(r, &mut ())] + } +} - $( - impl Encode>> for Marked { - fn encode(self, w: &mut Writer, s: &mut HandleStore>) { - s.$ity.alloc(self).encode(w, s); - } - } +impl Encode> for Marked { + fn encode(self, w: &mut Writer, s: &mut HandleStore) { + s.span.alloc(self).encode(w, s); + } +} - impl Decode<'_, '_, HandleStore>> - for Marked - { - fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { - s.$ity.copy(handle::Handle::decode(r, &mut ())) - } - } - )* +impl Decode<'_, '_, HandleStore> for Marked { + fn decode(r: &mut Reader<'_>, s: &mut HandleStore) -> Self { + s.span.copy(handle::Handle::decode(r, &mut ())) } } -with_api_handle_types!(define_server_handles); pub trait Types { - type FreeFunctions: 'static; type TokenStream: 'static + Clone; type Span: 'static + Copy + Eq + Hash; type Symbol: 'static; } -/// Declare an associated fn of one of the traits below, adding necessary -/// default bodies. -macro_rules! associated_fn { - (fn drop(&mut self, $arg:ident: $arg_ty:ty)) => - (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) }); - - (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) => - (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() }); - - ($($item:tt)*) => ($($item)*;) -} - macro_rules! declare_server_traits { - ($($name:ident { - $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* - }),* $(,)?) => { - $(pub trait $name: Types { - $(associated_fn!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)* - })* - - pub trait Server: Types $(+ $name)* { + ( + Methods { + $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* + }, + $($name:ident),* $(,)? + ) => { + pub trait Server: Types { fn globals(&mut self) -> ExpnGlobals; /// Intern a symbol received from RPC @@ -114,41 +72,12 @@ macro_rules! declare_server_traits { /// Recover the string value of a symbol, and invoke a callback with it. fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)); - } - } -} -with_api!(Self, self_, declare_server_traits); - -pub(super) struct MarkedTypes(S); - -impl Server for MarkedTypes { - fn globals(&mut self) -> ExpnGlobals { - <_>::mark(Server::globals(&mut self.0)) - } - fn intern_symbol(ident: &str) -> Self::Symbol { - <_>::mark(S::intern_symbol(ident)) - } - fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) { - S::with_symbol_string(symbol.unmark(), f) - } -} -macro_rules! define_mark_types_impls { - ($($name:ident { - $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* - }),* $(,)?) => { - impl Types for MarkedTypes { - $(type $name = Marked;)* + $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?;)* } - - $(impl $name for MarkedTypes { - $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? { - <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*)) - })* - })* } } -with_api!(Self, self_, define_mark_types_impls); +with_api!(Self, self_, declare_server_traits); struct Dispatcher { handle_store: HandleStore, @@ -156,9 +85,12 @@ struct Dispatcher { } macro_rules! define_dispatcher_impl { - ($($name:ident { - $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* - }),* $(,)?) => { + ( + Methods { + $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* + }, + $($name:ident),* $(,)? + ) => { // FIXME(eddyb) `pub` only for `ExecutionStrategy` below. pub trait DispatcherTrait { // HACK(eddyb) these are here to allow `Self::$name` to work below. @@ -167,35 +99,37 @@ macro_rules! define_dispatcher_impl { fn dispatch(&mut self, buf: Buffer) -> Buffer; } - impl DispatcherTrait for Dispatcher> { - $(type $name = as Types>::$name;)* + impl DispatcherTrait for Dispatcher { + $(type $name = Marked;)* fn dispatch(&mut self, mut buf: Buffer) -> Buffer { let Dispatcher { handle_store, server } = self; let mut reader = &buf[..]; match api_tags::Method::decode(&mut reader, &mut ()) { - $(api_tags::Method::$name(m) => match m { - $(api_tags::$name::$method => { - let mut call_method = || { - $(let $arg = <$arg_ty>::decode(&mut reader, handle_store);)* - $name::$method(server, $($arg),*) - }; - // HACK(eddyb) don't use `panic::catch_unwind` in a panic. - // If client and server happen to use the same `std`, - // `catch_unwind` asserts that the panic counter was 0, - // even when the closure passed to it didn't panic. - let r = if thread::panicking() { - Ok(call_method()) - } else { - panic::catch_unwind(panic::AssertUnwindSafe(call_method)) - .map_err(PanicMessage::from) - }; - - buf.clear(); - r.encode(&mut buf, handle_store); - })* - }),* + $(api_tags::Method::$method => { + let mut call_method = || { + $(let $arg = <$arg_ty>::decode(&mut reader, handle_store).unmark();)* + let r = server.$method($($arg),*); + $( + let r: $ret_ty = Mark::mark(r); + )* + r + }; + // HACK(eddyb) don't use `panic::catch_unwind` in a panic. + // If client and server happen to use the same `std`, + // `catch_unwind` asserts that the panic counter was 0, + // even when the closure passed to it didn't panic. + let r = if thread::panicking() { + Ok(call_method()) + } else { + panic::catch_unwind(panic::AssertUnwindSafe(call_method)) + .map_err(PanicMessage::from) + }; + + buf.clear(); + r.encode(&mut buf, handle_store); + })* } buf } @@ -354,8 +288,8 @@ pub trait MessagePipe: Sized { fn run_server< S: Server, - I: Encode>>, - O: for<'a, 's> Decode<'a, 's, HandleStore>>, + I: Encode>, + O: for<'a, 's> Decode<'a, 's, HandleStore>, >( strategy: &impl ExecutionStrategy, handle_counters: &'static client::HandleCounters, @@ -364,13 +298,13 @@ fn run_server< run_client: extern "C" fn(BridgeConfig<'_>) -> Buffer, force_show_panics: bool, ) -> Result { - let mut dispatcher = - Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) }; + let mut dispatcher = Dispatcher { handle_store: HandleStore::new(handle_counters), server }; let globals = dispatcher.server.globals(); let mut buf = Buffer::new(); - (globals, input).encode(&mut buf, &mut dispatcher.handle_store); + (> as Mark>::mark(globals), input) + .encode(&mut buf, &mut dispatcher.handle_store); buf = strategy.run_bridge_and_client(&mut dispatcher, buf, run_client, force_show_panics); @@ -394,11 +328,13 @@ impl client::Client { strategy, handle_counters, server, - as Types>::TokenStream::mark(input), + >::mark(input), run, force_show_panics, ) - .map(|s| as Types>::TokenStream>>::unmark(s).unwrap_or_default()) + .map(|s| { + >>::unmark(s).unwrap_or_default() + }) } } @@ -421,12 +357,14 @@ impl client::Client<(crate::TokenStream, crate::TokenStream), crate::TokenStream handle_counters, server, ( - as Types>::TokenStream::mark(input), - as Types>::TokenStream::mark(input2), + >::mark(input), + >::mark(input2), ), run, force_show_panics, ) - .map(|s| as Types>::TokenStream>>::unmark(s).unwrap_or_default()) + .map(|s| { + >>::unmark(s).unwrap_or_default() + }) } } diff --git a/library/proc_macro/src/bridge/symbol.rs b/library/proc_macro/src/bridge/symbol.rs index e070ec07681d3..edba142bad721 100644 --- a/library/proc_macro/src/bridge/symbol.rs +++ b/library/proc_macro/src/bridge/symbol.rs @@ -46,7 +46,7 @@ impl Symbol { if string.is_ascii() { Err(()) } else { - client::Symbol::normalize_and_validate_ident(string) + client::Methods::symbol_normalize_and_validate_ident(string) } .unwrap_or_else(|_| panic!("`{:?}` is not a valid identifier", string)) } @@ -99,18 +99,14 @@ impl Encode for Symbol { } } -impl Decode<'_, '_, server::HandleStore>> - for Marked -{ - fn decode(r: &mut Reader<'_>, s: &mut server::HandleStore>) -> Self { +impl Decode<'_, '_, server::HandleStore> for Marked { + fn decode(r: &mut Reader<'_>, s: &mut server::HandleStore) -> Self { Mark::mark(S::intern_symbol(<&str>::decode(r, s))) } } -impl Encode>> - for Marked -{ - fn encode(self, w: &mut Writer, s: &mut server::HandleStore>) { +impl Encode> for Marked { + fn encode(self, w: &mut Writer, s: &mut server::HandleStore) { S::with_symbol_string(&self.unmark(), |sym| sym.encode(w, s)) } } diff --git a/library/proc_macro/src/diagnostic.rs b/library/proc_macro/src/diagnostic.rs index 5a209f7c7aa18..39a8ecb2ee52e 100644 --- a/library/proc_macro/src/diagnostic.rs +++ b/library/proc_macro/src/diagnostic.rs @@ -170,6 +170,6 @@ impl Diagnostic { } } - crate::bridge::client::FreeFunctions::emit_diagnostic(to_internal(self)); + crate::bridge::client::Methods::emit_diagnostic(to_internal(self)); } } diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index a005f743ddfac..95a7ea7d7b3b7 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -58,6 +58,7 @@ use rustc_literal_escaper::{MixedUnit, unescape_byte_str, unescape_c_str, unesca #[unstable(feature = "proc_macro_totokens", issue = "130977")] pub use to_tokens::ToTokens; +use crate::bridge::client::Methods as BridgeMethods; use crate::escape::{EscapeOptions, escape_bytes}; /// Errors returned when trying to retrieve a literal unescaped value. @@ -158,7 +159,7 @@ impl TokenStream { /// Checks if this `TokenStream` is empty. #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub fn is_empty(&self) -> bool { - self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true) + self.0.as_ref().map(|h| BridgeMethods::ts_is_empty(h)).unwrap_or(true) } /// Parses this `TokenStream` as an expression and attempts to expand any @@ -174,7 +175,7 @@ impl TokenStream { #[unstable(feature = "proc_macro_expand", issue = "90765")] pub fn expand_expr(&self) -> Result { let stream = self.0.as_ref().ok_or(ExpandError)?; - match bridge::client::TokenStream::expand_expr(stream) { + match BridgeMethods::ts_expand_expr(stream) { Ok(stream) => Ok(TokenStream(Some(stream))), Err(_) => Err(ExpandError), } @@ -193,7 +194,7 @@ impl FromStr for TokenStream { type Err = LexError; fn from_str(src: &str) -> Result { - Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src)))) + Ok(TokenStream(Some(BridgeMethods::ts_from_str(src)))) } } @@ -212,7 +213,7 @@ impl FromStr for TokenStream { impl fmt::Display for TokenStream { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.0 { - Some(ts) => write!(f, "{}", ts.to_string()), + Some(ts) => write!(f, "{}", BridgeMethods::ts_to_string(ts)), None => Ok(()), } } @@ -252,7 +253,7 @@ fn tree_to_bridge_tree( #[stable(feature = "proc_macro_lib2", since = "1.29.0")] impl From for TokenStream { fn from(tree: TokenTree) -> TokenStream { - TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree)))) + TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree)))) } } @@ -281,7 +282,7 @@ impl ConcatTreesHelper { if self.trees.is_empty() { TokenStream(None) } else { - TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees))) + TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees))) } } @@ -289,7 +290,7 @@ impl ConcatTreesHelper { if self.trees.is_empty() { return; } - stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees)) + stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees)) } } @@ -314,7 +315,7 @@ impl ConcatStreamsHelper { if self.streams.len() <= 1 { TokenStream(self.streams.pop()) } else { - TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams))) + TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams))) } } @@ -326,7 +327,7 @@ impl ConcatStreamsHelper { if base.is_none() && self.streams.len() == 1 { stream.0 = self.streams.pop(); } else { - stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams)); + stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams)); } } } @@ -377,7 +378,7 @@ impl Extend for TokenStream { macro_rules! extend_items { ($($item:ident)*) => { $( - #[stable(feature = "token_stream_extend_tt_items", since = "1.92.0")] + #[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")] impl Extend<$item> for TokenStream { fn extend>(&mut self, iter: T) { self.extend(iter.into_iter().map(TokenTree::$item)); @@ -392,7 +393,7 @@ extend_items!(Group Literal Punct Ident); /// Public implementation details for the `TokenStream` type, such as iterators. #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub mod token_stream { - use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge}; + use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge}; /// An iterator over `TokenStream`'s `TokenTree`s. /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups, @@ -437,7 +438,9 @@ pub mod token_stream { type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { - IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter()) + IntoIter( + self.0.map(|v| BridgeMethods::ts_into_trees(v)).unwrap_or_default().into_iter(), + ) } } } @@ -509,7 +512,7 @@ impl Span { /// `self` was generated from, if any. #[unstable(feature = "proc_macro_span", issue = "54725")] pub fn parent(&self) -> Option { - self.0.parent().map(Span) + BridgeMethods::span_parent(self.0).map(Span) } /// The span for the origin source code that `self` was generated from. If @@ -517,25 +520,25 @@ impl Span { /// value is the same as `*self`. #[unstable(feature = "proc_macro_span", issue = "54725")] pub fn source(&self) -> Span { - Span(self.0.source()) + Span(BridgeMethods::span_source(self.0)) } /// Returns the span's byte position range in the source file. #[unstable(feature = "proc_macro_span", issue = "54725")] pub fn byte_range(&self) -> Range { - self.0.byte_range() + BridgeMethods::span_byte_range(self.0) } /// Creates an empty span pointing to directly before this span. #[stable(feature = "proc_macro_span_location", since = "1.88.0")] pub fn start(&self) -> Span { - Span(self.0.start()) + Span(BridgeMethods::span_start(self.0)) } /// Creates an empty span pointing to directly after this span. #[stable(feature = "proc_macro_span_location", since = "1.88.0")] pub fn end(&self) -> Span { - Span(self.0.end()) + Span(BridgeMethods::span_end(self.0)) } /// The one-indexed line of the source file where the span starts. @@ -543,7 +546,7 @@ impl Span { /// To obtain the line of the span's end, use `span.end().line()`. #[stable(feature = "proc_macro_span_location", since = "1.88.0")] pub fn line(&self) -> usize { - self.0.line() + BridgeMethods::span_line(self.0) } /// The one-indexed column of the source file where the span starts. @@ -551,7 +554,7 @@ impl Span { /// To obtain the column of the span's end, use `span.end().column()`. #[stable(feature = "proc_macro_span_location", since = "1.88.0")] pub fn column(&self) -> usize { - self.0.column() + BridgeMethods::span_column(self.0) } /// The path to the source file in which this span occurs, for display purposes. @@ -560,7 +563,7 @@ impl Span { /// It might be remapped (e.g. `"/src/lib.rs"`) or an artificial path (e.g. `""`). #[stable(feature = "proc_macro_span_file", since = "1.88.0")] pub fn file(&self) -> String { - self.0.file() + BridgeMethods::span_file(self.0) } /// The path to the source file in which this span occurs on the local file system. @@ -570,7 +573,7 @@ impl Span { /// This path should not be embedded in the output of the macro; prefer `file()` instead. #[stable(feature = "proc_macro_span_file", since = "1.88.0")] pub fn local_file(&self) -> Option { - self.0.local_file().map(PathBuf::from) + BridgeMethods::span_local_file(self.0).map(PathBuf::from) } /// Creates a new span encompassing `self` and `other`. @@ -578,14 +581,14 @@ impl Span { /// Returns `None` if `self` and `other` are from different files. #[unstable(feature = "proc_macro_span", issue = "54725")] pub fn join(&self, other: Span) -> Option { - self.0.join(other.0).map(Span) + BridgeMethods::span_join(self.0, other.0).map(Span) } /// Creates a new span with the same line/column information as `self` but /// that resolves symbols as though it were at `other`. #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")] pub fn resolved_at(&self, other: Span) -> Span { - Span(self.0.resolved_at(other.0)) + Span(BridgeMethods::span_resolved_at(self.0, other.0)) } /// Creates a new span with the same name resolution behavior as `self` but @@ -610,21 +613,21 @@ impl Span { /// be used for diagnostics only. #[stable(feature = "proc_macro_source_text", since = "1.66.0")] pub fn source_text(&self) -> Option { - self.0.source_text() + BridgeMethods::span_source_text(self.0) } // Used by the implementation of `Span::quote` #[doc(hidden)] #[unstable(feature = "proc_macro_internals", issue = "27812")] pub fn save_span(&self) -> usize { - self.0.save_span() + BridgeMethods::span_save_span(self.0) } // Used by the implementation of `Span::quote` #[doc(hidden)] #[unstable(feature = "proc_macro_internals", issue = "27812")] pub fn recover_proc_macro_span(id: usize) -> Span { - Span(bridge::client::Span::recover_proc_macro_span(id)) + Span(BridgeMethods::span_recover_proc_macro_span(id)) } diagnostic_method!(error, Level::Error); @@ -1389,7 +1392,12 @@ impl Literal { // was 'c' or whether it was '\u{63}'. #[unstable(feature = "proc_macro_span", issue = "54725")] pub fn subspan>(&self, range: R) -> Option { - self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span) + BridgeMethods::span_subspan( + self.0.span, + range.start_bound().cloned(), + range.end_bound().cloned(), + ) + .map(Span) } fn with_symbol_and_suffix(&self, f: impl FnOnce(&str, &str) -> R) -> R { @@ -1559,7 +1567,7 @@ impl FromStr for Literal { type Err = LexError; fn from_str(src: &str) -> Result { - match bridge::client::FreeFunctions::literal_from_str(src) { + match BridgeMethods::literal_from_str(src) { Ok(literal) => Ok(Literal(literal)), Err(()) => Err(LexError), } @@ -1601,11 +1609,12 @@ impl fmt::Debug for Literal { )] /// Functionality for adding environment state to the build dependency info. pub mod tracked { - use std::env::{self, VarError}; use std::ffi::OsStr; use std::path::Path; + use crate::BridgeMethods; + /// Retrieve an environment variable and add it to build dependency info. /// The build system executing the compiler will know that the variable was accessed during /// compilation, and will be able to rerun the build when the value of that variable changes. @@ -1614,9 +1623,8 @@ pub mod tracked { #[unstable(feature = "proc_macro_tracked_env", issue = "99515")] pub fn env_var + AsRef>(key: K) -> Result { let key: &str = key.as_ref(); - let value = crate::bridge::client::FreeFunctions::injected_env_var(key) - .map_or_else(|| env::var(key), Ok); - crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok()); + let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok); + BridgeMethods::track_env_var(key, value.as_deref().ok()); value } @@ -1626,6 +1634,6 @@ pub mod tracked { #[unstable(feature = "proc_macro_tracked_path", issue = "99515")] pub fn path>(path: P) { let path: &str = path.as_ref().to_str().unwrap(); - crate::bridge::client::FreeFunctions::track_path(path); + BridgeMethods::track_path(path); } } diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 44db1bf22bc83..8bec157e4e6e6 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -468,7 +468,9 @@ extern crate std as realstd; // The standard macros that are not built-in to the compiler. #[macro_use] -mod macros; +#[doc(hidden)] +#[unstable(feature = "std_internals", issue = "none")] +pub mod macros; // The runtime entry point and a few unstable public functions used by the // compiler diff --git a/library/std/src/macros.rs b/library/std/src/macros.rs index 25e2b7ea13703..0bb14552432d5 100644 --- a/library/std/src/macros.rs +++ b/library/std/src/macros.rs @@ -347,35 +347,70 @@ macro_rules! eprintln { /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html /// [`log`]: https://crates.io/crates/log #[macro_export] +#[allow_internal_unstable(std_internals)] #[cfg_attr(not(test), rustc_diagnostic_item = "dbg_macro")] #[stable(feature = "dbg_macro", since = "1.32.0")] macro_rules! dbg { - // NOTE: We cannot use `concat!` to make a static string as a format argument - // of `eprintln!` because `file!` could contain a `{` or - // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!` - // will be malformed. () => { $crate::eprintln!("[{}:{}:{}]", $crate::file!(), $crate::line!(), $crate::column!()) }; - ($val:expr $(,)?) => { + ($($val:expr),+ $(,)?) => { + $crate::macros::dbg_internal!(() () ($($val),+)) + }; +} + +/// Internal macro that processes a list of expressions and produces a chain of +/// nested `match`es, one for each expression, before finally calling `eprint!` +/// with the collected information and returning all the evaluated expressions +/// in a tuple. +/// +/// E.g. `dbg_internal!(() () (1, 2))` expands into +/// ```rust, ignore +/// match 1 { +/// tmp_1 => match 2 { +/// tmp_2 => { +/// eprint!("...", &tmp_1, &tmp_2, /* some other arguments */); +/// (tmp_1, tmp_2) +/// } +/// } +/// } +/// ``` +/// +/// This is necessary so that `dbg!` outputs don't get torn, see #136703. +#[doc(hidden)] +#[rustc_macro_transparency = "semiopaque"] +pub macro dbg_internal { + (($($piece:literal),+) ($($processed:expr => $bound:expr),+) ()) => {{ + $crate::eprint!( + $crate::concat!($($piece),+), + $( + $crate::stringify!($processed), + // The `&T: Debug` check happens here (not in the format literal desugaring) + // to avoid format literal related messages and suggestions. + &&$bound as &dyn $crate::fmt::Debug + ),+, + // The location returned here is that of the macro invocation, so + // it will be the same for all expressions. Thus, label these + // arguments so that they can be reused in every piece of the + // formatting template. + file=$crate::file!(), + line=$crate::line!(), + column=$crate::column!() + ); + // Comma separate the variables only when necessary so that this will + // not yield a tuple for a single expression, but rather just parenthesize + // the expression. + ($($bound),+) + }}, + (($($piece:literal),*) ($($processed:expr => $bound:expr),*) ($val:expr $(,$rest:expr)*)) => { // Use of `match` here is intentional because it affects the lifetimes // of temporaries - https://stackoverflow.com/a/48732525/1063961 match $val { - tmp => { - $crate::eprintln!("[{}:{}:{}] {} = {:#?}", - $crate::file!(), - $crate::line!(), - $crate::column!(), - $crate::stringify!($val), - // The `&T: Debug` check happens here (not in the format literal desugaring) - // to avoid format literal related messages and suggestions. - &&tmp as &dyn $crate::fmt::Debug, - ); - tmp - } + tmp => $crate::macros::dbg_internal!( + ($($piece,)* "[{file}:{line}:{column}] {} = {:#?}\n") + ($($processed => $bound,)* $val => tmp) + ($($rest),*) + ), } - }; - ($($val:expr),+ $(,)?) => { - ($($crate::dbg!($val)),+,) - }; + }, } diff --git a/library/std/src/sys/thread/windows.rs b/library/std/src/sys/thread/windows.rs index 6a21b11e0312c..ea18572489ee0 100644 --- a/library/std/src/sys/thread/windows.rs +++ b/library/std/src/sys/thread/windows.rs @@ -8,7 +8,7 @@ use crate::sys::pal::time::WaitableTimer; use crate::sys::pal::{dur2timeout, to_u16s}; use crate::sys::{FromInner, c, stack_overflow}; use crate::thread::ThreadInit; -use crate::time::Duration; +use crate::time::{Duration, Instant}; use crate::{io, ptr}; pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024; @@ -120,11 +120,28 @@ pub fn sleep(dur: Duration) { timer.set(dur)?; timer.wait() } + // Directly forward to `Sleep` for its zero duration behavior when indeed + // zero in order to skip the `Instant::now` calls, useless in this case. + if dur.is_zero() { + unsafe { c::Sleep(0) }; // Attempt to use high-precision sleep (Windows 10, version 1803+). - // On error fallback to the standard `Sleep` function. - // Also preserves the zero duration behavior of `Sleep`. - if dur.is_zero() || high_precision_sleep(dur).is_err() { - unsafe { c::Sleep(dur2timeout(dur)) } + // On error, fallback to the standard `Sleep` function. + } else if high_precision_sleep(dur).is_err() { + let start = Instant::now(); + unsafe { c::Sleep(dur2timeout(dur)) }; + + // See #149935: `Sleep` under Windows 7 and probably 8 as well seems a + // bit buggy for us as it can last less than the requested time while + // our API is meant to guarantee that. This is fixed by measuring the + // effective time difference and if needed, sleeping a bit more in + // order to ensure the duration is always exceeded. A fixed single + // millisecond works because `Sleep` operates based on a system-wide + // (until Windows 10 2004 that makes it process-local) interrupt timer + // that counts in "tick" units of ~15ms by default: a 1ms timeout + // therefore passes the next tick boundary. + if start.elapsed() < dur { + unsafe { c::Sleep(1) }; + } } } diff --git a/library/std_detect/src/detect/arch/mod.rs b/library/std_detect/src/detect/arch/mod.rs index 2be7f091c285e..2e545845f8176 100644 --- a/library/std_detect/src/detect/arch/mod.rs +++ b/library/std_detect/src/detect/arch/mod.rs @@ -66,7 +66,7 @@ cfg_select! { _ => { // Unimplemented architecture: #[doc(hidden)] - pub(crate) enum Feature { + pub enum Feature { Null } #[doc(hidden)] diff --git a/library/std_detect/src/detect/cache.rs b/library/std_detect/src/detect/cache.rs index c0c0b7b7f8635..e43b76d1419df 100644 --- a/library/std_detect/src/detect/cache.rs +++ b/library/std_detect/src/detect/cache.rs @@ -30,21 +30,21 @@ const CACHE_CAPACITY: u32 = 93; // The derived `Default` implementation will initialize the field to zero, // which is what we want. #[derive(Copy, Clone, Default, PartialEq, Eq)] -pub(crate) struct Initializer(u128); +pub struct Initializer(u128); // NOTE: the `debug_assert!` would catch that we do not add more Features than // the one fitting our cache. impl Initializer { /// Tests the `bit` of the cache. #[inline] - pub(crate) fn test(self, bit: u32) -> bool { + pub fn test(self, bit: u32) -> bool { debug_assert!(bit < CACHE_CAPACITY, "too many features, time to increase the cache size!"); test_bit(self.0, bit) } /// Sets the `bit` of the cache. #[inline] - pub(crate) fn set(&mut self, bit: u32) { + pub fn set(&mut self, bit: u32) { debug_assert!(bit < CACHE_CAPACITY, "too many features, time to increase the cache size!"); let v = self.0; self.0 = set_bit(v, bit); diff --git a/library/std_detect/src/detect/macros.rs b/library/std_detect/src/detect/macros.rs index 17140e15653d2..7a99be5bd2bc4 100644 --- a/library/std_detect/src/detect/macros.rs +++ b/library/std_detect/src/detect/macros.rs @@ -149,7 +149,7 @@ macro_rules! features { #[repr(u8)] #[unstable(feature = "stdarch_internal", issue = "none")] #[cfg($cfg)] - pub(crate) enum Feature { + pub enum Feature { $( $(#[$feature_comment])* $feature, diff --git a/library/std_detect/src/detect/mod.rs b/library/std_detect/src/detect/mod.rs index c888dd34d9db5..d41526aacd8cc 100644 --- a/library/std_detect/src/detect/mod.rs +++ b/library/std_detect/src/detect/mod.rs @@ -32,6 +32,11 @@ pub(crate) use self::arch::Feature; mod bit; mod cache; +pub mod __test { + pub use super::arch::Feature; + pub use super::cache::Initializer; +} + cfg_select! { miri => { // When running under miri all target-features that are not enabled at @@ -53,6 +58,14 @@ cfg_select! { mod riscv; #[path = "os/linux/mod.rs"] mod os; + #[unstable(feature = "stdarch_internal", issue = "none")] + pub mod __test_os { + #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] + pub use super::riscv::imply_features; + #[cfg(target_arch = "aarch64")] + pub use super::os::aarch64::AtHwcap; + pub use super::os::auxvec::{auxv, auxv_from_file}; + } } target_os = "freebsd" => { #[cfg(target_arch = "aarch64")] diff --git a/library/std_detect/src/detect/os/linux/aarch64.rs b/library/std_detect/src/detect/os/linux/aarch64.rs index b733b8a9eb236..b3f6fbb273d20 100644 --- a/library/std_detect/src/detect/os/linux/aarch64.rs +++ b/library/std_detect/src/detect/os/linux/aarch64.rs @@ -35,106 +35,106 @@ pub(crate) fn detect_features() -> cache::Initializer { /// /// [hwcap]: https://github.com/torvalds/linux/blob/master/arch/arm64/include/uapi/asm/hwcap.h #[derive(Debug, Default, PartialEq)] -struct AtHwcap { +pub struct AtHwcap { // AT_HWCAP - fp: bool, - asimd: bool, - // evtstrm: No LLVM support. - aes: bool, - pmull: bool, - sha1: bool, - sha2: bool, - crc32: bool, - atomics: bool, - fphp: bool, - asimdhp: bool, - // cpuid: No LLVM support. - asimdrdm: bool, - jscvt: bool, - fcma: bool, - lrcpc: bool, - dcpop: bool, - sha3: bool, - sm3: bool, - sm4: bool, - asimddp: bool, - sha512: bool, - sve: bool, - fhm: bool, - dit: bool, - uscat: bool, - ilrcpc: bool, - flagm: bool, - ssbs: bool, - sb: bool, - paca: bool, - pacg: bool, + pub fp: bool, + pub asimd: bool, + // pub evtstrm: No LLVM support. + pub aes: bool, + pub pmull: bool, + pub sha1: bool, + pub sha2: bool, + pub crc32: bool, + pub atomics: bool, + pub fphp: bool, + pub asimdhp: bool, + // pub cpuid: No LLVM support. + pub asimdrdm: bool, + pub jscvt: bool, + pub fcma: bool, + pub lrcpc: bool, + pub dcpop: bool, + pub sha3: bool, + pub sm3: bool, + pub sm4: bool, + pub asimddp: bool, + pub sha512: bool, + pub sve: bool, + pub fhm: bool, + pub dit: bool, + pub uscat: bool, + pub ilrcpc: bool, + pub flagm: bool, + pub ssbs: bool, + pub sb: bool, + pub paca: bool, + pub pacg: bool, // AT_HWCAP2 - dcpodp: bool, - sve2: bool, - sveaes: bool, - svepmull: bool, - svebitperm: bool, - svesha3: bool, - svesm4: bool, - flagm2: bool, - frint: bool, - // svei8mm: See i8mm feature. - svef32mm: bool, - svef64mm: bool, - // svebf16: See bf16 feature. - i8mm: bool, - bf16: bool, - // dgh: No LLVM support. - rng: bool, - bti: bool, - mte: bool, - ecv: bool, - // afp: bool, - // rpres: bool, - // mte3: bool, - sme: bool, - smei16i64: bool, - smef64f64: bool, - // smei8i32: bool, - // smef16f32: bool, - // smeb16f32: bool, - // smef32f32: bool, - smefa64: bool, - wfxt: bool, - // ebf16: bool, - // sveebf16: bool, - cssc: bool, - // rprfm: bool, - sve2p1: bool, - sme2: bool, - sme2p1: bool, - // smei16i32: bool, - // smebi32i32: bool, - smeb16b16: bool, - smef16f16: bool, - mops: bool, - hbc: bool, - sveb16b16: bool, - lrcpc3: bool, - lse128: bool, - fpmr: bool, - lut: bool, - faminmax: bool, - f8cvt: bool, - f8fma: bool, - f8dp4: bool, - f8dp2: bool, - f8e4m3: bool, - f8e5m2: bool, - smelutv2: bool, - smef8f16: bool, - smef8f32: bool, - smesf8fma: bool, - smesf8dp4: bool, - smesf8dp2: bool, - // pauthlr: bool, + pub dcpodp: bool, + pub sve2: bool, + pub sveaes: bool, + pub svepmull: bool, + pub svebitperm: bool, + pub svesha3: bool, + pub svesm4: bool, + pub flagm2: bool, + pub frint: bool, + // pub svei8mm: See i8mm feature. + pub svef32mm: bool, + pub svef64mm: bool, + // pub svebf16: See bf16 feature. + pub i8mm: bool, + pub bf16: bool, + // pub dgh: No LLVM support. + pub rng: bool, + pub bti: bool, + pub mte: bool, + pub ecv: bool, + // pub afp: bool, + // pub rpres: bool, + // pub mte3: bool, + pub sme: bool, + pub smei16i64: bool, + pub smef64f64: bool, + // pub smei8i32: bool, + // pub smef16f32: bool, + // pub smeb16f32: bool, + // pub smef32f32: bool, + pub smefa64: bool, + pub wfxt: bool, + // pub ebf16: bool, + // pub sveebf16: bool, + pub cssc: bool, + // pub rprfm: bool, + pub sve2p1: bool, + pub sme2: bool, + pub sme2p1: bool, + // pub smei16i32: bool, + // pub smebi32i32: bool, + pub smeb16b16: bool, + pub smef16f16: bool, + pub mops: bool, + pub hbc: bool, + pub sveb16b16: bool, + pub lrcpc3: bool, + pub lse128: bool, + pub fpmr: bool, + pub lut: bool, + pub faminmax: bool, + pub f8cvt: bool, + pub f8fma: bool, + pub f8dp4: bool, + pub f8dp2: bool, + pub f8e4m3: bool, + pub f8e5m2: bool, + pub smelutv2: bool, + pub smef8f16: bool, + pub smef8f32: bool, + pub smesf8fma: bool, + pub smesf8dp4: bool, + pub smesf8dp2: bool, + // pub pauthlr: bool, } impl From for AtHwcap { @@ -403,7 +403,3 @@ impl AtHwcap { value } } - -#[cfg(target_endian = "little")] -#[cfg(test)] -mod tests; diff --git a/library/std_detect/src/detect/os/linux/auxvec.rs b/library/std_detect/src/detect/os/linux/auxvec.rs index c0bbc7d4efa88..2a5d475b5f403 100644 --- a/library/std_detect/src/detect/os/linux/auxvec.rs +++ b/library/std_detect/src/detect/os/linux/auxvec.rs @@ -20,8 +20,8 @@ pub(crate) const AT_HWCAP2: usize = 26; /// If an entry cannot be read all the bits in the bitfield are set to zero. /// This should be interpreted as all the features being disabled. #[derive(Debug, Copy, Clone)] -#[cfg_attr(test, derive(PartialEq))] -pub(crate) struct AuxVec { +#[derive(PartialEq)] +pub struct AuxVec { pub hwcap: usize, #[cfg(any( target_arch = "aarch64", @@ -68,7 +68,7 @@ pub(crate) struct AuxVec { /// [auxvec_h]: https://github.com/torvalds/linux/blob/master/include/uapi/linux/auxvec.h /// [auxv_docs]: https://docs.rs/auxv/0.3.3/auxv/ /// [`getauxval`]: https://man7.org/linux/man-pages/man3/getauxval.3.html -pub(crate) fn auxv() -> Result { +pub fn auxv() -> Result { // Try to call a getauxval function. if let Ok(hwcap) = getauxval(AT_HWCAP) { // Targets with only AT_HWCAP: @@ -146,13 +146,9 @@ fn getauxval(key: usize) -> Result { /// Tries to read the auxiliary vector from the `file`. If this fails, this /// function returns `Err`. -pub(super) fn auxv_from_file(file: &str) -> Result { - let file = super::read_file(file)?; - auxv_from_file_bytes(&file) -} +pub fn auxv_from_file(file: &str) -> Result { + let bytes = super::read_file(file)?; -/// Read auxiliary vector from a slice of bytes. -pub(super) fn auxv_from_file_bytes(bytes: &[u8]) -> Result { // See . // // The auxiliary vector contains at most 34 (key,value) fields: from @@ -216,6 +212,3 @@ fn auxv_from_buf(buf: &[usize]) -> Result { let _ = buf; Err(alloc::string::String::from("hwcap not found")) } - -#[cfg(test)] -mod tests; diff --git a/library/std_detect/src/detect/os/linux/mod.rs b/library/std_detect/src/detect/os/linux/mod.rs index aec94f963f5c1..fe810597bc745 100644 --- a/library/std_detect/src/detect/os/linux/mod.rs +++ b/library/std_detect/src/detect/os/linux/mod.rs @@ -2,7 +2,7 @@ use alloc::vec::Vec; -mod auxvec; +pub(super) mod auxvec; fn read_file(orig_path: &str) -> Result, alloc::string::String> { use alloc::format; @@ -37,7 +37,7 @@ fn read_file(orig_path: &str) -> Result, alloc::string::String> { cfg_select! { target_arch = "aarch64" => { - mod aarch64; + pub(super) mod aarch64; pub(crate) use self::aarch64::detect_features; } target_arch = "arm" => { diff --git a/library/std_detect/src/detect/os/riscv.rs b/library/std_detect/src/detect/os/riscv.rs index 9b9e0cba09d1c..1c59cb50e02c9 100644 --- a/library/std_detect/src/detect/os/riscv.rs +++ b/library/std_detect/src/detect/os/riscv.rs @@ -18,7 +18,7 @@ use crate::detect::{Feature, cache}; /// conflicting extensions and/or complicated requirements. Eliminating such /// inconsistencies is the responsibility of the feature detection logic and /// its provider(s). -pub(crate) fn imply_features(mut value: cache::Initializer) -> cache::Initializer { +pub fn imply_features(mut value: cache::Initializer) -> cache::Initializer { loop { // Check convergence of the feature flags later. let prev = value; @@ -153,7 +153,3 @@ pub(crate) fn imply_features(mut value: cache::Initializer) -> cache::Initialize } } } - -#[cfg(test)] -#[path = "riscv/tests.rs"] -mod tests; diff --git a/library/std_detect_tests/Cargo.toml b/library/std_detect_tests/Cargo.toml new file mode 100644 index 0000000000000..4b1ab8e7603f0 --- /dev/null +++ b/library/std_detect_tests/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "std_detect_tests" +version = "0.0.0" +license = "MIT OR Apache-2.0" +description = "Tests for std_detect" +edition = "2024" + +[dependencies] +std_detect = { path = "../std_detect" } diff --git a/library/std_detect/src/detect/test_data/linux-artificial-aarch64.auxv b/library/std_detect_tests/test_data/linux-artificial-aarch64.auxv similarity index 100% rename from library/std_detect/src/detect/test_data/linux-artificial-aarch64.auxv rename to library/std_detect_tests/test_data/linux-artificial-aarch64.auxv diff --git a/library/std_detect/src/detect/test_data/linux-empty-hwcap2-aarch64.auxv b/library/std_detect_tests/test_data/linux-empty-hwcap2-aarch64.auxv similarity index 100% rename from library/std_detect/src/detect/test_data/linux-empty-hwcap2-aarch64.auxv rename to library/std_detect_tests/test_data/linux-empty-hwcap2-aarch64.auxv diff --git a/library/std_detect/src/detect/test_data/linux-hwcap2-aarch64.auxv b/library/std_detect_tests/test_data/linux-hwcap2-aarch64.auxv similarity index 100% rename from library/std_detect/src/detect/test_data/linux-hwcap2-aarch64.auxv rename to library/std_detect_tests/test_data/linux-hwcap2-aarch64.auxv diff --git a/library/std_detect/src/detect/test_data/linux-no-hwcap2-aarch64.auxv b/library/std_detect_tests/test_data/linux-no-hwcap2-aarch64.auxv similarity index 100% rename from library/std_detect/src/detect/test_data/linux-no-hwcap2-aarch64.auxv rename to library/std_detect_tests/test_data/linux-no-hwcap2-aarch64.auxv diff --git a/library/std_detect/src/detect/test_data/linux-rpi3.auxv b/library/std_detect_tests/test_data/linux-rpi3.auxv similarity index 100% rename from library/std_detect/src/detect/test_data/linux-rpi3.auxv rename to library/std_detect_tests/test_data/linux-rpi3.auxv diff --git a/library/std_detect/src/detect/test_data/macos-virtualbox-linux-x86-4850HQ.auxv b/library/std_detect_tests/test_data/macos-virtualbox-linux-x86-4850HQ.auxv similarity index 100% rename from library/std_detect/src/detect/test_data/macos-virtualbox-linux-x86-4850HQ.auxv rename to library/std_detect_tests/test_data/macos-virtualbox-linux-x86-4850HQ.auxv diff --git a/library/std_detect/src/detect/os/linux/auxvec/tests.rs b/library/std_detect_tests/tests/auxvec.rs similarity index 78% rename from library/std_detect/src/detect/os/linux/auxvec/tests.rs rename to library/std_detect_tests/tests/auxvec.rs index 88f0d6d493376..9cfc770254770 100644 --- a/library/std_detect/src/detect/os/linux/auxvec/tests.rs +++ b/library/std_detect_tests/tests/auxvec.rs @@ -1,4 +1,7 @@ -use super::*; +#![allow(internal_features)] +#![feature(cfg_select, stdarch_internal)] + +use std_detect::detect::__test_os::{auxv, auxv_from_file}; // FIXME: on mips/mips64 getauxval returns 0, and /proc/self/auxv // does not always contain the AT_HWCAP key under qemu. @@ -47,17 +50,17 @@ cfg_select! { // files on disk, so we need to embed them with `include_bytes!`. #[test] fn linux_rpi3() { - let auxv = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/detect/test_data/linux-rpi3.auxv")); - let v = auxv_from_file_bytes(auxv).unwrap(); + let file = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/linux-rpi3.auxv"); + let v = auxv_from_file(file).unwrap(); assert_eq!(v.hwcap, 4174038); assert_eq!(v.hwcap2, 16); } #[test] fn linux_macos_vb() { - let auxv = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/detect/test_data/macos-virtualbox-linux-x86-4850HQ.auxv")); + let file = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/macos-virtualbox-linux-x86-4850HQ.auxv"); // The file contains HWCAP but not HWCAP2. In that case, we treat HWCAP2 as zero. - let v = auxv_from_file_bytes(auxv).unwrap(); + let v = auxv_from_file(file).unwrap(); assert_eq!(v.hwcap, 126614527); assert_eq!(v.hwcap2, 0); } @@ -66,16 +69,16 @@ cfg_select! { #[cfg(target_endian = "little")] #[test] fn linux_artificial_aarch64() { - let auxv = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/detect/test_data/linux-artificial-aarch64.auxv")); - let v = auxv_from_file_bytes(auxv).unwrap(); + let file = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/linux-artificial-aarch64.auxv"); + let v = auxv_from_file(file).unwrap(); assert_eq!(v.hwcap, 0x0123456789abcdef); assert_eq!(v.hwcap2, 0x02468ace13579bdf); } #[cfg(target_endian = "little")] #[test] fn linux_no_hwcap2_aarch64() { - let auxv = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/detect/test_data/linux-no-hwcap2-aarch64.auxv")); - let v = auxv_from_file_bytes(auxv).unwrap(); + let file = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/linux-no-hwcap2-aarch64.auxv"); + let v = auxv_from_file(file).unwrap(); // An absent HWCAP2 is treated as zero, and does not prevent acceptance of HWCAP. assert_ne!(v.hwcap, 0); assert_eq!(v.hwcap2, 0); diff --git a/library/std_detect/tests/cpu-detection.rs b/library/std_detect_tests/tests/cpu-detection.rs similarity index 100% rename from library/std_detect/tests/cpu-detection.rs rename to library/std_detect_tests/tests/cpu-detection.rs diff --git a/library/std_detect/src/detect/os/linux/aarch64/tests.rs b/library/std_detect_tests/tests/linux_aarch64.rs similarity index 73% rename from library/std_detect/src/detect/os/linux/aarch64/tests.rs rename to library/std_detect_tests/tests/linux_aarch64.rs index 4d7c9a419d386..99a4fe6026d85 100644 --- a/library/std_detect/src/detect/os/linux/aarch64/tests.rs +++ b/library/std_detect_tests/tests/linux_aarch64.rs @@ -1,5 +1,13 @@ -use super::auxvec::auxv_from_file; -use super::*; +#![cfg(all( + any(target_os = "linux", target_os = "android"), + target_arch = "aarch64", + target_endian = "little" +))] +#![allow(internal_features)] +#![feature(stdarch_internal)] + +use std_detect::detect::__test_os::{AtHwcap, auxv_from_file}; + // The baseline hwcaps used in the (artificial) auxv test files. fn baseline_hwcaps() -> AtHwcap { AtHwcap { @@ -24,10 +32,7 @@ fn baseline_hwcaps() -> AtHwcap { #[test] fn linux_empty_hwcap2_aarch64() { - let file = concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/detect/test_data/linux-empty-hwcap2-aarch64.auxv" - ); + let file = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/linux-empty-hwcap2-aarch64.auxv"); println!("file: {file}"); let v = auxv_from_file(file).unwrap(); println!("HWCAP : 0x{:0x}", v.hwcap); @@ -36,8 +41,7 @@ fn linux_empty_hwcap2_aarch64() { } #[test] fn linux_no_hwcap2_aarch64() { - let file = - concat!(env!("CARGO_MANIFEST_DIR"), "/src/detect/test_data/linux-no-hwcap2-aarch64.auxv"); + let file = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/linux-no-hwcap2-aarch64.auxv"); println!("file: {file}"); let v = auxv_from_file(file).unwrap(); println!("HWCAP : 0x{:0x}", v.hwcap); @@ -46,8 +50,7 @@ fn linux_no_hwcap2_aarch64() { } #[test] fn linux_hwcap2_aarch64() { - let file = - concat!(env!("CARGO_MANIFEST_DIR"), "/src/detect/test_data/linux-hwcap2-aarch64.auxv"); + let file = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/linux-hwcap2-aarch64.auxv"); println!("file: {file}"); let v = auxv_from_file(file).unwrap(); println!("HWCAP : 0x{:0x}", v.hwcap); diff --git a/library/std_detect/tests/macro_trailing_commas.rs b/library/std_detect_tests/tests/macro_trailing_commas.rs similarity index 100% rename from library/std_detect/tests/macro_trailing_commas.rs rename to library/std_detect_tests/tests/macro_trailing_commas.rs diff --git a/library/std_detect/src/detect/os/riscv/tests.rs b/library/std_detect_tests/tests/riscv.rs similarity index 77% rename from library/std_detect/src/detect/os/riscv/tests.rs rename to library/std_detect_tests/tests/riscv.rs index 99a81dee05a6c..24e042a691b31 100644 --- a/library/std_detect/src/detect/os/riscv/tests.rs +++ b/library/std_detect_tests/tests/riscv.rs @@ -1,8 +1,13 @@ -use super::*; +#![cfg(any(target_arch = "riscv32", target_arch = "riscv64"))] +#![allow(internal_features)] +#![feature(stdarch_internal)] + +use std_detect::detect::__test::{Feature, Initializer}; +use std_detect::detect::__test_os::imply_features; #[test] fn simple_direct() { - let mut value = cache::Initializer::default(); + let mut value = Initializer::default(); value.set(Feature::f as u32); // F (and other extensions with CSRs) -> Zicsr assert!(imply_features(value).test(Feature::zicsr as u32)); @@ -10,7 +15,7 @@ fn simple_direct() { #[test] fn simple_indirect() { - let mut value = cache::Initializer::default(); + let mut value = Initializer::default(); value.set(Feature::q as u32); // Q -> D, D -> F, F -> Zicsr assert!(imply_features(value).test(Feature::zicsr as u32)); @@ -18,7 +23,7 @@ fn simple_indirect() { #[test] fn complex_zcd() { - let mut value = cache::Initializer::default(); + let mut value = Initializer::default(); // C & D -> Zcd value.set(Feature::c as u32); assert!(!imply_features(value).test(Feature::zcd as u32)); @@ -28,7 +33,7 @@ fn complex_zcd() { #[test] fn group_simple_forward() { - let mut value = cache::Initializer::default(); + let mut value = Initializer::default(); // A -> Zalrsc & Zaamo (forward implication) value.set(Feature::a as u32); let value = imply_features(value); @@ -38,7 +43,7 @@ fn group_simple_forward() { #[test] fn group_simple_backward() { - let mut value = cache::Initializer::default(); + let mut value = Initializer::default(); // Zalrsc & Zaamo -> A (reverse implication) value.set(Feature::zalrsc as u32); value.set(Feature::zaamo as u32); @@ -47,7 +52,7 @@ fn group_simple_backward() { #[test] fn group_complex_convergence() { - let mut value = cache::Initializer::default(); + let mut value = Initializer::default(); // Needs 3 iterations to converge // (and 4th iteration for convergence checking): // 1. [Zvksc] -> Zvks & Zvbc diff --git a/library/std_detect/tests/x86-specific.rs b/library/std_detect_tests/tests/x86-specific.rs similarity index 100% rename from library/std_detect/tests/x86-specific.rs rename to library/std_detect_tests/tests/x86-specific.rs diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index f983c59f9bf8c..73b16a1cbf96c 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -33,7 +33,7 @@ pub struct Std { } impl Std { - const CRATE_OR_DEPS: &[&str] = &["sysroot", "coretests", "alloctests"]; + const CRATE_OR_DEPS: &[&str] = &["sysroot", "coretests", "alloctests", "std_detect_tests"]; } impl Step for Std { diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 52b38421eec22..9fbad496afade 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -509,6 +509,12 @@ impl Step for RustAnalyzer { cargo.arg("--workspace"); cargo.arg("--exclude=xtask"); + if build_compiler.stage == 0 { + // This builds a proc macro against the bootstrap libproc_macro, which is not ABI + // compatible with the ABI proc-macro-srv expects to load. + cargo.arg("--exclude=proc-macro-srv"); + } + let mut skip_tests = vec![]; // NOTE: the following test skips is a bit cheeky in that it assumes there are no @@ -3012,7 +3018,10 @@ impl Step for Crate { type Output = (); fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.crate_or_deps("sysroot").crate_or_deps("coretests").crate_or_deps("alloctests") + run.crate_or_deps("sysroot") + .crate_or_deps("coretests") + .crate_or_deps("alloctests") + .crate_or_deps("std_detect_tests") } fn is_default_step(_builder: &Builder<'_>) -> bool { @@ -3132,6 +3141,9 @@ impl Step for Crate { if crates.iter().any(|crate_| crate_ == "alloc") { crates.push("alloctests".to_owned()); } + if crates.iter().any(|crate_| crate_ == "std_detect") { + crates.push("std_detect_tests".to_owned()); + } run_cargo_test(cargo, &[], &crates, &*crate_description(&self.crates), target, builder); } diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_bench.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_bench.snap index 8a7815487913e..504f954b29951 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_bench.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_bench.snap @@ -15,6 +15,7 @@ expression: bench - Set({bench::library/rustc-std-workspace-core}) - Set({bench::library/std}) - Set({bench::library/std_detect}) + - Set({bench::library/std_detect_tests}) - Set({bench::library/sysroot}) - Set({bench::library/test}) - Set({bench::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check.snap index 0fe26fac57fc5..d7bbe88cfb457 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check.snap @@ -129,6 +129,7 @@ expression: check - Set({check::library/rustc-std-workspace-core}) - Set({check::library/std}) - Set({check::library/std_detect}) + - Set({check::library/std_detect_tests}) - Set({check::library/sysroot}) - Set({check::library/test}) - Set({check::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiletest_include_default_paths.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiletest_include_default_paths.snap index dae515c67ec6d..56af0b77bf3c3 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiletest_include_default_paths.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiletest_include_default_paths.snap @@ -129,6 +129,7 @@ expression: check compiletest --include-default-paths - Set({check::library/rustc-std-workspace-core}) - Set({check::library/std}) - Set({check::library/std_detect}) + - Set({check::library/std_detect_tests}) - Set({check::library/sysroot}) - Set({check::library/test}) - Set({check::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_library.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_library.snap index 1a41aa98555b6..e1ef04dcf2669 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_library.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_library.snap @@ -16,6 +16,7 @@ expression: check library - Set({check::library/rustc-std-workspace-core}) - Set({check::library/std}) - Set({check::library/std_detect}) + - Set({check::library/std_detect_tests}) - Set({check::library/sysroot}) - Set({check::library/test}) - Set({check::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_fix.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_fix.snap index 222c0ffb40503..d7a8b466fc80e 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_fix.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_fix.snap @@ -129,6 +129,7 @@ expression: fix - Set({fix::library/rustc-std-workspace-core}) - Set({fix::library/std}) - Set({fix::library/std_detect}) + - Set({fix::library/std_detect_tests}) - Set({fix::library/sysroot}) - Set({fix::library/test}) - Set({fix::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_miri.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_miri.snap index 552697b378bcc..e61249a6e7f34 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_miri.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_miri.snap @@ -15,6 +15,7 @@ expression: miri - Set({miri::library/rustc-std-workspace-core}) - Set({miri::library/std}) - Set({miri::library/std_detect}) + - Set({miri::library/std_detect_tests}) - Set({miri::library/sysroot}) - Set({miri::library/test}) - Set({miri::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap index 4ab84c3cabc1a..70271cab48bf5 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap @@ -65,6 +65,7 @@ expression: test - Set({test::library/rustc-std-workspace-core}) - Set({test::library/std}) - Set({test::library/std_detect}) + - Set({test::library/std_detect_tests}) - Set({test::library/sysroot}) - Set({test::library/test}) - Set({test::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_library.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_library.snap index dfc397597a877..b74912ce7f460 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_library.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_library.snap @@ -15,6 +15,7 @@ expression: test library - Set({test::library/rustc-std-workspace-core}) - Set({test::library/std}) - Set({test::library/std_detect}) + - Set({test::library/std_detect_tests}) - Set({test::library/sysroot}) - Set({test::library/test}) - Set({test::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap index 2a4805e4fd687..bba6987da7b06 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap @@ -64,6 +64,7 @@ expression: test --skip=coverage - Set({test::library/rustc-std-workspace-core}) - Set({test::library/std}) - Set({test::library/std_detect}) + - Set({test::library/std_detect_tests}) - Set({test::library/sysroot}) - Set({test::library/test}) - Set({test::library/unwind}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap index 1468964c78189..fcd5e0da39ccf 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap @@ -1,6 +1,5 @@ --- source: src/bootstrap/src/core/builder/cli_paths/tests.rs -assertion_line: 68 expression: test --skip=tests --- [Test] test::Tidy @@ -29,6 +28,7 @@ expression: test --skip=tests - Set({test::library/rustc-std-workspace-core}) - Set({test::library/std}) - Set({test::library/std_detect}) + - Set({test::library/std_detect_tests}) - Set({test::library/sysroot}) - Set({test::library/test}) - Set({test::library/unwind}) diff --git a/src/tools/clippy/clippy_lints/src/dbg_macro.rs b/src/tools/clippy/clippy_lints/src/dbg_macro.rs index 152516baf7342..9197870cb6952 100644 --- a/src/tools/clippy/clippy_lints/src/dbg_macro.rs +++ b/src/tools/clippy/clippy_lints/src/dbg_macro.rs @@ -5,7 +5,7 @@ use clippy_utils::macros::{MacroCall, macro_backtrace}; use clippy_utils::source::snippet_with_applicability; use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; -use rustc_hir::{Closure, ClosureKind, CoroutineKind, Expr, ExprKind, LetStmt, LocalSource, Node, Stmt, StmtKind}; +use rustc_hir::{Arm, Closure, ClosureKind, CoroutineKind, Expr, ExprKind, LetStmt, LocalSource, Node, Stmt, StmtKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_session::impl_lint_pass; use rustc_span::{Span, SyntaxContext, sym}; @@ -90,33 +90,27 @@ impl LateLintPass<'_> for DbgMacro { (macro_call.span, String::from("()")) } }, - // dbg!(1) - ExprKind::Match(val, ..) => ( - macro_call.span, - snippet_with_applicability(cx, val.span.source_callsite(), "..", &mut applicability) - .to_string(), - ), - // dbg!(2, 3) - ExprKind::Tup( - [ - Expr { - kind: ExprKind::Match(first, ..), - .. - }, - .., - Expr { - kind: ExprKind::Match(last, ..), - .. - }, - ], - ) => { - let snippet = snippet_with_applicability( - cx, - first.span.source_callsite().to(last.span.source_callsite()), - "..", - &mut applicability, - ); - (macro_call.span, format!("({snippet})")) + ExprKind::Match(first, arms, _) => { + let vals = collect_vals(first, arms); + let suggestion = match vals.as_slice() { + // dbg!(1) => 1 + &[val] => { + snippet_with_applicability(cx, val.span.source_callsite(), "..", &mut applicability) + .to_string() + } + // dbg!(2, 3) => (2, 3) + &[first, .., last] => { + let snippet = snippet_with_applicability( + cx, + first.span.source_callsite().to(last.span.source_callsite()), + "..", + &mut applicability, + ); + format!("({snippet})") + } + _ => unreachable!(), + }; + (macro_call.span, suggestion) }, _ => unreachable!(), }; @@ -169,3 +163,33 @@ fn is_async_move_desugar<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx fn first_dbg_macro_in_expansion(cx: &LateContext<'_>, span: Span) -> Option { macro_backtrace(span).find(|mc| cx.tcx.is_diagnostic_item(sym::dbg_macro, mc.def_id)) } + +/// Extracts all value expressions from the `match`-tree generated by `dbg!`. +/// +/// E.g. from +/// ```rust, ignore +/// match 1 { +/// tmp_1 => match 2 { +/// tmp_2 => { +/// /* printing */ +/// (tmp_1, tmp_2) +/// } +/// } +/// } +/// ``` +/// this extracts `1` and `2`. +fn collect_vals<'hir>(first: &'hir Expr<'hir>, mut arms: &'hir [Arm<'hir>]) -> Vec<&'hir Expr<'hir>> { + let mut vals = vec![first]; + loop { + let [arm] = arms else { unreachable!("dbg! macro expansion only has single-arm matches") }; + + match is_async_move_desugar(arm.body).unwrap_or(arm.body).peel_drop_temps().kind { + ExprKind::Block(..) => return vals, + ExprKind::Match(val, a, _) => { + vals.push(val); + arms = a; + } + _ => unreachable!("dbg! macro expansion only results in block or match expressions"), + } + } +} diff --git a/src/tools/miri/tests/fail/dangling_pointers/dangling_primitive.stderr b/src/tools/miri/tests/fail/dangling_pointers/dangling_primitive.stderr index 354cb882fd9f1..24a807afd73df 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/dangling_primitive.stderr +++ b/src/tools/miri/tests/fail/dangling_pointers/dangling_primitive.stderr @@ -16,7 +16,7 @@ help: ALLOC was deallocated here: | LL | }; | ^ - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace diff --git a/src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr b/src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr index d653ec3a069ca..845b4f977ca3c 100644 --- a/src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr +++ b/src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr @@ -11,7 +11,7 @@ LL | dbg!(x.0); | = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) Uninitialized memory occurred at ALLOC[0x0..0x4], in this allocation: ALLOC (stack variable, size: 132, align: 4) { diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/bridge.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/bridge.rs index fc063a07b5f8a..fc62f9413a34e 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/bridge.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/bridge.rs @@ -1,6 +1,6 @@ //! `proc_macro::bridge` newtypes. -use proc_macro::bridge as pm_bridge; +use rustc_proc_macro::bridge as pm_bridge; pub use pm_bridge::{DelimSpan, Diagnostic, ExpnGlobals, LitKind}; diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs index 02bdcc50d3871..8680e9180e3ab 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib.rs @@ -3,7 +3,7 @@ mod proc_macros; mod version; -use proc_macro::bridge; +use rustc_proc_macro::bridge; use std::{fmt, fs, io, time::SystemTime}; use temp_dir::TempDir; diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib/proc_macros.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib/proc_macros.rs index c763301135ee8..76c5097101c70 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib/proc_macros.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/dylib/proc_macros.rs @@ -1,6 +1,6 @@ //! Proc macro ABI use crate::{ProcMacroClientHandle, ProcMacroKind, ProcMacroSrvSpan, token_stream::TokenStream}; -use proc_macro::bridge; +use rustc_proc_macro::bridge; #[repr(transparent)] pub(crate) struct ProcMacros([bridge::client::ProcMacro]); diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs index f2d1dfbba4ccb..920d58b4e981e 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/lib.rs @@ -22,9 +22,9 @@ )] #![deny(deprecated_safe, clippy::undocumented_unsafe_blocks)] -extern crate proc_macro; #[cfg(feature = "in-rust-tree")] extern crate rustc_driver as _; +extern crate rustc_proc_macro; #[cfg(not(feature = "in-rust-tree"))] extern crate ra_ap_rustc_lexer as rustc_lexer; @@ -52,7 +52,7 @@ use temp_dir::TempDir; pub use crate::server_impl::token_id::SpanId; -pub use proc_macro::Delimiter; +pub use rustc_proc_macro::Delimiter; pub use span; pub use crate::bridge::*; @@ -181,7 +181,9 @@ impl ProcMacroSrv<'_> { } pub trait ProcMacroSrvSpan: Copy + Send + Sync { - type Server<'a>: proc_macro::bridge::server::Server>; + type Server<'a>: rustc_proc_macro::bridge::server::Server< + TokenStream = crate::token_stream::TokenStream, + >; fn make_server<'a>( call_site: Self, def_site: Self, diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/rust_analyzer_span.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/rust_analyzer_span.rs index 32725afc55272..ec30630c10bbe 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/rust_analyzer_span.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/rust_analyzer_span.rs @@ -10,7 +10,7 @@ use std::{ }; use intern::Symbol; -use proc_macro::bridge::server; +use rustc_proc_macro::bridge::server; use span::{FIXUP_ERASED_FILE_AST_ID_MARKER, Span, TextRange, TextSize}; use crate::{ @@ -19,8 +19,6 @@ use crate::{ server_impl::literal_from_str, }; -pub struct FreeFunctions; - pub struct RaSpanServer<'a> { // FIXME: Report this back to the caller to track as dependencies pub tracked_env_vars: HashMap, Option>>, @@ -33,13 +31,28 @@ pub struct RaSpanServer<'a> { } impl server::Types for RaSpanServer<'_> { - type FreeFunctions = FreeFunctions; type TokenStream = crate::token_stream::TokenStream; type Span = Span; type Symbol = Symbol; } -impl server::FreeFunctions for RaSpanServer<'_> { +impl server::Server for RaSpanServer<'_> { + fn globals(&mut self) -> ExpnGlobals { + ExpnGlobals { + def_site: self.def_site, + call_site: self.call_site, + mixed_site: self.mixed_site, + } + } + + fn intern_symbol(ident: &str) -> Self::Symbol { + Symbol::intern(ident) + } + + fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) { + f(symbol.as_str()) + } + fn injected_env_var(&mut self, _: &str) -> Option { None } @@ -58,13 +71,19 @@ impl server::FreeFunctions for RaSpanServer<'_> { fn emit_diagnostic(&mut self, _: Diagnostic) { // FIXME handle diagnostic } -} -impl server::TokenStream for RaSpanServer<'_> { - fn is_empty(&mut self, stream: &Self::TokenStream) -> bool { + fn ts_drop(&mut self, stream: Self::TokenStream) { + drop(stream); + } + + fn ts_clone(&mut self, stream: &Self::TokenStream) -> Self::TokenStream { + stream.clone() + } + + fn ts_is_empty(&mut self, stream: &Self::TokenStream) -> bool { stream.is_empty() } - fn from_str(&mut self, src: &str) -> Self::TokenStream { + fn ts_from_str(&mut self, src: &str) -> Self::TokenStream { Self::TokenStream::from_str(src, self.call_site).unwrap_or_else(|e| { Self::TokenStream::from_str( &format!("compile_error!(\"failed to parse str to token stream: {e}\")"), @@ -73,15 +92,15 @@ impl server::TokenStream for RaSpanServer<'_> { .unwrap() }) } - fn to_string(&mut self, stream: &Self::TokenStream) -> String { + fn ts_to_string(&mut self, stream: &Self::TokenStream) -> String { stream.to_string() } - fn from_token_tree(&mut self, tree: TokenTree) -> Self::TokenStream { + fn ts_from_token_tree(&mut self, tree: TokenTree) -> Self::TokenStream { Self::TokenStream::new(vec![tree]) } - fn expand_expr(&mut self, self_: &Self::TokenStream) -> Result { + fn ts_expand_expr(&mut self, self_: &Self::TokenStream) -> Result { // FIXME: requires db, more importantly this requires name resolution so we would need to // eagerly expand this proc-macro, but we can't know that this proc-macro is eager until we // expand it ... @@ -90,7 +109,7 @@ impl server::TokenStream for RaSpanServer<'_> { Ok(self_.clone()) } - fn concat_trees( + fn ts_concat_trees( &mut self, base: Option, trees: Vec>, @@ -106,7 +125,7 @@ impl server::TokenStream for RaSpanServer<'_> { } } - fn concat_streams( + fn ts_concat_streams( &mut self, base: Option, streams: Vec, @@ -118,28 +137,26 @@ impl server::TokenStream for RaSpanServer<'_> { stream } - fn into_trees(&mut self, stream: Self::TokenStream) -> Vec> { + fn ts_into_trees(&mut self, stream: Self::TokenStream) -> Vec> { (*stream.0).clone() } -} -impl server::Span for RaSpanServer<'_> { - fn debug(&mut self, span: Self::Span) -> String { + fn span_debug(&mut self, span: Self::Span) -> String { format!("{:?}", span) } - fn file(&mut self, span: Self::Span) -> String { + fn span_file(&mut self, span: Self::Span) -> String { self.callback.as_mut().map(|cb| cb.file(span.anchor.file_id.file_id())).unwrap_or_default() } - fn local_file(&mut self, span: Self::Span) -> Option { + fn span_local_file(&mut self, span: Self::Span) -> Option { self.callback.as_mut().and_then(|cb| cb.local_file(span.anchor.file_id.file_id())) } - fn save_span(&mut self, _span: Self::Span) -> usize { + fn span_save_span(&mut self, _span: Self::Span) -> usize { // FIXME, quote is incompatible with third-party tools // This is called by the quote proc-macro which is expanded when the proc-macro is compiled // As such, r-a will never observe this 0 } - fn recover_proc_macro_span(&mut self, _id: usize) -> Self::Span { + fn span_recover_proc_macro_span(&mut self, _id: usize) -> Self::Span { // FIXME, quote is incompatible with third-party tools // This is called by the expansion of quote!, r-a will observe this, but we don't have // access to the spans that were encoded @@ -149,23 +166,23 @@ impl server::Span for RaSpanServer<'_> { /// /// See PR: /// https://github.com/rust-lang/rust/pull/55780 - fn source_text(&mut self, span: Self::Span) -> Option { + fn span_source_text(&mut self, span: Self::Span) -> Option { self.callback.as_mut()?.source_text(span) } - fn parent(&mut self, _span: Self::Span) -> Option { + fn span_parent(&mut self, _span: Self::Span) -> Option { // FIXME requires db, looks up the parent call site None } - fn source(&mut self, span: Self::Span) -> Self::Span { + fn span_source(&mut self, span: Self::Span) -> Self::Span { // FIXME requires db, returns the top level call site span } - fn byte_range(&mut self, span: Self::Span) -> Range { + fn span_byte_range(&mut self, span: Self::Span) -> Range { // FIXME requires db to resolve the ast id, THIS IS NOT INCREMENTAL Range { start: span.range.start().into(), end: span.range.end().into() } } - fn join(&mut self, first: Self::Span, second: Self::Span) -> Option { + fn span_join(&mut self, first: Self::Span, second: Self::Span) -> Option { // We can't modify the span range for fixup spans, those are meaningful to fixup, so just // prefer the non-fixup span. if first.anchor.ast_id == FIXUP_ERASED_FILE_AST_ID_MARKER { @@ -193,7 +210,7 @@ impl server::Span for RaSpanServer<'_> { ctx: second.ctx, }) } - fn subspan( + fn span_subspan( &mut self, span: Self::Span, start: Bound, @@ -237,11 +254,11 @@ impl server::Span for RaSpanServer<'_> { }) } - fn resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span { + fn span_resolved_at(&mut self, span: Self::Span, at: Self::Span) -> Self::Span { Span { ctx: at.ctx, ..span } } - fn end(&mut self, span: Self::Span) -> Self::Span { + fn span_end(&mut self, span: Self::Span) -> Self::Span { // We can't modify the span range for fixup spans, those are meaningful to fixup. if span.anchor.ast_id == FIXUP_ERASED_FILE_AST_ID_MARKER { return span; @@ -249,7 +266,7 @@ impl server::Span for RaSpanServer<'_> { Span { range: TextRange::empty(span.range.end()), ..span } } - fn start(&mut self, span: Self::Span) -> Self::Span { + fn span_start(&mut self, span: Self::Span) -> Self::Span { // We can't modify the span range for fixup spans, those are meaningful to fixup. if span.anchor.ast_id == FIXUP_ERASED_FILE_AST_ID_MARKER { return span; @@ -257,38 +274,18 @@ impl server::Span for RaSpanServer<'_> { Span { range: TextRange::empty(span.range.start()), ..span } } - fn line(&mut self, _span: Self::Span) -> usize { + fn span_line(&mut self, _span: Self::Span) -> usize { // FIXME requires db to resolve line index, THIS IS NOT INCREMENTAL 1 } - fn column(&mut self, _span: Self::Span) -> usize { + fn span_column(&mut self, _span: Self::Span) -> usize { // FIXME requires db to resolve line index, THIS IS NOT INCREMENTAL 1 } -} -impl server::Symbol for RaSpanServer<'_> { - fn normalize_and_validate_ident(&mut self, string: &str) -> Result { + fn symbol_normalize_and_validate_ident(&mut self, string: &str) -> Result { // FIXME: nfc-normalize and validate idents Ok(::intern_symbol(string)) } } - -impl server::Server for RaSpanServer<'_> { - fn globals(&mut self) -> ExpnGlobals { - ExpnGlobals { - def_site: self.def_site, - call_site: self.call_site, - mixed_site: self.mixed_site, - } - } - - fn intern_symbol(ident: &str) -> Self::Symbol { - Symbol::intern(ident) - } - - fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) { - f(symbol.as_str()) - } -} diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/token_id.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/token_id.rs index a968ea4cd225e..3bf07290c8c05 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/token_id.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/server_impl/token_id.rs @@ -6,7 +6,7 @@ use std::{ }; use intern::Symbol; -use proc_macro::bridge::server; +use rustc_proc_macro::bridge::server; use crate::{ ProcMacroClientHandle, @@ -25,8 +25,6 @@ impl std::fmt::Debug for SpanId { type Span = SpanId; -pub struct FreeFunctions; - pub struct SpanIdServer<'a> { // FIXME: Report this back to the caller to track as dependencies pub tracked_env_vars: HashMap, Option>>, @@ -39,13 +37,28 @@ pub struct SpanIdServer<'a> { } impl server::Types for SpanIdServer<'_> { - type FreeFunctions = FreeFunctions; type TokenStream = crate::token_stream::TokenStream; type Span = Span; type Symbol = Symbol; } -impl server::FreeFunctions for SpanIdServer<'_> { +impl server::Server for SpanIdServer<'_> { + fn globals(&mut self) -> ExpnGlobals { + ExpnGlobals { + def_site: self.def_site, + call_site: self.call_site, + mixed_site: self.mixed_site, + } + } + + fn intern_symbol(ident: &str) -> Self::Symbol { + Symbol::intern(ident) + } + + fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) { + f(symbol.as_str()) + } + fn injected_env_var(&mut self, _: &str) -> Option { None } @@ -61,13 +74,19 @@ impl server::FreeFunctions for SpanIdServer<'_> { } fn emit_diagnostic(&mut self, _: Diagnostic) {} -} -impl server::TokenStream for SpanIdServer<'_> { - fn is_empty(&mut self, stream: &Self::TokenStream) -> bool { + fn ts_drop(&mut self, stream: Self::TokenStream) { + drop(stream); + } + + fn ts_clone(&mut self, stream: &Self::TokenStream) -> Self::TokenStream { + stream.clone() + } + + fn ts_is_empty(&mut self, stream: &Self::TokenStream) -> bool { stream.is_empty() } - fn from_str(&mut self, src: &str) -> Self::TokenStream { + fn ts_from_str(&mut self, src: &str) -> Self::TokenStream { Self::TokenStream::from_str(src, self.call_site).unwrap_or_else(|e| { Self::TokenStream::from_str( &format!("compile_error!(\"failed to parse str to token stream: {e}\")"), @@ -76,18 +95,18 @@ impl server::TokenStream for SpanIdServer<'_> { .unwrap() }) } - fn to_string(&mut self, stream: &Self::TokenStream) -> String { + fn ts_to_string(&mut self, stream: &Self::TokenStream) -> String { stream.to_string() } - fn from_token_tree(&mut self, tree: TokenTree) -> Self::TokenStream { + fn ts_from_token_tree(&mut self, tree: TokenTree) -> Self::TokenStream { Self::TokenStream::new(vec![tree]) } - fn expand_expr(&mut self, self_: &Self::TokenStream) -> Result { + fn ts_expand_expr(&mut self, self_: &Self::TokenStream) -> Result { Ok(self_.clone()) } - fn concat_trees( + fn ts_concat_trees( &mut self, base: Option, trees: Vec>, @@ -103,7 +122,7 @@ impl server::TokenStream for SpanIdServer<'_> { } } - fn concat_streams( + fn ts_concat_streams( &mut self, base: Option, streams: Vec, @@ -115,49 +134,47 @@ impl server::TokenStream for SpanIdServer<'_> { stream } - fn into_trees(&mut self, stream: Self::TokenStream) -> Vec> { + fn ts_into_trees(&mut self, stream: Self::TokenStream) -> Vec> { (*stream.0).clone() } -} -impl server::Span for SpanIdServer<'_> { - fn debug(&mut self, span: Self::Span) -> String { + fn span_debug(&mut self, span: Self::Span) -> String { format!("{:?}", span.0) } - fn file(&mut self, _span: Self::Span) -> String { + fn span_file(&mut self, _span: Self::Span) -> String { String::new() } - fn local_file(&mut self, _span: Self::Span) -> Option { + fn span_local_file(&mut self, _span: Self::Span) -> Option { None } - fn save_span(&mut self, _span: Self::Span) -> usize { + fn span_save_span(&mut self, _span: Self::Span) -> usize { 0 } - fn recover_proc_macro_span(&mut self, _id: usize) -> Self::Span { + fn span_recover_proc_macro_span(&mut self, _id: usize) -> Self::Span { self.call_site } /// Recent feature, not yet in the proc_macro /// /// See PR: /// https://github.com/rust-lang/rust/pull/55780 - fn source_text(&mut self, _span: Self::Span) -> Option { + fn span_source_text(&mut self, _span: Self::Span) -> Option { None } - fn parent(&mut self, _span: Self::Span) -> Option { + fn span_parent(&mut self, _span: Self::Span) -> Option { None } - fn source(&mut self, span: Self::Span) -> Self::Span { + fn span_source(&mut self, span: Self::Span) -> Self::Span { span } - fn byte_range(&mut self, _span: Self::Span) -> Range { + fn span_byte_range(&mut self, _span: Self::Span) -> Range { Range { start: 0, end: 0 } } - fn join(&mut self, first: Self::Span, _second: Self::Span) -> Option { + fn span_join(&mut self, first: Self::Span, _second: Self::Span) -> Option { // Just return the first span again, because some macros will unwrap the result. Some(first) } - fn subspan( + fn span_subspan( &mut self, span: Self::Span, _start: Bound, @@ -166,48 +183,28 @@ impl server::Span for SpanIdServer<'_> { // Just return the span again, because some macros will unwrap the result. Some(span) } - fn resolved_at(&mut self, _span: Self::Span, _at: Self::Span) -> Self::Span { + fn span_resolved_at(&mut self, _span: Self::Span, _at: Self::Span) -> Self::Span { self.call_site } - fn end(&mut self, _self_: Self::Span) -> Self::Span { + fn span_end(&mut self, _self_: Self::Span) -> Self::Span { self.call_site } - fn start(&mut self, _self_: Self::Span) -> Self::Span { + fn span_start(&mut self, _self_: Self::Span) -> Self::Span { self.call_site } - fn line(&mut self, _span: Self::Span) -> usize { + fn span_line(&mut self, _span: Self::Span) -> usize { 1 } - fn column(&mut self, _span: Self::Span) -> usize { + fn span_column(&mut self, _span: Self::Span) -> usize { 1 } -} -impl server::Symbol for SpanIdServer<'_> { - fn normalize_and_validate_ident(&mut self, string: &str) -> Result { + fn symbol_normalize_and_validate_ident(&mut self, string: &str) -> Result { // FIXME: nfc-normalize and validate idents Ok(::intern_symbol(string)) } } - -impl server::Server for SpanIdServer<'_> { - fn globals(&mut self) -> ExpnGlobals { - ExpnGlobals { - def_site: self.def_site, - call_site: self.call_site, - mixed_site: self.mixed_site, - } - } - - fn intern_symbol(ident: &str) -> Self::Symbol { - Symbol::intern(ident) - } - - fn with_symbol_string(symbol: &Self::Symbol, f: impl FnOnce(&str)) { - f(symbol.as_str()) - } -} diff --git a/src/tools/rust-analyzer/crates/proc-macro-srv/src/token_stream.rs b/src/tools/rust-analyzer/crates/proc-macro-srv/src/token_stream.rs index 36827d2561f9c..2358f6963c79e 100644 --- a/src/tools/rust-analyzer/crates/proc-macro-srv/src/token_stream.rs +++ b/src/tools/rust-analyzer/crates/proc-macro-srv/src/token_stream.rs @@ -4,8 +4,8 @@ use core::fmt; use std::{mem, sync::Arc}; use intern::Symbol; -use proc_macro::Delimiter; use rustc_lexer::{DocStyle, LiteralKind}; +use rustc_proc_macro::Delimiter; use crate::bridge::{DelimSpan, Group, Ident, LitKind, Literal, Punct, TokenTree}; @@ -52,7 +52,7 @@ impl TokenStream { S: SpanLike + Copy, { let mut groups = Vec::new(); - groups.push((proc_macro::Delimiter::None, 0..0, vec![])); + groups.push((rustc_proc_macro::Delimiter::None, 0..0, vec![])); let mut offset = 0; let mut tokens = rustc_lexer::tokenize(s, rustc_lexer::FrontmatterAllowed::No).peekable(); while let Some(token) = tokens.next() { @@ -102,7 +102,7 @@ impl TokenStream { }; match token.kind { rustc_lexer::TokenKind::OpenParen => { - groups.push((proc_macro::Delimiter::Parenthesis, range, vec![])) + groups.push((rustc_proc_macro::Delimiter::Parenthesis, range, vec![])) } rustc_lexer::TokenKind::CloseParen if *open_delim != Delimiter::Parenthesis => { return if *open_delim == Delimiter::None { @@ -130,7 +130,7 @@ impl TokenStream { ); } rustc_lexer::TokenKind::OpenBrace => { - groups.push((proc_macro::Delimiter::Brace, range, vec![])) + groups.push((rustc_proc_macro::Delimiter::Brace, range, vec![])) } rustc_lexer::TokenKind::CloseBrace if *open_delim != Delimiter::Brace => { return if *open_delim == Delimiter::None { @@ -158,7 +158,7 @@ impl TokenStream { ); } rustc_lexer::TokenKind::OpenBracket => { - groups.push((proc_macro::Delimiter::Bracket, range, vec![])) + groups.push((rustc_proc_macro::Delimiter::Bracket, range, vec![])) } rustc_lexer::TokenKind::CloseBracket if *open_delim != Delimiter::Bracket => { return if *open_delim == Delimiter::None { @@ -460,10 +460,10 @@ fn display_token_tree( f, "{}", match delimiter { - proc_macro::Delimiter::Parenthesis => "(", - proc_macro::Delimiter::Brace => "{", - proc_macro::Delimiter::Bracket => "[", - proc_macro::Delimiter::None => "", + rustc_proc_macro::Delimiter::Parenthesis => "(", + rustc_proc_macro::Delimiter::Brace => "{", + rustc_proc_macro::Delimiter::Bracket => "[", + rustc_proc_macro::Delimiter::None => "", } )?; if let Some(stream) = stream { @@ -473,10 +473,10 @@ fn display_token_tree( f, "{}", match delimiter { - proc_macro::Delimiter::Parenthesis => ")", - proc_macro::Delimiter::Brace => "}", - proc_macro::Delimiter::Bracket => "]", - proc_macro::Delimiter::None => "", + rustc_proc_macro::Delimiter::Parenthesis => ")", + rustc_proc_macro::Delimiter::Brace => "}", + rustc_proc_macro::Delimiter::Bracket => "]", + rustc_proc_macro::Delimiter::None => "", } )?; } @@ -587,16 +587,16 @@ fn debug_token_tree( f, "GROUP {}{} {:#?} {:#?} {:#?}", match delimiter { - proc_macro::Delimiter::Parenthesis => "(", - proc_macro::Delimiter::Brace => "{", - proc_macro::Delimiter::Bracket => "[", - proc_macro::Delimiter::None => "$", + rustc_proc_macro::Delimiter::Parenthesis => "(", + rustc_proc_macro::Delimiter::Brace => "{", + rustc_proc_macro::Delimiter::Bracket => "[", + rustc_proc_macro::Delimiter::None => "$", }, match delimiter { - proc_macro::Delimiter::Parenthesis => ")", - proc_macro::Delimiter::Brace => "}", - proc_macro::Delimiter::Bracket => "]", - proc_macro::Delimiter::None => "$", + rustc_proc_macro::Delimiter::Parenthesis => ")", + rustc_proc_macro::Delimiter::Brace => "}", + rustc_proc_macro::Delimiter::Bracket => "]", + rustc_proc_macro::Delimiter::None => "$", }, span.open, span.close, diff --git a/src/tools/tidy/src/unit_tests.rs b/src/tools/tidy/src/unit_tests.rs index 74b6c4a3845a6..7d36797b270e0 100644 --- a/src/tools/tidy/src/unit_tests.rs +++ b/src/tools/tidy/src/unit_tests.rs @@ -3,7 +3,7 @@ //! //! `core` and `alloc` cannot be tested directly due to duplicating lang items. //! All tests and benchmarks must be written externally in -//! `{coretests,alloctests}/{tests,benches}`. +//! `*tests/{tests,benches}`. //! //! Outside of the standard library, tests and benchmarks should be outlined //! into separate files named `tests.rs` or `benches.rs`, or directories named @@ -52,7 +52,7 @@ pub fn check(root_path: &Path, stdlib: bool, tidy_ctx: TidyCtx) { if is_dir { // FIXME remove those exceptions once no longer necessary - file_name == "std_detect" || file_name == "std" || file_name == "test" + file_name == "std" || file_name == "test" } else { // Tests which use non-public internals and, as such, need to // have the types in the same crate as the tests themselves. See diff --git a/tests/codegen-llvm/issues/issue-138497-nonzero-remove-trailing-zeroes.rs b/tests/codegen-llvm/issues/issue-138497-nonzero-remove-trailing-zeroes.rs new file mode 100644 index 0000000000000..77cdbaf2bfe51 --- /dev/null +++ b/tests/codegen-llvm/issues/issue-138497-nonzero-remove-trailing-zeroes.rs @@ -0,0 +1,17 @@ +//! This test checks that removing trailing zeroes from a `NonZero`, +//! then creating a new `NonZero` from the result does not panic. + +//@ min-llvm-version: 21 +//@ compile-flags: -O -Zmerge-functions=disabled +#![crate_type = "lib"] + +use std::num::NonZero; + +// CHECK-LABEL: @remove_trailing_zeros +#[no_mangle] +pub fn remove_trailing_zeros(x: NonZero) -> NonZero { + // CHECK: %[[TRAILING:[a-z0-9_-]+]] = {{.*}} call {{.*}} i8 @llvm.cttz.i8(i8 %x, i1 true) + // CHECK-NEXT: %[[RET:[a-z0-9_-]+]] = lshr exact i8 %x, %[[TRAILING]] + // CHECK-NEXT: ret i8 %[[RET]] + NonZero::new(x.get() >> x.trailing_zeros()).unwrap() +} diff --git a/tests/codegen-llvm/slice_cse_optimization.rs b/tests/codegen-llvm/slice_cse_optimization.rs new file mode 100644 index 0000000000000..2b1851d8ae44d --- /dev/null +++ b/tests/codegen-llvm/slice_cse_optimization.rs @@ -0,0 +1,46 @@ +//! Various iterating method over slice correctly optimized using common subexpression elimination. +//! Checks function has memory(argmem: read) attribute. +//! Regression test for . +//@ compile-flags: -O + +#![crate_type = "lib"] +// CHECK-LABEL: @has_zero_iter +// CHECK-SAME: #[[ATTR:[0-9]+]] +#[inline(never)] +#[unsafe(no_mangle)] +pub fn has_zero_iter(xs: &[u8]) -> bool { + xs.iter().any(|&x| x == 0) +} + +// CHECK-LABEL: @has_zero_ptr +// CHECK-SAME: #[[ATTR]] +#[inline(never)] +#[unsafe(no_mangle)] +fn has_zero_ptr(xs: &[u8]) -> bool { + let range = xs.as_ptr_range(); + let mut start = range.start; + let end = range.end; + while start < end { + unsafe { + if *start == 0 { + return true; + } + start = start.add(1); + } + } + false +} +// CHECK-LABEL: @has_zero_for +// CHECK-SAME: #[[ATTR]] +#[inline(never)] +#[unsafe(no_mangle)] +fn has_zero_for(xs: &[u8]) -> bool { + for x in xs { + if *x == 0 { + return true; + } + } + false +} + +// CHECK: attributes #[[ATTR]] = { {{.*}}memory(argmem: read){{.*}} } diff --git a/tests/debuginfo/dummy_span.rs b/tests/debuginfo/dummy_span.rs index 6cf79c46d9a9e..c7b74068db97b 100644 --- a/tests/debuginfo/dummy_span.rs +++ b/tests/debuginfo/dummy_span.rs @@ -1,13 +1,11 @@ //@ min-lldb-version: 310 //@ compile-flags:-g -// FIXME: Investigate why test fails without SimplifyComparisonIntegral pass. -//@ compile-flags: -Zmir-enable-passes=+SimplifyComparisonIntegral //@ ignore-backends: gcc // === GDB TESTS =================================================================================== -//@ gdb-command:run 7 +//@ gdb-command:run //@ gdb-command:next //@ gdb-command:next @@ -17,7 +15,7 @@ // === LLDB TESTS ================================================================================== -//@ lldb-command:run 7 +//@ lldb-command:run //@ lldb-command:next //@ lldb-command:next @@ -30,10 +28,15 @@ use std::env; use std::num::ParseIntError; +struct Foo; + +impl Drop for Foo { + fn drop(&mut self) {} +} + fn main() -> Result<(), ParseIntError> { - let args = env::args(); - let number_str = args.skip(1).next().unwrap(); - let number = number_str.parse::()?; + let foo = Foo; + let number = Ok(7)?; zzz(); // #break if number % 7 == 0 { // This generates code with a dummy span for @@ -41,7 +44,6 @@ fn main() -> Result<(), ParseIntError> { // test will not test what it wants to test. return Ok(()); // #loc1 } - println!("{}", number); Ok(()) } // #loc2 diff --git a/tests/ui/delegation/ice-line-bounds-issue-148732.stderr b/tests/ui/delegation/ice-line-bounds-issue-148732.stderr index f332bc6a7a210..f34ac0ea306c7 100644 --- a/tests/ui/delegation/ice-line-bounds-issue-148732.stderr +++ b/tests/ui/delegation/ice-line-bounds-issue-148732.stderr @@ -4,7 +4,7 @@ error[E0106]: missing lifetime specifier LL | dbg!(b); | ^^^^^^^ expected named lifetime parameter | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0425]: cannot find function `a` in this scope --> $DIR/ice-line-bounds-issue-148732.rs:1:7 @@ -37,7 +37,7 @@ LL | dbg!(b); | ^^^^^^^ the trait `Debug` is not implemented for fn item `fn() {b}` | = help: use parentheses to call this function: `b()` - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 4 previous errors diff --git a/tests/ui/mismatched_types/mismatched-types-issue-126222.stderr b/tests/ui/mismatched_types/mismatched-types-issue-126222.stderr index 2a8f9867abb89..6843cb65a8cdf 100644 --- a/tests/ui/mismatched_types/mismatched-types-issue-126222.stderr +++ b/tests/ui/mismatched_types/mismatched-types-issue-126222.stderr @@ -4,7 +4,7 @@ error[E0308]: mismatched types LL | x => dbg!(x), | ^^^^^^^ expected `()`, found integer | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: you might have meant to return this value | LL | x => return dbg!(x), @@ -16,7 +16,7 @@ error[E0308]: mismatched types LL | dbg!(x) | ^^^^^^^ expected `()`, found integer | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: you might have meant to return this value | LL | return dbg!(x) @@ -28,7 +28,7 @@ error[E0308]: mismatched types LL | _ => dbg!(1) | ^^^^^^^ expected `()`, found integer | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: you might have meant to return this value | LL | _ => return dbg!(1) @@ -40,7 +40,7 @@ error[E0308]: mismatched types LL | _ => {dbg!(1)} | ^^^^^^^ expected `()`, found integer | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: you might have meant to return this value | LL | _ => {return dbg!(1)} diff --git a/tests/ui/modules/issue-107649.stderr b/tests/ui/modules/issue-107649.stderr index 49d7cb4e0aad6..45cb29d10ec2c 100644 --- a/tests/ui/modules/issue-107649.stderr +++ b/tests/ui/modules/issue-107649.stderr @@ -5,7 +5,7 @@ error[E0277]: `Dummy` doesn't implement `Debug` | ^^^^^^^^^^^^^^^^ the trait `Debug` is not implemented for `Dummy` | = note: add `#[derive(Debug)]` to `Dummy` or manually `impl Debug for Dummy` - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Dummy` with `#[derive(Debug)]` --> $DIR/auxiliary/dummy_lib.rs:2:1 | diff --git a/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-move-semantics.stderr b/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-move-semantics.stderr index f515cb62c7cde..fdf5115303ba8 100644 --- a/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-move-semantics.stderr +++ b/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-move-semantics.stderr @@ -8,7 +8,7 @@ LL | let _ = dbg!(a); LL | let _ = dbg!(a); | ^^^^^^^ value used here after move | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider borrowing instead of transferring ownership | LL | let _ = dbg!(&a); diff --git a/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-requires-debug.stderr b/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-requires-debug.stderr index 4e0ae9184150d..2c4ce2676b070 100644 --- a/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-requires-debug.stderr +++ b/tests/ui/rfcs/rfc-2361-dbg-macro/dbg-macro-requires-debug.stderr @@ -5,7 +5,7 @@ LL | let _: NotDebug = dbg!(NotDebug); | ^^^^^^^^^^^^^^ the trait `Debug` is not implemented for `NotDebug` | = note: add `#[derive(Debug)]` to `NotDebug` or manually `impl Debug for NotDebug` - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `NotDebug` with `#[derive(Debug)]` | LL + #[derive(Debug)] diff --git a/tests/ui/typeck/closure-ty-mismatch-issue-128561.stderr b/tests/ui/typeck/closure-ty-mismatch-issue-128561.stderr index 31acc5bb10ec0..0907489f8e8a0 100644 --- a/tests/ui/typeck/closure-ty-mismatch-issue-128561.stderr +++ b/tests/ui/typeck/closure-ty-mismatch-issue-128561.stderr @@ -15,7 +15,7 @@ error[E0308]: mismatched types LL | b"abc".iter().for_each(|x| dbg!(x)); | ^^^^^^^ expected `()`, found `&u8` | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0308]: mismatched types --> $DIR/closure-ty-mismatch-issue-128561.rs:8:9 diff --git a/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr b/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr index 59e56f672374e..972c2ced00376 100644 --- a/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr +++ b/tests/ui/typeck/suggestions/suggest-clone-in-macro-issue-139253.stderr @@ -26,7 +26,7 @@ error[E0308]: mismatched types LL | let c: S = dbg!(field); | ^^^^^^^^^^^ expected `S`, found `&S` | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider using clone here | LL | let c: S = dbg!(field).clone(); @@ -38,7 +38,7 @@ error[E0308]: mismatched types LL | let c: S = dbg!(dbg!(field)); | ^^^^^^^^^^^^^^^^^ expected `S`, found `&S` | - = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) + = note: this error originates in the macro `$crate::macros::dbg_internal` which comes from the expansion of the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider using clone here | LL | let c: S = dbg!(dbg!(field)).clone();