]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/completion/completion_context.rs
d351be054b4abce02fc984fc3f339a05e99d844d
[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) 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,
39 }
40
41 impl<'a> CompletionContext<'a> {
42     pub(super) fn new(
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 {
51             db,
52             leaf,
53             offset: position.offset,
54             resolver,
55             module,
56             function: None,
57             function_syntax: None,
58             use_item_syntax: None,
59             struct_lit_syntax: None,
60             is_param: false,
61             is_trivial_path: false,
62             path_prefix: None,
63             after_if: false,
64             can_be_stmt: false,
65             is_new_item: false,
66             dot_receiver: None,
67             is_call: false,
68         };
69         ctx.fill(original_file, position.offset);
70         Some(ctx)
71     }
72
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()),
79         }
80     }
81
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
85         // actual completion.
86         let file = {
87             let edit = AtomTextEdit::insert(offset, "intellijRulezz".to_string());
88             original_file.reparse(&edit)
89         };
90
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) {} }`.
94             // See RFC#1685.
95             if is_node::<ast::Param>(name_ref.syntax()) {
96                 self.is_param = true;
97                 return;
98             }
99             self.classify_name_ref(original_file, name_ref);
100         }
101
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;
107                 return;
108             }
109         }
110     }
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);
115         }
116
117         let top_node =
118             name_ref.syntax().ancestors().take_while(|it| it.range() == name_range).last().unwrap();
119
120         match top_node.parent().map(|it| it.kind()) {
121             Some(SOURCE_FILE) | Some(ITEM_LIST) => {
122                 self.is_new_item = true;
123                 return;
124             }
125             _ => (),
126         }
127
128         self.use_item_syntax = self.leaf.ancestors().find_map(ast::UseItem::cast);
129
130         self.function_syntax = self
131             .leaf
132             .ancestors()
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);
138         }
139
140         let parent = match name_ref.syntax().parent() {
141             Some(it) => it,
142             None => return,
143         };
144         if let Some(segment) = ast::PathSegment::cast(parent) {
145             let path = segment.parent_path();
146             self.is_call = path
147                 .syntax()
148                 .parent()
149                 .and_then(ast::PathExpr::cast)
150                 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
151                 .is_some();
152
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);
157                     return;
158                 }
159             }
160             if path.qualifier().is_none() {
161                 self.is_trivial_path = true;
162
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
166                     .syntax()
167                     .ancestors()
168                     .find_map(|node| {
169                         if let Some(stmt) = ast::ExprStmt::cast(node) {
170                             return Some(stmt.syntax().range() == name_ref.syntax().range());
171                         }
172                         if let Some(block) = ast::Block::cast(node) {
173                             return Some(
174                                 block.expr().map(|e| e.syntax().range())
175                                     == Some(name_ref.syntax().range()),
176                             );
177                         }
178                         None
179                     })
180                     .unwrap_or(false);
181
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)
185                     {
186                         if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
187                             self.after_if = true;
188                         }
189                     }
190                 }
191             }
192         }
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
197                 .expr()
198                 .map(|e| e.syntax().range())
199                 .and_then(|r| find_node_with_range(original_file.syntax(), r));
200         }
201         if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
202             // As above
203             self.dot_receiver = method_call_expr
204                 .expr()
205                 .map(|e| e.syntax().range())
206                 .and_then(|r| find_node_with_range(original_file.syntax(), r));
207             self.is_call = true;
208         }
209     }
210 }
211
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)
215 }
216
217 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
218     match node.ancestors().filter_map(N::cast).next() {
219         None => false,
220         Some(n) => n.syntax().range() == node.range(),
221     }
222 }