1use proc_macro::TokenStream;
2use proc_macro2::TokenStream as TokenStream2;
3use quote::{format_ident, quote, ToTokens};
4use syn::{
5 parse_macro_input, parse_quote,
6 punctuated::Punctuated,
7 visit_mut::{self, VisitMut},
8 Attribute, Expr, ExprLit, Fields, GenericArgument, Generics, Ident, Item, Lit, Meta,
9 MetaNameValue, Path, PathArguments, StaticMutability, Token, Type, TypePath,
10};
11
12struct StdMaps(bool);
15
16impl VisitMut for StdMaps {
17 fn visit_type_path_mut(&mut self, tp: &mut TypePath) {
18 visit_mut::visit_type_path_mut(self, tp);
19 let first = tp.path.segments.first().map(|s| s.ident.to_string());
20 let last = tp.path.segments.last().unwrap();
21 let is_map = last.ident == "HashMap" || last.ident == "HashSet";
22 if is_map && tp.qself.is_none() && first.as_deref() != Some("std") {
23 let (ident, args) = (&last.ident, &last.arguments);
24 tp.path = parse_quote!(::std::collections::#ident #args);
25 self.0 = true;
26 }
27 }
28}
29
30#[proc_macro_attribute]
40pub fn wire(attr: TokenStream, item: TokenStream) -> TokenStream {
41 if !attr.is_empty() {
42 return error(TokenStream2::from(attr), "#[wire] takes no arguments");
43 }
44 match parse_macro_input!(item as Item) {
45 Item::Struct(mut s) => {
46 let contract = match contract(&s.attrs) {
47 Ok(c) => c,
48 Err(e) => return error(&s.ident, e),
49 };
50 annotate_fields(&mut s.fields);
51 prepend_derive(&mut s.attrs);
52 let extra = registration(&s.ident, &s.generics, &contract);
53 quote!(#s #extra).into()
54 }
55 Item::Enum(mut e) => {
56 let contract = match contract(&e.attrs) {
57 Ok(c) => c,
58 Err(msg) => return error(&e.ident, msg),
59 };
60 e.variants
61 .iter_mut()
62 .for_each(|v| annotate_fields(&mut v.fields));
63 prepend_derive(&mut e.attrs);
64 let extra = registration(&e.ident, &e.generics, &contract);
65 quote!(#e #extra).into()
66 }
67 Item::Type(t) if t.generics.params.is_empty() => {
68 let mut ty = (*t.ty).clone();
69 let mut maps = StdMaps(false);
70 maps.visit_type_mut(&mut ty);
71 if !maps.0 {
72 let submit = submit(&t.ident, &t.ident, quote!(registration));
73 return quote!(#t #submit).into();
74 }
75 let (vis, twin) = (&t.vis, format_ident!("{}Wire", t.ident));
76 let submit = submit(&twin, &t.ident, quote!(map_registration));
77 quote! {
78 #t
79 #[doc(hidden)]
80 #vis type #twin = #ty;
81 #submit
82 }
83 .into()
84 }
85 Item::Const(c) => {
86 let submit = const_submit(&c.ident, &c.attrs, &c.ty);
87 quote!(#c #submit).into()
88 }
89 Item::Static(s) if matches!(s.mutability, StaticMutability::None) => {
90 let submit = const_submit(&s.ident, &s.attrs, &s.ty);
91 quote!(#s #submit).into()
92 }
93 other => error(
94 other,
95 "#[wire] goes on a struct, an enum, a non-generic type alias, a const or a static",
96 ),
97 }
98}
99
100fn contract(attrs: &[Attribute]) -> Result<Ident, &'static str> {
101 let mut derived = Vec::new();
102 for attr in attrs.iter().filter(|a| a.path().is_ident("derive")) {
103 if let Ok(paths) = attr.parse_args_with(Punctuated::<Path, Token![,]>::parse_terminated) {
104 derived.extend(
105 paths
106 .into_iter()
107 .filter_map(|p| p.segments.last().map(|s| s.ident.to_string())),
108 );
109 }
110 }
111 let has = |name: &str| derived.iter().any(|d| d == name);
112 match (has("Serialize"), has("Deserialize")) {
113 (true, _) => Ok(Ident::new("Serialize", proc_macro2::Span::call_site())),
114 (false, true) => Ok(Ident::new("Deserialize", proc_macro2::Span::call_site())),
115 (false, false) => Err("#[wire] needs a serde Serialize or Deserialize derive below it"),
116 }
117}
118
119fn prepend_derive(attrs: &mut Vec<Attribute>) {
120 attrs.insert(
121 0,
122 parse_quote!(#[derive(::wiretypes::schemars::JsonSchema)]),
123 );
124 attrs.insert(
125 1,
126 parse_quote!(#[schemars(crate = "::wiretypes::schemars")]),
127 );
128}
129
130fn annotate_fields(fields: &mut Fields) {
131 for field in fields.iter_mut() {
132 let spelled = |name: &str| -> String {
133 field
134 .attrs
135 .iter()
136 .filter(|a| a.path().is_ident(name))
137 .map(|a| a.to_token_stream().to_string().replace(' ', ""))
138 .collect()
139 };
140 let (serde, schemars) = (spelled("serde"), spelled("schemars"));
141 if !schemars.contains("with=") {
142 let mut ty = field.ty.clone();
143 let mut maps = StdMaps(false);
144 maps.visit_type_mut(&mut ty);
145 if maps.0 {
146 let with = ty.to_token_stream().to_string();
147 field.attrs.push(parse_quote!(#[schemars(with = #with)]));
148 }
149 }
150 if serde.contains("skip_serializing_if=\"Option::is_none\"") {
151 field
152 .attrs
153 .push(parse_quote!(#[schemars(transform = ::wiretypes::never_null)]));
154 }
155 }
156}
157
158fn registration(ident: &Ident, generics: &Generics, contract: &Ident) -> TokenStream2 {
159 let mut bounded = generics.clone();
160 bounded
161 .make_where_clause()
162 .predicates
163 .push(parse_quote!(Self: ::wiretypes::schemars::JsonSchema));
164 let (impl_generics, ty_generics, where_clause) = bounded.split_for_impl();
165 let wire_impl = quote! {
166 impl #impl_generics ::wiretypes::Wire for #ident #ty_generics #where_clause {
167 const CONTRACT: ::wiretypes::Contract = ::wiretypes::Contract::#contract;
168 }
169 };
170 match generics.params.is_empty() {
171 true => {
172 let submit = submit(ident, ident, quote!(registration));
173 quote!(#wire_impl #submit)
174 }
175 false => wire_impl,
176 }
177}
178
179fn submit(ty: &Ident, name: &Ident, constructor: TokenStream2) -> TokenStream2 {
180 let name = name.to_string();
181 quote! {
182 ::wiretypes::inventory::submit! {
183 ::wiretypes::#constructor::<#ty>(::core::module_path!(), #name, ::core::line!())
184 }
185 }
186}
187
188fn const_submit(ident: &Ident, attrs: &[Attribute], ty: &Type) -> TokenStream2 {
189 let (name, doc) = (ident.to_string(), doc(attrs));
190 let (ty, value) = match lazy_value(ty) {
191 Some(inner) => (inner, quote!(&*#ident)),
192 None => (ty, quote!(&#ident)),
193 };
194 quote! {
195 ::wiretypes::inventory::submit! {
196 ::wiretypes::WireConst {
197 module: ::core::module_path!(),
198 name: #name,
199 line: ::core::line!(),
200 doc: #doc,
201 value: || ::wiretypes::serde_json::to_value(#value),
202 schema: ::wiretypes::subschema::<#ty>,
203 }
204 }
205 }
206}
207
208fn lazy_value(ty: &Type) -> Option<&Type> {
210 let Type::Path(tp) = ty else { return None };
211 let last = tp.path.segments.last()?;
212 let PathArguments::AngleBracketed(args) = &last.arguments else {
213 return None;
214 };
215 match args.args.first()? {
216 GenericArgument::Type(inner) if last.ident == "LazyLock" => Some(inner),
217 _ => None,
218 }
219}
220
221fn doc(attrs: &[Attribute]) -> String {
223 let lines: Vec<String> = attrs
224 .iter()
225 .filter_map(|a| match &a.meta {
226 Meta::NameValue(MetaNameValue {
227 path,
228 value:
229 Expr::Lit(ExprLit {
230 lit: Lit::Str(s), ..
231 }),
232 ..
233 }) if path.is_ident("doc") => Some(s.value()),
234 _ => None,
235 })
236 .map(|l| l.strip_prefix(' ').map(str::to_string).unwrap_or(l))
237 .collect();
238 lines.join("\n").trim().to_string()
239}
240
241fn error(tokens: impl ToTokens, msg: &str) -> TokenStream {
242 syn::Error::new_spanned(tokens, msg)
243 .to_compile_error()
244 .into()
245}