Debian Codegraph @

third_party/rust/uniffi_macros/src/util.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use crate::ffiops;
6 use proc_macro2::{Ident, Span, TokenStream};
7 use quote::{format_ident, quote, ToTokens};
8 use std::path::{Path as StdPath, PathBuf};
9 use syn::{
10 ext::IdentExt,
11 parse::{Parse, ParseStream},
12 Attribute, Expr, Lit, Token,
13 };
14
15 pub fn manifest_path() -> Result<PathBuf, String> {
16 let manifest_dir =
17 std::env::var_os("CARGO_MANIFEST_DIR").ok_or("`CARGO_MANIFEST_DIR` is not set")?;
18
19 Ok(StdPath::new(&manifest_dir).join("Cargo.toml"))
20 }
21
22 #[cfg(not(feature = "nightly"))]
23 pub fn mod_path() -> syn::Result<String> {
24 // Without the nightly feature and TokenStream::expand_expr, just return the crate name
25
26 use fs_err as fs;
27 use once_cell::sync::Lazy;
28 use serde::Deserialize;
29
30 #[derive(Deserialize)]
31 struct CargoToml {
32 package: Package,
33 #[serde(default)]
34 lib: Lib,
35 }
36
37 #[derive(Deserialize)]
38 struct Package {
39 name: String,
40 }
41
42 #[derive(Default, Deserialize)]
43 struct Lib {
44 name: Option<String>,
45 }
46
47 static LIB_CRATE_MOD_PATH: Lazy<Result<String, String>> = Lazy::new(|| {
48 let file = manifest_path()?;
49 let cargo_toml_bytes = fs::read(file).map_err(|e| e.to_string())?;
50
51 let cargo_toml = toml::from_slice::<CargoToml>(&cargo_toml_bytes)
52 .map_err(|e| format!("Failed to parse `Cargo.toml`: {e}"))?;
53
54 let lib_crate_name = cargo_toml
55 .lib
56 .name
57 .unwrap_or_else(|| cargo_toml.package.name.replace('-', "_"));
58
59 Ok(lib_crate_name)
60 });
61
62 LIB_CRATE_MOD_PATH
63 .clone()
64 .map_err(|e| syn::Error::new(Span::call_site(), e))
65 }
66
67 #[cfg(feature = "nightly")]
68 pub fn mod_path() -> syn::Result<String> {
69 use proc_macro::TokenStream;
70
71 let module_path_invoc = TokenStream::from(quote! { ::core::module_path!() });
72 // We ask the compiler what `module_path!()` expands to here.
73 // This is a nightly feature, tracked at https://github.com/rust-lang/rust/issues/90765
74 let expanded_module_path = TokenStream::expand_expr(&module_path_invoc)
75 .map_err(|e| syn::Error::new(Span::call_site(), e))?;
76 Ok(syn::parse::<syn::LitStr>(expanded_module_path)?.value())
77 }
78
79 pub fn try_read_field(f: &syn::Field) -> TokenStream {
80 let ident = &f.ident;
81 let try_read = ffiops::try_read(&f.ty);
82
83 match ident {
84 Some(ident) => quote! {
85 #ident: #try_read(buf)?,
86 },
87 None => quote! {
88 #try_read(buf)?,
89 },
90 }
91 }
92
93 pub fn ident_to_string(ident: &Ident) -> String {
94 ident.unraw().to_string()
95 }
96
97 pub fn crate_name() -> String {
98 std::env::var("CARGO_CRATE_NAME").unwrap().replace('-', "_")
99 }
100
101 pub fn create_metadata_items(
102 kind: &str,
103 name: &str,
104 metadata_expr: TokenStream,
105 checksum_fn_name: Option<String>,
106 ) -> TokenStream {
107 let crate_name = crate_name();
108 let crate_name_upper = crate_name.to_uppercase();
109 let kind_upper = kind.to_uppercase();
110 let name_upper = name.to_uppercase();
111 let const_ident =
112 format_ident!("UNIFFI_META_CONST_{crate_name_upper}_{kind_upper}_{name_upper}");
113 let static_ident = format_ident!("UNIFFI_META_{crate_name_upper}_{kind_upper}_{name_upper}");
114 let checksum_fn = checksum_fn_name.map(|name| {
115 let ident = Ident::new(&name, Span::call_site());
116 quote! {
117 #[doc(hidden)]
118 #[unsafe(no_mangle)]
119 pub extern "C" fn #ident() -> u16 {
120 // Force constant evaluation to ensure:
121 // 1. The checksum is computed at compile time; and
122 // 2. The metadata buffer is not embedded into the binary.
123 const CHECKSUM: u16 = #const_ident.checksum();
124 CHECKSUM
125 }
126 }
127 });
128
129 quote! {
130 const #const_ident: ::uniffi::MetadataBuffer = #metadata_expr;
131 #[unsafe(no_mangle)]
132 #[doc(hidden)]
133 pub static #static_ident: [u8; #const_ident.size] = #const_ident.into_array();
134
135 #checksum_fn
136 }
137 }
138
139 pub fn try_metadata_value_from_usize(value: usize, error_message: &str) -> syn::Result<u8> {
140 value
141 .try_into()
142 .map_err(|_| syn::Error::new(Span::call_site(), error_message))
143 }
144
145 pub fn chain<T>(
146 a: impl IntoIterator<Item = T>,
147 b: impl IntoIterator<Item = T>,
148 ) -> impl Iterator<Item = T> {
149 a.into_iter().chain(b)
150 }
151
152 pub trait UniffiAttributeArgs: Default {
153 fn parse_one(input: ParseStream<'_>) -> syn::Result<Self>;
154 fn merge(self, other: Self) -> syn::Result<Self>;
155 }
156
157 pub fn parse_comma_separated<T: UniffiAttributeArgs>(input: ParseStream<'_>) -> syn::Result<T> {
158 let punctuated = input.parse_terminated(T::parse_one, Token![,])?;
159 punctuated.into_iter().try_fold(T::default(), T::merge)
160 }
161
162 #[derive(Default)]
163 struct ArgumentNotAllowedHere;
164
165 impl UniffiAttributeArgs for ArgumentNotAllowedHere {
166 fn parse_one(input: ParseStream<'_>) -> syn::Result<Self> {
167 Err(syn::Error::new(
168 input.span(),
169 "attribute arguments are not currently recognized in this position",
170 ))
171 }
172
173 fn merge(self, _other: Self) -> syn::Result<Self> {
174 Ok(Self)
175 }
176 }
177
178 pub trait AttributeSliceExt {
179 fn parse_uniffi_attr_args<T: UniffiAttributeArgs>(&self) -> syn::Result<T>;
180 fn uniffi_attr_args_not_allowed_here(&self) -> Option<syn::Error> {
181 self.parse_uniffi_attr_args::<ArgumentNotAllowedHere>()
182 .err()
183 }
184 }
185
186 impl AttributeSliceExt for [Attribute] {
187 fn parse_uniffi_attr_args<T: UniffiAttributeArgs>(&self) -> syn::Result<T> {
188 self.iter()
189 .filter(|attr| attr.path().is_ident("uniffi"))
190 .try_fold(T::default(), |res, attr| {
191 let parsed = attr.parse_args_with(parse_comma_separated)?;
192 res.merge(parsed)
193 })
194 }
195 }
196
197 pub fn either_attribute_arg<T: ToTokens>(a: Option<T>, b: Option<T>) -> syn::Result<Option<T>> {
198 match (a, b) {
199 (None, None) => Ok(None),
200 (Some(val), None) | (None, Some(val)) => Ok(Some(val)),
201 (Some(a), Some(b)) => {
202 let mut error = syn::Error::new_spanned(a, "redundant attribute argument");
203 error.combine(syn::Error::new_spanned(b, "note: first one here"));
204 Err(error)
205 }
206 }
207 }
208
209 pub(crate) fn tagged_impl_header(
210 trait_name: &str,
211 ident: &impl ToTokens,
212 remote: bool,
213 ) -> TokenStream {
214 let trait_name = Ident::new(trait_name, Span::call_site());
215 if remote {
216 quote! { impl ::uniffi::#trait_name<crate::UniFfiTag> for #ident }
217 } else {
218 quote! { impl<T> ::uniffi::#trait_name<T> for #ident }
219 }
220 }
221
222 pub(crate) fn derive_ffi_traits(
223 ty: impl ToTokens,
224 remote: bool,
225 trait_names: &[&str],
226 ) -> TokenStream {
227 let trait_idents = trait_names
228 .iter()
229 .map(|name| Ident::new(name, Span::call_site()));
230 if remote {
231 quote! {
232 #(
233 ::uniffi::derive_ffi_traits!(impl #trait_idents<crate::UniFfiTag> for #ty);
234 )*
235 }
236 } else {
237 quote! {
238 #(
239 ::uniffi::derive_ffi_traits!(impl<UT> #trait_idents<UT> for #ty);
240 )*
241 }
242 }
243 }
244
245 /// Custom keywords
246 pub mod kw {
247 syn::custom_keyword!(async_runtime);
248 syn::custom_keyword!(callback_interface);
249 syn::custom_keyword!(with_foreign);
250 syn::custom_keyword!(default);
251 syn::custom_keyword!(flat_error);
252 syn::custom_keyword!(None);
253 syn::custom_keyword!(Some);
254 syn::custom_keyword!(with_try_read);
255 syn::custom_keyword!(name);
256 syn::custom_keyword!(non_exhaustive);
257 syn::custom_keyword!(lower);
258 syn::custom_keyword!(try_lift);
259 syn::custom_keyword!(remote);
260 syn::custom_keyword!(Record);
261 syn::custom_keyword!(Enum);
262 syn::custom_keyword!(Error);
263 syn::custom_keyword!(Object);
264 syn::custom_keyword!(Debug);
265 syn::custom_keyword!(Display);
266 syn::custom_keyword!(Eq);
267 syn::custom_keyword!(Hash);
268 // Not used anymore
269 syn::custom_keyword!(handle_unknown_callback_error);
270 }
271
272 /// Specifies a type from a dependent crate
273 pub struct ExternalTypeItem {
274 pub crate_ident: Ident,
275 pub sep: Token![,],
276 pub type_ident: Ident,
277 }
278
279 impl Parse for ExternalTypeItem {
280 fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
281 Ok(Self {
282 crate_ident: input.parse()?,
283 sep: input.parse()?,
284 type_ident: input.parse()?,
285 })
286 }
287 }
288
289 pub(crate) fn extract_docstring(attrs: &[Attribute]) -> syn::Result<String> {
290 attrs
291 .iter()
292 .filter(|attr| attr.path().is_ident("doc"))
293 .map(|attr| {
294 let name_value = attr.meta.require_name_value()?;
295 if let Expr::Lit(expr) = &name_value.value {
296 if let Lit::Str(lit_str) = &expr.lit {
297 return Ok(lit_str.value().trim().to_owned());
298 }
299 }
300 Err(syn::Error::new_spanned(attr, "Cannot parse doc attribute"))
301 })
302 .collect::<syn::Result<Vec<_>>>()
303 .map(|lines| lines.join("\n"))
304 }