Skip to main content

ide_db/syntax_helpers/
suggest_name.rs

1//! This module contains functions to suggest names for expressions, functions and other items
2
3use std::{collections::hash_map::Entry, str::FromStr};
4
5use hir::{Semantics, SemanticsScope};
6use itertools::Itertools;
7use rustc_hash::FxHashMap;
8use stdx::to_lower_snake_case;
9use syntax::{
10    AstNode, Edition, SmolStr, SmolStrBuilder, ToSmolStr,
11    ast::{self, HasName},
12    match_ast,
13};
14
15use crate::RootDatabase;
16
17/// Trait names, that will be ignored when in `impl Trait` and `dyn Trait`
18const USELESS_TRAITS: &[&str] = &["Send", "Sync", "Copy", "Clone", "Eq", "PartialEq"];
19
20/// Identifier names that won't be suggested, ever
21///
22/// **NOTE**: they all must be snake lower case
23const USELESS_NAMES: &[&str] =
24    &["new", "default", "option", "some", "none", "ok", "err", "str", "string", "from", "into"];
25
26const USELESS_NAME_PREFIXES: &[&str] = &["from_", "with_", "into_"];
27
28/// Generic types replaced by their first argument
29///
30/// # Examples
31/// `Option<Name>` -> `Name`
32/// `Result<User, Error>` -> `User`
33const WRAPPER_TYPES: &[&str] = &["Box", "Arc", "Rc", "Option", "Result"];
34
35/// Generic types replaced by a plural of their first argument.
36///
37/// # Examples
38/// `Vec<Name>` -> "names"
39const SEQUENCE_TYPES: &[&str] = &["Vec", "VecDeque", "LinkedList"];
40
41/// Prefixes to strip from methods names
42///
43/// # Examples
44/// `vec.as_slice()` -> `slice`
45/// `args.into_config()` -> `config`
46/// `bytes.to_vec()` -> `vec`
47const USELESS_METHOD_PREFIXES: &[&str] = &["try_into_", "into_", "as_", "to_"];
48
49/// Useless methods that are stripped from expression
50///
51/// # Examples
52/// `var.name().to_string()` -> `var.name()`
53const USELESS_METHODS: &[&str] = &[
54    "to_string",
55    "as_str",
56    "to_owned",
57    "as_ref",
58    "clone",
59    "cloned",
60    "expect",
61    "expect_none",
62    "unwrap",
63    "unwrap_none",
64    "unwrap_or",
65    "unwrap_or_default",
66    "unwrap_or_else",
67    "unwrap_unchecked",
68    "iter",
69    "into_iter",
70    "iter_mut",
71    "into_future",
72];
73
74/// Generator for new names
75///
76/// The generator keeps track of existing names and suggests new names that do
77/// not conflict with existing names.
78///
79/// The generator will try to resolve conflicts by adding a numeric suffix to
80/// the name, e.g. `a`, `a1`, `a2`, ...
81///
82/// # Examples
83///
84/// ```
85/// # use ide_db::syntax_helpers::suggest_name::NameGenerator;
86/// let mut generator = NameGenerator::default();
87/// assert_eq!(generator.suggest_name("a"), "a");
88/// assert_eq!(generator.suggest_name("a"), "a1");
89///
90/// assert_eq!(generator.suggest_name("b2"), "b2");
91/// assert_eq!(generator.suggest_name("b"), "b3");
92///
93/// // Multi-byte UTF-8 identifiers (e.g. CJK) are handled correctly
94/// assert_eq!(generator.suggest_name("日本語"), "日本語");
95/// assert_eq!(generator.suggest_name("日本語"), "日本語1");
96/// assert_eq!(generator.suggest_name("données3"), "données3");
97/// assert_eq!(generator.suggest_name("données"), "données4");
98/// ```
99#[derive(Debug, Default)]
100pub struct NameGenerator {
101    pool: FxHashMap<SmolStr, usize>,
102}
103
104impl NameGenerator {
105    /// Create a new generator with existing names. When suggesting a name, it will
106    /// avoid conflicts with existing names.
107    pub fn new_with_names<'a>(existing_names: impl Iterator<Item = &'a str>) -> Self {
108        let mut generator = Self::default();
109        existing_names.for_each(|name| generator.insert(name));
110        generator
111    }
112
113    pub fn new_from_scope_locals(scope: Option<SemanticsScope<'_>>) -> Self {
114        let mut generator = Self::default();
115        if let Some(scope) = scope {
116            scope.process_all_names(&mut |name, scope| {
117                if let hir::ScopeDef::Local(_) = scope {
118                    generator.insert(name.as_str());
119                }
120            });
121        }
122
123        generator
124    }
125
126    pub fn new_from_scope_non_locals(scope: Option<SemanticsScope<'_>>) -> Self {
127        let mut generator = Self::default();
128        if let Some(scope) = scope {
129            scope.process_all_names(&mut |name, scope| {
130                if let hir::ScopeDef::Local(_) = scope {
131                    return;
132                }
133                generator.insert(name.as_str());
134            });
135        }
136
137        generator
138    }
139
140    /// Suggest a name without conflicts. If the name conflicts with existing names,
141    /// it will try to resolve the conflict by adding a numeric suffix.
142    pub fn suggest_name(&mut self, name: &str) -> SmolStr {
143        let (prefix, suffix) = Self::split_numeric_suffix(name);
144        let prefix = SmolStr::new(prefix);
145        let suffix = suffix.unwrap_or(0);
146
147        match self.pool.entry(prefix.clone()) {
148            Entry::Vacant(entry) => {
149                entry.insert(suffix);
150                SmolStr::from_str(name).unwrap()
151            }
152            Entry::Occupied(mut entry) => {
153                let count = entry.get_mut();
154                *count = (*count + 1).max(suffix);
155
156                let mut new_name = SmolStrBuilder::new();
157                new_name.push_str(&prefix);
158                new_name.push_str(count.to_string().as_str());
159                new_name.finish()
160            }
161        }
162    }
163
164    /// Suggest a name for given type.
165    ///
166    /// The function will strip references first, and suggest name from the inner type.
167    ///
168    /// - If `ty` is an ADT, it will suggest the name of the ADT.
169    ///   + If `ty` is wrapped in `Box`, `Option` or `Result`, it will suggest the name from the inner type.
170    /// - If `ty` is a trait, it will suggest the name of the trait.
171    /// - If `ty` is an `impl Trait`, it will suggest the name of the first trait.
172    ///
173    /// If the suggested name conflicts with reserved keywords, it will return `None`.
174    pub fn for_type<'db>(
175        &mut self,
176        ty: &hir::Type<'db>,
177        db: &'db RootDatabase,
178        edition: Edition,
179    ) -> Option<SmolStr> {
180        let name = name_of_type(ty, db, edition)?;
181        Some(self.suggest_name(&name))
182    }
183
184    /// Suggest name of impl trait type
185    ///
186    /// # Current implementation
187    ///
188    /// In current implementation, the function tries to get the name from the first
189    /// uppercase character of the name for the first type bound.
190    pub fn for_impl_trait_as_generic(&mut self, ty: &ast::ImplTraitType) -> SmolStr {
191        let c = ty
192            .type_bound_list()
193            .and_then(|bounds| {
194                let ty = bounds.bounds().next()?.ty()?;
195                ty.syntax().text().to_smolstr().chars().find(|ch| ch.is_uppercase())
196            })
197            .unwrap_or('T');
198
199        self.suggest_name(&c.to_string())
200    }
201
202    /// Suggest name of variable for given expression
203    ///
204    /// In current implementation, the function tries to get the name from
205    /// the following sources:
206    ///
207    /// * if expr is an argument to function/method, use parameter name
208    /// * if expr is a function/method call, use function name
209    /// * expression type name if it exists (E.g. `()`, `fn() -> ()` or `!` do not have names)
210    /// * fallback: `var_name`
211    ///
212    /// It also applies heuristics to filter out less informative names
213    ///
214    /// Currently it sticks to the first name found.
215    pub fn for_variable(
216        &mut self,
217        expr: &ast::Expr,
218        sema: &Semantics<'_, RootDatabase>,
219    ) -> SmolStr {
220        self.try_for_variable(expr, sema).unwrap_or(SmolStr::new_static("var_name"))
221    }
222
223    /// Similar to `for_variable`, but fallback returns `None`
224    pub fn try_for_variable(
225        &mut self,
226        expr: &ast::Expr,
227        sema: &Semantics<'_, RootDatabase>,
228    ) -> Option<SmolStr> {
229        let edition = sema.scope(expr.syntax())?.krate().edition(sema.db);
230        // `from_param` does not benefit from stripping it need the largest
231        // context possible so we check firstmost
232        if let Some(name) = from_param(expr, sema, edition) {
233            return Some(self.suggest_name(&name));
234        }
235
236        let mut next_expr = Some(expr.clone());
237        while let Some(expr) = next_expr {
238            let name = from_call(&expr, edition)
239                .or_else(|| from_type(&expr, sema, edition))
240                .or_else(|| from_field_name(&expr, edition));
241            if let Some(name) = name {
242                return Some(self.suggest_name(&name));
243            }
244
245            match expr {
246                ast::Expr::RefExpr(inner) => next_expr = inner.expr(),
247                ast::Expr::AwaitExpr(inner) => next_expr = inner.expr(),
248                // ast::Expr::BlockExpr(block) => expr = block.tail_expr(),
249                ast::Expr::CastExpr(inner) => next_expr = inner.expr(),
250                ast::Expr::MethodCallExpr(method) if is_useless_method(&method) => {
251                    next_expr = method.receiver();
252                }
253                ast::Expr::ParenExpr(inner) => next_expr = inner.expr(),
254                ast::Expr::TryExpr(inner) => next_expr = inner.expr(),
255                ast::Expr::PrefixExpr(prefix) if prefix.op_kind() == Some(ast::UnaryOp::Deref) => {
256                    next_expr = prefix.expr()
257                }
258                _ => break,
259            }
260        }
261
262        None
263    }
264
265    /// Insert a name into the pool
266    fn insert(&mut self, name: &str) {
267        let (prefix, suffix) = Self::split_numeric_suffix(name);
268        let prefix = SmolStr::new(prefix);
269        let suffix = suffix.unwrap_or(0);
270
271        match self.pool.entry(prefix) {
272            Entry::Vacant(entry) => {
273                entry.insert(suffix);
274            }
275            Entry::Occupied(mut entry) => {
276                let count = entry.get_mut();
277                *count = (*count).max(suffix);
278            }
279        }
280    }
281
282    /// Remove the numeric suffix from the name
283    ///
284    /// # Examples
285    /// `a1b2c3` -> (`a1b2c`, Some(3))
286    fn split_numeric_suffix(name: &str) -> (&str, Option<usize>) {
287        let pos =
288            name.rfind(|c: char| !c.is_numeric()).expect("Name cannot be empty or all-numeric");
289        // `rfind` returns the byte offset of the matched character, which may be
290        // multi-byte (e.g. CJK identifiers). Use `ceil_char_boundary` to advance
291        // past the full character to the next valid split point.
292        let split = name.ceil_char_boundary(pos + 1);
293        let (prefix, suffix) = name.split_at(split);
294        (prefix, suffix.parse().ok())
295    }
296}
297
298fn normalize(name: &str, edition: syntax::Edition) -> Option<SmolStr> {
299    let name = to_lower_snake_case(name).to_smolstr();
300
301    if USELESS_NAMES.contains(&name.as_str()) {
302        return None;
303    }
304
305    if USELESS_NAME_PREFIXES.iter().any(|prefix| name.starts_with(prefix)) {
306        return None;
307    }
308
309    if !is_valid_name(&name, edition) {
310        return None;
311    }
312
313    Some(name)
314}
315
316fn is_valid_name(name: &str, edition: syntax::Edition) -> bool {
317    matches!(
318        super::LexedStr::single_token(edition, name),
319        Some((syntax::SyntaxKind::IDENT, _error))
320    )
321}
322
323fn is_useless_method(method: &ast::MethodCallExpr) -> bool {
324    let ident = method.name_ref().and_then(|it| it.ident_token());
325
326    match ident {
327        Some(ident) => USELESS_METHODS.contains(&ident.text()),
328        None => false,
329    }
330}
331
332fn from_call(expr: &ast::Expr, edition: syntax::Edition) -> Option<SmolStr> {
333    from_func_call(expr, edition).or_else(|| from_method_call(expr, edition))
334}
335
336fn from_func_call(expr: &ast::Expr, edition: syntax::Edition) -> Option<SmolStr> {
337    let call = match expr {
338        ast::Expr::CallExpr(call) => call,
339        _ => return None,
340    };
341    let func = match call.expr()? {
342        ast::Expr::PathExpr(path) => path,
343        _ => return None,
344    };
345    let ident = func.path()?.segment()?.name_ref()?.ident_token()?;
346    normalize(ident.text(), edition)
347}
348
349fn from_method_call(expr: &ast::Expr, edition: syntax::Edition) -> Option<SmolStr> {
350    let method = match expr {
351        ast::Expr::MethodCallExpr(call) => call,
352        _ => return None,
353    };
354    let ident = method.name_ref()?.ident_token()?;
355    let mut name = ident.text();
356
357    if USELESS_METHODS.contains(&name) {
358        return None;
359    }
360
361    for prefix in USELESS_METHOD_PREFIXES {
362        if let Some(suffix) = name.strip_prefix(prefix) {
363            name = suffix;
364            break;
365        }
366    }
367
368    normalize(name, edition)
369}
370
371fn from_param(
372    expr: &ast::Expr,
373    sema: &Semantics<'_, RootDatabase>,
374    edition: Edition,
375) -> Option<SmolStr> {
376    let arg_list = expr.syntax().parent().and_then(ast::ArgList::cast)?;
377    let args_parent = arg_list.syntax().parent()?;
378    let func = match_ast! {
379        match args_parent {
380            ast::CallExpr(call) => {
381                let func = call.expr()?;
382                let func_ty = sema.type_of_expr(&func)?.adjusted();
383                func_ty.as_callable(sema.db)?
384            },
385            ast::MethodCallExpr(method) => sema.resolve_method_call_as_callable(&method)?,
386            _ => return None,
387        }
388    };
389
390    let (idx, _) = arg_list.args().find_position(|it| it == expr).unwrap();
391    let param = func.params().into_iter().nth(idx)?;
392    let pat = sema.source(param)?.value.right()?.pat()?;
393    let name = var_name_from_pat(&pat)?;
394    normalize(&name.to_smolstr(), edition)
395}
396
397fn var_name_from_pat(pat: &ast::Pat) -> Option<ast::Name> {
398    match pat {
399        ast::Pat::IdentPat(var) => var.name(),
400        ast::Pat::RefPat(ref_pat) => var_name_from_pat(&ref_pat.pat()?),
401        ast::Pat::BoxPat(box_pat) => var_name_from_pat(&box_pat.pat()?),
402        _ => None,
403    }
404}
405
406fn from_type(
407    expr: &ast::Expr,
408    sema: &Semantics<'_, RootDatabase>,
409    edition: Edition,
410) -> Option<SmolStr> {
411    let ty = sema.type_of_expr(expr)?.adjusted();
412    let ty = ty.strip_reference();
413
414    name_of_type(&ty, sema.db, edition)
415}
416
417fn name_of_type<'db>(
418    ty: &hir::Type<'db>,
419    db: &'db RootDatabase,
420    edition: Edition,
421) -> Option<SmolStr> {
422    let name = if let Some(adt) = ty.as_adt() {
423        let name = adt.name(db).display(db, edition).to_string();
424
425        if WRAPPER_TYPES.contains(&name.as_str()) {
426            let inner_ty = ty.type_arguments().next()?;
427            return name_of_type(&inner_ty, db, edition);
428        }
429
430        if SEQUENCE_TYPES.contains(&name.as_str()) {
431            let inner_ty = ty.type_arguments().next();
432            return Some(sequence_name(inner_ty.as_ref(), db, edition));
433        }
434
435        name
436    } else if let Some(trait_) = ty.as_dyn_trait() {
437        trait_name(&trait_, db, edition)?
438    } else if let Some(traits) = ty.as_impl_traits(db) {
439        let mut iter = traits.filter_map(|t| trait_name(&t, db, edition));
440        let name = iter.next()?;
441        if iter.next().is_some() {
442            return None;
443        }
444        name
445    } else if let Some((inner_ty, _)) = ty.as_reference() {
446        return name_of_type(&inner_ty, db, edition);
447    } else {
448        let inner_ty = ty.as_slice()?;
449        return Some(sequence_name(Some(&inner_ty), db, edition));
450    };
451    normalize(&name, edition)
452}
453
454fn sequence_name<'db>(
455    inner_ty: Option<&hir::Type<'db>>,
456    db: &'db RootDatabase,
457    edition: Edition,
458) -> SmolStr {
459    let items_str = SmolStr::new_static("items");
460    let Some(inner_ty) = inner_ty else {
461        return items_str;
462    };
463    let Some(name) = name_of_type(inner_ty, db, edition) else {
464        return items_str;
465    };
466
467    if name.ends_with(['s', 'x', 'y']) {
468        // Given a type called e.g. "Boss", "Fox" or "Story", don't try to
469        // create a plural.
470        items_str
471    } else {
472        SmolStr::new(format!("{name}s"))
473    }
474}
475
476fn trait_name(trait_: &hir::Trait, db: &RootDatabase, edition: Edition) -> Option<String> {
477    let name = trait_.name(db).display(db, edition).to_string();
478    if USELESS_TRAITS.contains(&name.as_str()) {
479        return None;
480    }
481    Some(name)
482}
483
484fn from_field_name(expr: &ast::Expr, edition: syntax::Edition) -> Option<SmolStr> {
485    let field = match expr {
486        ast::Expr::FieldExpr(field) => field,
487        _ => return None,
488    };
489    let ident = field.name_ref()?.ident_token()?;
490    normalize(ident.text(), edition)
491}
492
493#[cfg(test)]
494mod tests {
495    use hir::FileRange;
496    use test_fixture::WithFixture;
497
498    use super::*;
499
500    #[track_caller]
501    fn check(#[rust_analyzer::rust_fixture] ra_fixture: &str, expected: &str) {
502        let (db, file_id, range_or_offset) = RootDatabase::with_range_or_offset(ra_fixture);
503        let frange = FileRange { file_id, range: range_or_offset.into() };
504        let sema = Semantics::new(&db);
505
506        let source_file = sema.parse(frange.file_id);
507
508        let element = source_file.syntax().covering_element(frange.range);
509        let expr =
510            element.ancestors().find_map(ast::Expr::cast).expect("selection is not an expression");
511        assert_eq!(
512            expr.syntax().text_range(),
513            frange.range,
514            "selection is not an expression(yet contained in one)"
515        );
516        let name = hir::attach_db(sema.db, || NameGenerator::default().for_variable(&expr, &sema));
517        assert_eq!(&name, expected);
518    }
519
520    #[test]
521    fn no_args() {
522        check(r#"fn foo() { $0bar()$0 }"#, "bar");
523        check(r#"fn foo() { $0bar.frobnicate()$0 }"#, "frobnicate");
524    }
525
526    #[test]
527    fn single_arg() {
528        check(r#"fn foo() { $0bar(1)$0 }"#, "bar");
529    }
530
531    #[test]
532    fn many_args() {
533        check(r#"fn foo() { $0bar(1, 2, 3)$0 }"#, "bar");
534    }
535
536    #[test]
537    fn path() {
538        check(r#"fn foo() { $0i32::bar(1, 2, 3)$0 }"#, "bar");
539    }
540
541    #[test]
542    fn generic_params() {
543        check(r#"fn foo() { $0bar::<i32>(1, 2, 3)$0 }"#, "bar");
544        check(r#"fn foo() { $0bar.frobnicate::<i32, u32>()$0 }"#, "frobnicate");
545    }
546
547    #[test]
548    fn to_name() {
549        check(
550            r#"
551struct Args;
552struct Config;
553impl Args {
554    fn to_config(&self) -> Config {}
555}
556fn foo() {
557    $0Args.to_config()$0;
558}
559"#,
560            "config",
561        );
562    }
563
564    #[test]
565    fn plain_func() {
566        check(
567            r#"
568fn bar(n: i32, m: u32);
569fn foo() { bar($01$0, 2) }
570"#,
571            "n",
572        );
573    }
574
575    #[test]
576    fn mut_param() {
577        check(
578            r#"
579fn bar(mut n: i32, m: u32);
580fn foo() { bar($01$0, 2) }
581"#,
582            "n",
583        );
584    }
585
586    #[test]
587    fn func_does_not_exist() {
588        check(r#"fn foo() { bar($01$0, 2) }"#, "var_name");
589    }
590
591    #[test]
592    fn unnamed_param() {
593        check(
594            r#"
595fn bar(_: i32, m: u32);
596fn foo() { bar($01$0, 2) }
597"#,
598            "var_name",
599        );
600    }
601
602    #[test]
603    fn tuple_pat() {
604        check(
605            r#"
606fn bar((n, k): (i32, i32), m: u32);
607fn foo() {
608    bar($0(1, 2)$0, 3)
609}
610"#,
611            "var_name",
612        );
613    }
614
615    #[test]
616    fn ref_pat() {
617        check(
618            r#"
619fn bar(&n: &i32, m: u32);
620fn foo() { bar($0&1$0, 3) }
621"#,
622            "n",
623        );
624    }
625
626    #[test]
627    fn box_pat() {
628        check(
629            r#"
630fn bar(box n: &i32, m: u32);
631fn foo() { bar($01$0, 3) }
632"#,
633            "n",
634        );
635    }
636
637    #[test]
638    fn param_out_of_index() {
639        check(
640            r#"
641fn bar(n: i32, m: u32);
642fn foo() { bar(1, 2, $03$0) }
643"#,
644            "var_name",
645        );
646    }
647
648    #[test]
649    fn generic_param_resolved() {
650        check(
651            r#"
652fn bar<T>(n: T, m: u32);
653fn foo() { bar($01$0, 2) }
654"#,
655            "n",
656        );
657    }
658
659    #[test]
660    fn generic_param_unresolved() {
661        check(
662            r#"
663fn bar<T>(n: T, m: u32);
664fn foo<T>(x: T) { bar($0x$0, 2) }
665"#,
666            "n",
667        );
668    }
669
670    #[test]
671    fn method() {
672        check(
673            r#"
674struct S;
675impl S { fn bar(&self, n: i32, m: u32); }
676fn foo() { S.bar($01$0, 2) }
677"#,
678            "n",
679        );
680    }
681
682    #[test]
683    fn method_on_impl_trait() {
684        check(
685            r#"
686struct S;
687trait T {
688    fn bar(&self, n: i32, m: u32);
689}
690impl T for S { fn bar(&self, n: i32, m: u32); }
691fn foo() { S.bar($01$0, 2) }
692"#,
693            "n",
694        );
695    }
696
697    #[test]
698    fn method_ufcs() {
699        check(
700            r#"
701struct S;
702impl S { fn bar(&self, n: i32, m: u32); }
703fn foo() { S::bar(&S, $01$0, 2) }
704"#,
705            "n",
706        );
707    }
708
709    #[test]
710    fn method_self() {
711        check(
712            r#"
713struct S;
714impl S { fn bar(&self, n: i32, m: u32); }
715fn foo() { S::bar($0&S$0, 1, 2) }
716"#,
717            "s",
718        );
719    }
720
721    #[test]
722    fn method_self_named() {
723        check(
724            r#"
725struct S;
726impl S { fn bar(strukt: &Self, n: i32, m: u32); }
727fn foo() { S::bar($0&S$0, 1, 2) }
728"#,
729            "strukt",
730        );
731    }
732
733    #[test]
734    fn i32() {
735        check(r#"fn foo() { let _: i32 = $01$0; }"#, "var_name");
736    }
737
738    #[test]
739    fn u64() {
740        check(r#"fn foo() { let _: u64 = $01$0; }"#, "var_name");
741    }
742
743    #[test]
744    fn bool() {
745        check(r#"fn foo() { let _: bool = $0true$0; }"#, "var_name");
746    }
747
748    #[test]
749    fn struct_unit() {
750        check(
751            r#"
752struct Seed;
753fn foo() { let _ = $0Seed$0; }
754"#,
755            "seed",
756        );
757    }
758
759    #[test]
760    fn struct_unit_to_snake() {
761        check(
762            r#"
763struct SeedState;
764fn foo() { let _ = $0SeedState$0; }
765"#,
766            "seed_state",
767        );
768    }
769
770    #[test]
771    fn struct_single_arg() {
772        check(
773            r#"
774struct Seed(u32);
775fn foo() { let _ = $0Seed(0)$0; }
776"#,
777            "seed",
778        );
779    }
780
781    #[test]
782    fn struct_with_fields() {
783        check(
784            r#"
785struct Seed { value: u32 }
786fn foo() { let _ = $0Seed { value: 0 }$0; }
787"#,
788            "seed",
789        );
790    }
791
792    #[test]
793    fn enum_() {
794        check(
795            r#"
796enum Kind { A, B }
797fn foo() { let _ = $0Kind::A$0; }
798"#,
799            "kind",
800        );
801    }
802
803    #[test]
804    fn enum_generic_resolved() {
805        check(
806            r#"
807enum Kind<T> { A { x: T }, B }
808fn foo() { let _ = $0Kind::A { x:1 }$0; }
809"#,
810            "kind",
811        );
812    }
813
814    #[test]
815    fn enum_generic_unresolved() {
816        check(
817            r#"
818enum Kind<T> { A { x: T }, B }
819fn foo<T>(x: T) { let _ = $0Kind::A { x }$0; }
820"#,
821            "kind",
822        );
823    }
824
825    #[test]
826    fn dyn_trait() {
827        check(
828            r#"
829trait DynHandler {}
830fn bar() -> dyn DynHandler {}
831fn foo() { $0(bar())$0; }
832"#,
833            "dyn_handler",
834        );
835    }
836
837    #[test]
838    fn impl_trait() {
839        check(
840            r#"
841trait StaticHandler {}
842fn bar() -> impl StaticHandler {}
843fn foo() { $0(bar())$0; }
844"#,
845            "static_handler",
846        );
847    }
848
849    #[test]
850    fn impl_trait_plus_clone() {
851        check(
852            r#"
853trait StaticHandler {}
854trait Clone {}
855fn bar() -> impl StaticHandler + Clone {}
856fn foo() { $0(bar())$0; }
857"#,
858            "static_handler",
859        );
860    }
861
862    #[test]
863    fn impl_trait_plus_lifetime() {
864        check(
865            r#"
866trait StaticHandler {}
867trait Clone {}
868fn bar<'a>(&'a i32) -> impl StaticHandler + 'a {}
869fn foo() { $0(bar(&1))$0; }
870"#,
871            "static_handler",
872        );
873    }
874
875    #[test]
876    fn impl_trait_plus_trait() {
877        check(
878            r#"
879trait Handler {}
880trait StaticHandler {}
881fn bar() -> impl StaticHandler + Handler {}
882fn foo() { $0(bar())$0; }
883"#,
884            "bar",
885        );
886    }
887
888    #[test]
889    fn ref_value() {
890        check(
891            r#"
892struct Seed;
893fn bar() -> &Seed {}
894fn foo() { $0(bar())$0; }
895"#,
896            "seed",
897        );
898    }
899
900    #[test]
901    fn box_value() {
902        check(
903            r#"
904struct Box<T>(*const T);
905struct Seed;
906fn bar() -> Box<Seed> {}
907fn foo() { $0(bar())$0; }
908"#,
909            "seed",
910        );
911    }
912
913    #[test]
914    fn box_generic() {
915        check(
916            r#"
917struct Box<T>(*const T);
918fn bar<T>() -> Box<T> {}
919fn foo<T>() { $0(bar::<T>())$0; }
920"#,
921            "bar",
922        );
923    }
924
925    #[test]
926    fn option_value() {
927        check(
928            r#"
929enum Option<T> { Some(T) }
930struct Seed;
931fn bar() -> Option<Seed> {}
932fn foo() { $0(bar())$0; }
933"#,
934            "seed",
935        );
936    }
937
938    #[test]
939    fn result_value() {
940        check(
941            r#"
942enum Result<T, E> { Ok(T), Err(E) }
943struct Seed;
944struct Error;
945fn bar() -> Result<Seed, Error> {}
946fn foo() { $0(bar())$0; }
947"#,
948            "seed",
949        );
950    }
951
952    #[test]
953    fn arc_value() {
954        check(
955            r#"
956struct Arc<T>(*const T);
957struct Seed;
958fn bar() -> Arc<Seed> {}
959fn foo() { $0(bar())$0; }
960"#,
961            "seed",
962        );
963    }
964
965    #[test]
966    fn rc_value() {
967        check(
968            r#"
969struct Rc<T>(*const T);
970struct Seed;
971fn bar() -> Rc<Seed> {}
972fn foo() { $0(bar())$0; }
973"#,
974            "seed",
975        );
976    }
977
978    #[test]
979    fn vec_value() {
980        check(
981            r#"
982struct Vec<T> {};
983struct Seed;
984fn bar() -> Vec<Seed> {}
985fn foo() { $0(bar())$0; }
986"#,
987            "seeds",
988        );
989    }
990
991    #[test]
992    fn vec_value_ends_with_s() {
993        check(
994            r#"
995struct Vec<T> {};
996struct Boss;
997fn bar() -> Vec<Boss> {}
998fn foo() { $0(bar())$0; }
999"#,
1000            "items",
1001        );
1002    }
1003
1004    #[test]
1005    fn vecdeque_value() {
1006        check(
1007            r#"
1008struct VecDeque<T> {};
1009struct Seed;
1010fn bar() -> VecDeque<Seed> {}
1011fn foo() { $0(bar())$0; }
1012"#,
1013            "seeds",
1014        );
1015    }
1016
1017    #[test]
1018    fn slice_value() {
1019        check(
1020            r#"
1021struct Vec<T> {};
1022struct Seed;
1023fn bar() -> &[Seed] {}
1024fn foo() { $0(bar())$0; }
1025"#,
1026            "seeds",
1027        );
1028    }
1029
1030    #[test]
1031    fn ref_call() {
1032        check(
1033            r#"
1034fn foo() { $0&bar(1, 3)$0 }
1035"#,
1036            "bar",
1037        );
1038    }
1039
1040    #[test]
1041    fn name_to_string() {
1042        check(
1043            r#"
1044fn foo() { $0function.name().to_string()$0 }
1045"#,
1046            "name",
1047        );
1048    }
1049
1050    #[test]
1051    fn nested_useless_method() {
1052        check(
1053            r#"
1054fn foo() { $0function.name().as_ref().unwrap().to_string()$0 }
1055"#,
1056            "name",
1057        );
1058    }
1059
1060    #[test]
1061    fn struct_field_name() {
1062        check(
1063            r#"
1064struct S<T> {
1065    some_field: T;
1066}
1067fn foo<T>(some_struct: S<T>) { $0some_struct.some_field$0 }
1068"#,
1069            "some_field",
1070        );
1071    }
1072
1073    #[test]
1074    fn from_and_to_func() {
1075        check(
1076            r#"
1077//- minicore: from
1078struct Foo;
1079struct Bar;
1080
1081impl From<Foo> for Bar {
1082    fn from(_: Foo) -> Self {
1083        Bar;
1084    }
1085}
1086
1087fn f(_: Bar) {}
1088
1089fn main() {
1090    let foo = Foo {};
1091    f($0Bar::from(foo)$0);
1092}
1093"#,
1094            "bar",
1095        );
1096
1097        check(
1098            r#"
1099//- minicore: from
1100struct Foo;
1101struct Bar;
1102
1103impl From<Foo> for Bar {
1104    fn from(_: Foo) -> Self {
1105        Bar;
1106    }
1107}
1108
1109fn f(_: Bar) {}
1110
1111fn main() {
1112    let foo = Foo {};
1113    f($0Into::<Bar>::into(foo)$0);
1114}
1115"#,
1116            "bar",
1117        );
1118    }
1119
1120    #[test]
1121    fn useless_name_prefix() {
1122        check(
1123            r#"
1124struct Foo;
1125struct Bar;
1126
1127impl Bar {
1128    fn from_foo(_: Foo) -> Self {
1129        Foo {}
1130    }
1131}
1132
1133fn main() {
1134    let foo = Foo {};
1135    let _ = $0Bar::from_foo(foo)$0;
1136}
1137"#,
1138            "bar",
1139        );
1140
1141        check(
1142            r#"
1143struct Foo;
1144struct Bar;
1145
1146impl Bar {
1147    fn with_foo(_: Foo) -> Self {
1148        Bar {}
1149    }
1150}
1151
1152fn main() {
1153    let foo = Foo {};
1154    let _ = $0Bar::with_foo(foo)$0;
1155}
1156"#,
1157            "bar",
1158        );
1159    }
1160
1161    #[test]
1162    fn conflicts_with_existing_names() {
1163        let mut generator = NameGenerator::default();
1164        assert_eq!(generator.suggest_name("a"), "a");
1165        assert_eq!(generator.suggest_name("a"), "a1");
1166        assert_eq!(generator.suggest_name("a"), "a2");
1167        assert_eq!(generator.suggest_name("a"), "a3");
1168
1169        assert_eq!(generator.suggest_name("b"), "b");
1170        assert_eq!(generator.suggest_name("b2"), "b2");
1171        assert_eq!(generator.suggest_name("b"), "b3");
1172        assert_eq!(generator.suggest_name("b"), "b4");
1173        assert_eq!(generator.suggest_name("b3"), "b5");
1174
1175        // ---------
1176        let mut generator = NameGenerator::new_with_names(["a", "b", "b2", "c4"].into_iter());
1177        assert_eq!(generator.suggest_name("a"), "a1");
1178        assert_eq!(generator.suggest_name("a"), "a2");
1179
1180        assert_eq!(generator.suggest_name("b"), "b3");
1181        assert_eq!(generator.suggest_name("b2"), "b4");
1182
1183        assert_eq!(generator.suggest_name("c"), "c5");
1184    }
1185}