1 //! Tests and test utilities for completions.
3 //! Most tests live in this module or its submodules. The tests in these submodules are "location"
4 //! oriented, that is they try to check completions for something like type position, param position
6 //! Tests that are more orientated towards specific completion types like visibility checks of path
7 //! completions or `check_edit` tests usually live in their respective completion modules instead.
8 //! This gives this test module and its submodules here the main purpose of giving the developer an
9 //! overview of whats being completed where, not how.
27 use hir::{db::DefDatabase, PrefixKind, Semantics};
29 base_db::{fixture::ChangeFixture, FileLoader, FilePosition},
31 insert_use::{ImportGranularity, InsertUseConfig},
36 use itertools::Itertools;
37 use stdx::{format_to, trim_indent};
38 use syntax::{AstNode, NodeOrToken, SyntaxElement};
39 use test_utils::assert_eq_text;
41 use crate::{CompletionConfig, CompletionItem, CompletionItemKind};
43 /// Lots of basic item definitions
44 const BASE_ITEMS_FIXTURE: &str = r#"
45 enum Enum { TupleV(u32), RecordV { field: u32 }, UnitV }
46 use self::Enum::TupleV;
50 static STATIC: Unit = Unit;
51 const CONST: Unit = Unit;
52 struct Record { field: u32 }
57 #[rustc_builtin_macro]
60 union Union { field: i32 }
63 pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig {
64 enable_postfix_completions: true,
65 enable_imports_on_the_fly: true,
66 enable_self_on_the_fly: true,
67 add_call_parenthesis: true,
68 add_call_argument_snippets: true,
69 snippet_cap: SnippetCap::new(true),
70 insert_use: InsertUseConfig {
71 granularity: ImportGranularity::Crate,
72 prefix_kind: PrefixKind::Plain,
73 enforce_granularity: true,
75 skip_glob_imports: true,
80 pub(crate) fn completion_list(ra_fixture: &str) -> String {
81 completion_list_with_config(TEST_CONFIG, ra_fixture, true)
84 pub(crate) fn completion_list_no_kw(ra_fixture: &str) -> String {
85 completion_list_with_config(TEST_CONFIG, ra_fixture, false)
88 fn completion_list_with_config(
89 config: CompletionConfig,
91 include_keywords: bool,
93 // filter out all but one builtintype completion for smaller test outputs
94 let items = get_all_items(config, ra_fixture);
95 let mut bt_seen = false;
99 it.kind() != CompletionItemKind::BuiltinType || !mem::replace(&mut bt_seen, true)
101 .filter(|it| include_keywords || it.kind() != CompletionItemKind::Keyword)
102 .filter(|it| include_keywords || it.kind() != CompletionItemKind::Snippet)
104 render_completion_list(items)
107 /// Creates analysis from a multi-file fixture, returns positions marked with $0.
108 pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) {
109 let change_fixture = ChangeFixture::parse(ra_fixture);
110 let mut database = RootDatabase::default();
111 database.set_enable_proc_attr_macros(true);
112 database.apply_change(change_fixture.change);
113 let (file_id, range_or_offset) = change_fixture.file_position.expect("expected a marker ($0)");
114 let offset = range_or_offset.expect_offset();
115 (database, FilePosition { file_id, offset })
118 pub(crate) fn do_completion(code: &str, kind: CompletionItemKind) -> Vec<CompletionItem> {
119 do_completion_with_config(TEST_CONFIG, code, kind)
122 pub(crate) fn do_completion_with_config(
123 config: CompletionConfig,
125 kind: CompletionItemKind,
126 ) -> Vec<CompletionItem> {
127 get_all_items(config, code)
129 .filter(|c| c.kind() == kind)
130 .sorted_by(|l, r| l.label().cmp(r.label()))
134 fn render_completion_list(completions: Vec<CompletionItem>) -> String {
135 fn monospace_width(s: &str) -> usize {
139 completions.iter().map(|it| monospace_width(it.label())).max().unwrap_or_default().min(22);
143 let tag = it.kind().tag();
144 let var_name = format!("{} {}", tag, it.label());
145 let mut buf = var_name;
146 if let Some(detail) = it.detail() {
147 let width = label_width.saturating_sub(monospace_width(it.label()));
148 format_to!(buf, "{:width$} {}", "", detail, width = width);
151 format_to!(buf, " DEPRECATED");
153 format_to!(buf, "\n");
159 pub(crate) fn check_edit(what: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
160 check_edit_with_config(TEST_CONFIG, what, ra_fixture_before, ra_fixture_after)
163 pub(crate) fn check_edit_with_config(
164 config: CompletionConfig,
166 ra_fixture_before: &str,
167 ra_fixture_after: &str,
169 let ra_fixture_after = trim_indent(ra_fixture_after);
170 let (db, position) = position(ra_fixture_before);
171 let completions: Vec<CompletionItem> =
172 crate::completions(&db, &config, position).unwrap().into();
173 let (completion,) = completions
175 .filter(|it| it.lookup() == what)
177 .unwrap_or_else(|| panic!("can't find {:?} completion in {:#?}", what, completions));
178 let mut actual = db.file_text(position.file_id).to_string();
180 let mut combined_edit = completion.text_edit().to_owned();
184 .filter_map(|edit| edit.to_text_edit(config.insert_use))
185 .for_each(|text_edit| {
186 combined_edit.union(text_edit).expect(
187 "Failed to apply completion resolve changes: change ranges overlap, but should not",
191 combined_edit.apply(&mut actual);
192 assert_eq_text!(&ra_fixture_after, &actual)
195 pub(crate) fn check_pattern_is_applicable(code: &str, check: impl FnOnce(SyntaxElement) -> bool) {
196 let (db, pos) = position(code);
198 let sema = Semantics::new(&db);
199 let original_file = sema.parse(pos.file_id);
200 let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
201 assert!(check(NodeOrToken::Token(token)));
204 pub(crate) fn check_pattern_is_not_applicable(code: &str, check: fn(SyntaxElement) -> bool) {
205 let (db, pos) = position(code);
206 let sema = Semantics::new(&db);
207 let original_file = sema.parse(pos.file_id);
208 let token = original_file.syntax().token_at_offset(pos.offset).left_biased().unwrap();
209 assert!(!check(NodeOrToken::Token(token)));
212 pub(crate) fn get_all_items(config: CompletionConfig, code: &str) -> Vec<CompletionItem> {
213 let (db, position) = position(code);
214 crate::completions(&db, &config, position).map_or_else(Vec::default, Into::into)
217 fn check_no_completion(ra_fixture: &str) {
218 let (db, position) = position(ra_fixture);
221 crate::completions(&db, &TEST_CONFIG, position).is_none(),
222 "Completions were generated, but weren't expected"
227 fn test_no_completions_required() {
228 cov_mark::check!(no_completion_required);
229 check_no_completion(r#"fn foo() { for i i$0 }"#);
233 fn regression_10042() {
236 macro_rules! preset {
237 ($($x:ident)&&*) => {
239 let mut v = Vec::new();
256 fn no_completions_in_comments() {
257 cov_mark::check!(no_keyword_completion_in_comments);
262 let x = 2; // A comment$0
272 Some multi-line comment$0