1 use ra_text_edit::AtomTextEdit;
3 AstNode, SyntaxNode, SourceFile, TextUnit, TextRange,
5 algo::{find_leaf_at_offset, find_covering_node, find_node_at_offset},
8 use hir::source_binder;
10 use crate::{db, FilePosition};
12 /// `CompletionContext` is created early during completion to figure out, where
13 /// exactly is the cursor, syntax-wise.
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,
39 impl<'a> CompletionContext<'a> {
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 {
50 offset: position.offset,
53 function_syntax: None,
54 use_item_syntax: None,
56 is_trivial_path: false,
64 ctx.fill(original_file, position.offset);
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()
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
84 let edit = AtomTextEdit::insert(offset, "intellijRulezz".to_string());
85 original_file.reparse(&edit)
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) {} }`.
92 if is_node::<ast::Param>(name_ref.syntax()) {
96 self.classify_name_ref(original_file, name_ref);
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;
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
113 .take_while(|it| it.range() == name_range)
117 match top_node.parent().map(|it| it.kind()) {
118 Some(SOURCE_FILE) | Some(ITEM_LIST) => {
119 self.is_new_item = true;
125 self.use_item_syntax = self.leaf.ancestors().find_map(ast::UseItem::cast);
127 self.function_syntax = self
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);
140 let parent = match name_ref.syntax().parent() {
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);
153 if path.qualifier().is_none() {
154 self.is_trivial_path = true;
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
162 if let Some(stmt) = ast::ExprStmt::cast(node) {
163 return Some(stmt.syntax().range() == name_ref.syntax().range());
165 if let Some(block) = ast::Block::cast(node) {
167 block.expr().map(|e| e.syntax().range())
168 == Some(name_ref.syntax().range()),
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)
179 if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
180 self.after_if = true;
188 .and_then(ast::PathExpr::cast)
189 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
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
197 .map(|e| e.syntax().range())
198 .and_then(|r| find_node_with_range(original_file.syntax(), r));
200 if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
202 self.dot_receiver = method_call_expr
204 .map(|e| e.syntax().range())
205 .and_then(|r| find_node_with_range(original_file.syntax(), r));
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)
216 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
217 match node.ancestors().filter_map(N::cast).next() {
219 Some(n) => n.syntax().range() == node.range(),