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, Resolver};
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) 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,
40 impl<'a> CompletionContext<'a> {
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 {
52 offset: position.offset,
56 function_syntax: None,
57 use_item_syntax: None,
59 is_trivial_path: false,
67 ctx.fill(original_file, position.offset);
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()),
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
85 let edit = AtomTextEdit::insert(offset, "intellijRulezz".to_string());
86 original_file.reparse(&edit)
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) {} }`.
93 if is_node::<ast::Param>(name_ref.syntax()) {
97 self.classify_name_ref(original_file, name_ref);
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;
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
114 .take_while(|it| it.range() == name_range)
118 match top_node.parent().map(|it| it.kind()) {
119 Some(SOURCE_FILE) | Some(ITEM_LIST) => {
120 self.is_new_item = true;
126 self.use_item_syntax = self.leaf.ancestors().find_map(ast::UseItem::cast);
128 self.function_syntax = self
131 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
132 .find_map(ast::FnDef::cast);
133 match (self.module, self.function_syntax) {
134 (Some(module), Some(fn_def)) => {
135 let function = source_binder::function_from_module(self.db, module, fn_def);
136 self.function = Some(function);
141 let parent = match name_ref.syntax().parent() {
145 if let Some(segment) = ast::PathSegment::cast(parent) {
146 let path = segment.parent_path();
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);
154 if path.qualifier().is_none() {
155 self.is_trivial_path = true;
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
163 if let Some(stmt) = ast::ExprStmt::cast(node) {
164 return Some(stmt.syntax().range() == name_ref.syntax().range());
166 if let Some(block) = ast::Block::cast(node) {
168 block.expr().map(|e| e.syntax().range())
169 == Some(name_ref.syntax().range()),
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)
180 if if_expr.syntax().range().end() < name_ref.syntax().range().start() {
181 self.after_if = true;
189 .and_then(ast::PathExpr::cast)
190 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
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
198 .map(|e| e.syntax().range())
199 .and_then(|r| find_node_with_range(original_file.syntax(), r));
201 if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
203 self.dot_receiver = method_call_expr
205 .map(|e| e.syntax().range())
206 .and_then(|r| find_node_with_range(original_file.syntax(), r));
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)
217 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
218 match node.ancestors().filter_map(N::cast).next() {
220 Some(n) => n.syntax().range() == node.range(),