]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/completion/completion_context.rs
refactor completions to use TextEdit instead of InsertText
[rust.git] / crates / ra_ide_api / src / completion / completion_context.rs
1 use ra_text_edit::AtomTextEdit;
2 use ra_syntax::{
3     AstNode, SyntaxNode, SourceFile, TextUnit, TextRange,
4     ast,
5     algo::{find_leaf_at_offset, find_covering_node, find_node_at_offset},
6     SyntaxKind::*,
7 };
8 use hir::source_binder;
9
10 use crate::{db, FilePosition};
11
12 /// `CompletionContext` is created early during completion to figure out, where
13 /// exactly is the cursor, syntax-wise.
14 #[derive(Debug)]
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) module: Option<hir::Module>,
20     pub(super) function: Option<hir::Function>,
21     pub(super) function_syntax: Option<&'a ast::FnDef>,
22     pub(super) use_item_syntax: Option<&'a ast::UseItem>,
23     pub(super) is_param: bool,
24     /// A single-indent path, like `foo`.
25     pub(super) is_trivial_path: bool,
26     /// If not a trivial, path, the prefix (qualifier).
27     pub(super) path_prefix: Option<hir::Path>,
28     pub(super) after_if: bool,
29     /// `true` if we are a statement or a last expr in the block.
30     pub(super) can_be_stmt: bool,
31     /// Something is typed at the "top" level, in module or impl/trait.
32     pub(super) is_new_item: bool,
33     /// The receiver if this is a field or method access, i.e. writing something.<|>
34     pub(super) dot_receiver: Option<&'a ast::Expr>,
35     /// If this is a call (method or function) in particular, i.e. the () are already there.
36     pub(super) is_call: bool,
37 }
38
39 impl<'a> CompletionContext<'a> {
40     pub(super) fn new(
41         db: &'a db::RootDatabase,
42         original_file: &'a SourceFile,
43         position: FilePosition,
44     ) -> Option<CompletionContext<'a>> {
45         let module = source_binder::module_from_position(db, position);
46         let leaf = find_leaf_at_offset(original_file.syntax(), position.offset).left_biased()?;
47         let mut ctx = CompletionContext {
48             db,
49             leaf,
50             offset: position.offset,
51             module,
52             function: None,
53             function_syntax: None,
54             use_item_syntax: None,
55             is_param: false,
56             is_trivial_path: false,
57             path_prefix: None,
58             after_if: false,
59             can_be_stmt: false,
60             is_new_item: false,
61             dot_receiver: None,
62             is_call: false,
63         };
64         ctx.fill(original_file, position.offset);
65         Some(ctx)
66     }
67
68     pub(crate) fn leaf_range(&self) -> TextRange {
69         self.leaf.range()
70     }
71
72     fn fill(&mut self, original_file: &'a SourceFile, offset: TextUnit) {
73         // Insert a fake ident to get a valid parse tree. We will use this file
74         // to determine context, though the original_file will be used for
75         // actual completion.
76         let file = {
77             let edit = AtomTextEdit::insert(offset, "intellijRulezz".to_string());
78             original_file.reparse(&edit)
79         };
80
81         // First, let's try to complete a reference to some declaration.
82         if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(file.syntax(), offset) {
83             // Special case, `trait T { fn foo(i_am_a_name_ref) {} }`.
84             // See RFC#1685.
85             if is_node::<ast::Param>(name_ref.syntax()) {
86                 self.is_param = true;
87                 return;
88             }
89             self.classify_name_ref(original_file, name_ref);
90         }
91
92         // Otherwise, see if this is a declaration. We can use heuristics to
93         // suggest declaration names, see `CompletionKind::Magic`.
94         if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), offset) {
95             if is_node::<ast::Param>(name.syntax()) {
96                 self.is_param = true;
97                 return;
98             }
99         }
100     }
101     fn classify_name_ref(&mut self, original_file: &'a SourceFile, name_ref: &ast::NameRef) {
102         let name_range = name_ref.syntax().range();
103         let top_node = name_ref
104             .syntax()
105             .ancestors()
106             .take_while(|it| it.range() == name_range)
107             .last()
108             .unwrap();
109
110         match top_node.parent().map(|it| it.kind()) {
111             Some(SOURCE_FILE) | Some(ITEM_LIST) => {
112                 self.is_new_item = true;
113                 return;
114             }
115             _ => (),
116         }
117
118         self.use_item_syntax = self.leaf.ancestors().find_map(ast::UseItem::cast);
119
120         self.function_syntax = self
121             .leaf
122             .ancestors()
123             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
124             .find_map(ast::FnDef::cast);
125         match (&self.module, self.function_syntax) {
126             (Some(module), Some(fn_def)) => {
127                 let function = source_binder::function_from_module(self.db, module, fn_def);
128                 self.function = Some(function);
129             }
130             _ => (),
131         }
132
133         let parent = match name_ref.syntax().parent() {
134             Some(it) => it,
135             None => return,
136         };
137         if let Some(segment) = ast::PathSegment::cast(parent) {
138             let path = segment.parent_path();
139             if let Some(mut path) = hir::Path::from_ast(path) {
140                 if !path.is_ident() {
141                     path.segments.pop().unwrap();
142                     self.path_prefix = Some(path);
143                     return;
144                 }
145             }
146             if path.qualifier().is_none() {
147                 self.is_trivial_path = true;
148
149                 // Find either enclosing expr statement (thing with `;`) or a
150                 // block. If block, check that we are the last expr.
151                 self.can_be_stmt = name_ref
152                     .syntax()
153                     .ancestors()
154                     .find_map(|node| {
155                         if let Some(stmt) = ast::ExprStmt::cast(node) {
156                             return Some(stmt.syntax().range() == name_ref.syntax().range());
157                         }
158                         if let Some(block) = ast::Block::cast(node) {
159                             return Some(
160                                 block.expr().map(|e| e.syntax().range())
161                                     == Some(name_ref.syntax().range()),
162                             );
163                         }
164                         None
165                     })
166                     .unwrap_or(false);
167
168                 if let Some(off) = name_ref.syntax().range().start().checked_sub(2.into()) {
169                     if let Some(if_expr) =
170                         find_node_at_offset::<ast::IfExpr>(original_file.syntax(), off)
171                     {
172                         if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
173                             self.after_if = true;
174                         }
175                     }
176                 }
177             }
178             self.is_call = path
179                 .syntax()
180                 .parent()
181                 .and_then(ast::PathExpr::cast)
182                 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
183                 .is_some()
184         }
185         if let Some(field_expr) = ast::FieldExpr::cast(parent) {
186             // The receiver comes before the point of insertion of the fake
187             // ident, so it should have the same range in the non-modified file
188             self.dot_receiver = field_expr
189                 .expr()
190                 .map(|e| e.syntax().range())
191                 .and_then(|r| find_node_with_range(original_file.syntax(), r));
192         }
193         if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
194             // As above
195             self.dot_receiver = method_call_expr
196                 .expr()
197                 .map(|e| e.syntax().range())
198                 .and_then(|r| find_node_with_range(original_file.syntax(), r));
199             self.is_call = true;
200         }
201     }
202 }
203
204 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<&N> {
205     let node = find_covering_node(syntax, range);
206     node.ancestors().find_map(N::cast)
207 }
208
209 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
210     match node.ancestors().filter_map(N::cast).next() {
211         None => false,
212         Some(n) => n.syntax().range() == node.range(),
213     }
214 }