]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/completion/completion_context.rs
workaround for trigger character
[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     // The range of the identifier that is being completed.
69     // This is purely advisory and can be used, for example, to highlight this range in the editor.
70     // Clients are expected to ignore this field.
71     pub(crate) fn source_range(&self) -> TextRange {
72         match self.leaf.kind() {
73             // workaroud when completion is triggered by trigger characters.
74             DOT | COLONCOLON => TextRange::from_to(self.offset, self.offset),
75             _ => self.leaf.range()
76         }
77     }
78
79     fn fill(&mut self, original_file: &'a SourceFile, offset: TextUnit) {
80         // Insert a fake ident to get a valid parse tree. We will use this file
81         // to determine context, though the original_file will be used for
82         // actual completion.
83         let file = {
84             let edit = AtomTextEdit::insert(offset, "intellijRulezz".to_string());
85             original_file.reparse(&edit)
86         };
87
88         // First, let's try to complete a reference to some declaration.
89         if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(file.syntax(), offset) {
90             // Special case, `trait T { fn foo(i_am_a_name_ref) {} }`.
91             // See RFC#1685.
92             if is_node::<ast::Param>(name_ref.syntax()) {
93                 self.is_param = true;
94                 return;
95             }
96             self.classify_name_ref(original_file, name_ref);
97         }
98
99         // Otherwise, see if this is a declaration. We can use heuristics to
100         // suggest declaration names, see `CompletionKind::Magic`.
101         if let Some(name) = find_node_at_offset::<ast::Name>(file.syntax(), offset) {
102             if is_node::<ast::Param>(name.syntax()) {
103                 self.is_param = true;
104                 return;
105             }
106         }
107     }
108     fn classify_name_ref(&mut self, original_file: &'a SourceFile, name_ref: &ast::NameRef) {
109         let name_range = name_ref.syntax().range();
110         let top_node = name_ref
111             .syntax()
112             .ancestors()
113             .take_while(|it| it.range() == name_range)
114             .last()
115             .unwrap();
116
117         match top_node.parent().map(|it| it.kind()) {
118             Some(SOURCE_FILE) | Some(ITEM_LIST) => {
119                 self.is_new_item = true;
120                 return;
121             }
122             _ => (),
123         }
124
125         self.use_item_syntax = self.leaf.ancestors().find_map(ast::UseItem::cast);
126
127         self.function_syntax = self
128             .leaf
129             .ancestors()
130             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
131             .find_map(ast::FnDef::cast);
132         match (&self.module, self.function_syntax) {
133             (Some(module), Some(fn_def)) => {
134                 let function = source_binder::function_from_module(self.db, module, fn_def);
135                 self.function = Some(function);
136             }
137             _ => (),
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             if let Some(mut path) = hir::Path::from_ast(path) {
147                 if !path.is_ident() {
148                     path.segments.pop().unwrap();
149                     self.path_prefix = Some(path);
150                     return;
151                 }
152             }
153             if path.qualifier().is_none() {
154                 self.is_trivial_path = true;
155
156                 // Find either enclosing expr statement (thing with `;`) or a
157                 // block. If block, check that we are the last expr.
158                 self.can_be_stmt = name_ref
159                     .syntax()
160                     .ancestors()
161                     .find_map(|node| {
162                         if let Some(stmt) = ast::ExprStmt::cast(node) {
163                             return Some(stmt.syntax().range() == name_ref.syntax().range());
164                         }
165                         if let Some(block) = ast::Block::cast(node) {
166                             return Some(
167                                 block.expr().map(|e| e.syntax().range())
168                                     == Some(name_ref.syntax().range()),
169                             );
170                         }
171                         None
172                     })
173                     .unwrap_or(false);
174
175                 if let Some(off) = name_ref.syntax().range().start().checked_sub(2.into()) {
176                     if let Some(if_expr) =
177                         find_node_at_offset::<ast::IfExpr>(original_file.syntax(), off)
178                     {
179                         if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
180                             self.after_if = true;
181                         }
182                     }
183                 }
184             }
185             self.is_call = path
186                 .syntax()
187                 .parent()
188                 .and_then(ast::PathExpr::cast)
189                 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
190                 .is_some()
191         }
192         if let Some(field_expr) = ast::FieldExpr::cast(parent) {
193             // The receiver comes before the point of insertion of the fake
194             // ident, so it should have the same range in the non-modified file
195             self.dot_receiver = field_expr
196                 .expr()
197                 .map(|e| e.syntax().range())
198                 .and_then(|r| find_node_with_range(original_file.syntax(), r));
199         }
200         if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
201             // As above
202             self.dot_receiver = method_call_expr
203                 .expr()
204                 .map(|e| e.syntax().range())
205                 .and_then(|r| find_node_with_range(original_file.syntax(), r));
206             self.is_call = true;
207         }
208     }
209 }
210
211 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<&N> {
212     let node = find_covering_node(syntax, range);
213     node.ancestors().find_map(N::cast)
214 }
215
216 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
217     match node.ancestors().filter_map(N::cast).next() {
218         None => false,
219         Some(n) => n.syntax().range() == node.range(),
220     }
221 }