File size: 13,660 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
use proc_macro::TokenStream;
use proc_macro2::{Ident, TokenStream as TokenStream2};
use quote::{ToTokens, quote};
use syn::{
Error, Expr, ExprLit, Generics, ImplItem, ImplItemFn, ItemImpl, Lit, LitStr, Meta,
MetaNameValue, Path, Token, Type,
parse::{Parse, ParseStream},
parse_macro_input, parse_quote,
spanned::Spanned,
};
use turbo_tasks_macros_shared::{
get_inherent_impl_function_ident, get_path_ident, get_register_trait_impls_ident,
get_register_trait_methods_ident, get_trait_impl_function_ident, get_type_ident, is_self_used,
};
use crate::func::{
DefinitionContext, FunctionArguments, NativeFn, TurboFn, filter_inline_attributes,
split_function_attributes,
};
struct ValueImplArguments {
ident: Option<LitStr>,
}
impl Parse for ValueImplArguments {
fn parse(input: ParseStream) -> syn::Result<Self> {
let mut result = ValueImplArguments { ident: None };
let punctuated = input.parse_terminated(Meta::parse, Token![,])?;
for meta in punctuated {
match (
meta.path()
.get_ident()
.map(ToString::to_string)
.as_deref()
.unwrap_or_default(),
meta,
) {
(
"ident",
Meta::NameValue(MetaNameValue {
value:
Expr::Lit(ExprLit {
lit: Lit::Str(lit), ..
}),
..
}),
) => {
result.ident = Some(lit);
}
(_, meta) => {
return Err(Error::new_spanned(
&meta,
format!("unexpected {meta:?}, expected \"ident\""),
));
}
}
}
Ok(result)
}
}
pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
let ValueImplArguments { ident } = parse_macro_input!(args as ValueImplArguments);
fn inherent_value_impl(ty: &Type, ty_ident: &Ident, items: &[ImplItem]) -> TokenStream2 {
let mut all_definitions = Vec::new();
let mut exposed_impl_items = Vec::new();
let mut errors = Vec::new();
for item in items.iter() {
if let ImplItem::Fn(ImplItemFn {
attrs,
vis,
defaultness: _,
sig,
block,
}) = item
{
let ident = &sig.ident;
let (func_args, attrs) = split_function_attributes(attrs);
let func_args = match func_args {
Ok(None) => {
item.span()
.unwrap()
.error("#[turbo_tasks::function] attribute missing")
.emit();
FunctionArguments::default()
}
Ok(Some(func_args)) => func_args,
Err(error) => {
errors.push(error.to_compile_error());
FunctionArguments::default()
}
};
let local = func_args.local.is_some();
let is_self_used = func_args.operation.is_some() || is_self_used(block);
let Some(turbo_fn) =
TurboFn::new(sig, DefinitionContext::ValueInherentImpl, func_args)
else {
return quote! {
// An error occurred while parsing the function signature.
};
};
let inline_function_ident = turbo_fn.inline_ident();
let (inline_signature, inline_block) =
turbo_fn.inline_signature_and_block(block, is_self_used);
let inline_attrs = filter_inline_attributes(attrs.iter().copied());
let native_fn = NativeFn {
function_path_string: format!("{ty}::{ident}", ty = ty.to_token_stream()),
function_path: parse_quote! { <#ty>::#inline_function_ident },
is_method: turbo_fn.is_method(),
is_self_used,
filter_trait_call_args: None, // not a trait method
local,
};
let native_function_ident = get_inherent_impl_function_ident(ty_ident, ident);
let native_function_ty = native_fn.ty();
let native_function_def = native_fn.definition();
let turbo_signature = turbo_fn.signature();
let turbo_block = turbo_fn.static_block(&native_function_ident);
exposed_impl_items.push(quote! {
#(#attrs)*
#vis #turbo_signature #turbo_block
});
all_definitions.push(quote! {
#[doc(hidden)]
impl #ty {
// By declaring the native function's body within an `impl` block, we ensure
// that `Self` refers to `#ty`. This is necessary because the function's
// body is originally declared within an `impl` block already.
#(#inline_attrs)*
#[doc(hidden)]
#[deprecated(note = "This function is only exposed for use in macros. Do not call it directly.")]
pub(self) #inline_signature #inline_block
}
#[doc(hidden)]
pub(crate) static #native_function_ident:
turbo_tasks::macro_helpers::Lazy<#native_function_ty> =
turbo_tasks::macro_helpers::Lazy::new(|| #native_function_def);
})
}
}
quote! {
impl #ty {
#(#exposed_impl_items)*
}
#(#all_definitions)*
#(#errors)*
}
}
fn trait_value_impl(
ty: &Type,
generics: &Generics,
ty_ident: &Ident,
trait_path: &Path,
items: &[ImplItem],
) -> TokenStream2 {
let trait_ident = get_path_ident(trait_path);
let (impl_generics, _, where_clause) = generics.split_for_impl();
let register_trait_methods: Ident =
get_register_trait_methods_ident(&trait_ident, ty_ident);
let register_trait_impls: Ident = get_register_trait_impls_ident(&trait_ident, ty_ident);
let mut trait_registers = Vec::new();
let mut trait_functions = Vec::with_capacity(items.len());
let mut trait_items = Vec::new();
let mut all_definitions = Vec::with_capacity(items.len());
let mut errors = Vec::new();
for item in items.iter() {
if let ImplItem::Fn(ImplItemFn {
sig, attrs, block, ..
}) = item
{
let ident = &sig.ident;
let (func_args, attrs) = split_function_attributes(attrs);
let func_args = match func_args {
Ok(None) => {
// Missing annotations are allowed if a turbo tasks trait has a trait item
// that is not a turbo tasks function.
trait_items.push(item);
continue;
}
Ok(Some(func_args)) => func_args,
Err(error) => {
errors.push(error.to_compile_error());
continue;
}
};
let local = func_args.local.is_some();
let is_self_used = func_args.operation.is_some() || is_self_used(block);
let Some(turbo_fn) =
TurboFn::new(sig, DefinitionContext::ValueTraitImpl, func_args)
else {
return quote! {
// An error occurred while parsing the function signature.
};
};
let inline_function_ident = turbo_fn.inline_ident();
let inline_extension_trait_ident = Ident::new(
&format!("{ty_ident}_{trait_ident}_{ident}_inline"),
ident.span(),
);
let (inline_signature, inline_block) =
turbo_fn.inline_signature_and_block(block, is_self_used);
let inline_attrs = filter_inline_attributes(attrs.iter().copied());
let native_fn = NativeFn {
function_path_string: format!(
"<{ty} as {trait_path}>::{ident}",
ty = ty.to_token_stream(),
trait_path = trait_path.to_token_stream()
),
function_path: parse_quote! {
<#ty as #inline_extension_trait_ident>::#inline_function_ident
},
is_method: turbo_fn.is_method(),
is_self_used,
filter_trait_call_args: turbo_fn.filter_trait_call_args(),
local,
};
let native_function_ident =
get_trait_impl_function_ident(ty_ident, &trait_ident, ident);
let native_function_ty = native_fn.ty();
let native_function_def = native_fn.definition();
let turbo_signature = turbo_fn.signature();
let turbo_block = turbo_fn.static_block(&native_function_ident);
trait_functions.push(quote! {
#(#attrs)*
#turbo_signature #turbo_block
});
all_definitions.push(quote! {
#[doc(hidden)]
#[allow(non_camel_case_types)]
trait #inline_extension_trait_ident: std::marker::Send {
#(#inline_attrs)*
#[doc(hidden)]
#inline_signature;
}
#[doc(hidden)]
impl #impl_generics #inline_extension_trait_ident for #ty #where_clause {
#(#inline_attrs)*
#[doc(hidden)]
#[deprecated(note = "This function is only exposed for use in macros. Do not call it directly.")]
#inline_signature #inline_block
}
#[doc(hidden)]
pub(crate) static #native_function_ident:
turbo_tasks::macro_helpers::Lazy<#native_function_ty> =
turbo_tasks::macro_helpers::Lazy::new(|| #native_function_def);
});
trait_registers.push(quote! {
value.register_trait_method(
<Box<dyn #trait_path> as turbo_tasks::VcValueTrait>::get_trait_type_id(),
stringify!(#ident),
&#native_function_ident);
});
}
}
quote! {
#[doc(hidden)]
#[allow(non_snake_case)]
pub(crate) fn #register_trait_methods(value: &mut turbo_tasks::ValueType) {
value.register_trait(<Box<dyn #trait_path> as turbo_tasks::VcValueTrait>::get_trait_type_id());
#(#trait_registers)*
}
#[doc(hidden)]
#[allow(non_snake_case)]
pub(crate) fn #register_trait_impls(value_id: turbo_tasks::ValueTypeId) {
// NOTE(lukesandberg): This relies on the nightly ptr_metadata feature. Alternatively
// we could generate a function that does the downcasting and pass that up to register_trait.
// This would avoid the nightly feature.
let fat_pointer: *const dyn #trait_path = ::std::ptr::null::<#ty>() as *const dyn #trait_path;
let metadata = turbo_tasks::macro_helpers::metadata(fat_pointer);
turbo_tasks::macro_helpers::register_trait_impl::<dyn #trait_path, Box<dyn #trait_path>>(value_id, metadata);
}
// NOTE(alexkirsz) We can't have a general `turbo_tasks::Upcast<Box<dyn Trait>> for T where T: Trait` because
// rustc complains: error[E0210]: type parameter `T` must be covered by another type when it appears before
// the first local type (`dyn Trait`).
unsafe impl #impl_generics turbo_tasks::Upcast<Box<dyn #trait_path>> for #ty #where_clause {}
impl #impl_generics #trait_path for #ty #where_clause {
#(#trait_items)*
#(#trait_functions)*
}
#(#all_definitions)*
#(#errors)*
}
}
let item = parse_macro_input!(input as ItemImpl);
let Some(ty_ident) = ident
.map(|ident| Ident::new(&ident.value(), ident.span()))
.or_else(|| get_type_ident(&item.self_ty))
else {
return quote! {
// An error occurred while parsing the type.
}
.into();
};
match &item.trait_ {
None => inherent_value_impl(&item.self_ty, &ty_ident, &item.items).into(),
Some((_, trait_path, _)) => trait_value_impl(
&item.self_ty,
&item.generics,
&ty_ident,
trait_path,
&item.items,
)
.into(),
}
}
|