Debian Codegraph @

third_party/rust/uniffi_macros/src/export/attributes.rs

raw
1 use std::collections::{HashMap, HashSet};
2
3 use crate::{
4 default::DefaultValue,
5 util::{either_attribute_arg, kw, parse_comma_separated, UniffiAttributeArgs},
6 };
7
8 use proc_macro2::TokenStream;
9 use quote::ToTokens;
10 use syn::{
11 parenthesized,
12 parse::{Parse, ParseStream},
13 punctuated::Punctuated,
14 Attribute, Ident, LitStr, Meta, Path, PathArguments, PathSegment, Token,
15 };
16 use uniffi_meta::UniffiTraitDiscriminants;
17
18 #[derive(Default)]
19 pub struct ExportTraitArgs {
20 pub(crate) async_runtime: Option<AsyncRuntime>,
21 pub(crate) callback_interface: Option<kw::callback_interface>,
22 pub(crate) with_foreign: Option<kw::with_foreign>,
23 }
24
25 impl Parse for ExportTraitArgs {
26 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
27 parse_comma_separated(input)
28 }
29 }
30
31 impl UniffiAttributeArgs for ExportTraitArgs {
32 fn parse_one(input: ParseStream<'_>) -> syn::Result<Self> {
33 let lookahead = input.lookahead1();
34 if lookahead.peek(kw::async_runtime) {
35 let _: kw::async_runtime = input.parse()?;
36 let _: Token![=] = input.parse()?;
37 Ok(Self {
38 async_runtime: Some(input.parse()?),
39 ..Self::default()
40 })
41 } else if lookahead.peek(kw::callback_interface) {
42 Ok(Self {
43 callback_interface: input.parse()?,
44 ..Self::default()
45 })
46 } else if lookahead.peek(kw::with_foreign) {
47 Ok(Self {
48 with_foreign: input.parse()?,
49 ..Self::default()
50 })
51 } else {
52 Ok(Self::default())
53 }
54 }
55
56 fn merge(self, other: Self) -> syn::Result<Self> {
57 let merged = Self {
58 async_runtime: either_attribute_arg(self.async_runtime, other.async_runtime)?,
59 callback_interface: either_attribute_arg(
60 self.callback_interface,
61 other.callback_interface,
62 )?,
63 with_foreign: either_attribute_arg(self.with_foreign, other.with_foreign)?,
64 };
65 if merged.callback_interface.is_some() && merged.with_foreign.is_some() {
66 return Err(syn::Error::new(
67 merged.callback_interface.unwrap().span,
68 "`callback_interface` and `with_foreign` are mutually exclusive",
69 ));
70 }
71 Ok(merged)
72 }
73 }
74
75 /// Attribute arguments for function
76 ///
77 /// This includes top-level functions, constructors, and methods.
78 #[derive(Clone, Default)]
79 pub struct ExportFnArgs {
80 pub(crate) async_runtime: Option<AsyncRuntime>,
81 pub(crate) name: Option<String>,
82 pub(crate) defaults: DefaultMap,
83 }
84
85 impl Parse for ExportFnArgs {
86 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
87 parse_comma_separated(input)
88 }
89 }
90
91 impl UniffiAttributeArgs for ExportFnArgs {
92 fn parse_one(input: ParseStream<'_>) -> syn::Result<Self> {
93 let lookahead = input.lookahead1();
94 if lookahead.peek(kw::async_runtime) {
95 let _: kw::async_runtime = input.parse()?;
96 let _: Token![=] = input.parse()?;
97 Ok(Self {
98 async_runtime: Some(input.parse()?),
99 ..Self::default()
100 })
101 } else if lookahead.peek(kw::name) {
102 let _: kw::name = input.parse()?;
103 let _: Token![=] = input.parse()?;
104 let name = Some(input.parse::<LitStr>()?.value());
105 Ok(Self {
106 name,
107 ..Self::default()
108 })
109 } else if lookahead.peek(kw::default) {
110 Ok(Self {
111 defaults: DefaultMap::parse(input)?,
112 ..Self::default()
113 })
114 } else {
115 Err(syn::Error::new(
116 input.span(),
117 format!("attribute `{input}` is not supported here."),
118 ))
119 }
120 }
121
122 fn merge(self, other: Self) -> syn::Result<Self> {
123 Ok(Self {
124 async_runtime: either_attribute_arg(self.async_runtime, other.async_runtime)?,
125 name: either_attribute_arg(self.name, other.name)?,
126 defaults: self.defaults.merge(other.defaults),
127 })
128 }
129 }
130
131 #[derive(Default)]
132 pub struct ExportImplArgs {
133 pub(crate) async_runtime: Option<AsyncRuntime>,
134 }
135
136 impl Parse for ExportImplArgs {
137 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
138 parse_comma_separated(input)
139 }
140 }
141
142 impl UniffiAttributeArgs for ExportImplArgs {
143 fn parse_one(input: ParseStream<'_>) -> syn::Result<Self> {
144 let lookahead = input.lookahead1();
145 if lookahead.peek(kw::async_runtime) {
146 let _: kw::async_runtime = input.parse()?;
147 let _: Token![=] = input.parse()?;
148 Ok(Self {
149 async_runtime: Some(input.parse()?),
150 })
151 } else {
152 Err(syn::Error::new(
153 input.span(),
154 format!("uniffi::export attribute `{input}` is not supported here."),
155 ))
156 }
157 }
158
159 fn merge(self, other: Self) -> syn::Result<Self> {
160 Ok(Self {
161 async_runtime: either_attribute_arg(self.async_runtime, other.async_runtime)?,
162 })
163 }
164 }
165
166 #[derive(Default)]
167 pub struct ExportStructArgs {
168 pub(crate) traits: HashSet<UniffiTraitDiscriminants>,
169 }
170
171 impl Parse for ExportStructArgs {
172 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
173 parse_comma_separated(input)
174 }
175 }
176
177 impl UniffiAttributeArgs for ExportStructArgs {
178 fn parse_one(input: ParseStream<'_>) -> syn::Result<Self> {
179 let lookahead = input.lookahead1();
180 if lookahead.peek(kw::Debug) {
181 input.parse::<Option<kw::Debug>>()?;
182 Ok(Self {
183 traits: HashSet::from([UniffiTraitDiscriminants::Debug]),
184 })
185 } else if lookahead.peek(kw::Display) {
186 input.parse::<Option<kw::Display>>()?;
187 Ok(Self {
188 traits: HashSet::from([UniffiTraitDiscriminants::Display]),
189 })
190 } else if lookahead.peek(kw::Hash) {
191 input.parse::<Option<kw::Hash>>()?;
192 Ok(Self {
193 traits: HashSet::from([UniffiTraitDiscriminants::Hash]),
194 })
195 } else if lookahead.peek(kw::Eq) {
196 input.parse::<Option<kw::Eq>>()?;
197 Ok(Self {
198 traits: HashSet::from([UniffiTraitDiscriminants::Eq]),
199 })
200 } else {
201 Err(syn::Error::new(
202 input.span(),
203 format!(
204 "uniffi::export struct attributes must be builtin trait names; `{input}` is invalid"
205 ),
206 ))
207 }
208 }
209
210 fn merge(self, other: Self) -> syn::Result<Self> {
211 let mut traits = self.traits;
212 traits.extend(other.traits);
213 Ok(Self { traits })
214 }
215 }
216
217 #[derive(Clone)]
218 pub enum AsyncRuntime {
219 Tokio(LitStr),
220 }
221
222 impl Parse for AsyncRuntime {
223 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
224 let lit: LitStr = input.parse()?;
225 match lit.value().as_str() {
226 "tokio" => Ok(Self::Tokio(lit)),
227 _ => Err(syn::Error::new_spanned(
228 lit,
229 "unknown async runtime, currently only `tokio` is supported",
230 )),
231 }
232 }
233 }
234
235 impl ToTokens for AsyncRuntime {
236 fn to_tokens(&self, tokens: &mut TokenStream) {
237 match self {
238 AsyncRuntime::Tokio(lit) => lit.to_tokens(tokens),
239 }
240 }
241 }
242
243 #[derive(Default)]
244 pub(super) struct ExportedImplFnAttributes {
245 pub constructor: bool,
246 pub args: ExportFnArgs,
247 }
248
249 impl ExportedImplFnAttributes {
250 pub fn new(attrs: &[Attribute]) -> syn::Result<Self> {
251 let mut this = Self::default();
252 for attr in attrs {
253 let path = attr.path();
254
255 if is_uniffi_path(path) {
256 this.process_path(path, attr, &attr.meta)?;
257 } else if is_cfg_attr(attr) {
258 if let Ok(nested) =
259 attr.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
260 {
261 for meta in &nested {
262 if let Meta::Path(path) = meta {
263 this.process_path(path, attr, meta)?
264 }
265 }
266 };
267 }
268 }
269
270 Ok(this)
271 }
272
273 fn process_path(&mut self, path: &Path, attr: &Attribute, meta: &Meta) -> syn::Result<()> {
274 let segs = &path.segments;
275
276 let fst = segs
277 .first()
278 .expect("attributes have at least one path segment");
279
280 if fst.ident != "uniffi" {
281 return Ok(());
282 }
283 ensure_no_path_args(fst)?;
284
285 let args = match meta {
286 Meta::List(_) => attr.parse_args::<ExportFnArgs>()?,
287 _ => Default::default(),
288 };
289 self.args = args;
290
291 if segs.len() != 2 {
292 return Err(syn::Error::new_spanned(
293 segs,
294 "unsupported uniffi attribute",
295 ));
296 }
297 let snd = &segs[1];
298 ensure_no_path_args(snd)?;
299
300 match snd.ident.to_string().as_str() {
301 "constructor" => {
302 if self.constructor {
303 return Err(syn::Error::new_spanned(
304 attr,
305 "duplicate constructor attribute",
306 ));
307 }
308 self.constructor = true;
309 }
310 "method" => {
311 if self.constructor {
312 return Err(syn::Error::new_spanned(
313 attr,
314 "confused constructor/method attributes",
315 ));
316 }
317 }
318 _ => return Err(syn::Error::new_spanned(snd, "unknown uniffi attribute")),
319 }
320
321 Ok(())
322 }
323 }
324
325 fn is_uniffi_path(path: &Path) -> bool {
326 path.segments
327 .first()
328 .map(|segment| segment.ident == "uniffi")
329 .unwrap_or(false)
330 }
331
332 fn is_cfg_attr(attr: &Attribute) -> bool {
333 attr.meta
334 .path()
335 .get_ident()
336 .is_some_and(|ident| *ident == "cfg_attr")
337 }
338
339 fn ensure_no_path_args(seg: &PathSegment) -> syn::Result<()> {
340 if matches!(seg.arguments, PathArguments::None) {
341 Ok(())
342 } else {
343 Err(syn::Error::new_spanned(&seg.arguments, "unexpected syntax"))
344 }
345 }
346
347 /// Maps arguments to defaults for functions
348 #[derive(Clone, Default)]
349 pub struct DefaultMap {
350 map: HashMap<Ident, DefaultValue>,
351 }
352
353 impl DefaultMap {
354 pub fn merge(self, other: Self) -> Self {
355 let mut map = self.map;
356 map.extend(other.map);
357 Self { map }
358 }
359
360 pub fn remove(&mut self, ident: &Ident) -> Option<DefaultValue> {
361 self.map.remove(ident)
362 }
363
364 pub fn idents(&self) -> Vec<&Ident> {
365 self.map.keys().collect()
366 }
367 }
368
369 impl Parse for DefaultMap {
370 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
371 let _: kw::default = input.parse()?;
372 let content;
373 let _ = parenthesized!(content in input);
374 let pairs = content.parse_terminated(DefaultPair::parse, Token![,])?;
375 Ok(Self {
376 map: pairs.into_iter().map(|p| (p.name, p.value)).collect(),
377 })
378 }
379 }
380
381 pub struct DefaultPair {
382 pub name: Ident,
383 pub eq_token: Token![=],
384 pub value: DefaultValue,
385 }
386
387 impl Parse for DefaultPair {
388 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
389 Ok(Self {
390 name: input.parse()?,
391 eq_token: input.parse()?,
392 value: input.parse()?,
393 })
394 }
395 }