runtime.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use proc_macro2::TokenStream;
  5. use quote::quote;
  6. use syn::parse::{Parse, ParseStream};
  7. use syn::{parse_quote, DeriveInput, GenericParam, Ident, Token, Type, TypeParam};
  8. /// The default runtime type to enable when the provided feature is enabled.
  9. pub(crate) struct Attributes {
  10. default_type: Type,
  11. feature: Ident,
  12. }
  13. impl Parse for Attributes {
  14. fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
  15. let default_type = input.parse()?;
  16. input.parse::<Token![,]>()?;
  17. Ok(Attributes {
  18. default_type,
  19. feature: input.parse()?,
  20. })
  21. }
  22. }
  23. pub(crate) fn default_runtime(attributes: Attributes, input: DeriveInput) -> TokenStream {
  24. // create a new copy to manipulate for the wry feature flag
  25. let mut wry = input.clone();
  26. let wry_runtime = wry
  27. .generics
  28. .params
  29. .last_mut()
  30. .expect("default_runtime requires the item to have at least 1 generic parameter");
  31. // set the default value of the last generic parameter to the provided runtime type
  32. match wry_runtime {
  33. GenericParam::Type(
  34. param @ TypeParam {
  35. eq_token: None,
  36. default: None,
  37. ..
  38. },
  39. ) => {
  40. param.eq_token = Some(parse_quote!(=));
  41. param.default = Some(attributes.default_type);
  42. }
  43. _ => {
  44. panic!("DefaultRuntime requires the last parameter to not have a default value")
  45. }
  46. };
  47. let feature = attributes.feature.to_string();
  48. quote!(
  49. #[cfg(feature = #feature)]
  50. #wry
  51. #[cfg(not(feature = #feature))]
  52. #input
  53. )
  54. }