aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_db/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_ide_db/src')
-rw-r--r--crates/ra_ide_db/src/defs.rs22
-rw-r--r--crates/ra_ide_db/src/lib.rs3
-rw-r--r--crates/ra_ide_db/src/line_index.rs29
-rw-r--r--crates/ra_ide_db/src/line_index_utils.rs302
-rw-r--r--crates/ra_ide_db/src/marks.rs11
-rw-r--r--crates/ra_ide_db/src/search.rs42
-rw-r--r--crates/ra_ide_db/src/source_change.rs68
-rw-r--r--crates/ra_ide_db/src/symbol_index.rs21
8 files changed, 148 insertions, 350 deletions
diff --git a/crates/ra_ide_db/src/defs.rs b/crates/ra_ide_db/src/defs.rs
index 7cd2384e9..8b06cbfc5 100644
--- a/crates/ra_ide_db/src/defs.rs
+++ b/crates/ra_ide_db/src/defs.rs
@@ -14,7 +14,6 @@ use ra_syntax::{
14 ast::{self, AstNode}, 14 ast::{self, AstNode},
15 match_ast, 15 match_ast,
16}; 16};
17use test_utils::tested_by;
18 17
19use crate::RootDatabase; 18use crate::RootDatabase;
20 19
@@ -42,12 +41,10 @@ impl Definition {
42 } 41 }
43 42
44 pub fn visibility(&self, db: &RootDatabase) -> Option<Visibility> { 43 pub fn visibility(&self, db: &RootDatabase) -> Option<Visibility> {
45 let module = self.module(db);
46
47 match self { 44 match self {
48 Definition::Macro(_) => None, 45 Definition::Macro(_) => None,
49 Definition::Field(sf) => Some(sf.visibility(db)), 46 Definition::Field(sf) => Some(sf.visibility(db)),
50 Definition::ModuleDef(def) => module?.visibility_of(db, def), 47 Definition::ModuleDef(def) => def.definition_visibility(db),
51 Definition::SelfType(_) => None, 48 Definition::SelfType(_) => None,
52 Definition::Local(_) => None, 49 Definition::Local(_) => None,
53 Definition::TypeParam(_) => None, 50 Definition::TypeParam(_) => None,
@@ -119,6 +116,15 @@ fn classify_name_inner(sema: &Semantics<RootDatabase>, name: &ast::Name) -> Opti
119 116
120 match_ast! { 117 match_ast! {
121 match parent { 118 match parent {
119 ast::Alias(it) => {
120 let use_tree = it.syntax().parent().and_then(ast::UseTree::cast)?;
121 let path = use_tree.path()?;
122 let path_segment = path.segment()?;
123 let name_ref = path_segment.name_ref()?;
124 let name_ref_class = classify_name_ref(sema, &name_ref)?;
125
126 Some(name_ref_class.definition())
127 },
122 ast::BindPat(it) => { 128 ast::BindPat(it) => {
123 let local = sema.to_def(&it)?; 129 let local = sema.to_def(&it)?;
124 Some(Definition::Local(local)) 130 Some(Definition::Local(local))
@@ -195,6 +201,8 @@ impl NameRefClass {
195 } 201 }
196} 202}
197 203
204// Note: we don't have unit-tests for this rather important function.
205// It is primarily exercised via goto definition tests in `ra_ide`.
198pub fn classify_name_ref( 206pub fn classify_name_ref(
199 sema: &Semantics<RootDatabase>, 207 sema: &Semantics<RootDatabase>,
200 name_ref: &ast::NameRef, 208 name_ref: &ast::NameRef,
@@ -204,22 +212,18 @@ pub fn classify_name_ref(
204 let parent = name_ref.syntax().parent()?; 212 let parent = name_ref.syntax().parent()?;
205 213
206 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) { 214 if let Some(method_call) = ast::MethodCallExpr::cast(parent.clone()) {
207 tested_by!(goto_def_for_methods; force);
208 if let Some(func) = sema.resolve_method_call(&method_call) { 215 if let Some(func) = sema.resolve_method_call(&method_call) {
209 return Some(NameRefClass::Definition(Definition::ModuleDef(func.into()))); 216 return Some(NameRefClass::Definition(Definition::ModuleDef(func.into())));
210 } 217 }
211 } 218 }
212 219
213 if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) { 220 if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
214 tested_by!(goto_def_for_fields; force);
215 if let Some(field) = sema.resolve_field(&field_expr) { 221 if let Some(field) = sema.resolve_field(&field_expr) {
216 return Some(NameRefClass::Definition(Definition::Field(field))); 222 return Some(NameRefClass::Definition(Definition::Field(field)));
217 } 223 }
218 } 224 }
219 225
220 if let Some(record_field) = ast::RecordField::for_field_name(name_ref) { 226 if let Some(record_field) = ast::RecordField::for_field_name(name_ref) {
221 tested_by!(goto_def_for_record_fields; force);
222 tested_by!(goto_def_for_field_init_shorthand; force);
223 if let Some((field, local)) = sema.resolve_record_field(&record_field) { 227 if let Some((field, local)) = sema.resolve_record_field(&record_field) {
224 let field = Definition::Field(field); 228 let field = Definition::Field(field);
225 let res = match local { 229 let res = match local {
@@ -231,7 +235,6 @@ pub fn classify_name_ref(
231 } 235 }
232 236
233 if let Some(record_field_pat) = ast::RecordFieldPat::cast(parent.clone()) { 237 if let Some(record_field_pat) = ast::RecordFieldPat::cast(parent.clone()) {
234 tested_by!(goto_def_for_record_field_pats; force);
235 if let Some(field) = sema.resolve_record_field_pat(&record_field_pat) { 238 if let Some(field) = sema.resolve_record_field_pat(&record_field_pat) {
236 let field = Definition::Field(field); 239 let field = Definition::Field(field);
237 return Some(NameRefClass::Definition(field)); 240 return Some(NameRefClass::Definition(field));
@@ -239,7 +242,6 @@ pub fn classify_name_ref(
239 } 242 }
240 243
241 if let Some(macro_call) = parent.ancestors().find_map(ast::MacroCall::cast) { 244 if let Some(macro_call) = parent.ancestors().find_map(ast::MacroCall::cast) {
242 tested_by!(goto_def_for_macros; force);
243 if let Some(macro_def) = sema.resolve_macro_call(&macro_call) { 245 if let Some(macro_def) = sema.resolve_macro_call(&macro_call) {
244 return Some(NameRefClass::Definition(Definition::Macro(macro_def))); 246 return Some(NameRefClass::Definition(Definition::Macro(macro_def)));
245 } 247 }
diff --git a/crates/ra_ide_db/src/lib.rs b/crates/ra_ide_db/src/lib.rs
index e6f2d36e9..1b74e6558 100644
--- a/crates/ra_ide_db/src/lib.rs
+++ b/crates/ra_ide_db/src/lib.rs
@@ -2,14 +2,13 @@
2//! 2//!
3//! It is mainly a `HirDatabase` for semantic analysis, plus a `SymbolsDatabase`, for fuzzy search. 3//! It is mainly a `HirDatabase` for semantic analysis, plus a `SymbolsDatabase`, for fuzzy search.
4 4
5pub mod marks;
6pub mod line_index; 5pub mod line_index;
7pub mod line_index_utils;
8pub mod symbol_index; 6pub mod symbol_index;
9pub mod change; 7pub mod change;
10pub mod defs; 8pub mod defs;
11pub mod search; 9pub mod search;
12pub mod imports_locator; 10pub mod imports_locator;
11pub mod source_change;
13mod wasm_shims; 12mod wasm_shims;
14 13
15use std::sync::Arc; 14use std::sync::Arc;
diff --git a/crates/ra_ide_db/src/line_index.rs b/crates/ra_ide_db/src/line_index.rs
index 00ba95913..c7c744fce 100644
--- a/crates/ra_ide_db/src/line_index.rs
+++ b/crates/ra_ide_db/src/line_index.rs
@@ -8,7 +8,9 @@ use superslice::Ext;
8 8
9#[derive(Clone, Debug, PartialEq, Eq)] 9#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct LineIndex { 10pub struct LineIndex {
11 /// Offset the the beginning of each line, zero-based
11 pub(crate) newlines: Vec<TextSize>, 12 pub(crate) newlines: Vec<TextSize>,
13 /// List of non-ASCII characters on each line
12 pub(crate) utf16_lines: FxHashMap<u32, Vec<Utf16Char>>, 14 pub(crate) utf16_lines: FxHashMap<u32, Vec<Utf16Char>>,
13} 15}
14 16
@@ -22,14 +24,26 @@ pub struct LineCol {
22 24
23#[derive(Clone, Debug, Hash, PartialEq, Eq)] 25#[derive(Clone, Debug, Hash, PartialEq, Eq)]
24pub(crate) struct Utf16Char { 26pub(crate) struct Utf16Char {
27 /// Start offset of a character inside a line, zero-based
25 pub(crate) start: TextSize, 28 pub(crate) start: TextSize,
29 /// End offset of a character inside a line, zero-based
26 pub(crate) end: TextSize, 30 pub(crate) end: TextSize,
27} 31}
28 32
29impl Utf16Char { 33impl Utf16Char {
34 /// Returns the length in 8-bit UTF-8 code units.
30 fn len(&self) -> TextSize { 35 fn len(&self) -> TextSize {
31 self.end - self.start 36 self.end - self.start
32 } 37 }
38
39 /// Returns the length in 16-bit UTF-16 code units.
40 fn len_utf16(&self) -> usize {
41 if self.len() == TextSize::from(4) {
42 2
43 } else {
44 1
45 }
46 }
33} 47}
34 48
35impl LineIndex { 49impl LineIndex {
@@ -106,7 +120,7 @@ impl LineIndex {
106 if let Some(utf16_chars) = self.utf16_lines.get(&line) { 120 if let Some(utf16_chars) = self.utf16_lines.get(&line) {
107 for c in utf16_chars { 121 for c in utf16_chars {
108 if c.end <= col { 122 if c.end <= col {
109 res -= usize::from(c.len()) - 1; 123 res -= usize::from(c.len()) - c.len_utf16();
110 } else { 124 } else {
111 // From here on, all utf16 characters come *after* the character we are mapping, 125 // From here on, all utf16 characters come *after* the character we are mapping,
112 // so we don't need to take them into account 126 // so we don't need to take them into account
@@ -120,8 +134,8 @@ impl LineIndex {
120 fn utf16_to_utf8_col(&self, line: u32, mut col: u32) -> TextSize { 134 fn utf16_to_utf8_col(&self, line: u32, mut col: u32) -> TextSize {
121 if let Some(utf16_chars) = self.utf16_lines.get(&line) { 135 if let Some(utf16_chars) = self.utf16_lines.get(&line) {
122 for c in utf16_chars { 136 for c in utf16_chars {
123 if col >= u32::from(c.start) { 137 if col > u32::from(c.start) {
124 col += u32::from(c.len()) - 1; 138 col += u32::from(c.len()) - c.len_utf16() as u32;
125 } else { 139 } else {
126 // From here on, all utf16 characters come *after* the character we are mapping, 140 // From here on, all utf16 characters come *after* the character we are mapping,
127 // so we don't need to take them into account 141 // so we don't need to take them into account
@@ -200,6 +214,9 @@ const C: char = 'メ';
200 214
201 // UTF-16 to UTF-8 215 // UTF-16 to UTF-8
202 assert_eq!(col_index.utf16_to_utf8_col(1, 19), TextSize::from(21)); 216 assert_eq!(col_index.utf16_to_utf8_col(1, 19), TextSize::from(21));
217
218 let col_index = LineIndex::new("a𐐏b");
219 assert_eq!(col_index.utf16_to_utf8_col(0, 3), TextSize::from(5));
203 } 220 }
204 221
205 #[test] 222 #[test]
@@ -226,8 +243,10 @@ const C: char = \"メ メ\";
226 // UTF-16 to UTF-8 243 // UTF-16 to UTF-8
227 assert_eq!(col_index.utf16_to_utf8_col(1, 15), TextSize::from(15)); 244 assert_eq!(col_index.utf16_to_utf8_col(1, 15), TextSize::from(15));
228 245
229 assert_eq!(col_index.utf16_to_utf8_col(1, 18), TextSize::from(20)); 246 // メ UTF-8: 0xE3 0x83 0xA1, UTF-16: 0x30E1
230 assert_eq!(col_index.utf16_to_utf8_col(1, 19), TextSize::from(23)); 247 assert_eq!(col_index.utf16_to_utf8_col(1, 17), TextSize::from(17)); // first メ at 17..20
248 assert_eq!(col_index.utf16_to_utf8_col(1, 18), TextSize::from(20)); // space
249 assert_eq!(col_index.utf16_to_utf8_col(1, 19), TextSize::from(21)); // second メ at 21..24
231 250
232 assert_eq!(col_index.utf16_to_utf8_col(2, 15), TextSize::from(15)); 251 assert_eq!(col_index.utf16_to_utf8_col(2, 15), TextSize::from(15));
233 } 252 }
diff --git a/crates/ra_ide_db/src/line_index_utils.rs b/crates/ra_ide_db/src/line_index_utils.rs
deleted file mode 100644
index 039a12c0d..000000000
--- a/crates/ra_ide_db/src/line_index_utils.rs
+++ /dev/null
@@ -1,302 +0,0 @@
1//! Code actions can specify desirable final position of the cursor.
2//!
3//! The position is specified as a `TextSize` in the final file. We need to send
4//! it in `(Line, Column)` coordinate though. However, we only have a LineIndex
5//! for a file pre-edit!
6//!
7//! Code in this module applies this "to (Line, Column) after edit"
8//! transformation.
9
10use std::convert::TryInto;
11
12use ra_syntax::{TextRange, TextSize};
13use ra_text_edit::{AtomTextEdit, TextEdit};
14
15use crate::line_index::{LineCol, LineIndex, Utf16Char};
16
17pub fn translate_offset_with_edit(
18 line_index: &LineIndex,
19 offset: TextSize,
20 text_edit: &TextEdit,
21) -> LineCol {
22 let mut state = Edits::from_text_edit(&text_edit);
23
24 let mut res = RunningLineCol::new();
25
26 macro_rules! test_step {
27 ($x:ident) => {
28 match &$x {
29 Step::Newline(n) => {
30 if offset < *n {
31 return res.to_line_col(offset);
32 } else {
33 res.add_line(*n);
34 }
35 }
36 Step::Utf16Char(x) => {
37 if offset < x.end() {
38 // if the offset is inside a multibyte char it's invalid
39 // clamp it to the start of the char
40 let clamp = offset.min(x.start());
41 return res.to_line_col(clamp);
42 } else {
43 res.adjust_col(*x);
44 }
45 }
46 }
47 };
48 }
49
50 for orig_step in LineIndexStepIter::from(line_index) {
51 loop {
52 let translated_step = state.translate_step(&orig_step);
53 match state.next_steps(&translated_step) {
54 NextSteps::Use => {
55 test_step!(translated_step);
56 break;
57 }
58 NextSteps::ReplaceMany(ns) => {
59 for n in ns {
60 test_step!(n);
61 }
62 break;
63 }
64 NextSteps::AddMany(ns) => {
65 for n in ns {
66 test_step!(n);
67 }
68 }
69 }
70 }
71 }
72
73 loop {
74 match state.next_inserted_steps() {
75 None => break,
76 Some(ns) => {
77 for n in ns {
78 test_step!(n);
79 }
80 }
81 }
82 }
83
84 res.to_line_col(offset)
85}
86
87#[derive(Debug, Clone)]
88enum Step {
89 Newline(TextSize),
90 Utf16Char(TextRange),
91}
92
93#[derive(Debug)]
94struct LineIndexStepIter<'a> {
95 line_index: &'a LineIndex,
96 next_newline_idx: usize,
97 utf16_chars: Option<(TextSize, std::slice::Iter<'a, Utf16Char>)>,
98}
99
100impl LineIndexStepIter<'_> {
101 fn from(line_index: &LineIndex) -> LineIndexStepIter {
102 let mut x = LineIndexStepIter { line_index, next_newline_idx: 0, utf16_chars: None };
103 // skip first newline since it's not real
104 x.next();
105 x
106 }
107}
108
109impl Iterator for LineIndexStepIter<'_> {
110 type Item = Step;
111 fn next(&mut self) -> Option<Step> {
112 self.utf16_chars
113 .as_mut()
114 .and_then(|(newline, x)| {
115 let x = x.next()?;
116 Some(Step::Utf16Char(TextRange::new(*newline + x.start, *newline + x.end)))
117 })
118 .or_else(|| {
119 let next_newline = *self.line_index.newlines.get(self.next_newline_idx)?;
120 self.utf16_chars = self
121 .line_index
122 .utf16_lines
123 .get(&(self.next_newline_idx as u32))
124 .map(|x| (next_newline, x.iter()));
125 self.next_newline_idx += 1;
126 Some(Step::Newline(next_newline))
127 })
128 }
129}
130
131#[derive(Debug)]
132struct OffsetStepIter<'a> {
133 text: &'a str,
134 offset: TextSize,
135}
136
137impl Iterator for OffsetStepIter<'_> {
138 type Item = Step;
139 fn next(&mut self) -> Option<Step> {
140 let (next, next_offset) = self
141 .text
142 .char_indices()
143 .filter_map(|(i, c)| {
144 let i: TextSize = i.try_into().unwrap();
145 let char_len = TextSize::of(c);
146 if c == '\n' {
147 let next_offset = self.offset + i + char_len;
148 let next = Step::Newline(next_offset);
149 Some((next, next_offset))
150 } else {
151 if !c.is_ascii() {
152 let start = self.offset + i;
153 let end = start + char_len;
154 let next = Step::Utf16Char(TextRange::new(start, end));
155 let next_offset = end;
156 Some((next, next_offset))
157 } else {
158 None
159 }
160 }
161 })
162 .next()?;
163 let next_idx: usize = (next_offset - self.offset).into();
164 self.text = &self.text[next_idx..];
165 self.offset = next_offset;
166 Some(next)
167 }
168}
169
170#[derive(Debug)]
171enum NextSteps<'a> {
172 Use,
173 ReplaceMany(OffsetStepIter<'a>),
174 AddMany(OffsetStepIter<'a>),
175}
176
177#[derive(Debug)]
178struct TranslatedEdit<'a> {
179 delete: TextRange,
180 insert: &'a str,
181 diff: i64,
182}
183
184struct Edits<'a> {
185 edits: &'a [AtomTextEdit],
186 current: Option<TranslatedEdit<'a>>,
187 acc_diff: i64,
188}
189
190impl<'a> Edits<'a> {
191 fn from_text_edit(text_edit: &'a TextEdit) -> Edits<'a> {
192 let mut x = Edits { edits: text_edit.as_atoms(), current: None, acc_diff: 0 };
193 x.advance_edit();
194 x
195 }
196 fn advance_edit(&mut self) {
197 self.acc_diff += self.current.as_ref().map_or(0, |x| x.diff);
198 match self.edits.split_first() {
199 Some((next, rest)) => {
200 let delete = self.translate_range(next.delete);
201 let diff = next.insert.len() as i64 - usize::from(next.delete.len()) as i64;
202 self.current = Some(TranslatedEdit { delete, insert: &next.insert, diff });
203 self.edits = rest;
204 }
205 None => {
206 self.current = None;
207 }
208 }
209 }
210
211 fn next_inserted_steps(&mut self) -> Option<OffsetStepIter<'a>> {
212 let cur = self.current.as_ref()?;
213 let res = Some(OffsetStepIter { offset: cur.delete.start(), text: &cur.insert });
214 self.advance_edit();
215 res
216 }
217
218 fn next_steps(&mut self, step: &Step) -> NextSteps {
219 let step_pos = match *step {
220 Step::Newline(n) => n,
221 Step::Utf16Char(r) => r.end(),
222 };
223 match &mut self.current {
224 Some(edit) => {
225 if step_pos <= edit.delete.start() {
226 NextSteps::Use
227 } else if step_pos <= edit.delete.end() {
228 let iter = OffsetStepIter { offset: edit.delete.start(), text: &edit.insert };
229 // empty slice to avoid returning steps again
230 edit.insert = &edit.insert[edit.insert.len()..];
231 NextSteps::ReplaceMany(iter)
232 } else {
233 let iter = OffsetStepIter { offset: edit.delete.start(), text: &edit.insert };
234 // empty slice to avoid returning steps again
235 edit.insert = &edit.insert[edit.insert.len()..];
236 self.advance_edit();
237 NextSteps::AddMany(iter)
238 }
239 }
240 None => NextSteps::Use,
241 }
242 }
243
244 fn translate_range(&self, range: TextRange) -> TextRange {
245 if self.acc_diff == 0 {
246 range
247 } else {
248 let start = self.translate(range.start());
249 let end = self.translate(range.end());
250 TextRange::new(start, end)
251 }
252 }
253
254 fn translate(&self, x: TextSize) -> TextSize {
255 if self.acc_diff == 0 {
256 x
257 } else {
258 TextSize::from((usize::from(x) as i64 + self.acc_diff) as u32)
259 }
260 }
261
262 fn translate_step(&self, x: &Step) -> Step {
263 if self.acc_diff == 0 {
264 x.clone()
265 } else {
266 match *x {
267 Step::Newline(n) => Step::Newline(self.translate(n)),
268 Step::Utf16Char(r) => Step::Utf16Char(self.translate_range(r)),
269 }
270 }
271 }
272}
273
274#[derive(Debug)]
275struct RunningLineCol {
276 line: u32,
277 last_newline: TextSize,
278 col_adjust: TextSize,
279}
280
281impl RunningLineCol {
282 fn new() -> RunningLineCol {
283 RunningLineCol { line: 0, last_newline: TextSize::from(0), col_adjust: TextSize::from(0) }
284 }
285
286 fn to_line_col(&self, offset: TextSize) -> LineCol {
287 LineCol {
288 line: self.line,
289 col_utf16: ((offset - self.last_newline) - self.col_adjust).into(),
290 }
291 }
292
293 fn add_line(&mut self, newline: TextSize) {
294 self.line += 1;
295 self.last_newline = newline;
296 self.col_adjust = TextSize::from(0);
297 }
298
299 fn adjust_col(&mut self, range: TextRange) {
300 self.col_adjust += range.len() - TextSize::from(1);
301 }
302}
diff --git a/crates/ra_ide_db/src/marks.rs b/crates/ra_ide_db/src/marks.rs
deleted file mode 100644
index 03b4be21c..000000000
--- a/crates/ra_ide_db/src/marks.rs
+++ /dev/null
@@ -1,11 +0,0 @@
1//! See test_utils/src/marks.rs
2
3test_utils::marks![
4 goto_def_for_macros
5 goto_def_for_methods
6 goto_def_for_fields
7 goto_def_for_record_fields
8 goto_def_for_field_init_shorthand
9 goto_def_for_record_field_pats
10 search_filters_by_range
11];
diff --git a/crates/ra_ide_db/src/search.rs b/crates/ra_ide_db/src/search.rs
index b464959fc..335a1ad03 100644
--- a/crates/ra_ide_db/src/search.rs
+++ b/crates/ra_ide_db/src/search.rs
@@ -12,7 +12,6 @@ use ra_db::{FileId, FileRange, SourceDatabaseExt};
12use ra_prof::profile; 12use ra_prof::profile;
13use ra_syntax::{ast, match_ast, AstNode, TextRange, TextSize}; 13use ra_syntax::{ast, match_ast, AstNode, TextRange, TextSize};
14use rustc_hash::FxHashMap; 14use rustc_hash::FxHashMap;
15use test_utils::tested_by;
16 15
17use crate::{ 16use crate::{
18 defs::{classify_name_ref, Definition, NameRefClass}, 17 defs::{classify_name_ref, Definition, NameRefClass},
@@ -125,29 +124,33 @@ impl Definition {
125 124
126 let vis = self.visibility(db); 125 let vis = self.visibility(db);
127 126
128 // FIXME:
129 // The following logic are wrong that it does not search
130 // for submodules within other files recursively.
131
132 if let Some(Visibility::Module(module)) = vis.and_then(|it| it.into()) { 127 if let Some(Visibility::Module(module)) = vis.and_then(|it| it.into()) {
133 let module: Module = module.into(); 128 let module: Module = module.into();
134 let mut res = FxHashMap::default(); 129 let mut res = FxHashMap::default();
135 let src = module.definition_source(db);
136 let file_id = src.file_id.original_file(db);
137 130
138 match src.value { 131 let mut to_visit = vec![module];
139 ModuleSource::Module(m) => { 132 let mut is_first = true;
140 let range = Some(m.syntax().text_range()); 133 while let Some(module) = to_visit.pop() {
141 res.insert(file_id, range); 134 let src = module.definition_source(db);
142 } 135 let file_id = src.file_id.original_file(db);
143 ModuleSource::SourceFile(_) => { 136 match src.value {
144 res.insert(file_id, None); 137 ModuleSource::Module(m) => {
145 res.extend(module.children(db).map(|m| { 138 if is_first {
146 let src = m.definition_source(db); 139 let range = Some(m.syntax().text_range());
147 (src.file_id.original_file(db), None) 140 res.insert(file_id, range);
148 })); 141 } else {
149 } 142 // We have already added the enclosing file to the search scope,
143 // so do nothing.
144 }
145 }
146 ModuleSource::SourceFile(_) => {
147 res.insert(file_id, None);
148 }
149 };
150 is_first = false;
151 to_visit.extend(module.children(db));
150 } 152 }
153
151 return SearchScope::new(res); 154 return SearchScope::new(res);
152 } 155 }
153 156
@@ -209,7 +212,6 @@ impl Definition {
209 for (idx, _) in text.match_indices(pat) { 212 for (idx, _) in text.match_indices(pat) {
210 let offset: TextSize = idx.try_into().unwrap(); 213 let offset: TextSize = idx.try_into().unwrap();
211 if !search_range.contains_inclusive(offset) { 214 if !search_range.contains_inclusive(offset) {
212 tested_by!(search_filters_by_range; force);
213 continue; 215 continue;
214 } 216 }
215 217
diff --git a/crates/ra_ide_db/src/source_change.rs b/crates/ra_ide_db/src/source_change.rs
new file mode 100644
index 000000000..e713f4b7e
--- /dev/null
+++ b/crates/ra_ide_db/src/source_change.rs
@@ -0,0 +1,68 @@
1//! This modules defines type to represent changes to the source code, that flow
2//! from the server to the client.
3//!
4//! It can be viewed as a dual for `AnalysisChange`.
5
6use ra_db::{FileId, RelativePathBuf, SourceRootId};
7use ra_text_edit::TextEdit;
8
9#[derive(Debug, Clone)]
10pub struct SourceChange {
11 pub source_file_edits: Vec<SourceFileEdit>,
12 pub file_system_edits: Vec<FileSystemEdit>,
13 pub is_snippet: bool,
14}
15
16impl SourceChange {
17 /// Creates a new SourceChange with the given label
18 /// from the edits.
19 pub fn from_edits(
20 source_file_edits: Vec<SourceFileEdit>,
21 file_system_edits: Vec<FileSystemEdit>,
22 ) -> Self {
23 SourceChange { source_file_edits, file_system_edits, is_snippet: false }
24 }
25
26 /// Creates a new SourceChange with the given label,
27 /// containing only the given `SourceFileEdits`.
28 pub fn source_file_edits(edits: Vec<SourceFileEdit>) -> Self {
29 SourceChange { source_file_edits: edits, file_system_edits: vec![], is_snippet: false }
30 }
31 /// Creates a new SourceChange with the given label
32 /// from the given `FileId` and `TextEdit`
33 pub fn source_file_edit_from(file_id: FileId, edit: TextEdit) -> Self {
34 SourceFileEdit { file_id, edit }.into()
35 }
36}
37
38#[derive(Debug, Clone)]
39pub struct SourceFileEdit {
40 pub file_id: FileId,
41 pub edit: TextEdit,
42}
43
44impl From<SourceFileEdit> for SourceChange {
45 fn from(edit: SourceFileEdit) -> SourceChange {
46 SourceChange {
47 source_file_edits: vec![edit],
48 file_system_edits: Vec::new(),
49 is_snippet: false,
50 }
51 }
52}
53
54#[derive(Debug, Clone)]
55pub enum FileSystemEdit {
56 CreateFile { source_root: SourceRootId, path: RelativePathBuf },
57 MoveFile { src: FileId, dst_source_root: SourceRootId, dst_path: RelativePathBuf },
58}
59
60impl From<FileSystemEdit> for SourceChange {
61 fn from(edit: FileSystemEdit) -> SourceChange {
62 SourceChange {
63 source_file_edits: Vec::new(),
64 file_system_edits: vec![edit],
65 is_snippet: false,
66 }
67 }
68}
diff --git a/crates/ra_ide_db/src/symbol_index.rs b/crates/ra_ide_db/src/symbol_index.rs
index 95be11134..acc31fe3b 100644
--- a/crates/ra_ide_db/src/symbol_index.rs
+++ b/crates/ra_ide_db/src/symbol_index.rs
@@ -110,6 +110,27 @@ fn file_symbols(db: &impl SymbolsDatabase, file_id: FileId) -> Arc<SymbolIndex>
110 Arc::new(SymbolIndex::new(symbols)) 110 Arc::new(SymbolIndex::new(symbols))
111} 111}
112 112
113// Feature: Workspace Symbol
114//
115// Uses fuzzy-search to find types, modules and functions by name across your
116// project and dependencies. This is **the** most useful feature, which improves code
117// navigation tremendously. It mostly works on top of the built-in LSP
118// functionality, however `#` and `*` symbols can be used to narrow down the
119// search. Specifically,
120//
121// - `Foo` searches for `Foo` type in the current workspace
122// - `foo#` searches for `foo` function in the current workspace
123// - `Foo*` searches for `Foo` type among dependencies, including `stdlib`
124// - `foo#*` searches for `foo` function among dependencies
125//
126// That is, `#` switches from "types" to all symbols, `*` switches from the current
127// workspace to dependencies.
128//
129// |===
130// | Editor | Shortcut
131//
132// | VS Code | kbd:[Ctrl+T]
133// |===
113pub fn world_symbols(db: &RootDatabase, query: Query) -> Vec<FileSymbol> { 134pub fn world_symbols(db: &RootDatabase, query: Query) -> Vec<FileSymbol> {
114 /// Need to wrap Snapshot to provide `Clone` impl for `map_with` 135 /// Need to wrap Snapshot to provide `Clone` impl for `map_with`
115 struct Snap(salsa::Snapshot<RootDatabase>); 136 struct Snap(salsa::Snapshot<RootDatabase>);