]> git.lizzy.rs Git - rust.git/blob - crates/completion/src/test_utils.rs
6ea6da9893c8bfb60bae3eb4f4dfa38ecc09a3a9
[rust.git] / crates / completion / src / test_utils.rs
1 //! Runs completion for testing purposes.
2
3 use hir::{PrefixKind, Semantics};
4 use ide_db::{
5     base_db::{fixture::ChangeFixture, FileLoader, FilePosition},
6     helpers::{
7         insert_use::{InsertUseConfig, MergeBehavior},
8         SnippetCap,
9     },
10     RootDatabase,
11 };
12 use itertools::Itertools;
13 use stdx::{format_to, trim_indent};
14 use syntax::{AstNode, NodeOrToken, SyntaxElement};
15 use test_utils::{assert_eq_text, RangeOrOffset};
16
17 use crate::{item::CompletionKind, CompletionConfig, CompletionItem};
18
19 pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig {
20     enable_postfix_completions: true,
21     enable_autoimport_completions: true,
22     add_call_parenthesis: true,
23     add_call_argument_snippets: true,
24     snippet_cap: SnippetCap::new(true),
25     insert_use: InsertUseConfig {
26         merge: Some(MergeBehavior::Full),
27         prefix_kind: PrefixKind::Plain,
28     },
29 };
30
31 /// Creates analysis from a multi-file fixture, returns positions marked with $0.
32 pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) {
33     let change_fixture = ChangeFixture::parse(ra_fixture);
34     let mut database = RootDatabase::default();
35     database.apply_change(change_fixture.change);
36     let (file_id, range_or_offset) = change_fixture.file_position.expect("expected a marker ($0)");
37     let offset = match range_or_offset {
38         RangeOrOffset::Range(_) => panic!(),
39         RangeOrOffset::Offset(it) => it,
40     };
41     (database, FilePosition { file_id, offset })
42 }
43
44 pub(crate) fn do_completion(code: &str, kind: CompletionKind) -> Vec<CompletionItem> {
45     do_completion_with_config(TEST_CONFIG, code, kind)
46 }
47
48 pub(crate) fn do_completion_with_config(
49     config: CompletionConfig,
50     code: &str,
51     kind: CompletionKind,
52 ) -> Vec<CompletionItem> {
53     let mut kind_completions: Vec<CompletionItem> =
54         get_all_items(config, code).into_iter().filter(|c| c.completion_kind == kind).collect();
55     kind_completions.sort_by(|l, r| l.label().cmp(r.label()));
56     kind_completions
57 }
58
59 pub(crate) fn completion_list(code: &str, kind: CompletionKind) -> String {
60     completion_list_with_config(TEST_CONFIG, code, kind)
61 }
62
63 pub(crate) fn completion_list_with_config(
64     config: CompletionConfig,
65     code: &str,
66     kind: CompletionKind,
67 ) -> String {
68     let kind_completions: Vec<CompletionItem> =
69         get_all_items(config, code).into_iter().filter(|c| c.completion_kind == kind).collect();
70     let label_width = kind_completions
71         .iter()
72         .map(|it| monospace_width(it.label()))
73         .max()
74         .unwrap_or_default()
75         .min(16);
76     kind_completions
77         .into_iter()
78         .map(|it| {
79             let tag = it.kind().unwrap().tag();
80             let var_name = format!("{} {}", tag, it.label());
81             let mut buf = var_name;
82             if let Some(detail) = it.detail() {
83                 let width = label_width.saturating_sub(monospace_width(it.label()));
84                 format_to!(buf, "{:width$} {}", "", detail, width = width);
85             }
86             format_to!(buf, "\n");
87             buf
88         })
89         .collect()
90 }
91
92 fn monospace_width(s: &str) -> usize {
93     s.chars().count()
94 }
95
96 pub(crate) fn check_edit(what: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
97     check_edit_with_config(TEST_CONFIG, what, ra_fixture_before, ra_fixture_after)
98 }
99
100 pub(crate) fn check_edit_with_config(
101     config: CompletionConfig,
102     what: &str,
103     ra_fixture_before: &str,
104     ra_fixture_after: &str,
105 ) {
106     let ra_fixture_after = trim_indent(ra_fixture_after);
107     let (db, position) = position(ra_fixture_before);
108     let completions: Vec<CompletionItem> =
109         crate::completions(&db, &config, position).unwrap().into();
110     let (completion,) = completions
111         .iter()
112         .filter(|it| it.lookup() == what)
113         .collect_tuple()
114         .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions));
115     let mut actual = db.file_text(position.file_id).to_string();
116
117     let mut combined_edit = completion.text_edit().to_owned();
118     if let Some(import_text_edit) =
119         completion.import_to_add().and_then(|edit| edit.to_text_edit(config.insert_use.merge))
120     {
121         combined_edit.union(import_text_edit).expect(
122             "Failed to apply completion resolve changes: change ranges overlap, but should not",
123         )
124     }
125
126     combined_edit.apply(&mut actual);
127     assert_eq_text!(&ra_fixture_after, &actual)
128 }
129
130 pub(crate) fn check_pattern_is_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
131     let (db, pos) = position(code);
132
133     let sema = Semantics::new(&db);
134     let original_file = sema.parse(pos.file_id);
135     let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
136     assert!(check(NodeOrToken::Token(token)));
137 }
138
139 pub(crate) fn check_pattern_is_not_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
140     let (db, pos) = position(code);
141     let sema = Semantics::new(&db);
142     let original_file = sema.parse(pos.file_id);
143     let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
144     assert!(!check(NodeOrToken::Token(token)));
145 }
146
147 pub(crate) fn get_all_items(config: CompletionConfig, code: &str) -> Vec<CompletionItem> {
148     let (db, position) = position(code);
149     crate::completions(&db, &config, position).unwrap().into()
150 }