1 use ra_text_edit::AtomTextEdit;
3 AstNode, SyntaxNode, SourceFile, TextUnit, TextRange,
5 algo::{find_leaf_at_offset, find_covering_node, find_node_at_offset},
8 use hir::{source_binder, Resolver};
10 use crate::{db, FilePosition};
12 /// `CompletionContext` is created early during completion to figure out, where
13 /// exactly is the cursor, syntax-wise.
15 pub(crate) struct CompletionContext<'a> {
16 pub(super) db: &'a db::RootDatabase,
17 pub(super) offset: TextUnit,
18 pub(super) leaf: &'a SyntaxNode,
19 pub(super) resolver: Resolver,
20 pub(super) module: Option<hir::Module>,
21 pub(super) function: Option<hir::Function>,
22 pub(super) function_syntax: Option<&'a ast::FnDef>,
23 pub(super) use_item_syntax: Option<&'a ast::UseItem>,
24 pub(super) struct_lit_syntax: Option<&'a ast::StructLit>,
25 pub(super) is_param: bool,
26 /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
27 pub(super) is_trivial_path: bool,
28 /// If not a trivial, path, the prefix (qualifier).
29 pub(super) path_prefix: Option<hir::Path>,
30 pub(super) after_if: bool,
31 /// `true` if we are a statement or a last expr in the block.
32 pub(super) can_be_stmt: bool,
33 /// Something is typed at the "top" level, in module or impl/trait.
34 pub(super) is_new_item: bool,
35 /// The receiver if this is a field or method access, i.e. writing something.<|>
36 pub(super) dot_receiver: Option<&'a ast::Expr>,
37 /// If this is a call (method or function) in particular, i.e. the () are already there.
38 pub(super) is_call: bool,
41 impl<'a> CompletionContext<'a> {
43 db: &'a db::RootDatabase,
44 original_file: &'a SourceFile,
45 position: FilePosition,
46 ) -> Option<CompletionContext<'a>> {
47 let resolver = source_binder::resolver_for_position(db, position);
48 let module = source_binder::module_from_position(db, position);
49 let leaf = find_leaf_at_offset(original_file.syntax(), position.offset).left_biased()?;
50 let mut ctx = CompletionContext {
53 offset: position.offset,
57 function_syntax: None,
58 use_item_syntax: None,
59 struct_lit_syntax: None,
61 is_trivial_path: false,
69 ctx.fill(original_file, position.offset);
73 // The range of the identifier that is being completed.
74 pub(crate) fn source_range(&self) -> TextRange {
75 match self.leaf.kind() {
76 // workaroud when completion is triggered by trigger characters.
77 IDENT => self.leaf.range(),
78 _ => TextRange::offset_len(self.offset, 0.into()),
82 fn fill(&mut self, original_file: &'a SourceFile, offset: TextUnit) {
83 // Insert a fake ident to get a valid parse tree. We will use this file
84 // to determine context, though the original_file will be used for
87 let edit = AtomTextEdit::insert(offset, "intellijRulezz".to_string());
88 original_file.reparse(&edit)
91 // First, let's try to complete a reference to some declaration.
92 if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(file.syntax(), offset) {
93 // Special case, `trait T { fn foo(i_am_a_name_ref) {} }`.
95 if is_node::<ast::Param>(name_ref.syntax()) {
99 self.classify_name_ref(original_file, name_ref);
102 // Otherwise, see if this is a declaration. We can use heuristics to
103 // suggest declaration names, see `CompletionKind::Magic`.
104 if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), offset) {
105 if is_node::<ast::Param>(name.syntax()) {
106 self.is_param = true;
111 fn classify_name_ref(&mut self, original_file: &'a SourceFile, name_ref: &ast::NameRef) {
112 let name_range = name_ref.syntax().range();
113 if name_ref.syntax().parent().and_then(ast::NamedField::cast).is_some() {
114 self.struct_lit_syntax = find_node_at_offset(original_file.syntax(), self.offset);
118 name_ref.syntax().ancestors().take_while(|it| it.range() == name_range).last().unwrap();
120 match top_node.parent().map(|it| it.kind()) {
121 Some(SOURCE_FILE) | Some(ITEM_LIST) => {
122 self.is_new_item = true;
128 self.use_item_syntax = self.leaf.ancestors().find_map(ast::UseItem::cast);
130 self.function_syntax = self
133 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
134 .find_map(ast::FnDef::cast);
135 if let (Some(module), Some(fn_def)) = (self.module, self.function_syntax) {
136 let function = source_binder::function_from_module(self.db, module, fn_def);
137 self.function = Some(function);
140 let parent = match name_ref.syntax().parent() {
144 if let Some(segment) = ast::PathSegment::cast(parent) {
145 let path = segment.parent_path();
149 .and_then(ast::PathExpr::cast)
150 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
153 if let Some(mut path) = hir::Path::from_ast(path) {
154 if !path.is_ident() {
155 path.segments.pop().unwrap();
156 self.path_prefix = Some(path);
160 if path.qualifier().is_none() {
161 self.is_trivial_path = true;
163 // Find either enclosing expr statement (thing with `;`) or a
164 // block. If block, check that we are the last expr.
165 self.can_be_stmt = name_ref
169 if let Some(stmt) = ast::ExprStmt::cast(node) {
170 return Some(stmt.syntax().range() == name_ref.syntax().range());
172 if let Some(block) = ast::Block::cast(node) {
174 block.expr().map(|e| e.syntax().range())
175 == Some(name_ref.syntax().range()),
182 if let Some(off) = name_ref.syntax().range().start().checked_sub(2.into()) {
183 if let Some(if_expr) =
184 find_node_at_offset::<ast::IfExpr>(original_file.syntax(), off)
186 if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
187 self.after_if = true;
193 if let Some(field_expr) = ast::FieldExpr::cast(parent) {
194 // The receiver comes before the point of insertion of the fake
195 // ident, so it should have the same range in the non-modified file
196 self.dot_receiver = field_expr
198 .map(|e| e.syntax().range())
199 .and_then(|r| find_node_with_range(original_file.syntax(), r));
201 if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
203 self.dot_receiver = method_call_expr
205 .map(|e| e.syntax().range())
206 .and_then(|r| find_node_with_range(original_file.syntax(), r));
212 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<&N> {
213 let node = find_covering_node(syntax, range);
214 node.ancestors().find_map(N::cast)
217 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
218 match node.ancestors().filter_map(N::cast).next() {
220 Some(n) => n.syntax().range() == node.range(),