Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 use std::error::Error as StdError;
2 use std::str::FromStr;
3
4 use proc_macro::TokenStream;
5 use proc_macro2::{Span, TokenStream as TokenStream2};
6 use quote::quote;
7 use syn::{
8 fold::{self, Fold},
9 parse_quote,
10 punctuated::Punctuated,
11 token::Comma,
12 Error, Expr, Item, Stmt,
13 };
14
15 #[derive(PartialEq, Eq)]
16 struct Version {
17 major: usize,
18 minor: usize,
19 }
20
21 impl FromStr for Version {
22 type Err = Box<dyn StdError>;
23
24 fn from_str(s: &str) -> Result<Self, Self::Err> {
25 let (major_str, minor_str) = s
26 .split_once('.')
27 .ok_or_else(|| Self::Err::from("missing `.`".to_owned()))?;
28
29 Ok(Self {
30 major: major_str.parse()?,
31 minor: minor_str.parse()?,
32 })
33 }
34 }
35
36 impl Version {
37 fn as_ident(&self) -> syn::Ident {
38 syn::Ident::new(
39 &format!("v{}_{}", self.major, self.minor),
40 Span::call_site(),
41 )
42 }
43 }
44
45 enum VersionReq {
46 Any(Vec<Version>),
47 }
48
49 impl syn::parse::Parse for VersionReq {
50 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
51 let versions = Punctuated::<syn::LitStr, Comma>::parse_terminated(input)?
52 .into_iter()
53 .map(|s| s.value().parse().map_err(|err| Error::new(s.span(), err)))
54 .collect::<syn::Result<Vec<Version>>>()?;
55
56 Ok(Self::Any(versions))
57 }
58 }
59
60 impl VersionReq {
61 fn matches(&self, version: &Version) -> bool {
62 match self {
63 VersionReq::Any(versions) => versions.contains(version),
64 }
65 }
66 }
67
68 struct VersionFilter {
69 version: Version,
70 error: Option<Error>,
71 }
72
73 impl VersionFilter {
74 fn is_active(&mut self, attrs: &mut Vec<syn::Attribute>) -> bool {
75 let mut matches = true;
76
77 attrs.retain(|attr| {
78 let path = attr.path();
79
80 if path.is_ident("versioned") {
81 match attr.parse_args::<VersionReq>() {
82 Ok(req) => matches = req.matches(&self.version),
83 Err(err) => match self.error.as_mut() {
84 Some(error) => error.combine(err),
85 None => self.error = Some(err),
86 },
87 }
88
89 false
90 } else {
91 true
92 }
93 });
94
95 matches
96 }
97
98 fn filter_fields(
99 &mut self,
100 fields: Punctuated<syn::Field, Comma>,
101 ) -> Punctuated<syn::Field, Comma> {
102 fields
103 .into_pairs()
104 .filter_map(|mut pair| self.is_active(&mut pair.value_mut().attrs).then_some(pair))
105 .collect()
106 }
107 }
108
109 impl Fold for VersionFilter {
110 fn fold_fields_named(&mut self, mut fields: syn::FieldsNamed) -> syn::FieldsNamed {
111 fields.named = self.filter_fields(fields.named);
112 fields
113 }
114
115 fn fold_fields_unnamed(&mut self, mut fields: syn::FieldsUnnamed) -> syn::FieldsUnnamed {
116 fields.unnamed = self.filter_fields(fields.unnamed);
117 fields
118 }
119
120 fn fold_stmt(&mut self, mut stmt: Stmt) -> Stmt {
121 if let Stmt::Local(syn::Local { ref mut attrs, .. })
122 | Stmt::Macro(syn::StmtMacro { ref mut attrs, .. }) = &mut stmt
123 {
124 if !self.is_active(attrs) {
125 stmt = Stmt::Item(Item::Verbatim(TokenStream2::new()));
126 }
127 }
128
129 fold::fold_stmt(self, stmt)
130 }
131
132 fn fold_expr(&mut self, mut expr: Expr) -> Expr {
133 if let Expr::Array(syn::ExprArray { ref mut attrs, .. })
134 | Expr::Assign(syn::ExprAssign { ref mut attrs, .. })
135 | Expr::Async(syn::ExprAsync { ref mut attrs, .. })
136 | Expr::Await(syn::ExprAwait { ref mut attrs, .. })
137 | Expr::Binary(syn::ExprBinary { ref mut attrs, .. })
138 | Expr::Block(syn::ExprBlock { ref mut attrs, .. })
139 | Expr::Break(syn::ExprBreak { ref mut attrs, .. })
140 | Expr::Call(syn::ExprCall { ref mut attrs, .. })
141 | Expr::Cast(syn::ExprCast { ref mut attrs, .. })
142 | Expr::Closure(syn::ExprClosure { ref mut attrs, .. })
143 | Expr::Const(syn::ExprConst { ref mut attrs, .. })
144 | Expr::Continue(syn::ExprContinue { ref mut attrs, .. })
145 | Expr::Field(syn::ExprField { ref mut attrs, .. })
146 | Expr::ForLoop(syn::ExprForLoop { ref mut attrs, .. })
147 | Expr::Group(syn::ExprGroup { ref mut attrs, .. })
148 | Expr::If(syn::ExprIf { ref mut attrs, .. })
149 | Expr::Index(syn::ExprIndex { ref mut attrs, .. })
150 | Expr::Infer(syn::ExprInfer { ref mut attrs, .. })
151 | Expr::Let(syn::ExprLet { ref mut attrs, .. })
152 | Expr::Lit(syn::ExprLit { ref mut attrs, .. })
153 | Expr::Loop(syn::ExprLoop { ref mut attrs, .. })
154 | Expr::Macro(syn::ExprMacro { ref mut attrs, .. })
155 | Expr::Match(syn::ExprMatch { ref mut attrs, .. })
156 | Expr::MethodCall(syn::ExprMethodCall { ref mut attrs, .. })
157 | Expr::Paren(syn::ExprParen { ref mut attrs, .. })
158 | Expr::Path(syn::ExprPath { ref mut attrs, .. })
159 | Expr::Range(syn::ExprRange { ref mut attrs, .. })
160 | Expr::Reference(syn::ExprReference { ref mut attrs, .. })
161 | Expr::Repeat(syn::ExprRepeat { ref mut attrs, .. })
162 | Expr::Return(syn::ExprReturn { ref mut attrs, .. })
163 | Expr::Struct(syn::ExprStruct { ref mut attrs, .. })
164 | Expr::Try(syn::ExprTry { ref mut attrs, .. })
165 | Expr::TryBlock(syn::ExprTryBlock { ref mut attrs, .. })
166 | Expr::Tuple(syn::ExprTuple { ref mut attrs, .. })
167 | Expr::Unary(syn::ExprUnary { ref mut attrs, .. })
168 | Expr::Unsafe(syn::ExprUnsafe { ref mut attrs, .. })
169 | Expr::While(syn::ExprWhile { ref mut attrs, .. })
170 | Expr::Yield(syn::ExprYield { ref mut attrs, .. }) = &mut expr
171 {
172 if !self.is_active(attrs) {
173 expr = parse_quote!({});
174 }
175 }
176
177 fold::fold_expr(self, expr)
178 }
179
180 fn fold_expr_struct(&mut self, mut expr: syn::ExprStruct) -> syn::ExprStruct {
181 expr.fields = expr
182 .fields
183 .into_pairs()
184 .filter_map(|mut pair| self.is_active(&mut pair.value_mut().attrs).then_some(pair))
185 .collect();
186
187 fold::fold_expr_struct(self, expr)
188 }
189
190 fn fold_expr_match(&mut self, mut expr: syn::ExprMatch) -> syn::ExprMatch {
191 expr.arms.retain_mut(|arm| self.is_active(&mut arm.attrs));
192
193 fold::fold_expr_match(self, expr)
194 }
195
196 fn fold_item(&mut self, mut item: Item) -> Item {
197 if let Item::Const(syn::ItemConst { ref mut attrs, .. })
198 | Item::Enum(syn::ItemEnum { ref mut attrs, .. })
199 | Item::ExternCrate(syn::ItemExternCrate { ref mut attrs, .. })
200 | Item::Fn(syn::ItemFn { ref mut attrs, .. })
201 | Item::ForeignMod(syn::ItemForeignMod { ref mut attrs, .. })
202 | Item::Impl(syn::ItemImpl { ref mut attrs, .. })
203 | Item::Macro(syn::ItemMacro { ref mut attrs, .. })
204 | Item::Mod(syn::ItemMod { ref mut attrs, .. })
205 | Item::Static(syn::ItemStatic { ref mut attrs, .. })
206 | Item::Struct(syn::ItemStruct { ref mut attrs, .. })
207 | Item::Trait(syn::ItemTrait { ref mut attrs, .. })
208 | Item::TraitAlias(syn::ItemTraitAlias { ref mut attrs, .. })
209 | Item::Type(syn::ItemType { ref mut attrs, .. })
210 | Item::Union(syn::ItemUnion { ref mut attrs, .. })
211 | Item::Use(syn::ItemUse { ref mut attrs, .. }) = &mut item
212 {
213 if !self.is_active(attrs) {
214 item = Item::Verbatim(TokenStream2::new());
215 }
216 }
217
218 fold::fold_item(self, item)
219 }
220
221 fn fold_item_enum(&mut self, mut item: syn::ItemEnum) -> syn::ItemEnum {
222 item.variants = item
223 .variants
224 .into_iter()
225 .filter_map(|mut variant| self.is_active(&mut variant.attrs).then_some(variant))
226 .collect();
227
228 fold::fold_item_enum(self, item)
229 }
230 }
231
232 fn helper(input: TokenStream, annotated_item: TokenStream) -> syn::Result<TokenStream2> {
233 // This parses the module being annotated by the `#[versioned(..)]` attribute.
234 let module = syn::parse::<syn::ItemMod>(annotated_item)
235 .map_err(|err| Error::new(err.span(), format!("cannot parse module: {err}")))?;
236
237 // This parses the versions passed to the attribute, e.g. the `"1.3"`
238 // and `"1.4"`in `#[versioned("1.3", "1.4")]
239 let versions =
240 syn::parse::Parser::parse(Punctuated::<syn::LitStr, Comma>::parse_terminated, input)?
241 .into_iter()
242 .map(|s| s.value().parse().map_err(|err| Error::new(s.span(), err)))
243 .collect::<syn::Result<Vec<Version>>>()?;
244
245 let content = module
246 .content
247 .as_ref()
248 .ok_or_else(|| Error::new(module.ident.span(), "found module without content"))?;
249
250 let mut tokens = TokenStream2::new();
251
252 for version in versions {
253 let mod_vis = &module.vis;
254 let mod_ident = version.as_ident();
255
256 let items = content.1.clone();
257
258 let mut folded_items = Vec::new();
259
260 let mut filter = VersionFilter {
261 version,
262 error: None,
263 };
264
265 for item in items {
266 folded_items.push(filter.fold_item(item));
267 if let Some(error) = filter.error {
268 return Err(error);
269 }
270 }
271
272 tokens.extend(quote! {
273 #mod_vis mod #mod_ident {
274 #(#folded_items)*
275 }
276 })
277 }
278
279 Ok(tokens)
280 }
281
282 /// A `cfg`-like attribute macro to generate versioned modules.
283 ///
284 /// This macro allows to duplicate a module by providing version numbers to the
285 /// macro itself. For example:
286 /// ```rust
287 /// use cyclonedx_bom_macros::versioned;
288 ///
289 /// #[versioned("1.0", "2.0")]
290 /// mod base {
291 /// pub(super) struct Foo;
292 /// }
293 /// ```
294 /// Will generate two modules: `v1_0` and `v2_0`, where each one of them
295 /// contains the definition of `Foo`:
296 /// ```rust
297 /// mod v1_0 {
298 /// pub(super) struct Foo;
299 /// }
300 ///
301 /// mod v2_0 {
302 /// pub(super) struct Foo;
303 /// }
304 /// ```
305 /// Additionally the macro can be used to gate definitions and expressions
306 /// behind a specific version, very much like the `cfg` attribute. Based on the
307 /// previous example:
308 /// ```rust
309 /// use cyclonedx_bom_macros::versioned;
310 ///
311 /// #[versioned("1.0", "2.0")]
312 /// mod base {
313 /// pub(super) struct Foo;
314 ///
315 /// #[versioned("2.0")]
316 /// pub(super) struct Bar;
317 /// }
318 /// ```
319 /// The following code will be generated:
320 /// ```rust
321 /// mod v1_0 {
322 /// pub(super) struct Foo;
323 /// }
324 ///
325 /// mod v2_0 {
326 /// pub(super) struct Foo;
327 /// pub(super) struct Bar;
328 /// }
329 /// ```
330 /// Note that `Bar` only exists inside the `v2_0` module. Note that the
331 /// `versioned` attribute annotating the module defines the versions that will be
332 /// used to generate the modules and the attribute annotating the `Bar` definition
333 /// states that this definition will only appear on the `2.0` module.
334 ///
335 /// Check the test folder for more usage examples.
336 #[proc_macro_attribute]
337 pub fn versioned(input: TokenStream, annotated_item: TokenStream) -> TokenStream {
338 match helper(input, annotated_item) {
339 Ok(tokens) => tokens,
340 Err(err) => Error::new(
341 err.span(),
342 format!("{err} while using the `#[versioned]` macro"),
343 )
344 .into_compile_error(),
345 }
346 .into()
347 }