vtable.rs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-License-Identifier: GPL-2.0
  2. use proc_macro::{Delimiter, Group, TokenStream, TokenTree};
  3. use std::collections::HashSet;
  4. use std::fmt::Write;
  5. pub(crate) fn vtable(_attr: TokenStream, ts: TokenStream) -> TokenStream {
  6. let mut tokens: Vec<_> = ts.into_iter().collect();
  7. // Scan for the `trait` or `impl` keyword.
  8. let is_trait = tokens
  9. .iter()
  10. .find_map(|token| match token {
  11. TokenTree::Ident(ident) => match ident.to_string().as_str() {
  12. "trait" => Some(true),
  13. "impl" => Some(false),
  14. _ => None,
  15. },
  16. _ => None,
  17. })
  18. .expect("#[vtable] attribute should only be applied to trait or impl block");
  19. // Retrieve the main body. The main body should be the last token tree.
  20. let body = match tokens.pop() {
  21. Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => group,
  22. _ => panic!("cannot locate main body of trait or impl block"),
  23. };
  24. let mut body_it = body.stream().into_iter();
  25. let mut functions = Vec::new();
  26. let mut consts = HashSet::new();
  27. while let Some(token) = body_it.next() {
  28. match token {
  29. TokenTree::Ident(ident) if ident.to_string() == "fn" => {
  30. let fn_name = match body_it.next() {
  31. Some(TokenTree::Ident(ident)) => ident.to_string(),
  32. // Possibly we've encountered a fn pointer type instead.
  33. _ => continue,
  34. };
  35. functions.push(fn_name);
  36. }
  37. TokenTree::Ident(ident) if ident.to_string() == "const" => {
  38. let const_name = match body_it.next() {
  39. Some(TokenTree::Ident(ident)) => ident.to_string(),
  40. // Possibly we've encountered an inline const block instead.
  41. _ => continue,
  42. };
  43. consts.insert(const_name);
  44. }
  45. _ => (),
  46. }
  47. }
  48. let mut const_items;
  49. if is_trait {
  50. const_items = "
  51. /// A marker to prevent implementors from forgetting to use [`#[vtable]`](vtable)
  52. /// attribute when implementing this trait.
  53. const USE_VTABLE_ATTR: ();
  54. "
  55. .to_owned();
  56. for f in functions {
  57. let gen_const_name = format!("HAS_{}", f.to_uppercase());
  58. // Skip if it's declared already -- this allows user override.
  59. if consts.contains(&gen_const_name) {
  60. continue;
  61. }
  62. // We don't know on the implementation-site whether a method is required or provided
  63. // so we have to generate a const for all methods.
  64. write!(
  65. const_items,
  66. "/// Indicates if the `{f}` method is overridden by the implementor.
  67. const {gen_const_name}: bool = false;",
  68. )
  69. .unwrap();
  70. consts.insert(gen_const_name);
  71. }
  72. } else {
  73. const_items = "const USE_VTABLE_ATTR: () = ();".to_owned();
  74. for f in functions {
  75. let gen_const_name = format!("HAS_{}", f.to_uppercase());
  76. if consts.contains(&gen_const_name) {
  77. continue;
  78. }
  79. write!(const_items, "const {gen_const_name}: bool = true;").unwrap();
  80. }
  81. }
  82. let new_body = vec![const_items.parse().unwrap(), body.stream()]
  83. .into_iter()
  84. .collect();
  85. tokens.push(TokenTree::Group(Group::new(Delimiter::Brace, new_body)));
  86. tokens.into_iter().collect()
  87. }