1 use proc_macro::TokenStream;
3 Token, Ident, Type, Attribute, ReturnType, Expr, Block, Error,
4 braced, parenthesized, parse_macro_input,
6 use syn::spanned::Spanned;
7 use syn::parse::{Result, Parse, ParseStream};
8 use syn::punctuated::Punctuated;
12 #[allow(non_camel_case_types)]
14 syn::custom_keyword!(query);
17 /// Ident or a wildcard `_`.
18 struct IdentOrWild(Ident);
20 impl Parse for IdentOrWild {
21 fn parse(input: ParseStream<'_>) -> Result<Self> {
22 Ok(if input.peek(Token![_]) {
23 let underscore = input.parse::<Token![_]>()?;
24 IdentOrWild(Ident::new("_", underscore.span()))
26 IdentOrWild(input.parse()?)
31 /// A modifier for a query
33 /// The description of the query.
34 Desc(Option<Ident>, Punctuated<Expr, Token![,]>),
36 /// Cache the query to disk if the `Expr` returns true.
37 Cache(Option<Ident>, Expr),
39 /// Custom code to load the query from disk.
40 LoadCached(Ident, Ident, Block),
42 /// A cycle error for this query aborting the compilation with a fatal error.
46 impl Parse for QueryModifier {
47 fn parse(input: ParseStream<'_>) -> Result<Self> {
48 let modifier: Ident = input.parse()?;
49 if modifier == "desc" {
50 // Parse a description modifier like:
51 // `desc { |tcx| "foo {}", tcx.item_path(key) }`
53 braced!(attr_content in input);
54 let tcx = if attr_content.peek(Token![|]) {
55 attr_content.parse::<Token![|]>()?;
56 let tcx = attr_content.parse()?;
57 attr_content.parse::<Token![|]>()?;
62 let desc = attr_content.parse_terminated(Expr::parse)?;
63 Ok(QueryModifier::Desc(tcx, desc))
64 } else if modifier == "cache" {
65 // Parse a cache modifier like:
66 // `cache { |tcx| key.is_local() }`
68 braced!(attr_content in input);
69 let tcx = if attr_content.peek(Token![|]) {
70 attr_content.parse::<Token![|]>()?;
71 let tcx = attr_content.parse()?;
72 attr_content.parse::<Token![|]>()?;
77 let expr = attr_content.parse()?;
78 Ok(QueryModifier::Cache(tcx, expr))
79 } else if modifier == "load_cached" {
80 // Parse a load_cached modifier like:
81 // `load_cached(tcx, id) { tcx.queries.on_disk_cache.try_load_query_result(tcx, id) }`
83 parenthesized!(args in input);
84 let tcx = args.parse()?;
85 args.parse::<Token![,]>()?;
86 let id = args.parse()?;
87 let block = input.parse()?;
88 Ok(QueryModifier::LoadCached(tcx, id, block))
89 } else if modifier == "fatal_cycle" {
90 Ok(QueryModifier::FatalCycle)
92 Err(Error::new(modifier.span(), "unknown query modifier"))
97 /// Ensures only doc comment attributes are used
98 fn check_attributes(attrs: Vec<Attribute>) -> Result<()> {
100 if !attr.path.is_ident("doc") {
101 return Err(Error::new(attr.span(), "attributes not supported on queries"));
107 /// A compiler query. `query ... { ... }`
109 modifiers: List<QueryModifier>,
116 impl Parse for Query {
117 fn parse(input: ParseStream<'_>) -> Result<Self> {
118 check_attributes(input.call(Attribute::parse_outer)?)?;
120 // Parse the query declaration. Like `query type_of(key: DefId) -> Ty<'tcx>`
121 input.parse::<kw::query>()?;
122 let name: Ident = input.parse()?;
124 parenthesized!(arg_content in input);
125 let key = arg_content.parse()?;
126 arg_content.parse::<Token![:]>()?;
127 let arg = arg_content.parse()?;
128 let result = input.parse()?;
130 // Parse the query modifiers
132 braced!(content in input);
133 let modifiers = content.parse()?;
145 /// A type used to greedily parse another type until the input is empty.
146 struct List<T>(Vec<T>);
148 impl<T: Parse> Parse for List<T> {
149 fn parse(input: ParseStream<'_>) -> Result<Self> {
150 let mut list = Vec::new();
151 while !input.is_empty() {
152 list.push(input.parse()?);
158 /// A named group containing queries.
161 queries: List<Query>,
164 impl Parse for Group {
165 fn parse(input: ParseStream<'_>) -> Result<Self> {
166 let name: Ident = input.parse()?;
168 braced!(content in input);
171 queries: content.parse()?,
176 struct QueryModifiers {
177 /// The description of the query.
178 desc: Option<(Option<Ident>, Punctuated<Expr, Token![,]>)>,
180 /// Cache the query to disk if the `Expr` returns true.
181 cache: Option<(Option<Ident>, Expr)>,
183 /// Custom code to load the query from disk.
184 load_cached: Option<(Ident, Ident, Block)>,
186 /// A cycle error for this query aborting the compilation with a fatal error.
190 /// Process query modifiers into a struct, erroring on duplicates
191 fn process_modifiers(query: &mut Query) -> QueryModifiers {
192 let mut load_cached = None;
193 let mut cache = None;
195 let mut fatal_cycle = false;
196 for modifier in query.modifiers.0.drain(..) {
198 QueryModifier::LoadCached(tcx, id, block) => {
199 if load_cached.is_some() {
200 panic!("duplicate modifier `load_cached` for query `{}`", query.name);
202 load_cached = Some((tcx, id, block));
204 QueryModifier::Cache(tcx, expr) => {
206 panic!("duplicate modifier `cache` for query `{}`", query.name);
208 cache = Some((tcx, expr));
210 QueryModifier::Desc(tcx, list) => {
212 panic!("duplicate modifier `desc` for query `{}`", query.name);
214 desc = Some((tcx, list));
216 QueryModifier::FatalCycle => {
218 panic!("duplicate modifier `fatal_cycle` for query `{}`", query.name);
232 /// Add the impl of QueryDescription for the query to `impls` if one is requested
233 fn add_query_description_impl(
235 modifiers: QueryModifiers,
236 impls: &mut proc_macro2::TokenStream
238 let name = &query.name;
239 let arg = &query.arg;
240 let key = &query.key.0;
242 // Find out if we should cache the query on disk
243 let cache = modifiers.cache.as_ref().map(|(tcx, expr)| {
244 let try_load_from_disk = if let Some((tcx, id, block)) = modifiers.load_cached.as_ref() {
245 // Use custom code to load the query from disk
248 fn try_load_from_disk(
249 #tcx: TyCtxt<'_, 'tcx, 'tcx>,
250 #id: SerializedDepNodeIndex
251 ) -> Option<Self::Value> {
256 // Use the default code to load the query from disk
259 fn try_load_from_disk(
260 tcx: TyCtxt<'_, 'tcx, 'tcx>,
261 id: SerializedDepNodeIndex
262 ) -> Option<Self::Value> {
263 tcx.queries.on_disk_cache.try_load_query_result(tcx, id)
268 let tcx = tcx.as_ref().map(|t| quote! { #t }).unwrap_or(quote! { _ });
271 fn cache_on_disk(#tcx: TyCtxt<'_, 'tcx, 'tcx>, #key: Self::Key) -> bool {
279 if cache.is_none() && modifiers.load_cached.is_some() {
280 panic!("load_cached modifier on query `{}` without a cache modifier", name);
283 let desc = modifiers.desc.as_ref().map(|(tcx, desc)| {
284 let tcx = tcx.as_ref().map(|t| quote! { #t }).unwrap_or(quote! { _ });
287 #tcx: TyCtxt<'_, '_, '_>,
289 ) -> Cow<'static, str> {
290 format!(#desc).into()
295 if desc.is_some() || cache.is_some() {
296 let cache = cache.unwrap_or(quote! {});
297 let desc = desc.unwrap_or(quote! {});
299 impls.extend(quote! {
300 impl<'tcx> QueryDescription<'tcx> for queries::#name<'tcx> {
308 pub fn rustc_queries(input: TokenStream) -> TokenStream {
309 let groups = parse_macro_input!(input as List<Group>);
311 let mut query_stream = quote! {};
312 let mut query_description_stream = quote! {};
313 let mut dep_node_def_stream = quote! {};
314 let mut dep_node_force_stream = quote! {};
316 for group in groups.0 {
317 let mut group_stream = quote! {};
318 for mut query in group.queries.0 {
319 let modifiers = process_modifiers(&mut query);
320 let name = &query.name;
321 let arg = &query.arg;
322 let result_full = &query.result;
323 let result = match query.result {
324 ReturnType::Default => quote! { -> () },
325 _ => quote! { #result_full },
328 // Pass on the fatal_cycle modifier
329 let fatal_cycle = if modifiers.fatal_cycle {
330 quote! { fatal_cycle }
335 // Add the query to the group
336 group_stream.extend(quote! {
337 [#fatal_cycle] fn #name: #name(#arg) #result,
340 add_query_description_impl(&query, modifiers, &mut query_description_stream);
342 // Create a dep node for the query
343 dep_node_def_stream.extend(quote! {
347 // Add a match arm to force the query given the dep node
348 dep_node_force_stream.extend(quote! {
350 if let Some(key) = RecoverKey::recover($tcx, $dep_node) {
351 force_ex!($tcx, #name, key);
358 let name = &group.name;
359 query_stream.extend(quote! {
360 #name { #group_stream },
363 TokenStream::from(quote! {
364 macro_rules! rustc_query_append {
365 ([$($macro:tt)*][$($other:tt)*]) => {
374 macro_rules! rustc_dep_node_append {
375 ([$($macro:tt)*][$($other:tt)*]) => {
383 macro_rules! rustc_dep_node_force {
384 ([$dep_node:expr, $tcx:expr] $($other:tt)*) => {
385 match $dep_node.kind {
388 #dep_node_force_stream
392 #query_description_stream