pin_data.rs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. use crate::helpers::{parse_generics, Generics};
  3. use proc_macro::{Group, Punct, Spacing, TokenStream, TokenTree};
  4. pub(crate) fn pin_data(args: TokenStream, input: TokenStream) -> TokenStream {
  5. // This proc-macro only does some pre-parsing and then delegates the actual parsing to
  6. // `kernel::__pin_data!`.
  7. let (
  8. Generics {
  9. impl_generics,
  10. decl_generics,
  11. ty_generics,
  12. },
  13. rest,
  14. ) = parse_generics(input);
  15. // The struct definition might contain the `Self` type. Since `__pin_data!` will define a new
  16. // type with the same generics and bounds, this poses a problem, since `Self` will refer to the
  17. // new type as opposed to this struct definition. Therefore we have to replace `Self` with the
  18. // concrete name.
  19. // Errors that occur when replacing `Self` with `struct_name`.
  20. let mut errs = TokenStream::new();
  21. // The name of the struct with ty_generics.
  22. let struct_name = rest
  23. .iter()
  24. .skip_while(|tt| !matches!(tt, TokenTree::Ident(i) if i.to_string() == "struct"))
  25. .nth(1)
  26. .and_then(|tt| match tt {
  27. TokenTree::Ident(_) => {
  28. let tt = tt.clone();
  29. let mut res = vec![tt];
  30. if !ty_generics.is_empty() {
  31. // We add this, so it is maximally compatible with e.g. `Self::CONST` which
  32. // will be replaced by `StructName::<$generics>::CONST`.
  33. res.push(TokenTree::Punct(Punct::new(':', Spacing::Joint)));
  34. res.push(TokenTree::Punct(Punct::new(':', Spacing::Alone)));
  35. res.push(TokenTree::Punct(Punct::new('<', Spacing::Alone)));
  36. res.extend(ty_generics.iter().cloned());
  37. res.push(TokenTree::Punct(Punct::new('>', Spacing::Alone)));
  38. }
  39. Some(res)
  40. }
  41. _ => None,
  42. })
  43. .unwrap_or_else(|| {
  44. // If we did not find the name of the struct then we will use `Self` as the replacement
  45. // and add a compile error to ensure it does not compile.
  46. errs.extend(
  47. "::core::compile_error!(\"Could not locate type name.\");"
  48. .parse::<TokenStream>()
  49. .unwrap(),
  50. );
  51. "Self".parse::<TokenStream>().unwrap().into_iter().collect()
  52. });
  53. let impl_generics = impl_generics
  54. .into_iter()
  55. .flat_map(|tt| replace_self_and_deny_type_defs(&struct_name, tt, &mut errs))
  56. .collect::<Vec<_>>();
  57. let mut rest = rest
  58. .into_iter()
  59. .flat_map(|tt| {
  60. // We ignore top level `struct` tokens, since they would emit a compile error.
  61. if matches!(&tt, TokenTree::Ident(i) if i.to_string() == "struct") {
  62. vec![tt]
  63. } else {
  64. replace_self_and_deny_type_defs(&struct_name, tt, &mut errs)
  65. }
  66. })
  67. .collect::<Vec<_>>();
  68. // This should be the body of the struct `{...}`.
  69. let last = rest.pop();
  70. let mut quoted = quote!(::kernel::__pin_data! {
  71. parse_input:
  72. @args(#args),
  73. @sig(#(#rest)*),
  74. @impl_generics(#(#impl_generics)*),
  75. @ty_generics(#(#ty_generics)*),
  76. @decl_generics(#(#decl_generics)*),
  77. @body(#last),
  78. });
  79. quoted.extend(errs);
  80. quoted
  81. }
  82. /// Replaces `Self` with `struct_name` and errors on `enum`, `trait`, `struct` `union` and `impl`
  83. /// keywords.
  84. ///
  85. /// The error is appended to `errs` to allow normal parsing to continue.
  86. fn replace_self_and_deny_type_defs(
  87. struct_name: &Vec<TokenTree>,
  88. tt: TokenTree,
  89. errs: &mut TokenStream,
  90. ) -> Vec<TokenTree> {
  91. match tt {
  92. TokenTree::Ident(ref i)
  93. if i.to_string() == "enum"
  94. || i.to_string() == "trait"
  95. || i.to_string() == "struct"
  96. || i.to_string() == "union"
  97. || i.to_string() == "impl" =>
  98. {
  99. errs.extend(
  100. format!(
  101. "::core::compile_error!(\"Cannot use `{i}` inside of struct definition with \
  102. `#[pin_data]`.\");"
  103. )
  104. .parse::<TokenStream>()
  105. .unwrap()
  106. .into_iter()
  107. .map(|mut tok| {
  108. tok.set_span(tt.span());
  109. tok
  110. }),
  111. );
  112. vec![tt]
  113. }
  114. TokenTree::Ident(i) if i.to_string() == "Self" => struct_name.clone(),
  115. TokenTree::Literal(_) | TokenTree::Punct(_) | TokenTree::Ident(_) => vec![tt],
  116. TokenTree::Group(g) => vec![TokenTree::Group(Group::new(
  117. g.delimiter(),
  118. g.stream()
  119. .into_iter()
  120. .flat_map(|tt| replace_self_and_deny_type_defs(struct_name, tt, errs))
  121. .collect(),
  122. ))],
  123. }
  124. }