helpers.rs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // SPDX-License-Identifier: GPL-2.0
  2. use proc_macro2::TokenStream;
  3. use quote::ToTokens;
  4. use syn::{
  5. parse::{
  6. Parse,
  7. ParseStream, //
  8. },
  9. Attribute,
  10. Error,
  11. LitStr,
  12. Result, //
  13. };
  14. /// A string literal that is required to have ASCII value only.
  15. pub(crate) struct AsciiLitStr(LitStr);
  16. impl Parse for AsciiLitStr {
  17. fn parse(input: ParseStream<'_>) -> Result<Self> {
  18. let s: LitStr = input.parse()?;
  19. if !s.value().is_ascii() {
  20. return Err(Error::new_spanned(s, "expected ASCII-only string literal"));
  21. }
  22. Ok(Self(s))
  23. }
  24. }
  25. impl ToTokens for AsciiLitStr {
  26. fn to_tokens(&self, ts: &mut TokenStream) {
  27. self.0.to_tokens(ts);
  28. }
  29. }
  30. impl AsciiLitStr {
  31. pub(crate) fn value(&self) -> String {
  32. self.0.value()
  33. }
  34. }
  35. pub(crate) fn file() -> String {
  36. #[cfg(not(CONFIG_RUSTC_HAS_SPAN_FILE))]
  37. {
  38. proc_macro::Span::call_site()
  39. .source_file()
  40. .path()
  41. .to_string_lossy()
  42. .into_owned()
  43. }
  44. #[cfg(CONFIG_RUSTC_HAS_SPAN_FILE)]
  45. #[allow(clippy::incompatible_msrv)]
  46. {
  47. proc_macro::Span::call_site().file()
  48. }
  49. }
  50. /// Obtain all `#[cfg]` attributes.
  51. pub(crate) fn gather_cfg_attrs(attr: &[Attribute]) -> impl Iterator<Item = &Attribute> + '_ {
  52. attr.iter().filter(|a| a.path().is_ident("cfg"))
  53. }