1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/// Prototype of removing an inner attribute (`#![...]`) from a syntax tree. Requires the `visit-mut'
/// feature of `syn`.
//# Purpose: Demonstrate making changes to a `syn` AST.
//# Categories: AST, crates, prototype, technique
use quote::quote;
use syn::visit_mut::{self, VisitMut};
use syn::{AttrStyle, ExprBlock};
struct RemoveInnerAttributes;
impl VisitMut for RemoveInnerAttributes {
fn visit_expr_block_mut(&mut self, expr_block: &mut ExprBlock) {
// Filter out inner attributes
expr_block
.attrs
.retain(|attr| attr.style != AttrStyle::Inner(syn::token::Not::default()));
// Continue visiting the rest of the expression block
visit_mut::visit_expr_block_mut(self, expr_block);
}
}
fn main() {
let source = r#"{
#![feature(duration_constructors)]
use std::time::Duration;
Duration::from_days(10);
}"#;
println!("Before: {source}");
// Parse the source code into an expression block
let mut expr_block: ExprBlock = syn::parse_str(source).expect("Failed to parse source");
// Apply the RemoveInnerAttributes visitor to the expression block
RemoveInnerAttributes.visit_expr_block_mut(&mut expr_block);
// Print the modified expression block
// println!("{expr_block:#?}");
// Convert back using quote:
println!("After:{}", quote!(#expr_block));
}