From d5bc71141da0fe2dd4b9a3d88bb1b1541c82a3a8 Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Sun, 11 Aug 2024 17:32:03 +0200 Subject: [PATCH 01/14] deps(rustc_expand): Add `rustc_middle` as a dep --- Cargo.lock | 1 + compiler/rustc_expand/Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 81aecf1cea77f..ddbe9a04ee9e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3666,6 +3666,7 @@ dependencies = [ "rustc_lexer", "rustc_lint_defs", "rustc_macros", + "rustc_middle", "rustc_parse", "rustc_serialize", "rustc_session", diff --git a/compiler/rustc_expand/Cargo.toml b/compiler/rustc_expand/Cargo.toml index ce014364b0d01..5e9092c84d074 100644 --- a/compiler/rustc_expand/Cargo.toml +++ b/compiler/rustc_expand/Cargo.toml @@ -20,6 +20,7 @@ rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_lexer = { path = "../rustc_lexer" } rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_macros = { path = "../rustc_macros" } +rustc_middle = { path = "../rustc_middle" } rustc_parse = { path = "../rustc_parse" } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } From de3349ce5db1bd47baf5b2bc7fb1201cb6104cfe Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Sun, 11 Aug 2024 17:32:29 +0200 Subject: [PATCH 02/14] refactor(rustc_expand): Take &SyntaxExtension instead of only &*Kind --- compiler/rustc_expand/src/expand.rs | 35 +++++++++++++++-------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 0d56a005f159e..287cef732bb61 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -488,7 +488,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.cx.force_mode = force; let fragment_kind = invoc.fragment_kind; - match self.expand_invoc(invoc, &ext.kind) { + match self.expand_invoc(invoc, &ext) { ExpandResult::Ready(fragment) => { let mut derive_invocations = Vec::new(); let derive_placeholders = self @@ -650,7 +650,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { fn expand_invoc( &mut self, invoc: Invocation, - ext: &SyntaxExtensionKind, + ext: &Lrc, ) -> ExpandResult { let recursion_limit = match self.cx.reduced_recursion_limit { Some((limit, _)) => limit, @@ -671,7 +671,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { let (fragment_kind, span) = (invoc.fragment_kind, invoc.span()); ExpandResult::Ready(match invoc.kind { - InvocationKind::Bang { mac, span } => match ext { + InvocationKind::Bang { mac, span } => match &ext.kind { SyntaxExtensionKind::Bang(expander) => { match expander.expand(self.cx, span, mac.args.tokens.clone()) { Ok(tok_result) => { @@ -701,7 +701,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } _ => unreachable!(), }, - InvocationKind::Attr { attr, pos, mut item, derives } => match ext { + InvocationKind::Attr { attr, pos, mut item, derives } => match &ext.kind { SyntaxExtensionKind::Attr(expander) => { self.gate_proc_macro_input(&item); self.gate_proc_macro_attr_item(span, &item); @@ -780,10 +780,10 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } _ => unreachable!(), }, - InvocationKind::Derive { path, item, is_const } => match ext { + InvocationKind::Derive { path, item, is_const } => match &ext.kind { SyntaxExtensionKind::Derive(expander) | SyntaxExtensionKind::LegacyDerive(expander) => { - if let SyntaxExtensionKind::Derive(..) = ext { + if let SyntaxExtensionKind::Derive(..) = ext.kind { self.gate_proc_macro_input(&item); } // The `MetaItem` representing the trait to derive can't @@ -810,18 +810,19 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }, InvocationKind::GlobDelegation { item } => { let AssocItemKind::DelegationMac(deleg) = &item.kind else { unreachable!() }; - let suffixes = match ext { - SyntaxExtensionKind::GlobDelegation(expander) => match expander.expand(self.cx) - { - ExpandResult::Ready(suffixes) => suffixes, - ExpandResult::Retry(()) => { - // Reassemble the original invocation for retrying. - return ExpandResult::Retry(Invocation { - kind: InvocationKind::GlobDelegation { item }, - ..invoc - }); + let suffixes = match &ext.kind { + SyntaxExtensionKind::GlobDelegation(expander) => { + match expander.expand(self.cx) { + ExpandResult::Ready(suffixes) => suffixes, + ExpandResult::Retry(()) => { + // Reassemble the original invocation for retrying. + return ExpandResult::Retry(Invocation { + kind: InvocationKind::GlobDelegation { item }, + ..invoc + }); + } } - }, + } SyntaxExtensionKind::LegacyBang(..) => { let msg = "expanded a dummy glob delegation"; let guar = self.cx.dcx().span_delayed_bug(span, msg); From 461c7a77919d0b214cd9c69cbe43176aa674dc37 Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 03:24:07 +0200 Subject: [PATCH 03/14] wip: So yeah, tests pass, but still `eval_always` (not far from disk caching though I think) --- compiler/rustc_ast/src/tokenstream.rs | 100 +++++++++++++++- compiler/rustc_expand/src/base.rs | 3 + .../src/derive_macro_expansion.rs | 113 ++++++++++++++++++ compiler/rustc_expand/src/expand.rs | 5 + compiler/rustc_expand/src/lib.rs | 5 + compiler/rustc_expand/src/proc_macro.rs | 48 ++++---- compiler/rustc_interface/src/passes.rs | 1 + compiler/rustc_middle/src/arena.rs | 1 + compiler/rustc_middle/src/query/erase.rs | 6 + compiler/rustc_middle/src/query/keys.rs | 16 ++- compiler/rustc_middle/src/query/mod.rs | 9 +- compiler/rustc_resolve/src/macros.rs | 8 ++ compiler/rustc_span/src/hygiene.rs | 6 + 13 files changed, 288 insertions(+), 33 deletions(-) create mode 100644 compiler/rustc_expand/src/derive_macro_expansion.rs diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index fc1dd2caf681a..9eba534543541 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -14,12 +14,14 @@ //! ownership of the original. use std::borrow::Cow; +use std::hash::Hash; use std::{cmp, fmt, iter}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::{self, Lrc}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_serialize::{Decodable, Encodable}; +use rustc_serialize::{Decodable, Encodable, Encoder}; +use rustc_span::def_id::{CrateNum, DefIndex}; use rustc_span::{sym, Span, SpanDecoder, SpanEncoder, Symbol, DUMMY_SP}; use crate::ast::{AttrStyle, StmtKind}; @@ -139,8 +141,10 @@ impl fmt::Debug for LazyAttrTokenStream { } impl Encodable for LazyAttrTokenStream { - fn encode(&self, _s: &mut S) { - panic!("Attempted to encode LazyAttrTokenStream"); + fn encode(&self, s: &mut S) { + // TODO: welp + // TODO: (also) `.flattened()` here? + self.to_attr_token_stream().encode(s) } } @@ -296,6 +300,96 @@ pub struct AttrsTarget { #[derive(Clone, Debug, Default, Encodable, Decodable)] pub struct TokenStream(pub(crate) Lrc>); +struct HashEncoder { + hasher: H, +} + +impl Encoder for HashEncoder { + fn emit_usize(&mut self, v: usize) { + self.hasher.write_usize(v) + } + + fn emit_u128(&mut self, v: u128) { + self.hasher.write_u128(v) + } + + fn emit_u64(&mut self, v: u64) { + self.hasher.write_u64(v) + } + + fn emit_u32(&mut self, v: u32) { + self.hasher.write_u32(v) + } + + fn emit_u16(&mut self, v: u16) { + self.hasher.write_u16(v) + } + + fn emit_u8(&mut self, v: u8) { + self.hasher.write_u8(v) + } + + fn emit_isize(&mut self, v: isize) { + self.hasher.write_isize(v) + } + + fn emit_i128(&mut self, v: i128) { + self.hasher.write_i128(v) + } + + fn emit_i64(&mut self, v: i64) { + self.hasher.write_i64(v) + } + + fn emit_i32(&mut self, v: i32) { + self.hasher.write_i32(v) + } + + fn emit_i16(&mut self, v: i16) { + self.hasher.write_i16(v) + } + + fn emit_raw_bytes(&mut self, s: &[u8]) { + self.hasher.write(s) + } +} + +impl SpanEncoder for HashEncoder { + fn encode_span(&mut self, span: Span) { + span.hash(&mut self.hasher) + } + + fn encode_symbol(&mut self, symbol: Symbol) { + symbol.hash(&mut self.hasher) + } + + fn encode_expn_id(&mut self, expn_id: rustc_span::ExpnId) { + expn_id.hash(&mut self.hasher) + } + + fn encode_syntax_context(&mut self, syntax_context: rustc_span::SyntaxContext) { + syntax_context.hash(&mut self.hasher) + } + + fn encode_crate_num(&mut self, crate_num: CrateNum) { + crate_num.hash(&mut self.hasher) + } + + fn encode_def_index(&mut self, def_index: DefIndex) { + def_index.hash(&mut self.hasher) + } + + fn encode_def_id(&mut self, def_id: rustc_span::def_id::DefId) { + def_id.hash(&mut self.hasher) + } +} + +impl Hash for TokenStream { + fn hash(&self, state: &mut H) { + Encodable::encode(self, &mut HashEncoder { hasher: state }); + } +} + /// Indicates whether a token can join with the following token to form a /// compound token. Used for conversions to `proc_macro::Spacing`. Also used to /// guide pretty-printing, which is where the `JointHidden` value (which isn't diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 8f9104135cddd..736e98ed9ea1f 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1072,6 +1072,9 @@ pub trait ResolverExpand { trait_def_id: DefId, impl_def_id: LocalDefId, ) -> Result)>, Indeterminate>; + + fn register_proc_macro_invoc(&mut self, invoc_id: LocalExpnId, ext: Lrc); + fn unregister_proc_macro_invoc(&mut self, invoc_id: LocalExpnId); } pub trait LintStoreExpand { diff --git a/compiler/rustc_expand/src/derive_macro_expansion.rs b/compiler/rustc_expand/src/derive_macro_expansion.rs new file mode 100644 index 0000000000000..ef58851a2e246 --- /dev/null +++ b/compiler/rustc_expand/src/derive_macro_expansion.rs @@ -0,0 +1,113 @@ +// TODO: remove +#![allow(dead_code)] + +use std::cell::Cell; +use std::ptr; + +use rustc_ast::tokenstream::TokenStream; +use rustc_middle::ty::TyCtxt; +use rustc_span::profiling::SpannedEventArgRecorder; +use rustc_span::LocalExpnId; + +use crate::base::ExtCtxt; +use crate::errors; + +pub(super) fn expand<'tcx>( + tcx: TyCtxt<'tcx>, + key: (LocalExpnId, &'tcx TokenStream), +) -> Result<&'tcx TokenStream, ()> { + let (invoc_id, input) = key; + + let res = with_context(|(ecx, client)| { + let span = invoc_id.expn_data().call_site; + let _timer = + ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| { + recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span); + }); + let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; + let strategy = crate::proc_macro::exec_strategy(ecx); + let server = crate::proc_macro_server::Rustc::new(ecx); + let res = match client.run(&strategy, server, input.clone(), proc_macro_backtrace) { + // TODO: without flattened some (weird) tests fail, but no idea if it's correct/enough + Ok(stream) => Ok(tcx.arena.alloc(stream.flattened()) as &TokenStream), + Err(e) => { + ecx.dcx().emit_err({ + errors::ProcMacroDerivePanicked { + span, + message: e.as_str().map(|message| errors::ProcMacroDerivePanickedHelp { + message: message.into(), + }), + } + }); + Err(()) + } + }; + res + }); + + res +} + +type CLIENT = pm::bridge::client::Client; + +// based on rust/compiler/rustc_middle/src/ty/context/tls.rs +// #[cfg(not(parallel_compiler))] +thread_local! { + /// A thread local variable that stores a pointer to the current `CONTEXT`. + static TLV: Cell<(*mut (), Option)> = const { Cell::new((ptr::null_mut(), None)) }; +} + +#[inline] +fn erase(context: &mut ExtCtxt<'_>) -> *mut () { + context as *mut _ as *mut () +} + +#[inline] +unsafe fn downcast<'a>(context: *mut ()) -> &'a mut ExtCtxt<'a> { + unsafe { &mut *(context as *mut ExtCtxt<'a>) } +} + +/// Sets `context` as the new current `CONTEXT` for the duration of the function `f`. +#[inline] +pub fn enter_context<'a, F, R>(context: (&mut ExtCtxt<'a>, CLIENT), f: F) -> R +where + F: FnOnce() -> R, +{ + let (ectx, client) = context; + let erased = (erase(ectx), Some(client)); + TLV.with(|tlv| { + let old = tlv.replace(erased); + let _reset = rustc_data_structures::defer(move || tlv.set(old)); + f() + }) +} + +/// Allows access to the current `CONTEXT` in a closure if one is available. +#[inline] +#[track_caller] +pub fn with_context_opt(f: F) -> R +where + F: for<'a, 'b> FnOnce(Option<&'b mut (&mut ExtCtxt<'a>, CLIENT)>) -> R, +{ + let (ectx, client_opt) = TLV.get(); + if ectx.is_null() { + f(None) + } else { + // We could get an `CONTEXT` pointer from another thread. + // Ensure that `CONTEXT` is `DynSync`. + // TODO: we should not be able to? + // sync::assert_dyn_sync::>(); + + unsafe { f(Some(&mut (downcast(ectx), client_opt.unwrap()))) } + } +} + +/// Allows access to the current `CONTEXT`. +/// Panics if there is no `CONTEXT` available. +#[inline] +pub fn with_context(f: F) -> R +where + F: for<'a, 'b> FnOnce(&'b mut (&mut ExtCtxt<'a>, CLIENT)) -> R, +{ + with_context_opt(|opt_context| f(opt_context.expect("no CONTEXT stored in tls"))) +} diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 287cef732bb61..d5d90a90ba29e 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -794,9 +794,14 @@ impl<'a, 'b> MacroExpander<'a, 'b> { span, path, }; + self.cx + .resolver + .register_proc_macro_invoc(invoc.expansion_data.id, ext.clone()); + invoc.expansion_data.id.expn_data(); let items = match expander.expand(self.cx, span, &meta, item, is_const) { ExpandResult::Ready(items) => items, ExpandResult::Retry(item) => { + self.cx.resolver.unregister_proc_macro_invoc(invoc.expansion_data.id); // Reassemble the original invocation for retrying. return ExpandResult::Retry(Invocation { kind: InvocationKind::Derive { path: meta.path, item, is_const }, diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index 777044e3f33bf..96e4677d7c5bb 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -29,10 +29,15 @@ mod proc_macro_server; pub use mbe::macro_rules::compile_declarative_macro; pub mod base; pub mod config; +pub(crate) mod derive_macro_expansion; pub mod expand; pub mod module; // FIXME(Nilstrieb) Translate proc_macro diagnostics #[allow(rustc::untranslatable_diagnostic)] pub mod proc_macro; +pub fn provide(providers: &mut rustc_middle::util::Providers) { + providers.derive_macro_expansion = derive_macro_expansion::expand; +} + rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 24f631ed5dc98..d39d4582f84bf 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -2,6 +2,7 @@ use rustc_ast as ast; use rustc_ast::ptr::P; use rustc_ast::tokenstream::TokenStream; use rustc_errors::ErrorGuaranteed; +use rustc_middle::ty; use rustc_parse::parser::{ForceCollect, Parser}; use rustc_session::config::ProcMacroExecutionStrategy; use rustc_span::profiling::SpannedEventArgRecorder; @@ -31,7 +32,7 @@ impl pm::bridge::server::MessagePipe for MessagePipe { } } -fn exec_strategy(ecx: &ExtCtxt<'_>) -> impl pm::bridge::server::ExecutionStrategy { +pub fn exec_strategy(ecx: &ExtCtxt<'_>) -> impl pm::bridge::server::ExecutionStrategy { pm::bridge::server::MaybeCrossThread::>::new( ecx.sess.opts.unstable_opts.proc_macro_execution_strategy == ProcMacroExecutionStrategy::CrossThread, @@ -124,36 +125,27 @@ impl MultiItemModifier for DeriveProcMacro { // altogether. See #73345. crate::base::ann_pretty_printing_compatibility_hack(&item, &ecx.sess); let input = item.to_tokens(); - let stream = { - let _timer = - ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| { - recorder.record_arg_with_span( - ecx.sess.source_map(), - ecx.expansion_descr(), - span, - ); - }); - let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; - let strategy = exec_strategy(ecx); - let server = proc_macro_server::Rustc::new(ecx); - match self.client.run(&strategy, server, input, proc_macro_backtrace) { - Ok(stream) => stream, - Err(e) => { - ecx.dcx().emit_err({ - errors::ProcMacroDerivePanicked { - span, - message: e.as_str().map(|message| { - errors::ProcMacroDerivePanickedHelp { message: message.into() } - }), - } - }); - return ExpandResult::Ready(vec![]); - } - } + let res = ty::tls::with(|tcx| { + // TODO: without flattened some (weird) tests fail, but no idea if it's correct/enough + let input = tcx.arena.alloc(input.flattened()) as &TokenStream; + let invoc_id = ecx.current_expansion.id; + + assert_eq!(invoc_id.expn_data().call_site, span); + + let res = crate::derive_macro_expansion::enter_context((ecx, self.client), move || { + let res = tcx.derive_macro_expansion((invoc_id, input)).cloned(); + res + }); + + res + }); + let Ok(output) = res else { + // error will already have been emitted + return ExpandResult::Ready(vec![]); }; let error_count_before = ecx.dcx().err_count(); - let mut parser = Parser::new(&ecx.sess.psess, stream, Some("proc-macro derive")); + let mut parser = Parser::new(&ecx.sess.psess, output, Some("proc-macro derive")); let mut items = vec![]; loop { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index c4a38047b5e3b..901d373fc11e4 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -624,6 +624,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock = LazyLock::new(|| { providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1; providers.early_lint_checks = early_lint_checks; proc_macro_decls::provide(providers); + rustc_expand::provide(providers); rustc_const_eval::provide(providers); rustc_middle::hir::provide(providers); rustc_borrowck::provide(providers); diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index 7050a06b8dc22..918ff15e70c55 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -114,6 +114,7 @@ macro_rules! arena_types { [decode] specialization_graph: rustc_middle::traits::specialization_graph::Graph, [] crate_inherent_impls: rustc_middle::ty::CrateInherentImpls, [] hir_owner_nodes: rustc_hir::OwnerNodes<'tcx>, + [] token_stream: rustc_ast::tokenstream::TokenStream, ]); ) } diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index bd20e6aa00537..8476e937c7f3f 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -1,6 +1,8 @@ use std::intrinsics::transmute_unchecked; use std::mem::MaybeUninit; +use rustc_ast::tokenstream::TokenStream; + use crate::query::CyclePlaceholder; use crate::ty::adjustment::CoerceUnsizedInfo; use crate::ty::{self, Ty}; @@ -172,6 +174,10 @@ impl EraseType for Result>, CyclePlaceholder> { type Result = [u8; size_of::>, CyclePlaceholder>>()]; } +impl EraseType for Result<&'_ TokenStream, ()> { + type Result = [u8; size_of::>()]; +} + impl EraseType for Option<&'_ T> { type Result = [u8; size_of::>()]; } diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 6562d46d7b866..7d24f28169c87 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -1,10 +1,11 @@ //! Defines the set of legal keys that can be used in queries. +use rustc_ast::tokenstream::TokenStream; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LOCAL_CRATE}; use rustc_hir::hir_id::{HirId, OwnerId}; use rustc_query_system::query::{DefIdCache, DefaultCache, SingleCache, VecCache}; use rustc_span::symbol::{Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{LocalExpnId, Span, DUMMY_SP}; use rustc_target::abi; use crate::infer::canonical::Canonical; @@ -575,6 +576,19 @@ impl Key for (LocalDefId, HirId) { } } +impl<'tcx> Key for (LocalExpnId, &'tcx TokenStream) { + type Cache = DefaultCache; + + fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { + self.0.expn_data().call_site + } + + #[inline(always)] + fn key_as_def_id(&self) -> Option { + None + } +} + impl<'tcx> Key for (ValidityRequirement, ty::ParamEnvAnd<'tcx, Ty<'tcx>>) { type Cache = DefaultCache; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 969374cb0e540..b11dd41624d35 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -14,6 +14,7 @@ use std::sync::Arc; use rustc_arena::TypedArena; use rustc_ast::expand::allocator::AllocatorKind; use rustc_ast::expand::StrippedCfgItem; +use rustc_ast::tokenstream::TokenStream; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::steal::Steal; @@ -39,7 +40,7 @@ use rustc_session::lint::LintExpectationId; use rustc_session::Limits; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{LocalExpnId, Span, DUMMY_SP}; use rustc_target::abi; use rustc_target::spec::PanicStrategy; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; @@ -103,6 +104,12 @@ pub use plumbing::{IntoQueryParam, TyCtxtAt, TyCtxtEnsure, TyCtxtEnsureWithValue // Queries marked with `fatal_cycle` do not need the latter implementation, // as they will raise an fatal error on query cycles instead. rustc_queries! { + query derive_macro_expansion(key: (LocalExpnId, &'tcx TokenStream)) -> Result<&'tcx TokenStream, ()> { + eval_always + no_hash + desc { "expanding a derive (proc) macro" } + } + /// This exists purely for testing the interactions between delayed bugs and incremental. query trigger_delayed_bug(key: DefId) { desc { "triggering a delayed bug for testing incremental" } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 7203fbe4a0c18..8cce9a95bb57c 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -526,6 +526,14 @@ impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> { }); Ok(idents) } + + fn register_proc_macro_invoc(&mut self, _invoc_id: LocalExpnId, _ext: Lrc) { + // TODO: dunno if need this yet + } + + fn unregister_proc_macro_invoc(&mut self, _invoc_id: LocalExpnId) { + // TODO: dunno if need this yet + } } impl<'a, 'tcx> Resolver<'a, 'tcx> { diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 463e0dbc30ce5..3ac842c2ca856 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -1572,3 +1572,9 @@ impl HashStable for ExpnId { hash.hash_stable(ctx, hasher); } } + +impl HashStable for LocalExpnId { + fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { + self.to_expn_id().hash_stable(hcx, hasher); + } +} From f2acfe5ac91da2ae75eac4350fcdc2afc4172587 Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 14:09:19 +0200 Subject: [PATCH 04/14] fix: Prevent double-enter with same `&mut ExtCtxt` (which would be UB) --- .../src/derive_macro_expansion.rs | 26 ++++++++++++++----- compiler/rustc_expand/src/lib.rs | 2 +- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_expand/src/derive_macro_expansion.rs b/compiler/rustc_expand/src/derive_macro_expansion.rs index ef58851a2e246..7a0535f6abdd0 100644 --- a/compiler/rustc_expand/src/derive_macro_expansion.rs +++ b/compiler/rustc_expand/src/derive_macro_expansion.rs @@ -12,7 +12,7 @@ use rustc_span::LocalExpnId; use crate::base::ExtCtxt; use crate::errors; -pub(super) fn expand<'tcx>( +pub(super) fn provide_derive_macro_expansion<'tcx>( tcx: TyCtxt<'tcx>, key: (LocalExpnId, &'tcx TokenStream), ) -> Result<&'tcx TokenStream, ()> { @@ -51,7 +51,6 @@ pub(super) fn expand<'tcx>( type CLIENT = pm::bridge::client::Client; // based on rust/compiler/rustc_middle/src/ty/context/tls.rs -// #[cfg(not(parallel_compiler))] thread_local! { /// A thread local variable that stores a pointer to the current `CONTEXT`. static TLV: Cell<(*mut (), Option)> = const { Cell::new((ptr::null_mut(), None)) }; @@ -67,14 +66,11 @@ unsafe fn downcast<'a>(context: *mut ()) -> &'a mut ExtCtxt<'a> { unsafe { &mut *(context as *mut ExtCtxt<'a>) } } -/// Sets `context` as the new current `CONTEXT` for the duration of the function `f`. #[inline] -pub fn enter_context<'a, F, R>(context: (&mut ExtCtxt<'a>, CLIENT), f: F) -> R +fn enter_context_erased(erased: (*mut (), Option), f: F) -> R where F: FnOnce() -> R, { - let (ectx, client) = context; - let erased = (erase(ectx), Some(client)); TLV.with(|tlv| { let old = tlv.replace(erased); let _reset = rustc_data_structures::defer(move || tlv.set(old)); @@ -82,6 +78,17 @@ where }) } +/// Sets `context` as the new current `CONTEXT` for the duration of the function `f`. +#[inline] +pub fn enter_context<'a, F, R>(context: (&mut ExtCtxt<'a>, CLIENT), f: F) -> R +where + F: FnOnce() -> R, +{ + let (ectx, client) = context; + let erased = (erase(ectx), Some(client)); + enter_context_erased(erased, f) +} + /// Allows access to the current `CONTEXT` in a closure if one is available. #[inline] #[track_caller] @@ -98,7 +105,12 @@ where // TODO: we should not be able to? // sync::assert_dyn_sync::>(); - unsafe { f(Some(&mut (downcast(ectx), client_opt.unwrap()))) } + // prevent double entering, as that would allow creating two `&mut ExtCtxt`s + // TODO: probably use a RefCell instead (which checks this properly)? + enter_context_erased((ptr::null_mut(), None), || unsafe { + let ectx = downcast(ectx); + f(Some(&mut (ectx, client_opt.unwrap()))) + }) } } diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index 96e4677d7c5bb..587784e7e5a87 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -37,7 +37,7 @@ pub mod module; pub mod proc_macro; pub fn provide(providers: &mut rustc_middle::util::Providers) { - providers.derive_macro_expansion = derive_macro_expansion::expand; + providers.derive_macro_expansion = derive_macro_expansion::provide_derive_macro_expansion; } rustc_fluent_macro::fluent_messages! { "../messages.ftl" } From 7ff46763bbce6effb0f5a51423d6666017341b68 Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 14:11:41 +0200 Subject: [PATCH 05/14] chore: Remove old `allow` --- compiler/rustc_expand/src/derive_macro_expansion.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/compiler/rustc_expand/src/derive_macro_expansion.rs b/compiler/rustc_expand/src/derive_macro_expansion.rs index 7a0535f6abdd0..061765cb87733 100644 --- a/compiler/rustc_expand/src/derive_macro_expansion.rs +++ b/compiler/rustc_expand/src/derive_macro_expansion.rs @@ -1,6 +1,3 @@ -// TODO: remove -#![allow(dead_code)] - use std::cell::Cell; use std::ptr; From 035d859bdcbf52d4eefd044a204ee6620e1ebcfb Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 14:48:43 +0200 Subject: [PATCH 06/14] chore: Remove unneeded code, adapt TODOs for pr-time --- compiler/rustc_ast/src/tokenstream.rs | 4 ++-- compiler/rustc_expand/src/base.rs | 3 --- compiler/rustc_expand/src/derive_macro_expansion.rs | 6 +++--- compiler/rustc_expand/src/expand.rs | 4 ---- compiler/rustc_expand/src/proc_macro.rs | 2 +- compiler/rustc_resolve/src/macros.rs | 8 -------- 6 files changed, 6 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index 9eba534543541..620171a38cb9b 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -142,8 +142,8 @@ impl fmt::Debug for LazyAttrTokenStream { impl Encodable for LazyAttrTokenStream { fn encode(&self, s: &mut S) { - // TODO: welp - // TODO: (also) `.flattened()` here? + // TODO(pr-time): welp, do we really want this impl? maybe newtype wrapper? + // TODO(pr-time): (also) `.flattened()` here? self.to_attr_token_stream().encode(s) } } diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 736e98ed9ea1f..8f9104135cddd 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1072,9 +1072,6 @@ pub trait ResolverExpand { trait_def_id: DefId, impl_def_id: LocalDefId, ) -> Result)>, Indeterminate>; - - fn register_proc_macro_invoc(&mut self, invoc_id: LocalExpnId, ext: Lrc); - fn unregister_proc_macro_invoc(&mut self, invoc_id: LocalExpnId); } pub trait LintStoreExpand { diff --git a/compiler/rustc_expand/src/derive_macro_expansion.rs b/compiler/rustc_expand/src/derive_macro_expansion.rs index 061765cb87733..2d79fca7a5d4e 100644 --- a/compiler/rustc_expand/src/derive_macro_expansion.rs +++ b/compiler/rustc_expand/src/derive_macro_expansion.rs @@ -25,7 +25,7 @@ pub(super) fn provide_derive_macro_expansion<'tcx>( let strategy = crate::proc_macro::exec_strategy(ecx); let server = crate::proc_macro_server::Rustc::new(ecx); let res = match client.run(&strategy, server, input.clone(), proc_macro_backtrace) { - // TODO: without flattened some (weird) tests fail, but no idea if it's correct/enough + // TODO(pr-time): without flattened some (weird) tests fail, but no idea if it's correct/enough Ok(stream) => Ok(tcx.arena.alloc(stream.flattened()) as &TokenStream), Err(e) => { ecx.dcx().emit_err({ @@ -99,11 +99,11 @@ where } else { // We could get an `CONTEXT` pointer from another thread. // Ensure that `CONTEXT` is `DynSync`. - // TODO: we should not be able to? + // TODO(pr-time): we should not be able to? // sync::assert_dyn_sync::>(); // prevent double entering, as that would allow creating two `&mut ExtCtxt`s - // TODO: probably use a RefCell instead (which checks this properly)? + // TODO(pr-time): probably use a RefCell instead (which checks this properly)? enter_context_erased((ptr::null_mut(), None), || unsafe { let ectx = downcast(ectx); f(Some(&mut (ectx, client_opt.unwrap()))) diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index d5d90a90ba29e..4da74befed4d9 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -794,14 +794,10 @@ impl<'a, 'b> MacroExpander<'a, 'b> { span, path, }; - self.cx - .resolver - .register_proc_macro_invoc(invoc.expansion_data.id, ext.clone()); invoc.expansion_data.id.expn_data(); let items = match expander.expand(self.cx, span, &meta, item, is_const) { ExpandResult::Ready(items) => items, ExpandResult::Retry(item) => { - self.cx.resolver.unregister_proc_macro_invoc(invoc.expansion_data.id); // Reassemble the original invocation for retrying. return ExpandResult::Retry(Invocation { kind: InvocationKind::Derive { path: meta.path, item, is_const }, diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index d39d4582f84bf..dfb67a35e1988 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -126,7 +126,7 @@ impl MultiItemModifier for DeriveProcMacro { crate::base::ann_pretty_printing_compatibility_hack(&item, &ecx.sess); let input = item.to_tokens(); let res = ty::tls::with(|tcx| { - // TODO: without flattened some (weird) tests fail, but no idea if it's correct/enough + // TODO(pr-time): without flattened some (weird) tests fail, but no idea if it's correct/enough let input = tcx.arena.alloc(input.flattened()) as &TokenStream; let invoc_id = ecx.current_expansion.id; diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 8cce9a95bb57c..7203fbe4a0c18 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -526,14 +526,6 @@ impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> { }); Ok(idents) } - - fn register_proc_macro_invoc(&mut self, _invoc_id: LocalExpnId, _ext: Lrc) { - // TODO: dunno if need this yet - } - - fn unregister_proc_macro_invoc(&mut self, _invoc_id: LocalExpnId) { - // TODO: dunno if need this yet - } } impl<'a, 'tcx> Resolver<'a, 'tcx> { From 7d6ce7736d8ba9ba73a96f95216e9ca062d79a6d Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 16:27:11 +0200 Subject: [PATCH 07/14] wip(test): Run with `-- --nocapture --verbose` and `invoked` should not appear in 2nd output --- .../auxiliary/derive_nothing.rs | 24 ++++++++++ .../derive_macro_expansion/item_changed.rs | 48 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs create mode 100644 tests/incremental/derive_macro_expansion/item_changed.rs diff --git a/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs b/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs new file mode 100644 index 0000000000000..cb572220aa197 --- /dev/null +++ b/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs @@ -0,0 +1,24 @@ +//@ force-host +//@ no-prefer-dynamic + +#![crate_type = "proc-macro"] + +extern crate proc_macro; +use proc_macro::TokenStream; + +#[proc_macro_derive(Nothing)] +pub fn derive(input: TokenStream) -> TokenStream { + eprintln!("invoked"); + + r#" + pub mod nothing_mod { + // #[cfg(cfail1)] + pub fn nothing() { + eprintln!("nothing"); + } + + // #[cfg(cfail2)] + // fn nothingx() {} + } + "#.parse().unwrap() +} diff --git a/tests/incremental/derive_macro_expansion/item_changed.rs b/tests/incremental/derive_macro_expansion/item_changed.rs new file mode 100644 index 0000000000000..c89a3d1c24d33 --- /dev/null +++ b/tests/incremental/derive_macro_expansion/item_changed.rs @@ -0,0 +1,48 @@ +//@ aux-build:derive_nothing.rs +//@ revisions:cfail1 cfail2 +//@ compile-flags: -Z query-dep-graph +//@ check-pass (FIXME(62277): could be check-pass?) + +// TODO(pr-time): do these revisions make sense? only "check" required? + +#![feature(rustc_attrs)] +#![feature(stmt_expr_attributes)] +#![allow(dead_code)] +#![crate_type = "rlib"] + +#![rustc_partition_codegened(module="item_changed-foo", cfg="cfail1")] +// #![rustc_partition_reused(module="item_changed-foo", cfg="cfail2")] +#![rustc_partition_reused(module="item_changed-foo-nothing_mod", cfg="cfail2")] + + #[macro_use] + extern crate derive_nothing; + +pub mod foo { + // #[rustc_clean(cfg="cfail2")] + #[derive(Nothing)] + pub struct Foo; + + #[cfg(cfail2)] + pub fn second_fn() { + eprintln!("just forcing codegen"); + } + + pub fn use_foo(_f: Foo) { + // #[cfg(cfail1)] + nothing_mod::nothing(); + + // #[cfg(cfail2)] + // nothingx(); + + eprintln!("foo used"); + } +} + +// fn main() { +// Foo; +// +// nothing(); +// +// #[cfg(rpass2)] +// Bar; +// } From 74dd64626ad8910276c60b21639f3bbf898b67da Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 18:20:49 +0200 Subject: [PATCH 08/14] wip: Activate, test (and fix) on_disk caching for proc-macro expansions! Also add manual test. --- compiler/rustc_ast/src/tokenstream.rs | 11 +++-- .../src/derive_macro_expansion.rs | 5 +- compiler/rustc_expand/src/proc_macro.rs | 10 +++- compiler/rustc_middle/src/arena.rs | 2 +- compiler/rustc_middle/src/query/keys.rs | 3 +- compiler/rustc_middle/src/query/mod.rs | 5 +- .../rustc_middle/src/query/on_disk_cache.rs | 7 +++ .../auxiliary/derive_nothing.rs | 8 +--- .../derive_macro_expansion/item_changed.rs | 48 ------------------- .../proc_macro_unchanged.rs | 37 ++++++++++++++ 10 files changed, 71 insertions(+), 65 deletions(-) delete mode 100644 tests/incremental/derive_macro_expansion/item_changed.rs create mode 100644 tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index 620171a38cb9b..6909f5e090227 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -141,10 +141,13 @@ impl fmt::Debug for LazyAttrTokenStream { } impl Encodable for LazyAttrTokenStream { - fn encode(&self, s: &mut S) { - // TODO(pr-time): welp, do we really want this impl? maybe newtype wrapper? - // TODO(pr-time): (also) `.flattened()` here? - self.to_attr_token_stream().encode(s) + fn encode(&self, _s: &mut S) { + // TODO(pr-time): Just a reminder that this exists/was tried out, + // but probably not necessary anymore (see below). + // self.to_attr_token_stream().encode(s) + // We should not need to anymore, now that we `flatten`? + // Yep, that seems to be true! :) + panic!("Attempted to encode LazyAttrTokenStream"); } } diff --git a/compiler/rustc_expand/src/derive_macro_expansion.rs b/compiler/rustc_expand/src/derive_macro_expansion.rs index 2d79fca7a5d4e..aa77e5a8ba4be 100644 --- a/compiler/rustc_expand/src/derive_macro_expansion.rs +++ b/compiler/rustc_expand/src/derive_macro_expansion.rs @@ -2,6 +2,7 @@ use std::cell::Cell; use std::ptr; use rustc_ast::tokenstream::TokenStream; +use rustc_data_structures::svh::Svh; use rustc_middle::ty::TyCtxt; use rustc_span::profiling::SpannedEventArgRecorder; use rustc_span::LocalExpnId; @@ -11,9 +12,9 @@ use crate::errors; pub(super) fn provide_derive_macro_expansion<'tcx>( tcx: TyCtxt<'tcx>, - key: (LocalExpnId, &'tcx TokenStream), + key: (LocalExpnId, Svh, &'tcx TokenStream), ) -> Result<&'tcx TokenStream, ()> { - let (invoc_id, input) = key; + let (invoc_id, _macro_crate_hash, input) = key; let res = with_context(|(ecx, client)| { let span = invoc_id.expn_data().call_site; diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index dfb67a35e1988..9e10b8cc72195 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -130,10 +130,18 @@ impl MultiItemModifier for DeriveProcMacro { let input = tcx.arena.alloc(input.flattened()) as &TokenStream; let invoc_id = ecx.current_expansion.id; + // TODO(pr-time): Just using the crate hash to notice when the proc-macro code has + // changed. How to *correctly* depend on exactly the macro definition? + // I.e., depending on the crate hash is just a HACK (and leaves garbage in the + // incremental compilation dir). + let macro_def_id = invoc_id.expn_data().macro_def_id.unwrap(); + let proc_macro_crate_hash = tcx.crate_hash(macro_def_id.krate); + assert_eq!(invoc_id.expn_data().call_site, span); let res = crate::derive_macro_expansion::enter_context((ecx, self.client), move || { - let res = tcx.derive_macro_expansion((invoc_id, input)).cloned(); + let res = + tcx.derive_macro_expansion((invoc_id, proc_macro_crate_hash, input)).cloned(); res }); diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index 918ff15e70c55..3a81f8f0167cf 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -114,7 +114,7 @@ macro_rules! arena_types { [decode] specialization_graph: rustc_middle::traits::specialization_graph::Graph, [] crate_inherent_impls: rustc_middle::ty::CrateInherentImpls, [] hir_owner_nodes: rustc_hir::OwnerNodes<'tcx>, - [] token_stream: rustc_ast::tokenstream::TokenStream, + [decode] token_stream: rustc_ast::tokenstream::TokenStream, ]); ) } diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 7d24f28169c87..470fe5ee69d80 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -1,6 +1,7 @@ //! Defines the set of legal keys that can be used in queries. use rustc_ast::tokenstream::TokenStream; +use rustc_data_structures::svh::Svh; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LOCAL_CRATE}; use rustc_hir::hir_id::{HirId, OwnerId}; use rustc_query_system::query::{DefIdCache, DefaultCache, SingleCache, VecCache}; @@ -576,7 +577,7 @@ impl Key for (LocalDefId, HirId) { } } -impl<'tcx> Key for (LocalExpnId, &'tcx TokenStream) { +impl<'tcx> Key for (LocalExpnId, Svh, &'tcx TokenStream) { type Cache = DefaultCache; fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b11dd41624d35..018e634696898 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -104,10 +104,11 @@ pub use plumbing::{IntoQueryParam, TyCtxtAt, TyCtxtEnsure, TyCtxtEnsureWithValue // Queries marked with `fatal_cycle` do not need the latter implementation, // as they will raise an fatal error on query cycles instead. rustc_queries! { - query derive_macro_expansion(key: (LocalExpnId, &'tcx TokenStream)) -> Result<&'tcx TokenStream, ()> { - eval_always + query derive_macro_expansion(key: (LocalExpnId, Svh, &'tcx TokenStream)) -> Result<&'tcx TokenStream, ()> { + // eval_always no_hash desc { "expanding a derive (proc) macro" } + cache_on_disk_if { true } } /// This exists purely for testing the interactions between delayed bugs and incremental. diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index ca52358218e92..da6bc33feaac0 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -790,6 +790,13 @@ impl<'a, 'tcx> Decodable> } } +impl<'a, 'tcx> Decodable> for &'tcx rustc_ast::tokenstream::TokenStream { + #[inline] + fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self { + RefDecodable::decode(d) + } +} + macro_rules! impl_ref_decoder { (<$tcx:tt> $($ty:ty,)*) => { $(impl<'a, $tcx> Decodable> for &$tcx [$ty] { diff --git a/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs b/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs index cb572220aa197..a0fcadc463b8c 100644 --- a/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs +++ b/tests/incremental/derive_macro_expansion/auxiliary/derive_nothing.rs @@ -10,15 +10,11 @@ use proc_macro::TokenStream; pub fn derive(input: TokenStream) -> TokenStream { eprintln!("invoked"); - r#" + return r#" pub mod nothing_mod { - // #[cfg(cfail1)] pub fn nothing() { eprintln!("nothing"); } - - // #[cfg(cfail2)] - // fn nothingx() {} } - "#.parse().unwrap() + "#.parse().unwrap(); } diff --git a/tests/incremental/derive_macro_expansion/item_changed.rs b/tests/incremental/derive_macro_expansion/item_changed.rs deleted file mode 100644 index c89a3d1c24d33..0000000000000 --- a/tests/incremental/derive_macro_expansion/item_changed.rs +++ /dev/null @@ -1,48 +0,0 @@ -//@ aux-build:derive_nothing.rs -//@ revisions:cfail1 cfail2 -//@ compile-flags: -Z query-dep-graph -//@ check-pass (FIXME(62277): could be check-pass?) - -// TODO(pr-time): do these revisions make sense? only "check" required? - -#![feature(rustc_attrs)] -#![feature(stmt_expr_attributes)] -#![allow(dead_code)] -#![crate_type = "rlib"] - -#![rustc_partition_codegened(module="item_changed-foo", cfg="cfail1")] -// #![rustc_partition_reused(module="item_changed-foo", cfg="cfail2")] -#![rustc_partition_reused(module="item_changed-foo-nothing_mod", cfg="cfail2")] - - #[macro_use] - extern crate derive_nothing; - -pub mod foo { - // #[rustc_clean(cfg="cfail2")] - #[derive(Nothing)] - pub struct Foo; - - #[cfg(cfail2)] - pub fn second_fn() { - eprintln!("just forcing codegen"); - } - - pub fn use_foo(_f: Foo) { - // #[cfg(cfail1)] - nothing_mod::nothing(); - - // #[cfg(cfail2)] - // nothingx(); - - eprintln!("foo used"); - } -} - -// fn main() { -// Foo; -// -// nothing(); -// -// #[cfg(rpass2)] -// Bar; -// } diff --git a/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs b/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs new file mode 100644 index 0000000000000..151c9af29c2b5 --- /dev/null +++ b/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs @@ -0,0 +1,37 @@ +// This test tests that derive-macro execution is cached. +// HOWEVER, this test can currently only be checked manually, +// by running it (through compiletest) with `-- --nocapture --verbose`. +// The proc-macro (for `Nothing`) prints a message to stderr when invoked, +// and this message should only be present during the second invocation +// (which has `cfail2` set via cfg). +// TODO(pr-time): Properly have the test check this, but how? UI-test that tests for `.stderr`? + +//@ aux-build:derive_nothing.rs +//@ revisions:cfail1 cfail2 +//@ compile-flags: -Z query-dep-graph +//@ build-pass + +#![feature(rustc_attrs)] +#![feature(stmt_expr_attributes)] +#![allow(dead_code)] +#![crate_type = "rlib"] + +#![rustc_partition_codegened(module="proc_macro_unchanged-foo", cfg="cfail1")] +#![rustc_partition_codegened(module="proc_macro_unchanged-foo", cfg="cfail2")] + +// `foo::nothing_mod` is created by the derive macro and doesn't change +#![rustc_partition_reused(module="proc_macro_unchanged-foo", cfg="cfail2")] + + #[macro_use] + extern crate derive_nothing; + +pub mod foo { + #[derive(Nothing)] + pub struct Foo; + + pub fn use_foo(_f: Foo) { + nothing_mod::nothing(); + + eprintln!("foo used"); + } +} From 10657b6422ffefa0d4b687300285b29669ae0edd Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 22:23:18 +0200 Subject: [PATCH 09/14] chore: Adjust timing outputs --- compiler/rustc_expand/src/derive_macro_expansion.rs | 8 +++++--- compiler/rustc_expand/src/proc_macro.rs | 7 +++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_expand/src/derive_macro_expansion.rs b/compiler/rustc_expand/src/derive_macro_expansion.rs index aa77e5a8ba4be..33349816f3afc 100644 --- a/compiler/rustc_expand/src/derive_macro_expansion.rs +++ b/compiler/rustc_expand/src/derive_macro_expansion.rs @@ -18,10 +18,12 @@ pub(super) fn provide_derive_macro_expansion<'tcx>( let res = with_context(|(ecx, client)| { let span = invoc_id.expn_data().call_site; - let _timer = - ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| { + let _timer = ecx.sess.prof.generic_activity_with_arg_recorder( + "expand_derive_proc_macro_inner", + |recorder| { recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span); - }); + }, + ); let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace; let strategy = crate::proc_macro::exec_strategy(ecx); let server = crate::proc_macro_server::Rustc::new(ecx); diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 9e10b8cc72195..055a306438d84 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -115,6 +115,13 @@ impl MultiItemModifier for DeriveProcMacro { item: Annotatable, _is_derive_const: bool, ) -> ExpandResult, Annotatable> { + let _timer = ecx.sess.prof.generic_activity_with_arg_recorder( + "expand_derive_proc_macro_outer", + |recorder| { + recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span); + }, + ); + // We need special handling for statement items // (e.g. `fn foo() { #[derive(Debug)] struct Bar; }`) let is_stmt = matches!(item, Annotatable::Stmt(..)); From 6296fcb27ca45163948d63ae7c5bdf9bf17bb0ab Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 22:23:39 +0200 Subject: [PATCH 10/14] feat: Add `-Zcache-all-derive-macros` to use/bypass cache --- compiler/rustc_expand/src/proc_macro.rs | 9 ++++++--- compiler/rustc_session/src/options.rs | 2 ++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 055a306438d84..f22525c0ceedc 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -147,9 +147,12 @@ impl MultiItemModifier for DeriveProcMacro { assert_eq!(invoc_id.expn_data().call_site, span); let res = crate::derive_macro_expansion::enter_context((ecx, self.client), move || { - let res = - tcx.derive_macro_expansion((invoc_id, proc_macro_crate_hash, input)).cloned(); - res + let key = (invoc_id, proc_macro_crate_hash, input); + if tcx.sess.opts.unstable_opts.cache_all_derive_macros { + tcx.derive_macro_expansion(key).cloned() + } else { + crate::derive_macro_expansion::provide_derive_macro_expansion(tcx, key).cloned() + } }); res diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index a57dc80b3168d..4e76241430beb 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1654,6 +1654,8 @@ options! { "emit noalias metadata for box (default: yes)"), branch_protection: Option = (None, parse_branch_protection, [TRACKED], "set options for branch target identification and pointer authentication on AArch64"), + cache_all_derive_macros: bool = (false, parse_bool, [UNTRACKED], + "cache the results of ALL derive macro invocations (potentially unsound!) (default: no)"), cf_protection: CFProtection = (CFProtection::None, parse_cfprotection, [TRACKED], "instrument control-flow architecture protection"), check_cfg_all_expected: bool = (false, parse_bool, [UNTRACKED], From 14cb620ba3efe28d59e77f6415577291dce95734 Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 12 Aug 2024 23:43:41 +0200 Subject: [PATCH 11/14] wip: try also hashing query output --- compiler/rustc_middle/src/query/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 018e634696898..9e31ea726f82a 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -106,7 +106,7 @@ pub use plumbing::{IntoQueryParam, TyCtxtAt, TyCtxtEnsure, TyCtxtEnsureWithValue rustc_queries! { query derive_macro_expansion(key: (LocalExpnId, Svh, &'tcx TokenStream)) -> Result<&'tcx TokenStream, ()> { // eval_always - no_hash + // no_hash desc { "expanding a derive (proc) macro" } cache_on_disk_if { true } } From ae181445b1d927eb73dbdbdf58a3c29c39dc1329 Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Wed, 14 Aug 2024 18:49:21 +0200 Subject: [PATCH 12/14] prepare for PR (tidy should pass, caching=yes by default for rustc-perf) --- compiler/rustc_ast/src/tokenstream.rs | 2 +- compiler/rustc_expand/src/derive_macro_expansion.rs | 6 +++--- compiler/rustc_expand/src/proc_macro.rs | 4 ++-- compiler/rustc_session/src/options.rs | 4 ++-- .../derive_macro_expansion/proc_macro_unchanged.rs | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index 6909f5e090227..25479fabe8154 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -142,7 +142,7 @@ impl fmt::Debug for LazyAttrTokenStream { impl Encodable for LazyAttrTokenStream { fn encode(&self, _s: &mut S) { - // TODO(pr-time): Just a reminder that this exists/was tried out, + // FIXME(pr-time): Just a reminder that this exists/was tried out, // but probably not necessary anymore (see below). // self.to_attr_token_stream().encode(s) // We should not need to anymore, now that we `flatten`? diff --git a/compiler/rustc_expand/src/derive_macro_expansion.rs b/compiler/rustc_expand/src/derive_macro_expansion.rs index 33349816f3afc..9f1b95eb9cf91 100644 --- a/compiler/rustc_expand/src/derive_macro_expansion.rs +++ b/compiler/rustc_expand/src/derive_macro_expansion.rs @@ -28,7 +28,7 @@ pub(super) fn provide_derive_macro_expansion<'tcx>( let strategy = crate::proc_macro::exec_strategy(ecx); let server = crate::proc_macro_server::Rustc::new(ecx); let res = match client.run(&strategy, server, input.clone(), proc_macro_backtrace) { - // TODO(pr-time): without flattened some (weird) tests fail, but no idea if it's correct/enough + // FIXME(pr-time): without flattened some (weird) tests fail, but no idea if it's correct/enough Ok(stream) => Ok(tcx.arena.alloc(stream.flattened()) as &TokenStream), Err(e) => { ecx.dcx().emit_err({ @@ -102,11 +102,11 @@ where } else { // We could get an `CONTEXT` pointer from another thread. // Ensure that `CONTEXT` is `DynSync`. - // TODO(pr-time): we should not be able to? + // FIXME(pr-time): we should not be able to? // sync::assert_dyn_sync::>(); // prevent double entering, as that would allow creating two `&mut ExtCtxt`s - // TODO(pr-time): probably use a RefCell instead (which checks this properly)? + // FIXME(pr-time): probably use a RefCell instead (which checks this properly)? enter_context_erased((ptr::null_mut(), None), || unsafe { let ectx = downcast(ectx); f(Some(&mut (ectx, client_opt.unwrap()))) diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index f22525c0ceedc..69ce831361c33 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -133,11 +133,11 @@ impl MultiItemModifier for DeriveProcMacro { crate::base::ann_pretty_printing_compatibility_hack(&item, &ecx.sess); let input = item.to_tokens(); let res = ty::tls::with(|tcx| { - // TODO(pr-time): without flattened some (weird) tests fail, but no idea if it's correct/enough + // FIXME(pr-time): without flattened some (weird) tests fail, but no idea if it's correct/enough let input = tcx.arena.alloc(input.flattened()) as &TokenStream; let invoc_id = ecx.current_expansion.id; - // TODO(pr-time): Just using the crate hash to notice when the proc-macro code has + // FIXME(pr-time): Just using the crate hash to notice when the proc-macro code has // changed. How to *correctly* depend on exactly the macro definition? // I.e., depending on the crate hash is just a HACK (and leaves garbage in the // incremental compilation dir). diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 4e76241430beb..14e188965497b 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1654,8 +1654,8 @@ options! { "emit noalias metadata for box (default: yes)"), branch_protection: Option = (None, parse_branch_protection, [TRACKED], "set options for branch target identification and pointer authentication on AArch64"), - cache_all_derive_macros: bool = (false, parse_bool, [UNTRACKED], - "cache the results of ALL derive macro invocations (potentially unsound!) (default: no)"), + cache_all_derive_macros: bool = (true, parse_bool, [UNTRACKED], + "cache the results of ALL derive macro invocations (potentially unsound!) (default: YES -- for rustc-perf)"), cf_protection: CFProtection = (CFProtection::None, parse_cfprotection, [TRACKED], "instrument control-flow architecture protection"), check_cfg_all_expected: bool = (false, parse_bool, [UNTRACKED], diff --git a/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs b/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs index 151c9af29c2b5..3b1505b171443 100644 --- a/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs +++ b/tests/incremental/derive_macro_expansion/proc_macro_unchanged.rs @@ -4,7 +4,7 @@ // The proc-macro (for `Nothing`) prints a message to stderr when invoked, // and this message should only be present during the second invocation // (which has `cfail2` set via cfg). -// TODO(pr-time): Properly have the test check this, but how? UI-test that tests for `.stderr`? +// FIXME(pr-time): Properly have the test check this, but how? UI-test that tests for `.stderr`? //@ aux-build:derive_nothing.rs //@ revisions:cfail1 cfail2 From 55289311280831090db8e4cf4a2476fdb5cc9d6d Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 19 Aug 2024 14:53:04 +0200 Subject: [PATCH 13/14] wip: Undo unnecessary refactoring --- compiler/rustc_expand/src/expand.rs | 36 ++++++++++++++--------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 4da74befed4d9..0d56a005f159e 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -488,7 +488,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.cx.force_mode = force; let fragment_kind = invoc.fragment_kind; - match self.expand_invoc(invoc, &ext) { + match self.expand_invoc(invoc, &ext.kind) { ExpandResult::Ready(fragment) => { let mut derive_invocations = Vec::new(); let derive_placeholders = self @@ -650,7 +650,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { fn expand_invoc( &mut self, invoc: Invocation, - ext: &Lrc, + ext: &SyntaxExtensionKind, ) -> ExpandResult { let recursion_limit = match self.cx.reduced_recursion_limit { Some((limit, _)) => limit, @@ -671,7 +671,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { let (fragment_kind, span) = (invoc.fragment_kind, invoc.span()); ExpandResult::Ready(match invoc.kind { - InvocationKind::Bang { mac, span } => match &ext.kind { + InvocationKind::Bang { mac, span } => match ext { SyntaxExtensionKind::Bang(expander) => { match expander.expand(self.cx, span, mac.args.tokens.clone()) { Ok(tok_result) => { @@ -701,7 +701,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } _ => unreachable!(), }, - InvocationKind::Attr { attr, pos, mut item, derives } => match &ext.kind { + InvocationKind::Attr { attr, pos, mut item, derives } => match ext { SyntaxExtensionKind::Attr(expander) => { self.gate_proc_macro_input(&item); self.gate_proc_macro_attr_item(span, &item); @@ -780,10 +780,10 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } _ => unreachable!(), }, - InvocationKind::Derive { path, item, is_const } => match &ext.kind { + InvocationKind::Derive { path, item, is_const } => match ext { SyntaxExtensionKind::Derive(expander) | SyntaxExtensionKind::LegacyDerive(expander) => { - if let SyntaxExtensionKind::Derive(..) = ext.kind { + if let SyntaxExtensionKind::Derive(..) = ext { self.gate_proc_macro_input(&item); } // The `MetaItem` representing the trait to derive can't @@ -794,7 +794,6 @@ impl<'a, 'b> MacroExpander<'a, 'b> { span, path, }; - invoc.expansion_data.id.expn_data(); let items = match expander.expand(self.cx, span, &meta, item, is_const) { ExpandResult::Ready(items) => items, ExpandResult::Retry(item) => { @@ -811,19 +810,18 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }, InvocationKind::GlobDelegation { item } => { let AssocItemKind::DelegationMac(deleg) = &item.kind else { unreachable!() }; - let suffixes = match &ext.kind { - SyntaxExtensionKind::GlobDelegation(expander) => { - match expander.expand(self.cx) { - ExpandResult::Ready(suffixes) => suffixes, - ExpandResult::Retry(()) => { - // Reassemble the original invocation for retrying. - return ExpandResult::Retry(Invocation { - kind: InvocationKind::GlobDelegation { item }, - ..invoc - }); - } + let suffixes = match ext { + SyntaxExtensionKind::GlobDelegation(expander) => match expander.expand(self.cx) + { + ExpandResult::Ready(suffixes) => suffixes, + ExpandResult::Retry(()) => { + // Reassemble the original invocation for retrying. + return ExpandResult::Retry(Invocation { + kind: InvocationKind::GlobDelegation { item }, + ..invoc + }); } - } + }, SyntaxExtensionKind::LegacyBang(..) => { let msg = "expanded a dummy glob delegation"; let guar = self.cx.dcx().span_delayed_bug(span, msg); From 267a5c4518442c2028c8741d3230670b963712ba Mon Sep 17 00:00:00 2001 From: Felix Rath Date: Mon, 9 Sep 2024 14:56:27 +0200 Subject: [PATCH 14/14] rebase + fix unreachable pub-items, inline some CONTEXT-things --- .../src/derive_macro_expansion.rs | 75 +++++++------------ compiler/rustc_expand/src/lib.rs | 2 +- 2 files changed, 27 insertions(+), 50 deletions(-) diff --git a/compiler/rustc_expand/src/derive_macro_expansion.rs b/compiler/rustc_expand/src/derive_macro_expansion.rs index 9f1b95eb9cf91..e93779819a967 100644 --- a/compiler/rustc_expand/src/derive_macro_expansion.rs +++ b/compiler/rustc_expand/src/derive_macro_expansion.rs @@ -1,5 +1,5 @@ use std::cell::Cell; -use std::ptr; +use std::ptr::{self, NonNull}; use rustc_ast::tokenstream::TokenStream; use rustc_data_structures::svh::Svh; @@ -56,21 +56,14 @@ thread_local! { static TLV: Cell<(*mut (), Option)> = const { Cell::new((ptr::null_mut(), None)) }; } +/// Sets `context` as the new current `CONTEXT` for the duration of the function `f`. #[inline] -fn erase(context: &mut ExtCtxt<'_>) -> *mut () { - context as *mut _ as *mut () -} - -#[inline] -unsafe fn downcast<'a>(context: *mut ()) -> &'a mut ExtCtxt<'a> { - unsafe { &mut *(context as *mut ExtCtxt<'a>) } -} - -#[inline] -fn enter_context_erased(erased: (*mut (), Option), f: F) -> R +pub(crate) fn enter_context<'a, F, R>(context: (&mut ExtCtxt<'a>, CLIENT), f: F) -> R where F: FnOnce() -> R, { + let (ectx, client) = context; + let erased = (ectx as *mut _ as *mut (), Some(client)); TLV.with(|tlv| { let old = tlv.replace(erased); let _reset = rustc_data_structures::defer(move || tlv.set(old)); @@ -78,48 +71,32 @@ where }) } -/// Sets `context` as the new current `CONTEXT` for the duration of the function `f`. -#[inline] -pub fn enter_context<'a, F, R>(context: (&mut ExtCtxt<'a>, CLIENT), f: F) -> R -where - F: FnOnce() -> R, -{ - let (ectx, client) = context; - let erased = (erase(ectx), Some(client)); - enter_context_erased(erased, f) -} - -/// Allows access to the current `CONTEXT` in a closure if one is available. +/// Allows access to the current `CONTEXT`. +/// Panics if there is no `CONTEXT` available. #[inline] #[track_caller] -pub fn with_context_opt(f: F) -> R +fn with_context(f: F) -> R where - F: for<'a, 'b> FnOnce(Option<&'b mut (&mut ExtCtxt<'a>, CLIENT)>) -> R, + F: for<'a, 'b> FnOnce(&'b mut (&mut ExtCtxt<'a>, CLIENT)) -> R, { let (ectx, client_opt) = TLV.get(); - if ectx.is_null() { - f(None) - } else { - // We could get an `CONTEXT` pointer from another thread. - // Ensure that `CONTEXT` is `DynSync`. - // FIXME(pr-time): we should not be able to? - // sync::assert_dyn_sync::>(); + let ectx = NonNull::new(ectx).expect("no CONTEXT stored in tls"); - // prevent double entering, as that would allow creating two `&mut ExtCtxt`s - // FIXME(pr-time): probably use a RefCell instead (which checks this properly)? - enter_context_erased((ptr::null_mut(), None), || unsafe { - let ectx = downcast(ectx); - f(Some(&mut (ectx, client_opt.unwrap()))) - }) - } -} + // We could get an `CONTEXT` pointer from another thread. + // Ensure that `CONTEXT` is `DynSync`. + // FIXME(pr-time): we should not be able to? + // sync::assert_dyn_sync::>(); -/// Allows access to the current `CONTEXT`. -/// Panics if there is no `CONTEXT` available. -#[inline] -pub fn with_context(f: F) -> R -where - F: for<'a, 'b> FnOnce(&'b mut (&mut ExtCtxt<'a>, CLIENT)) -> R, -{ - with_context_opt(|opt_context| f(opt_context.expect("no CONTEXT stored in tls"))) + // prevent double entering, as that would allow creating two `&mut ExtCtxt`s + // FIXME(pr-time): probably use a RefCell instead (which checks this properly)? + TLV.with(|tlv| { + let old = tlv.replace((ptr::null_mut(), None)); + let _reset = rustc_data_structures::defer(move || tlv.set(old)); + let ectx = { + let mut casted = ectx.cast::>(); + unsafe { casted.as_mut() } + }; + + f(&mut (ectx, client_opt.unwrap())) + }) } diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index 587784e7e5a87..8f66605d705a6 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -29,7 +29,7 @@ mod proc_macro_server; pub use mbe::macro_rules::compile_declarative_macro; pub mod base; pub mod config; -pub(crate) mod derive_macro_expansion; +mod derive_macro_expansion; pub mod expand; pub mod module; // FIXME(Nilstrieb) Translate proc_macro diagnostics