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