2020-10-18 10:09:00 +00:00
//! `completions` crate provides utilities for generating completions of user input.
2021-06-16 15:37:23 +00:00
mod completions ;
2020-10-25 07:59:15 +00:00
mod config ;
mod context ;
2021-06-16 15:37:23 +00:00
mod item ;
2020-11-01 09:35:04 +00:00
mod render ;
2019-01-08 19:33:36 +00:00
2024-01-26 19:08:10 +00:00
mod snippet ;
2021-06-16 15:37:23 +00:00
#[ cfg(test) ]
mod tests ;
2019-01-08 19:33:36 +00:00
2024-05-17 19:00:21 +00:00
use hir ::ImportPathConfig ;
2020-12-04 14:03:22 +00:00
use ide_db ::{
2021-02-24 23:06:31 +00:00
base_db ::FilePosition ,
2022-03-06 18:01:30 +00:00
helpers ::mod_path_to_ast ,
imports ::{
2021-10-04 20:05:30 +00:00
import_assets ::NameToImport ,
insert_use ::{ self , ImportScope } ,
2021-03-20 13:02:52 +00:00
} ,
2021-03-02 23:26:53 +00:00
items_locator , RootDatabase ,
2020-12-04 14:03:22 +00:00
} ;
2021-10-04 20:05:30 +00:00
use syntax ::algo ;
2020-12-04 14:03:22 +00:00
use text_edit ::TextEdit ;
2019-01-08 19:33:36 +00:00
2022-06-17 21:36:39 +00:00
use crate ::{
completions ::Completions ,
2022-06-20 11:17:30 +00:00
context ::{
2022-06-20 15:41:04 +00:00
CompletionAnalysis , CompletionContext , NameRefContext , NameRefKind , PathCompletionCtx ,
PathKind ,
2022-06-20 11:17:30 +00:00
} ,
2022-06-17 21:36:39 +00:00
} ;
2019-01-08 19:33:36 +00:00
2020-10-18 10:09:00 +00:00
pub use crate ::{
2022-05-13 17:52:44 +00:00
config ::{ CallableSnippets , CompletionConfig } ,
2022-04-01 17:50:27 +00:00
item ::{
CompletionItem , CompletionItemKind , CompletionRelevance , CompletionRelevancePostfixMatch ,
} ,
2021-10-05 15:18:40 +00:00
snippet ::{ Snippet , SnippetScope } ,
2019-07-04 20:05:17 +00:00
} ;
2019-01-08 19:33:36 +00:00
2020-05-31 09:29:19 +00:00
//FIXME: split the following feature into fine-grained features.
// Feature: Magic Completions
//
// In addition to usual reference completion, rust-analyzer provides some ✨magic✨
// completions as well:
//
// Keywords like `if`, `else` `while`, `loop` are completed with braces, and cursor
// is placed at the appropriate position. Even though `if` is easy to type, you
// still want to complete it, to get ` { }` for free! `return` is inserted with a
// space or `;` depending on the return type of the function.
//
// When completing a function call, `()` are automatically inserted. If a function
// takes arguments, the cursor is positioned inside the parenthesis.
//
// There are postfix completions, which can be triggered by typing something like
// `foo().if`. The word after `.` determines postfix completion. Possible variants are:
//
// - `expr.if` -> `if expr {}` or `if let ... {}` for `Option` or `Result`
// - `expr.match` -> `match expr {}`
// - `expr.while` -> `while expr {}` or `while let ... {}` for `Option` or `Result`
// - `expr.ref` -> `&expr`
// - `expr.refm` -> `&mut expr`
2021-01-06 20:15:48 +00:00
// - `expr.let` -> `let $0 = expr;`
2024-02-06 11:13:51 +00:00
// - `expr.lete` -> `let $1 = expr else { $0 };`
2021-01-06 20:15:48 +00:00
// - `expr.letm` -> `let mut $0 = expr;`
2020-05-31 09:29:19 +00:00
// - `expr.not` -> `!expr`
// - `expr.dbg` -> `dbg!(expr)`
2020-10-14 13:23:51 +00:00
// - `expr.dbgr` -> `dbg!(&expr)`
// - `expr.call` -> `(expr)`
2020-05-31 09:29:19 +00:00
//
// There also snippet completions:
//
// .Expressions
2020-07-19 16:25:19 +00:00
// - `pd` -> `eprintln!(" = {:?}", );`
2020-07-02 03:06:00 +00:00
// - `ppd` -> `eprintln!(" = {:#?}", );`
2020-05-31 09:29:19 +00:00
//
// .Items
2020-07-02 03:06:00 +00:00
// - `tfn` -> `#[test] fn feature(){}`
2020-05-31 09:29:19 +00:00
// - `tmod` ->
// ```rust
// #[cfg(test)]
// mod tests {
// use super::*;
//
// #[test]
2020-07-02 03:06:00 +00:00
// fn test_name() {}
2020-05-31 09:29:19 +00:00
// }
// ```
2020-11-24 22:42:58 +00:00
//
2020-12-08 12:27:18 +00:00
// And the auto import completions, enabled with the `rust-analyzer.completion.autoimport.enable` setting and the corresponding LSP client capabilities.
// Those are the additional completion options with automatic `use` import and options from all project importable items,
2021-05-10 18:05:32 +00:00
// fuzzy matched against the completion input.
2021-03-30 23:08:10 +00:00
//
// image::https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif[]
2020-05-31 09:29:19 +00:00
2019-01-08 19:33:36 +00:00
/// Main entry point for completion. We run completion as a two-phase process.
///
2023-03-29 12:08:25 +00:00
/// First, we look at the position and collect a so-called `CompletionContext`.
2019-01-08 19:33:36 +00:00
/// This is a somewhat messy process, because, during completion, syntax tree is
/// incomplete and can look really weird.
///
/// Once the context is collected, we run a series of completion routines which
2019-02-11 16:18:27 +00:00
/// look at the context and produce completion items. One subtlety about this
2019-01-08 19:33:36 +00:00
/// phase is that completion engine should not filter by the substring which is
/// already present, it should give all possible variants for the identifier at
/// the caret. In other words, for
///
2020-08-22 19:03:02 +00:00
/// ```no_run
2019-01-08 19:33:36 +00:00
/// fn f() {
/// let foo = 92;
2021-01-06 20:15:48 +00:00
/// let _ = bar$0
2019-01-08 19:33:36 +00:00
/// }
/// ```
///
/// `foo` *should* be present among the completion variants. Filtering by
/// identifier prefix/fuzzy match should be done higher in the stack, together
/// with ordering of completions (currently this is done by the client).
2021-04-05 13:27:45 +00:00
///
2021-05-24 19:21:25 +00:00
/// # Speculative Completion Problem
2021-04-05 13:27:45 +00:00
///
/// There's a curious unsolved problem in the current implementation. Often, you
/// want to compute completions on a *slightly different* text document.
///
/// In the simplest case, when the code looks like `let x = `, you want to
/// insert a fake identifier to get a better syntax tree: `let x = complete_me`.
///
/// We do this in `CompletionContext`, and it works OK-enough for *syntax*
/// analysis. However, we might want to, eg, ask for the type of `complete_me`
/// variable, and that's where our current infrastructure breaks down. salsa
/// doesn't allow such "phantom" inputs.
///
/// Another case where this would be instrumental is macro expansion. We want to
2021-05-24 19:21:25 +00:00
/// insert a fake ident and re-expand code. There's `expand_speculative` as a
2023-04-13 22:35:00 +00:00
/// workaround for this.
2021-04-05 13:27:45 +00:00
///
/// A different use-case is completion of injection (examples and links in doc
/// comments). When computing completion for a path in a doc-comment, you want
/// to inject a fake path expression into the item being documented and complete
/// that.
///
/// IntelliJ has CodeFragment/Context infrastructure for that. You can create a
/// temporary PSI node, and say that the context ("parent") of this node is some
/// existing node. Asking for, eg, type of this `CodeFragment` node works
/// correctly, as the underlying infrastructure makes use of contexts to do
/// analysis.
2020-10-18 10:09:00 +00:00
pub fn completions (
2020-03-10 17:39:17 +00:00
db : & RootDatabase ,
2020-03-31 14:02:55 +00:00
config : & CompletionConfig ,
2020-05-17 10:09:53 +00:00
position : FilePosition ,
2022-05-30 12:17:58 +00:00
trigger_character : Option < char > ,
2022-06-20 19:55:33 +00:00
) -> Option < Vec < CompletionItem > > {
2022-06-20 15:41:04 +00:00
let ( ctx , analysis ) = & CompletionContext ::new ( db , position , config ) ? ;
2022-06-17 21:36:39 +00:00
let mut completions = Completions ::default ( ) ;
2022-05-05 13:49:03 +00:00
2022-06-17 21:36:39 +00:00
// prevent `(` from triggering unwanted completion noise
if trigger_character = = Some ( '(' ) {
2023-02-15 12:38:42 +00:00
if let CompletionAnalysis ::NameRef ( NameRefContext {
kind :
NameRefKind ::Path (
path_ctx @ PathCompletionCtx { kind : PathKind ::Vis { has_in_token } , .. } ,
) ,
..
} ) = analysis
{
completions ::vis ::complete_vis_path ( & mut completions , ctx , path_ctx , has_in_token ) ;
2022-06-17 21:36:39 +00:00
}
2022-06-20 19:55:33 +00:00
return Some ( completions . into ( ) ) ;
2022-06-17 21:36:39 +00:00
}
2023-09-29 19:06:47 +00:00
// when the user types a bare `_` (that is it does not belong to an identifier)
// the user might just wanted to type a `_` for type inference or pattern discarding
// so try to suppress completions in those cases
if trigger_character = = Some ( '_' ) & & ctx . original_token . kind ( ) = = syntax ::SyntaxKind ::UNDERSCORE
{
if let CompletionAnalysis ::NameRef ( NameRefContext {
kind :
NameRefKind ::Path (
path_ctx @ PathCompletionCtx {
kind : PathKind ::Type { .. } | PathKind ::Pat { .. } ,
..
} ,
) ,
..
} ) = analysis
{
if path_ctx . is_trivial_path ( ) {
return None ;
}
}
}
2022-06-17 21:36:39 +00:00
{
let acc = & mut completions ;
2023-02-15 12:38:42 +00:00
match analysis {
2022-06-20 15:41:04 +00:00
CompletionAnalysis ::Name ( name_ctx ) = > completions ::complete_name ( acc , ctx , name_ctx ) ,
CompletionAnalysis ::NameRef ( name_ref_ctx ) = > {
2022-06-20 12:23:46 +00:00
completions ::complete_name_ref ( acc , ctx , name_ref_ctx )
}
2022-06-20 15:41:04 +00:00
CompletionAnalysis ::Lifetime ( lifetime_ctx ) = > {
2022-06-17 21:36:39 +00:00
completions ::lifetime ::complete_label ( acc , ctx , lifetime_ctx ) ;
completions ::lifetime ::complete_lifetime ( acc , ctx , lifetime_ctx ) ;
}
2022-06-20 15:41:04 +00:00
CompletionAnalysis ::String { original , expanded : Some ( expanded ) } = > {
2022-06-17 21:36:39 +00:00
completions ::extern_abi ::complete_extern_abi ( acc , ctx , expanded ) ;
completions ::format_string ::format_string ( acc , ctx , original , expanded ) ;
2024-03-14 14:48:46 +00:00
completions ::env_vars ::complete_cargo_env_vars ( acc , ctx , original , expanded ) ;
2022-06-17 21:36:39 +00:00
}
2022-06-20 15:41:04 +00:00
CompletionAnalysis ::UnexpandedAttrTT {
2022-06-20 13:07:48 +00:00
colon_prefix ,
fake_attribute_under_caret : Some ( attr ) ,
2023-12-16 16:19:58 +00:00
extern_crate ,
2022-06-20 13:07:48 +00:00
} = > {
completions ::attribute ::complete_known_attribute_input (
acc ,
ctx ,
colon_prefix ,
attr ,
2023-12-16 16:19:58 +00:00
extern_crate . as_ref ( ) ,
2022-06-20 13:07:48 +00:00
) ;
2022-06-17 21:36:39 +00:00
}
2022-06-20 15:41:04 +00:00
CompletionAnalysis ::UnexpandedAttrTT { .. } | CompletionAnalysis ::String { .. } = > ( ) ,
2022-05-29 15:06:48 +00:00
}
2022-05-05 13:49:03 +00:00
}
2020-02-09 18:24:34 +00:00
2022-06-20 19:55:33 +00:00
Some ( completions . into ( ) )
2019-01-08 19:33:36 +00:00
}
2020-05-31 15:33:48 +00:00
2020-12-04 14:03:22 +00:00
/// Resolves additional completion data at the position given.
2021-10-11 19:49:39 +00:00
/// This is used for import insertion done via completions like flyimport and custom user snippets.
2020-12-04 14:03:22 +00:00
pub fn resolve_completion_edits (
db : & RootDatabase ,
config : & CompletionConfig ,
2022-06-20 15:41:04 +00:00
FilePosition { file_id , offset } : FilePosition ,
2021-10-04 19:44:33 +00:00
imports : impl IntoIterator < Item = ( String , String ) > ,
2020-12-06 21:58:15 +00:00
) -> Option < Vec < TextEdit > > {
2024-06-06 23:52:25 +00:00
let _p = tracing ::info_span! ( " resolve_completion_edits " ) . entered ( ) ;
2022-06-20 15:41:04 +00:00
let sema = hir ::Semantics ::new ( db ) ;
let original_file = sema . parse ( file_id ) ;
let original_token =
syntax ::AstNode ::syntax ( & original_file ) . token_at_offset ( offset ) . left_biased ( ) ? ;
let position_for_import = & original_token . parent ( ) ? ;
let scope = ImportScope ::find_insert_use_container ( position_for_import , & sema ) ? ;
2020-12-04 14:03:22 +00:00
2022-06-20 15:41:04 +00:00
let current_module = sema . scope ( position_for_import ) ? . module ( ) ;
2020-12-04 14:03:22 +00:00
let current_crate = current_module . krate ( ) ;
2021-10-04 20:05:30 +00:00
let new_ast = scope . clone_for_update ( ) ;
let mut import_insert = TextEdit ::builder ( ) ;
2020-12-04 14:03:22 +00:00
2024-05-17 19:00:21 +00:00
let cfg = ImportPathConfig {
prefer_no_std : config . prefer_no_std ,
prefer_prelude : config . prefer_prelude ,
2024-07-01 16:52:34 +00:00
prefer_absolute : config . prefer_absolute ,
2024-05-17 19:00:21 +00:00
} ;
2021-10-04 20:05:30 +00:00
imports . into_iter ( ) . for_each ( | ( full_import_path , imported_name ) | {
let items_with_name = items_locator ::items_with_name (
2022-06-20 15:41:04 +00:00
& sema ,
2021-10-04 20:05:30 +00:00
current_crate ,
2021-12-09 18:18:11 +00:00
NameToImport ::exact_case_sensitive ( imported_name ) ,
2023-06-29 09:39:37 +00:00
items_locator ::AssocSearchMode ::Include ,
2021-10-04 20:05:30 +00:00
) ;
let import = items_with_name
. filter_map ( | candidate | {
2024-05-22 18:45:54 +00:00
current_module . find_use_path ( db , candidate , config . insert_use . prefix_kind , cfg )
2021-10-04 19:44:33 +00:00
} )
2023-05-24 16:04:29 +00:00
. find ( | mod_path | mod_path . display ( db ) . to_string ( ) = = full_import_path ) ;
2021-10-04 20:05:30 +00:00
if let Some ( import_path ) = import {
insert_use ::insert_use ( & new_ast , mod_path_to_ast ( & import_path ) , & config . insert_use ) ;
}
} ) ;
algo ::diff ( scope . as_syntax_node ( ) , new_ast . as_syntax_node ( ) ) . into_text_edit ( & mut import_insert ) ;
Some ( vec! [ import_insert . finish ( ) ] )
2020-12-04 14:03:22 +00:00
}