2020-10-18 13:09:00 +03:00
//! `completions` crate provides utilities for generating completions of user input.
2022-07-20 14:59:42 +02:00
#![ warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros) ]
2021-06-16 17:37:23 +02:00
mod completions ;
2020-10-25 10:59:15 +03:00
mod config ;
mod context ;
2021-06-16 17:37:23 +02:00
mod item ;
2020-11-01 12:35:04 +03:00
mod render ;
2019-01-08 22:33:36 +03:00
2021-06-16 17:37:23 +02:00
#[ cfg(test) ]
mod tests ;
2021-10-04 19:22:41 +02:00
mod snippet ;
2019-01-08 22:33:36 +03:00
2020-12-04 16:03:22 +02:00
use ide_db ::{
2021-02-25 01:06:31 +02:00
base_db ::FilePosition ,
2022-03-06 19:01:30 +01:00
helpers ::mod_path_to_ast ,
imports ::{
2021-10-04 22:05:30 +02:00
import_assets ::NameToImport ,
insert_use ::{ self , ImportScope } ,
2021-03-20 15:02:52 +02:00
} ,
2021-03-03 01:26:53 +02:00
items_locator , RootDatabase ,
2020-12-04 16:03:22 +02:00
} ;
2021-10-04 22:05:30 +02:00
use syntax ::algo ;
2020-12-04 16:03:22 +02:00
use text_edit ::TextEdit ;
2019-01-08 22:33:36 +03:00
2022-06-17 23:36:39 +02:00
use crate ::{
completions ::Completions ,
2022-06-20 13:17:30 +02:00
context ::{
2022-06-20 17:41:04 +02:00
CompletionAnalysis , CompletionContext , NameRefContext , NameRefKind , PathCompletionCtx ,
PathKind ,
2022-06-20 13:17:30 +02:00
} ,
2022-06-17 23:36:39 +02:00
} ;
2019-01-08 22:33:36 +03:00
2020-10-18 13:09:00 +03:00
pub use crate ::{
2022-05-13 19:52:44 +02:00
config ::{ CallableSnippets , CompletionConfig } ,
2022-04-01 20:50:27 +03:00
item ::{
CompletionItem , CompletionItemKind , CompletionRelevance , CompletionRelevancePostfixMatch ,
} ,
2021-10-05 17:18:40 +02:00
snippet ::{ Snippet , SnippetScope } ,
2019-07-04 23:05:17 +03:00
} ;
2019-01-08 22:33:36 +03:00
2020-05-31 11:29:19 +02: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;`
// - `expr.letm` -> `let mut $0 = expr;`
2020-05-31 11:29:19 +02:00
// - `expr.not` -> `!expr`
// - `expr.dbg` -> `dbg!(expr)`
2020-10-14 16:23:51 +03:00
// - `expr.dbgr` -> `dbg!(&expr)`
// - `expr.call` -> `(expr)`
2020-05-31 11:29:19 +02:00
//
// There also snippet completions:
//
// .Expressions
2020-07-19 18:25:19 +02:00
// - `pd` -> `eprintln!(" = {:?}", );`
2020-07-02 11:06:00 +08:00
// - `ppd` -> `eprintln!(" = {:#?}", );`
2020-05-31 11:29:19 +02:00
//
// .Items
2020-07-02 11:06:00 +08:00
// - `tfn` -> `#[test] fn feature(){}`
2020-05-31 11:29:19 +02:00
// - `tmod` ->
// ```rust
// #[cfg(test)]
// mod tests {
// use super::*;
//
// #[test]
2020-07-02 11:06:00 +08:00
// fn test_name() {}
2020-05-31 11:29:19 +02:00
// }
// ```
2020-11-25 00:42:58 +02:00
//
2020-12-08 14:27:18 +02: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 20:05:32 +02:00
// fuzzy matched against the completion input.
2021-03-31 00:08:10 +01:00
//
// image::https://user-images.githubusercontent.com/48062697/113020667-b72ab880-917a-11eb-8778-716cf26a0eb3.gif[]
2020-05-31 11:29:19 +02:00
2019-01-08 22:33:36 +03:00
/// Main entry point for completion. We run completion as a two-phase process.
///
/// First, we look at the position and collect a so-called `CompletionContext.
/// 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 17:18:27 +01:00
/// look at the context and produce completion items. One subtlety about this
2019-01-08 22:33:36 +03: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 22:03:02 +03:00
/// ```no_run
2019-01-08 22:33:36 +03:00
/// fn f() {
/// let foo = 92;
2021-01-06 20:15:48 +00:00
/// let _ = bar$0
2019-01-08 22:33:36 +03: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 16:27:45 +03:00
///
2021-05-24 22:21:25 +03:00
/// # Speculative Completion Problem
2021-04-05 16:27:45 +03: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 22:21:25 +03:00
/// insert a fake ident and re-expand code. There's `expand_speculative` as a
2021-04-05 16:27:45 +03:00
/// work-around for this.
///
/// 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 13:09:00 +03:00
pub fn completions (
2020-03-10 18:39:17 +01:00
db : & RootDatabase ,
2020-03-31 16:02:55 +02:00
config : & CompletionConfig ,
2020-05-17 12:09:53 +02:00
position : FilePosition ,
2022-05-30 14:17:58 +02:00
trigger_character : Option < char > ,
2022-06-20 21:55:33 +02:00
) -> Option < Vec < CompletionItem > > {
2022-06-20 17:41:04 +02:00
let ( ctx , analysis ) = & CompletionContext ::new ( db , position , config ) ? ;
2022-06-17 23:36:39 +02:00
let mut completions = Completions ::default ( ) ;
2022-05-05 15:49:03 +02:00
2022-06-17 23:36:39 +02:00
// prevent `(` from triggering unwanted completion noise
if trigger_character = = Some ( '(' ) {
2022-06-20 17:41:04 +02:00
if let CompletionAnalysis ::NameRef ( NameRefContext { kind , .. } ) = & analysis {
2022-06-20 14:23:46 +02:00
if let NameRefKind ::Path (
path_ctx @ PathCompletionCtx { kind : PathKind ::Vis { has_in_token } , .. } ,
) = kind
{
completions ::vis ::complete_vis_path ( & mut completions , ctx , path_ctx , has_in_token ) ;
}
2022-06-17 23:36:39 +02:00
}
2022-06-20 21:55:33 +02:00
return Some ( completions . into ( ) ) ;
2022-06-17 23:36:39 +02:00
}
{
let acc = & mut completions ;
2022-06-20 17:41:04 +02:00
match & analysis {
CompletionAnalysis ::Name ( name_ctx ) = > completions ::complete_name ( acc , ctx , name_ctx ) ,
CompletionAnalysis ::NameRef ( name_ref_ctx ) = > {
2022-06-20 14:23:46 +02:00
completions ::complete_name_ref ( acc , ctx , name_ref_ctx )
}
2022-06-20 17:41:04 +02:00
CompletionAnalysis ::Lifetime ( lifetime_ctx ) = > {
2022-06-17 23:36:39 +02:00
completions ::lifetime ::complete_label ( acc , ctx , lifetime_ctx ) ;
completions ::lifetime ::complete_lifetime ( acc , ctx , lifetime_ctx ) ;
}
2022-06-20 17:41:04 +02:00
CompletionAnalysis ::String { original , expanded : Some ( expanded ) } = > {
2022-06-17 23:36:39 +02:00
completions ::extern_abi ::complete_extern_abi ( acc , ctx , expanded ) ;
completions ::format_string ::format_string ( acc , ctx , original , expanded ) ;
2022-10-06 21:35:12 +02:00
completions ::env_vars ::complete_cargo_env_vars ( acc , ctx , expanded ) ;
2022-06-17 23:36:39 +02:00
}
2022-06-20 17:41:04 +02:00
CompletionAnalysis ::UnexpandedAttrTT {
2022-06-20 15:07:48 +02:00
colon_prefix ,
fake_attribute_under_caret : Some ( attr ) ,
} = > {
completions ::attribute ::complete_known_attribute_input (
acc ,
ctx ,
colon_prefix ,
attr ,
) ;
2022-06-17 23:36:39 +02:00
}
2022-06-20 17:41:04 +02:00
CompletionAnalysis ::UnexpandedAttrTT { .. } | CompletionAnalysis ::String { .. } = > ( ) ,
2022-05-30 00:06:48 +09:00
}
2022-05-05 15:49:03 +02:00
}
2020-02-09 12:24:34 -06:00
2022-06-20 21:55:33 +02:00
Some ( completions . into ( ) )
2019-01-08 22:33:36 +03:00
}
2020-05-31 11:33:48 -04:00
2020-12-04 16:03:22 +02:00
/// Resolves additional completion data at the position given.
2021-10-11 21:49:39 +02:00
/// This is used for import insertion done via completions like flyimport and custom user snippets.
2020-12-04 16:03:22 +02:00
pub fn resolve_completion_edits (
db : & RootDatabase ,
config : & CompletionConfig ,
2022-06-20 17:41:04 +02:00
FilePosition { file_id , offset } : FilePosition ,
2021-10-04 21:44:33 +02:00
imports : impl IntoIterator < Item = ( String , String ) > ,
2020-12-06 23:58:15 +02:00
) -> Option < Vec < TextEdit > > {
2021-10-04 22:05:30 +02:00
let _p = profile ::span ( " resolve_completion_edits " ) ;
2022-06-20 17:41:04 +02: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 16:03:22 +02:00
2022-06-20 17:41:04 +02:00
let current_module = sema . scope ( position_for_import ) ? . module ( ) ;
2020-12-04 16:03:22 +02:00
let current_crate = current_module . krate ( ) ;
2021-10-04 22:05:30 +02:00
let new_ast = scope . clone_for_update ( ) ;
let mut import_insert = TextEdit ::builder ( ) ;
2020-12-04 16:03:22 +02:00
2021-10-04 22:05:30 +02:00
imports . into_iter ( ) . for_each ( | ( full_import_path , imported_name ) | {
let items_with_name = items_locator ::items_with_name (
2022-06-20 17:41:04 +02:00
& sema ,
2021-10-04 22:05:30 +02:00
current_crate ,
2021-12-09 19:18:11 +01:00
NameToImport ::exact_case_sensitive ( imported_name ) ,
2021-10-04 22:05:30 +02:00
items_locator ::AssocItemSearch ::Include ,
Some ( items_locator ::DEFAULT_QUERY_SEARCH_LIMIT . inner ( ) ) ,
) ;
let import = items_with_name
. filter_map ( | candidate | {
2022-09-09 20:04:56 +02:00
current_module . find_use_path_prefixed (
db ,
candidate ,
config . insert_use . prefix_kind ,
2022-09-13 15:09:40 +02:00
config . prefer_no_std ,
2022-09-09 20:04:56 +02:00
)
2021-10-04 21:44:33 +02:00
} )
2021-10-04 22:05:30 +02:00
. find ( | mod_path | mod_path . to_string ( ) = = full_import_path ) ;
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 16:03:22 +02:00
}