Debian Codegraph @

debian/rust-vendor/rstest_macros/src/utils.rs

raw
1 /// Contains some unsorted functions used across others modules
2 ///
3 use quote::format_ident;
4 use std::collections::{HashMap, HashSet};
5 use unicode_ident::is_xid_continue;
6
7 use crate::refident::{MaybeIdent, MaybePat};
8 use syn::{Attribute, Expr, FnArg, Generics, Ident, ItemFn, Pat, ReturnType, Type, WherePredicate};
9
10 /// Return an iterator over fn arguments items.
11 ///
12 pub(crate) fn fn_args_pats(test: &ItemFn) -> impl Iterator<Item = &Pat> {
13 fn_args(test).filter_map(MaybePat::maybe_pat)
14 }
15
16 pub(crate) fn compare_pat(a: &Pat, b: &Pat) -> bool {
17 match (a, b) {
18 (Pat::Ident(a), Pat::Ident(b)) => a.ident == b.ident,
19 (Pat::Tuple(a), Pat::Tuple(b)) => a.elems == b.elems,
20 (Pat::TupleStruct(a), Pat::TupleStruct(b)) => a.path == b.path && a.elems == b.elems,
21 (Pat::Struct(a), Pat::Struct(b)) => a.path == b.path && a.fields == b.fields,
22 _ => false,
23 }
24 }
25
26 /// Return if function declaration has an ident
27 ///
28 pub(crate) fn fn_args_has_pat(fn_decl: &ItemFn, pat: &Pat) -> bool {
29 fn_args_pats(fn_decl).any(|id| compare_pat(id, pat))
30 }
31
32 /// Return an iterator over fn arguments.
33 ///
34 pub(crate) fn fn_args(item_fn: &ItemFn) -> impl Iterator<Item = &FnArg> {
35 item_fn.sig.inputs.iter()
36 }
37
38 pub(crate) fn attr_ends_with(attr: &Attribute, segment: &syn::PathSegment) -> bool {
39 attr.path().segments.iter().next_back() == Some(segment)
40 }
41
42 pub(crate) fn attr_starts_with(attr: &Attribute, segment: &syn::PathSegment) -> bool {
43 attr.path().segments.iter().next() == Some(segment)
44 }
45
46 pub(crate) fn attr_is(attr: &Attribute, name: &str) -> bool {
47 attr.path().is_ident(&format_ident!("{}", name))
48 }
49
50 pub(crate) fn attr_in(attr: &Attribute, names: &[&str]) -> bool {
51 names
52 .iter()
53 .any(|name| attr.path().is_ident(&format_ident!("{}", name)))
54 }
55
56 pub(crate) trait IsLiteralExpression {
57 fn is_literal(&self) -> bool;
58 }
59
60 impl<E: AsRef<Expr>> IsLiteralExpression for E {
61 fn is_literal(&self) -> bool {
62 matches!(
63 self.as_ref(),
64 Expr::Lit(syn::ExprLit {
65 lit: syn::Lit::Str(_),
66 ..
67 })
68 )
69 }
70 }
71
72 // Recoursive search id by reference till find one in ends
73 fn _is_used(
74 visited: &mut HashSet<Ident>,
75 id: &Ident,
76 references: &HashMap<Ident, HashSet<Ident>>,
77 ends: &HashSet<Ident>,
78 ) -> bool {
79 if visited.contains(id) {
80 return false;
81 }
82 visited.insert(id.clone());
83 if ends.contains(id) {
84 return true;
85 }
86 if references.contains_key(id) {
87 for referred in references.get(id).unwrap() {
88 if _is_used(visited, referred, references, ends) {
89 return true;
90 }
91 }
92 }
93 false
94 }
95
96 // Recoursive search id by reference till find one in ends
97 fn is_used(id: &Ident, references: &HashMap<Ident, HashSet<Ident>>, ends: &HashSet<Ident>) -> bool {
98 let mut visited = Default::default();
99 _is_used(&mut visited, id, references, ends)
100 }
101
102 impl MaybeIdent for syn::WherePredicate {
103 fn maybe_ident(&self) -> Option<&Ident> {
104 match self {
105 WherePredicate::Type(syn::PredicateType { bounded_ty: t, .. }) => {
106 first_type_path_segment_ident(t)
107 }
108 WherePredicate::Lifetime(syn::PredicateLifetime { lifetime, .. }) => {
109 Some(&lifetime.ident)
110 }
111 _ => None,
112 }
113 }
114 }
115
116 #[derive(Default)]
117 struct SearchSimpleTypeName(HashSet<Ident>);
118
119 impl SearchSimpleTypeName {
120 fn take(self) -> HashSet<Ident> {
121 self.0
122 }
123
124 fn visit_inputs<'a>(&mut self, inputs: impl Iterator<Item = &'a FnArg>) {
125 use syn::visit::Visit;
126 inputs.for_each(|fn_arg| self.visit_fn_arg(fn_arg));
127 }
128 fn visit_output(&mut self, output: &ReturnType) {
129 use syn::visit::Visit;
130 self.visit_return_type(output);
131 }
132
133 fn collect_from_type_param(tp: &syn::TypeParam) -> Self {
134 let mut s: Self = Default::default();
135 use syn::visit::Visit;
136 s.visit_type_param(tp);
137 s
138 }
139
140 fn collect_from_where_predicate(wp: &syn::WherePredicate) -> Self {
141 let mut s: Self = Default::default();
142 use syn::visit::Visit;
143 s.visit_where_predicate(wp);
144 s
145 }
146 }
147
148 impl<'ast> syn::visit::Visit<'ast> for SearchSimpleTypeName {
149 fn visit_path(&mut self, p: &'ast syn::Path) {
150 if let Some(id) = p.get_ident() {
151 self.0.insert(id.clone());
152 }
153 syn::visit::visit_path(self, p)
154 }
155
156 fn visit_lifetime(&mut self, i: &'ast syn::Lifetime) {
157 self.0.insert(i.ident.clone());
158 syn::visit::visit_lifetime(self, i)
159 }
160 }
161
162 // Take generics definitions and where clauses and return the
163 // a map from simple types (lifetime names or type with just names)
164 // to a set of all simple types that use it as some costrain.
165 fn extract_references_map(generics: &Generics) -> HashMap<Ident, HashSet<Ident>> {
166 let mut references = HashMap::<Ident, HashSet<Ident>>::default();
167 // Extracts references from types param
168 generics.type_params().for_each(|tp| {
169 SearchSimpleTypeName::collect_from_type_param(tp)
170 .take()
171 .into_iter()
172 .for_each(|id| {
173 references.entry(id).or_default().insert(tp.ident.clone());
174 });
175 });
176 // Extracts references from where clauses
177 generics
178 .where_clause
179 .iter()
180 .flat_map(|wc| wc.predicates.iter())
181 .filter_map(|wp| wp.maybe_ident().map(|id| (id, wp)))
182 .for_each(|(ref_ident, wp)| {
183 SearchSimpleTypeName::collect_from_where_predicate(wp)
184 .take()
185 .into_iter()
186 .for_each(|id| {
187 references.entry(id).or_default().insert(ref_ident.clone());
188 });
189 });
190 references
191 }
192
193 // Return a hash set that contains all types and lifetimes referenced
194 // in input/output expressed by a single ident.
195 fn references_ident_types<'a>(
196 generics: &Generics,
197 inputs: impl Iterator<Item = &'a FnArg>,
198 output: &ReturnType,
199 ) -> HashSet<Ident> {
200 let mut used: SearchSimpleTypeName = Default::default();
201 used.visit_output(output);
202 used.visit_inputs(inputs);
203 let references = extract_references_map(generics);
204 let mut used = used.take();
205 let input_output = used.clone();
206 // Extend the input output collected ref with the transitive ones:
207 used.extend(
208 generics
209 .params
210 .iter()
211 .filter_map(MaybeIdent::maybe_ident)
212 .filter(|&id| is_used(id, &references, &input_output))
213 .cloned(),
214 );
215 used
216 }
217
218 fn filtered_predicates(mut wc: syn::WhereClause, valids: &HashSet<Ident>) -> syn::WhereClause {
219 wc.predicates = wc
220 .predicates
221 .clone()
222 .into_iter()
223 .filter(|wp| {
224 wp.maybe_ident()
225 .map(|t| valids.contains(t))
226 .unwrap_or_default()
227 })
228 .collect();
229 wc
230 }
231
232 fn filtered_generics<'a>(
233 params: impl Iterator<Item = syn::GenericParam> + 'a,
234 valids: &'a HashSet<Ident>,
235 ) -> impl Iterator<Item = syn::GenericParam> + 'a {
236 params.filter(move |p| match p.maybe_ident() {
237 Some(id) => valids.contains(id),
238 None => false,
239 })
240 }
241
242 //noinspection RsTypeCheck
243 pub(crate) fn generics_clean_up<'a>(
244 original: &Generics,
245 inputs: impl Iterator<Item = &'a FnArg>,
246 output: &ReturnType,
247 ) -> syn::Generics {
248 let used = references_ident_types(original, inputs, output);
249 let mut result: Generics = original.clone();
250 result.params = filtered_generics(result.params.into_iter(), &used).collect();
251 result.where_clause = result.where_clause.map(|wc| filtered_predicates(wc, &used));
252 result
253 }
254
255 // If type is not self and doesn't starts with :: return the first ident
256 // of its path segment: only if is a simple path.
257 // If type is a simple ident just return the this ident. That is useful to
258 // find the base type for associate type indication
259 fn first_type_path_segment_ident(t: &Type) -> Option<&Ident> {
260 match t {
261 Type::Path(tp) if tp.qself.is_none() && tp.path.leading_colon.is_none() => tp
262 .path
263 .segments
264 .iter()
265 .next()
266 .and_then(|ps| match ps.arguments {
267 syn::PathArguments::None => Some(&ps.ident),
268 _ => None,
269 }),
270 _ => None,
271 }
272 }
273
274 pub(crate) fn fn_arg_mutability(arg: &FnArg) -> Option<syn::token::Mut> {
275 match arg {
276 FnArg::Typed(syn::PatType { pat, .. }) => match pat.as_ref() {
277 syn::Pat::Ident(syn::PatIdent { mutability, .. }) => *mutability,
278 _ => None,
279 },
280 _ => None,
281 }
282 }
283
284 pub(crate) fn sanitize_ident(name: &str) -> String {
285 name.chars()
286 .filter(|c| !c.is_whitespace())
287 .map(|c| match c {
288 '"' | '\'' => "__".to_owned(),
289 ':' | '(' | ')' | '{' | '}' | '[' | ']' | ',' | '.' | '*' | '+' | '/' | '-' | '%'
290 | '^' | '!' | '&' | '|' => "_".to_owned(),
291 _ => c.to_string(),
292 })
293 .collect::<String>()
294 .chars()
295 .filter(|&c| is_xid_continue(c))
296 .collect()
297 }
298
299 #[cfg(test)]
300 mod test {
301 use syn::parse_quote;
302
303 use super::*;
304 use crate::test::{assert_eq, *};
305
306 #[test]
307 fn fn_args_has_pat_should() {
308 let item_fn = parse_quote! {
309 fn the_function(first: u32, second: u32) {}
310 };
311
312 assert!(fn_args_has_pat(&item_fn, &pat("first")));
313 assert!(!fn_args_has_pat(&item_fn, &pat("third")));
314 }
315
316 #[rstest]
317 #[case::base("fn foo<A, B, C>(a: A) -> B {}", &["A", "B"])]
318 #[case::use_const_in_array("fn foo<A, const B: usize, C>(a: A) -> [u32; B] {}", &["A", "B", "u32"])]
319 #[case::in_type_args("fn foo<A, const B: usize, C>(a: A) -> SomeType<B> {}", &["A", "B"])]
320 #[case::in_type_args("fn foo<A, const B: usize, C>(a: SomeType<A>, b: SomeType<B>) {}", &["A", "B"])]
321 #[case::pointers("fn foo<A, B, C>(a: *const A, b: &B) {}", &["A", "B"])]
322 #[case::lifetime("fn foo<'a, A, B, C>(a: A, b: &'a B) {}", &["a", "A", "B"])]
323 #[case::transitive_lifetime("fn foo<'a, A, B, C>(a: A, b: B) where B: Iterator<Item=A> + 'a {}", &["a", "A", "B"])]
324 #[case::associated("fn foo<'a, A:Copy, C>(b: impl Iterator<Item=A> + 'a) {}", &["a", "A"])]
325 #[case::transitive_in_defs("fn foo<A:Copy, B: Iterator<Item=A>>(b: B) {}", &["A", "B"])]
326 #[case::transitive_in_where("fn foo<A:Copy, B>(b: B) where B: Iterator<Item=A> {}", &["A", "B"])]
327 #[case::transitive_const("fn foo<const A: usize, B, C>(b: B) where B: Some<A> {}", &["A", "B"])]
328 #[case::transitive_lifetime("fn foo<'a, A, B, C>(a: A, b: B) where B: Iterator<Item=A> + 'a {}", &["a", "A", "B"])]
329 #[case::transitive_lifetime(r#"fn foo<'a, 'b, 'c, 'd, A, B, C>
330 (a: A, b: B)
331 where B: Iterator<Item=A> + 'c,
332 'c: 'a + 'b {}"#, &["a", "b", "c", "A", "B"])]
333 fn references_ident_types_should(#[case] f: &str, #[case] expected: &[&str]) {
334 let f: ItemFn = f.ast();
335 let used = references_ident_types(&f.sig.generics, f.sig.inputs.iter(), &f.sig.output);
336
337 let expected = to_idents!(expected)
338 .into_iter()
339 .collect::<std::collections::HashSet<_>>();
340
341 assert_eq!(expected, used);
342 }
343
344 #[rstest]
345 #[case::remove_not_in_output(
346 r#"fn test<R: AsRef<str>, B, F, H: Iterator<Item=u32>>() -> (H, B, String, &str)
347 where F: ToString,
348 B: Borrow<u32>
349 {}"#,
350 r#"fn test<B, H: Iterator<Item=u32>>() -> (H, B, String, &str)
351 where B: Borrow<u32>
352 {}"#
353 )]
354 #[case::not_remove_used_in_arguments(
355 r#"fn test<R: AsRef<str>, B, F, H: Iterator<Item=u32>>
356 (h: H, it: impl Iterator<Item=R>, j: &[B])
357 where F: ToString,
358 B: Borrow<u32>
359 {}"#,
360 r#"fn test<R: AsRef<str>, B, H: Iterator<Item=u32>>
361 (h: H, it: impl Iterator<Item=R>, j: &[B])
362 where
363 B: Borrow<u32>
364 {}"#
365 )]
366 #[case::dont_remove_transitive(
367 r#"fn test<A, B, C, D, const F: usize, O>(a: A) where
368 B: AsRef<C>,
369 A: Iterator<Item=[B; F]>,
370 D: ArsRef<O> {}"#,
371 r#"fn test<A, B, C, const F: usize>(a: A) where
372 B: AsRef<C>,
373 A: Iterator<Item=[B; F]> {}"#
374 )]
375 #[case::remove_unused_lifetime(
376 "fn test<'a, 'b, 'c, 'd, 'e, 'f, 'g, A>(a: &'a uint32, b: impl AsRef<A> + 'b) where 'b: 'c + 'd, A: Copy + 'e, 'f: 'g {}",
377 "fn test<'a, 'b, 'c, 'd, 'e, A>(a: &'a uint32, b: impl AsRef<A> + 'b) where 'b: 'c + 'd, A: Copy + 'e {}"
378 )]
379 #[case::remove_unused_const(
380 r#"fn test<const A: usize, const B: usize, const C: usize, const D: usize, T, O>
381 (a: [u32; A], b: SomeType<B>, c: T) where
382 T: Iterator<Item=[i32; C]>,
383 O: AsRef<D>
384 {}"#,
385 r#"fn test<const A: usize, const B: usize, const C: usize, T>
386 (a: [u32; A], b: SomeType<B>, c: T) where
387 T: Iterator<Item=[i32; C]>
388 {}"#
389 )]
390 fn generics_cleaner(#[case] code: &str, #[case] expected: &str) {
391 // Should remove all generics parameters that are not present in output
392 let item_fn: ItemFn = code.ast();
393
394 let expected: ItemFn = expected.ast();
395
396 let cleaned = generics_clean_up(
397 &item_fn.sig.generics,
398 item_fn.sig.inputs.iter(),
399 &item_fn.sig.output,
400 );
401
402 assert_eq!(expected.sig.generics, cleaned);
403 }
404
405 #[rstest]
406 #[case("1", "1")]
407 #[case(r#""1""#, "__1__")]
408 #[case(r#"Some::SomeElse"#, "Some__SomeElse")]
409 #[case(r#""minnie".to_owned()"#, "__minnie___to_owned__")]
410 #[case(
411 r#"vec![1 , 2,
412 3]"#,
413 "vec__1_2_3_"
414 )]
415 #[case(
416 r#"some_macro!("first", {second}, [third])"#,
417 "some_macro____first____second___third__"
418 )]
419 #[case(r#"'x'"#, "__x__")]
420 #[case::ops(r#"a*b+c/d-e%f^g"#, "a_b_c_d_e_f_g")]
421 #[case(r#"filter whitespace"#, "filterwhitespace")]
422 fn sanitaze_ident_name(#[case] expression: impl AsRef<str>, #[case] expected: impl AsRef<str>) {
423 assert_eq!(expected.as_ref(), sanitize_ident(expression.as_ref()));
424 }
425 }