]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/completion/completion_context.rs
Merge #849
[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 =
112             name_ref.syntax().ancestors().take_while(|it| it.range() == name_range).last().unwrap();
113
114         match top_node.parent().map(|it| it.kind()) {
115             Some(SOURCE_FILE) | Some(ITEM_LIST) => {
116                 self.is_new_item = true;
117                 return;
118             }
119             _ => (),
120         }
121
122         self.use_item_syntax = self.leaf.ancestors().find_map(ast::UseItem::cast);
123
124         self.function_syntax = self
125             .leaf
126             .ancestors()
127             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
128             .find_map(ast::FnDef::cast);
129         if let (Some(module), Some(fn_def)) = (self.module, self.function_syntax) {
130             let function = source_binder::function_from_module(self.db, module, fn_def);
131             self.function = Some(function);
132         }
133
134         let parent = match name_ref.syntax().parent() {
135             Some(it) => it,
136             None => return,
137         };
138         if let Some(segment) = ast::PathSegment::cast(parent) {
139             let path = segment.parent_path();
140             self.is_call = path
141                 .syntax()
142                 .parent()
143                 .and_then(ast::PathExpr::cast)
144                 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
145                 .is_some();
146
147             if let Some(mut path) = hir::Path::from_ast(path) {
148                 if !path.is_ident() {
149                     path.segments.pop().unwrap();
150                     self.path_prefix = Some(path);
151                     return;
152                 }
153             }
154             if path.qualifier().is_none() {
155                 self.is_trivial_path = true;
156
157                 // Find either enclosing expr statement (thing with `;`) or a
158                 // block. If block, check that we are the last expr.
159                 self.can_be_stmt = name_ref
160                     .syntax()
161                     .ancestors()
162                     .find_map(|node| {
163                         if let Some(stmt) = ast::ExprStmt::cast(node) {
164                             return Some(stmt.syntax().range() == name_ref.syntax().range());
165                         }
166                         if let Some(block) = ast::Block::cast(node) {
167                             return Some(
168                                 block.expr().map(|e| e.syntax().range())
169                                     == Some(name_ref.syntax().range()),
170                             );
171                         }
172                         None
173                     })
174                     .unwrap_or(false);
175
176                 if let Some(off) = name_ref.syntax().range().start().checked_sub(2.into()) {
177                     if let Some(if_expr) =
178                         find_node_at_offset::<ast::IfExpr>(original_file.syntax(), off)
179                     {
180                         if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
181                             self.after_if = true;
182                         }
183                     }
184                 }
185             }
186         }
187         if let Some(field_expr) = ast::FieldExpr::cast(parent) {
188             // The receiver comes before the point of insertion of the fake
189             // ident, so it should have the same range in the non-modified file
190             self.dot_receiver = field_expr
191                 .expr()
192                 .map(|e| e.syntax().range())
193                 .and_then(|r| find_node_with_range(original_file.syntax(), r));
194         }
195         if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
196             // As above
197             self.dot_receiver = method_call_expr
198                 .expr()
199                 .map(|e| e.syntax().range())
200                 .and_then(|r| find_node_with_range(original_file.syntax(), r));
201             self.is_call = true;
202         }
203     }
204 }
205
206 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<&N> {
207     let node = find_covering_node(syntax, range);
208     node.ancestors().find_map(N::cast)
209 }
210
211 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
212     match node.ancestors().filter_map(N::cast).next() {
213         None => false,
214         Some(n) => n.syntax().range() == node.range(),
215     }
216 }