aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorbors[bot] <bors[bot]@users.noreply.github.com>2018-10-25 16:04:48 +0100
committerbors[bot] <bors[bot]@users.noreply.github.com>2018-10-25 16:04:48 +0100
commit5932bd0bb5fcd066a9d16abcd1597b7097978085 (patch)
tree7b6ea86855fe34c3d45d14262c8cf94e315566e8 /crates
parent2cb2074c4b7219b32993abdcc7084637c0123d49 (diff)
parent363adf07b7763cfe7e13fac0ee148361d51834e4 (diff)
Merge #162
162: Db everywhere r=matklad a=matklad This PR continues our switch to salsa. Now *all* state is handled by a single salsa database. Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_analysis/Cargo.toml3
-rw-r--r--crates/ra_analysis/src/completion.rs4
-rw-r--r--crates/ra_analysis/src/db.rs58
-rw-r--r--crates/ra_analysis/src/descriptors/module/imp.rs24
-rw-r--r--crates/ra_analysis/src/descriptors/module/mod.rs9
-rw-r--r--crates/ra_analysis/src/imp.rs184
-rw-r--r--crates/ra_analysis/src/input.rs79
-rw-r--r--crates/ra_analysis/src/lib.rs99
-rw-r--r--crates/ra_analysis/src/roots.rs116
-rw-r--r--crates/ra_analysis/src/symbol_index.rs2
-rw-r--r--crates/ra_analysis/tests/tests.rs29
-rw-r--r--crates/ra_lsp_server/src/main_loop/mod.rs20
-rw-r--r--crates/ra_lsp_server/src/path_map.rs26
-rw-r--r--crates/ra_lsp_server/src/server_world.rs73
14 files changed, 379 insertions, 347 deletions
diff --git a/crates/ra_analysis/Cargo.toml b/crates/ra_analysis/Cargo.toml
index 75a9dc844..5d7915fa5 100644
--- a/crates/ra_analysis/Cargo.toml
+++ b/crates/ra_analysis/Cargo.toml
@@ -5,12 +5,13 @@ version = "0.1.0"
5authors = ["Aleksey Kladov <[email protected]>"] 5authors = ["Aleksey Kladov <[email protected]>"]
6 6
7[dependencies] 7[dependencies]
8log = "0.4.5"
8relative-path = "0.4.0" 9relative-path = "0.4.0"
9rayon = "1.0.2" 10rayon = "1.0.2"
10fst = "0.3.1" 11fst = "0.3.1"
11ra_syntax = { path = "../ra_syntax" } 12ra_syntax = { path = "../ra_syntax" }
12ra_editor = { path = "../ra_editor" } 13ra_editor = { path = "../ra_editor" }
13salsa = "0.6.0" 14salsa = "0.6.2"
14rustc-hash = "1.0" 15rustc-hash = "1.0"
15 16
16[dev-dependencies] 17[dev-dependencies]
diff --git a/crates/ra_analysis/src/completion.rs b/crates/ra_analysis/src/completion.rs
index a0fd6828d..0a2f99575 100644
--- a/crates/ra_analysis/src/completion.rs
+++ b/crates/ra_analysis/src/completion.rs
@@ -6,13 +6,15 @@ use ra_syntax::{
6 6
7use crate::{ 7use crate::{
8 FileId, Cancelable, 8 FileId, Cancelable,
9 input::FilesDatabase,
9 db::{self, SyntaxDatabase}, 10 db::{self, SyntaxDatabase},
10 descriptors::module::{ModulesDatabase, ModuleTree, ModuleId}, 11 descriptors::module::{ModulesDatabase, ModuleTree, ModuleId},
11}; 12};
12 13
13pub(crate) fn resolve_based_completion(db: &db::RootDatabase, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> { 14pub(crate) fn resolve_based_completion(db: &db::RootDatabase, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> {
15 let source_root_id = db.file_source_root(file_id);
14 let file = db.file_syntax(file_id); 16 let file = db.file_syntax(file_id);
15 let module_tree = db.module_tree()?; 17 let module_tree = db.module_tree(source_root_id)?;
16 let file = { 18 let file = {
17 let edit = AtomEdit::insert(offset, "intellijRulezz".to_string()); 19 let edit = AtomEdit::insert(offset, "intellijRulezz".to_string());
18 file.reparse(&edit) 20 file.reparse(&edit)
diff --git a/crates/ra_analysis/src/db.rs b/crates/ra_analysis/src/db.rs
index b527cde61..3ca14af79 100644
--- a/crates/ra_analysis/src/db.rs
+++ b/crates/ra_analysis/src/db.rs
@@ -1,12 +1,9 @@
1use std::{ 1use std::{
2 fmt,
3 hash::{Hash, Hasher},
4 sync::Arc, 2 sync::Arc,
5}; 3};
6 4
7use ra_editor::LineIndex; 5use ra_editor::LineIndex;
8use ra_syntax::File; 6use ra_syntax::File;
9use rustc_hash::FxHashSet;
10use salsa; 7use salsa;
11 8
12use crate::{ 9use crate::{
@@ -14,20 +11,14 @@ use crate::{
14 Cancelable, Canceled, 11 Cancelable, Canceled,
15 descriptors::module::{SubmodulesQuery, ModuleTreeQuery, ModulesDatabase}, 12 descriptors::module::{SubmodulesQuery, ModuleTreeQuery, ModulesDatabase},
16 symbol_index::SymbolIndex, 13 symbol_index::SymbolIndex,
17 FileId, FileResolverImp, 14 FileId,
18}; 15};
19 16
20#[derive(Default)] 17#[derive(Default, Debug)]
21pub(crate) struct RootDatabase { 18pub(crate) struct RootDatabase {
22 runtime: salsa::Runtime<RootDatabase>, 19 runtime: salsa::Runtime<RootDatabase>,
23} 20}
24 21
25impl fmt::Debug for RootDatabase {
26 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
27 fmt.write_str("RootDatabase { ... }")
28 }
29}
30
31impl salsa::Database for RootDatabase { 22impl salsa::Database for RootDatabase {
32 fn salsa_runtime(&self) -> &salsa::Runtime<RootDatabase> { 23 fn salsa_runtime(&self) -> &salsa::Runtime<RootDatabase> {
33 &self.runtime 24 &self.runtime
@@ -58,9 +49,13 @@ impl Clone for RootDatabase {
58 49
59salsa::database_storage! { 50salsa::database_storage! {
60 pub(crate) struct RootDatabaseStorage for RootDatabase { 51 pub(crate) struct RootDatabaseStorage for RootDatabase {
61 impl FilesDatabase { 52 impl crate::input::FilesDatabase {
62 fn file_text() for FileTextQuery; 53 fn file_text() for crate::input::FileTextQuery;
63 fn file_set() for FileSetQuery; 54 fn file_source_root() for crate::input::FileSourceRootQuery;
55 fn source_root() for crate::input::SourceRootQuery;
56 fn libraries() for crate::input::LibrarieseQuery;
57 fn library_symbols() for crate::input::LibrarySymbolsQuery;
58 fn crate_graph() for crate::input::CrateGraphQuery;
64 } 59 }
65 impl SyntaxDatabase { 60 impl SyntaxDatabase {
66 fn file_syntax() for FileSyntaxQuery; 61 fn file_syntax() for FileSyntaxQuery;
@@ -75,40 +70,7 @@ salsa::database_storage! {
75} 70}
76 71
77salsa::query_group! { 72salsa::query_group! {
78 pub(crate) trait FilesDatabase: salsa::Database { 73 pub(crate) trait SyntaxDatabase: crate::input::FilesDatabase {
79 fn file_text(file_id: FileId) -> Arc<String> {
80 type FileTextQuery;
81 storage input;
82 }
83 fn file_set() -> Arc<FileSet> {
84 type FileSetQuery;
85 storage input;
86 }
87 }
88}
89
90#[derive(Default, Debug, Eq)]
91pub(crate) struct FileSet {
92 pub(crate) files: FxHashSet<FileId>,
93 pub(crate) resolver: FileResolverImp,
94}
95
96impl PartialEq for FileSet {
97 fn eq(&self, other: &FileSet) -> bool {
98 self.files == other.files && self.resolver == other.resolver
99 }
100}
101
102impl Hash for FileSet {
103 fn hash<H: Hasher>(&self, hasher: &mut H) {
104 let mut files = self.files.iter().cloned().collect::<Vec<_>>();
105 files.sort();
106 files.hash(hasher);
107 }
108}
109
110salsa::query_group! {
111 pub(crate) trait SyntaxDatabase: FilesDatabase {
112 fn file_syntax(file_id: FileId) -> File { 74 fn file_syntax(file_id: FileId) -> File {
113 type FileSyntaxQuery; 75 type FileSyntaxQuery;
114 } 76 }
diff --git a/crates/ra_analysis/src/descriptors/module/imp.rs b/crates/ra_analysis/src/descriptors/module/imp.rs
index 22e4bd785..aecf6e29a 100644
--- a/crates/ra_analysis/src/descriptors/module/imp.rs
+++ b/crates/ra_analysis/src/descriptors/module/imp.rs
@@ -8,8 +8,8 @@ use ra_syntax::{
8}; 8};
9 9
10use crate::{ 10use crate::{
11 FileId, Cancelable, FileResolverImp, 11 FileId, Cancelable, FileResolverImp, db,
12 db, 12 input::{SourceRoot, SourceRootId},
13}; 13};
14 14
15use super::{ 15use super::{
@@ -35,9 +35,12 @@ pub(super) fn modules(root: ast::Root<'_>) -> impl Iterator<Item = (SmolStr, ast
35 }) 35 })
36} 36}
37 37
38pub(super) fn module_tree(db: &impl ModulesDatabase) -> Cancelable<Arc<ModuleTree>> { 38pub(super) fn module_tree(
39 db: &impl ModulesDatabase,
40 source_root: SourceRootId,
41) -> Cancelable<Arc<ModuleTree>> {
39 db::check_canceled(db)?; 42 db::check_canceled(db)?;
40 let res = create_module_tree(db)?; 43 let res = create_module_tree(db, source_root)?;
41 Ok(Arc::new(res)) 44 Ok(Arc::new(res))
42} 45}
43 46
@@ -50,6 +53,7 @@ pub struct Submodule {
50 53
51fn create_module_tree<'a>( 54fn create_module_tree<'a>(
52 db: &impl ModulesDatabase, 55 db: &impl ModulesDatabase,
56 source_root: SourceRootId,
53) -> Cancelable<ModuleTree> { 57) -> Cancelable<ModuleTree> {
54 let mut tree = ModuleTree { 58 let mut tree = ModuleTree {
55 mods: Vec::new(), 59 mods: Vec::new(),
@@ -59,12 +63,13 @@ fn create_module_tree<'a>(
59 let mut roots = FxHashMap::default(); 63 let mut roots = FxHashMap::default();
60 let mut visited = FxHashSet::default(); 64 let mut visited = FxHashSet::default();
61 65
62 for &file_id in db.file_set().files.iter() { 66 let source_root = db.source_root(source_root);
67 for &file_id in source_root.files.iter() {
63 if visited.contains(&file_id) { 68 if visited.contains(&file_id) {
64 continue; // TODO: use explicit crate_roots here 69 continue; // TODO: use explicit crate_roots here
65 } 70 }
66 assert!(!roots.contains_key(&file_id)); 71 assert!(!roots.contains_key(&file_id));
67 let module_id = build_subtree(db, &mut tree, &mut visited, &mut roots, None, file_id)?; 72 let module_id = build_subtree(db, &source_root, &mut tree, &mut visited, &mut roots, None, file_id)?;
68 roots.insert(file_id, module_id); 73 roots.insert(file_id, module_id);
69 } 74 }
70 Ok(tree) 75 Ok(tree)
@@ -72,6 +77,7 @@ fn create_module_tree<'a>(
72 77
73fn build_subtree( 78fn build_subtree(
74 db: &impl ModulesDatabase, 79 db: &impl ModulesDatabase,
80 source_root: &SourceRoot,
75 tree: &mut ModuleTree, 81 tree: &mut ModuleTree,
76 visited: &mut FxHashSet<FileId>, 82 visited: &mut FxHashSet<FileId>,
77 roots: &mut FxHashMap<FileId, ModuleId>, 83 roots: &mut FxHashMap<FileId, ModuleId>,
@@ -84,10 +90,8 @@ fn build_subtree(
84 parent, 90 parent,
85 children: Vec::new(), 91 children: Vec::new(),
86 }); 92 });
87 let file_set = db.file_set();
88 let file_resolver = &file_set.resolver;
89 for name in db.submodules(file_id)?.iter() { 93 for name in db.submodules(file_id)?.iter() {
90 let (points_to, problem) = resolve_submodule(file_id, name, file_resolver); 94 let (points_to, problem) = resolve_submodule(file_id, name, &source_root.file_resolver);
91 let link = tree.push_link(LinkData { 95 let link = tree.push_link(LinkData {
92 name: name.clone(), 96 name: name.clone(),
93 owner: id, 97 owner: id,
@@ -102,7 +106,7 @@ fn build_subtree(
102 tree.module_mut(module_id).parent = Some(link); 106 tree.module_mut(module_id).parent = Some(link);
103 Ok(module_id) 107 Ok(module_id)
104 } 108 }
105 None => build_subtree(db, tree, visited, roots, Some(link), file_id), 109 None => build_subtree(db, source_root, tree, visited, roots, Some(link), file_id),
106 }) 110 })
107 .collect::<Cancelable<Vec<_>>>()?; 111 .collect::<Cancelable<Vec<_>>>()?;
108 tree.link_mut(link).points_to = points_to; 112 tree.link_mut(link).points_to = points_to;
diff --git a/crates/ra_analysis/src/descriptors/module/mod.rs b/crates/ra_analysis/src/descriptors/module/mod.rs
index 52da650b3..8968c4afd 100644
--- a/crates/ra_analysis/src/descriptors/module/mod.rs
+++ b/crates/ra_analysis/src/descriptors/module/mod.rs
@@ -8,11 +8,12 @@ use ra_syntax::{ast::{self, NameOwner, AstNode}, SmolStr, SyntaxNode};
8use crate::{ 8use crate::{
9 FileId, Cancelable, 9 FileId, Cancelable,
10 db::SyntaxDatabase, 10 db::SyntaxDatabase,
11 input::SourceRootId,
11}; 12};
12 13
13salsa::query_group! { 14salsa::query_group! {
14 pub(crate) trait ModulesDatabase: SyntaxDatabase { 15 pub(crate) trait ModulesDatabase: SyntaxDatabase {
15 fn module_tree() -> Cancelable<Arc<ModuleTree>> { 16 fn module_tree(source_root_id: SourceRootId) -> Cancelable<Arc<ModuleTree>> {
16 type ModuleTreeQuery; 17 type ModuleTreeQuery;
17 use fn imp::module_tree; 18 use fn imp::module_tree;
18 } 19 }
@@ -110,15 +111,9 @@ impl ModuleId {
110} 111}
111 112
112impl LinkId { 113impl LinkId {
113 pub(crate) fn name(self, tree: &ModuleTree) -> SmolStr {
114 tree.link(self).name.clone()
115 }
116 pub(crate) fn owner(self, tree: &ModuleTree) -> ModuleId { 114 pub(crate) fn owner(self, tree: &ModuleTree) -> ModuleId {
117 tree.link(self).owner 115 tree.link(self).owner
118 } 116 }
119 fn points_to(self, tree: &ModuleTree) -> &[ModuleId] {
120 &tree.link(self).points_to
121 }
122 pub(crate) fn bind_source<'a>( 117 pub(crate) fn bind_source<'a>(
123 self, 118 self,
124 tree: &ModuleTree, 119 tree: &ModuleTree,
diff --git a/crates/ra_analysis/src/imp.rs b/crates/ra_analysis/src/imp.rs
index f3e5b2887..5a6e2450d 100644
--- a/crates/ra_analysis/src/imp.rs
+++ b/crates/ra_analysis/src/imp.rs
@@ -1,7 +1,5 @@
1use std::{ 1use std::{
2 fmt,
3 hash::{Hash, Hasher}, 2 hash::{Hash, Hasher},
4 iter,
5 sync::Arc, 3 sync::Arc,
6}; 4};
7 5
@@ -14,12 +12,17 @@ use ra_syntax::{
14}; 12};
15use relative_path::RelativePath; 13use relative_path::RelativePath;
16use rustc_hash::FxHashSet; 14use rustc_hash::FxHashSet;
15use salsa::{ParallelDatabase, Database};
17 16
18use crate::{ 17use crate::{
19 db::SyntaxDatabase, 18 AnalysisChange,
19 db::{
20 self, SyntaxDatabase,
21
22 },
23 input::{SourceRootId, FilesDatabase, SourceRoot, WORKSPACE},
20 descriptors::module::{ModulesDatabase, ModuleTree, Problem}, 24 descriptors::module::{ModulesDatabase, ModuleTree, Problem},
21 descriptors::{FnDescriptor}, 25 descriptors::{FnDescriptor},
22 roots::{ReadonlySourceRoot, SourceRoot, WritableSourceRoot},
23 CrateGraph, CrateId, Diagnostic, FileId, FileResolver, FileSystemEdit, Position, 26 CrateGraph, CrateId, Diagnostic, FileId, FileResolver, FileSystemEdit, Position,
24 Query, SourceChange, SourceFileEdit, Cancelable, 27 Query, SourceChange, SourceFileEdit, Cancelable,
25}; 28};
@@ -80,96 +83,128 @@ impl Default for FileResolverImp {
80 } 83 }
81} 84}
82 85
83#[derive(Debug)] 86#[derive(Debug, Default)]
84pub(crate) struct AnalysisHostImpl { 87pub(crate) struct AnalysisHostImpl {
85 data: WorldData, 88 db: db::RootDatabase,
86} 89}
87 90
91
88impl AnalysisHostImpl { 92impl AnalysisHostImpl {
89 pub fn new() -> AnalysisHostImpl { 93 pub fn new() -> AnalysisHostImpl {
90 AnalysisHostImpl { 94 AnalysisHostImpl::default()
91 data: WorldData::default(),
92 }
93 } 95 }
94 pub fn analysis(&self) -> AnalysisImpl { 96 pub fn analysis(&self) -> AnalysisImpl {
95 AnalysisImpl { 97 AnalysisImpl {
96 data: self.data.clone(), 98 db: self.db.fork() // freeze revision here
97 } 99 }
98 } 100 }
99 pub fn change_files(&mut self, changes: &mut dyn Iterator<Item = (FileId, Option<String>)>) { 101 pub fn apply_change(&mut self, change: AnalysisChange) {
100 self.data_mut().root.apply_changes(changes, None); 102 log::info!("apply_change {:?}", change);
101 } 103
102 pub fn set_file_resolver(&mut self, resolver: FileResolverImp) { 104 for (file_id, text) in change.files_changed {
103 self.data_mut() 105 self.db
104 .root 106 .query(crate::input::FileTextQuery)
105 .apply_changes(&mut iter::empty(), Some(resolver)); 107 .set(file_id, Arc::new(text))
106 } 108 }
107 pub fn set_crate_graph(&mut self, graph: CrateGraph) { 109 if !(change.files_added.is_empty() && change.files_removed.is_empty()) {
108 let mut visited = FxHashSet::default(); 110 let file_resolver = change.file_resolver
109 for &file_id in graph.crate_roots.values() { 111 .expect("change resolver when changing set of files");
110 if !visited.insert(file_id) { 112 let mut source_root = SourceRoot::clone(&self.db.source_root(WORKSPACE));
111 panic!("duplicate crate root: {:?}", file_id); 113 for (file_id, text) in change.files_added {
114 self.db
115 .query(crate::input::FileTextQuery)
116 .set(file_id, Arc::new(text));
117 self.db
118 .query(crate::input::FileSourceRootQuery)
119 .set(file_id, crate::input::WORKSPACE);
120 source_root.files.insert(file_id);
121 }
122 for file_id in change.files_removed {
123 self.db
124 .query(crate::input::FileTextQuery)
125 .set(file_id, Arc::new(String::new()));
126 source_root.files.remove(&file_id);
112 } 127 }
128 source_root.file_resolver = file_resolver;
129 self.db
130 .query(crate::input::SourceRootQuery)
131 .set(WORKSPACE, Arc::new(source_root))
132 }
133 if !change.libraries_added.is_empty() {
134 let mut libraries = Vec::clone(&self.db.libraries());
135 for library in change.libraries_added {
136 let source_root_id = SourceRootId(1 + libraries.len() as u32);
137 libraries.push(source_root_id);
138 let mut files = FxHashSet::default();
139 for (file_id, text) in library.files {
140 files.insert(file_id);
141 self.db
142 .query(crate::input::FileSourceRootQuery)
143 .set_constant(file_id, source_root_id);
144 self.db
145 .query(crate::input::FileTextQuery)
146 .set_constant(file_id, Arc::new(text));
147 }
148 let source_root = SourceRoot {
149 files,
150 file_resolver: library.file_resolver,
151 };
152 self.db
153 .query(crate::input::SourceRootQuery)
154 .set(source_root_id, Arc::new(source_root));
155 self.db
156 .query(crate::input::LibrarySymbolsQuery)
157 .set(source_root_id, Arc::new(library.symbol_index));
158 }
159 self.db
160 .query(crate::input::LibrarieseQuery)
161 .set((), Arc::new(libraries));
162 }
163 if let Some(crate_graph) = change.crate_graph {
164 self.db.query(crate::input::CrateGraphQuery)
165 .set((), Arc::new(crate_graph))
113 } 166 }
114 self.data_mut().crate_graph = graph;
115 }
116 pub fn add_library(&mut self, root: ReadonlySourceRoot) {
117 self.data_mut().libs.push(root);
118 }
119 fn data_mut(&mut self) -> &mut WorldData {
120 &mut self.data
121 } 167 }
122} 168}
123 169
170#[derive(Debug)]
124pub(crate) struct AnalysisImpl { 171pub(crate) struct AnalysisImpl {
125 data: WorldData, 172 db: db::RootDatabase,
126}
127
128impl fmt::Debug for AnalysisImpl {
129 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
130 self.data.fmt(f)
131 }
132} 173}
133 174
134impl AnalysisImpl { 175impl AnalysisImpl {
135 fn root(&self, file_id: FileId) -> &SourceRoot {
136 if self.data.root.contains(file_id) {
137 return &self.data.root;
138 }
139 self
140 .data
141 .libs
142 .iter()
143 .find(|it| it.contains(file_id))
144 .unwrap()
145 }
146 pub fn file_syntax(&self, file_id: FileId) -> File { 176 pub fn file_syntax(&self, file_id: FileId) -> File {
147 self.root(file_id).db().file_syntax(file_id) 177 self.db.file_syntax(file_id)
148 } 178 }
149 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> { 179 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
150 self.root(file_id).db().file_lines(file_id) 180 self.db.file_lines(file_id)
151 } 181 }
152 pub fn world_symbols(&self, query: Query) -> Cancelable<Vec<(FileId, FileSymbol)>> { 182 pub fn world_symbols(&self, query: Query) -> Cancelable<Vec<(FileId, FileSymbol)>> {
153 let mut buf = Vec::new(); 183 let mut buf = Vec::new();
154 if query.libs { 184 if query.libs {
155 for lib in self.data.libs.iter() { 185 for &lib_id in self.db.libraries().iter() {
156 lib.symbols(&mut buf)?; 186 buf.push(self.db.library_symbols(lib_id));
157 } 187 }
158 } else { 188 } else {
159 self.data.root.symbols(&mut buf)?; 189 for &file_id in self.db.source_root(WORKSPACE).files.iter() {
190 buf.push(self.db.file_symbols(file_id)?);
191 }
160 } 192 }
161 Ok(query.search(&buf)) 193 Ok(query.search(&buf))
162 } 194 }
195 fn module_tree(&self, file_id: FileId) -> Cancelable<Arc<ModuleTree>> {
196 let source_root = self.db.file_source_root(file_id);
197 self.db.module_tree(source_root)
198 }
163 pub fn parent_module(&self, file_id: FileId) -> Cancelable<Vec<(FileId, FileSymbol)>> { 199 pub fn parent_module(&self, file_id: FileId) -> Cancelable<Vec<(FileId, FileSymbol)>> {
164 let root = self.root(file_id); 200 let module_tree = self.module_tree(file_id)?;
165 let module_tree = root.db().module_tree()?;
166 201
167 let res = module_tree.modules_for_file(file_id) 202 let res = module_tree.modules_for_file(file_id)
168 .into_iter() 203 .into_iter()
169 .filter_map(|module_id| { 204 .filter_map(|module_id| {
170 let link = module_id.parent_link(&module_tree)?; 205 let link = module_id.parent_link(&module_tree)?;
171 let file_id = link.owner(&module_tree).file_id(&module_tree); 206 let file_id = link.owner(&module_tree).file_id(&module_tree);
172 let syntax = root.db().file_syntax(file_id); 207 let syntax = self.db.file_syntax(file_id);
173 let decl = link.bind_source(&module_tree, syntax.ast()); 208 let decl = link.bind_source(&module_tree, syntax.ast());
174 209
175 let sym = FileSymbol { 210 let sym = FileSymbol {
@@ -183,8 +218,8 @@ impl AnalysisImpl {
183 Ok(res) 218 Ok(res)
184 } 219 }
185 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> { 220 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
186 let module_tree = self.root(file_id).db().module_tree()?; 221 let module_tree = self.module_tree(file_id)?;
187 let crate_graph = &self.data.crate_graph; 222 let crate_graph = self.db.crate_graph();
188 let res = module_tree.modules_for_file(file_id) 223 let res = module_tree.modules_for_file(file_id)
189 .into_iter() 224 .into_iter()
190 .map(|it| it.root(&module_tree)) 225 .map(|it| it.root(&module_tree))
@@ -195,7 +230,7 @@ impl AnalysisImpl {
195 Ok(res) 230 Ok(res)
196 } 231 }
197 pub fn crate_root(&self, crate_id: CrateId) -> FileId { 232 pub fn crate_root(&self, crate_id: CrateId) -> FileId {
198 self.data.crate_graph.crate_roots[&crate_id] 233 self.db.crate_graph().crate_roots[&crate_id]
199 } 234 }
200 pub fn completions(&self, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> { 235 pub fn completions(&self, file_id: FileId, offset: TextUnit) -> Cancelable<Option<Vec<CompletionItem>>> {
201 let mut res = Vec::new(); 236 let mut res = Vec::new();
@@ -205,8 +240,7 @@ impl AnalysisImpl {
205 res.extend(scope_based); 240 res.extend(scope_based);
206 has_completions = true; 241 has_completions = true;
207 } 242 }
208 let root = self.root(file_id); 243 if let Some(scope_based) = crate::completion::resolve_based_completion(&self.db, file_id, offset)? {
209 if let Some(scope_based) = crate::completion::resolve_based_completion(root.db(), file_id, offset)? {
210 res.extend(scope_based); 244 res.extend(scope_based);
211 has_completions = true; 245 has_completions = true;
212 } 246 }
@@ -222,9 +256,8 @@ impl AnalysisImpl {
222 file_id: FileId, 256 file_id: FileId,
223 offset: TextUnit, 257 offset: TextUnit,
224 ) -> Cancelable<Vec<(FileId, FileSymbol)>> { 258 ) -> Cancelable<Vec<(FileId, FileSymbol)>> {
225 let root = self.root(file_id); 259 let module_tree = self.module_tree(file_id)?;
226 let module_tree = root.db().module_tree()?; 260 let file = self.db.file_syntax(file_id);
227 let file = root.db().file_syntax(file_id);
228 let syntax = file.syntax(); 261 let syntax = file.syntax();
229 if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, offset) { 262 if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(syntax, offset) {
230 // First try to resolve the symbol locally 263 // First try to resolve the symbol locally
@@ -273,8 +306,7 @@ impl AnalysisImpl {
273 } 306 }
274 307
275 pub fn find_all_refs(&self, file_id: FileId, offset: TextUnit) -> Vec<(FileId, TextRange)> { 308 pub fn find_all_refs(&self, file_id: FileId, offset: TextUnit) -> Vec<(FileId, TextRange)> {
276 let root = self.root(file_id); 309 let file = self.db.file_syntax(file_id);
277 let file = root.db().file_syntax(file_id);
278 let syntax = file.syntax(); 310 let syntax = file.syntax();
279 311
280 let mut ret = vec![]; 312 let mut ret = vec![];
@@ -305,9 +337,8 @@ impl AnalysisImpl {
305 } 337 }
306 338
307 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> { 339 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
308 let root = self.root(file_id); 340 let module_tree = self.module_tree(file_id)?;
309 let module_tree = root.db().module_tree()?; 341 let syntax = self.db.file_syntax(file_id);
310 let syntax = root.db().file_syntax(file_id);
311 342
312 let mut res = ra_editor::diagnostics(&syntax) 343 let mut res = ra_editor::diagnostics(&syntax)
313 .into_iter() 344 .into_iter()
@@ -396,8 +427,7 @@ impl AnalysisImpl {
396 file_id: FileId, 427 file_id: FileId,
397 offset: TextUnit, 428 offset: TextUnit,
398 ) -> Cancelable<Option<(FnDescriptor, Option<usize>)>> { 429 ) -> Cancelable<Option<(FnDescriptor, Option<usize>)>> {
399 let root = self.root(file_id); 430 let file = self.db.file_syntax(file_id);
400 let file = root.db().file_syntax(file_id);
401 let syntax = file.syntax(); 431 let syntax = file.syntax();
402 432
403 // Find the calling expression and it's NameRef 433 // Find the calling expression and it's NameRef
@@ -412,9 +442,10 @@ impl AnalysisImpl {
412 442
413 // Resolve the function's NameRef (NOTE: this isn't entirely accurate). 443 // Resolve the function's NameRef (NOTE: this isn't entirely accurate).
414 let file_symbols = self.index_resolve(name_ref)?; 444 let file_symbols = self.index_resolve(name_ref)?;
415 for (_, fs) in file_symbols { 445 for (fn_fiel_id, fs) in file_symbols {
416 if fs.kind == FN_DEF { 446 if fs.kind == FN_DEF {
417 if let Some(fn_def) = find_node_at_offset(syntax, fs.node_range.start()) { 447 let fn_file = self.db.file_syntax(fn_fiel_id);
448 if let Some(fn_def) = find_node_at_offset(fn_file.syntax(), fs.node_range.start()) {
418 if let Some(descriptor) = FnDescriptor::new(fn_def) { 449 if let Some(descriptor) = FnDescriptor::new(fn_def) {
419 // If we have a calling expression let's find which argument we are on 450 // If we have a calling expression let's find which argument we are on
420 let mut current_parameter = None; 451 let mut current_parameter = None;
@@ -491,13 +522,6 @@ impl AnalysisImpl {
491 } 522 }
492} 523}
493 524
494#[derive(Default, Clone, Debug)]
495struct WorldData {
496 crate_graph: CrateGraph,
497 root: WritableSourceRoot,
498 libs: Vec<ReadonlySourceRoot>,
499}
500
501impl SourceChange { 525impl SourceChange {
502 pub(crate) fn from_local_edit(file_id: FileId, label: &str, edit: LocalEdit) -> SourceChange { 526 pub(crate) fn from_local_edit(file_id: FileId, label: &str, edit: LocalEdit) -> SourceChange {
503 let file_edit = SourceFileEdit { 527 let file_edit = SourceFileEdit {
diff --git a/crates/ra_analysis/src/input.rs b/crates/ra_analysis/src/input.rs
new file mode 100644
index 000000000..e64fad40c
--- /dev/null
+++ b/crates/ra_analysis/src/input.rs
@@ -0,0 +1,79 @@
1use std::{
2 sync::Arc,
3 fmt,
4};
5
6use salsa;
7use rustc_hash::FxHashSet;
8use relative_path::RelativePath;
9use rustc_hash::FxHashMap;
10
11use crate::{symbol_index::SymbolIndex, FileResolverImp};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub struct FileId(pub u32);
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
17pub struct CrateId(pub u32);
18
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct CrateGraph {
21 pub(crate) crate_roots: FxHashMap<CrateId, FileId>,
22}
23
24impl CrateGraph {
25 pub fn new() -> CrateGraph {
26 CrateGraph::default()
27 }
28 pub fn add_crate_root(&mut self, file_id: FileId) -> CrateId{
29 let crate_id = CrateId(self.crate_roots.len() as u32);
30 let prev = self.crate_roots.insert(crate_id, file_id);
31 assert!(prev.is_none());
32 crate_id
33 }
34}
35
36pub trait FileResolver: fmt::Debug + Send + Sync + 'static {
37 fn file_stem(&self, file_id: FileId) -> String;
38 fn resolve(&self, file_id: FileId, path: &RelativePath) -> Option<FileId>;
39}
40
41salsa::query_group! {
42 pub(crate) trait FilesDatabase: salsa::Database {
43 fn file_text(file_id: FileId) -> Arc<String> {
44 type FileTextQuery;
45 storage input;
46 }
47 fn file_source_root(file_id: FileId) -> SourceRootId {
48 type FileSourceRootQuery;
49 storage input;
50 }
51 fn source_root(id: SourceRootId) -> Arc<SourceRoot> {
52 type SourceRootQuery;
53 storage input;
54 }
55 fn libraries() -> Arc<Vec<SourceRootId>> {
56 type LibrarieseQuery;
57 storage input;
58 }
59 fn library_symbols(id: SourceRootId) -> Arc<SymbolIndex> {
60 type LibrarySymbolsQuery;
61 storage input;
62 }
63 fn crate_graph() -> Arc<CrateGraph> {
64 type CrateGraphQuery;
65 storage input;
66 }
67 }
68}
69
70#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
71pub(crate) struct SourceRootId(pub(crate) u32);
72
73#[derive(Clone, Default, Debug, PartialEq, Eq)]
74pub(crate) struct SourceRoot {
75 pub(crate) file_resolver: FileResolverImp,
76 pub(crate) files: FxHashSet<FileId>,
77}
78
79pub(crate) const WORKSPACE: SourceRootId = SourceRootId(0);
diff --git a/crates/ra_analysis/src/lib.rs b/crates/ra_analysis/src/lib.rs
index 7078e2d31..a67cac21e 100644
--- a/crates/ra_analysis/src/lib.rs
+++ b/crates/ra_analysis/src/lib.rs
@@ -6,23 +6,30 @@ extern crate relative_path;
6extern crate rustc_hash; 6extern crate rustc_hash;
7extern crate salsa; 7extern crate salsa;
8 8
9mod input;
9mod db; 10mod db;
10mod descriptors; 11mod descriptors;
11mod imp; 12mod imp;
12mod roots;
13mod symbol_index; 13mod symbol_index;
14mod completion; 14mod completion;
15 15
16use std::{fmt::Debug, sync::Arc}; 16use std::{
17 fmt,
18 sync::Arc,
19};
17 20
18use ra_syntax::{AtomEdit, File, TextRange, TextUnit}; 21use ra_syntax::{AtomEdit, File, TextRange, TextUnit};
19use relative_path::{RelativePath, RelativePathBuf}; 22use relative_path::RelativePathBuf;
20use rustc_hash::FxHashMap; 23use rayon::prelude::*;
21 24
22use crate::imp::{AnalysisHostImpl, AnalysisImpl, FileResolverImp}; 25use crate::{
26 imp::{AnalysisHostImpl, AnalysisImpl, FileResolverImp},
27 symbol_index::SymbolIndex,
28};
23 29
24pub use crate::{ 30pub use crate::{
25 descriptors::FnDescriptor, 31 descriptors::FnDescriptor,
32 input::{FileId, FileResolver, CrateGraph, CrateId}
26}; 33};
27pub use ra_editor::{ 34pub use ra_editor::{
28 CompletionItem, FileSymbol, Fold, FoldKind, HighlightedRange, LineIndex, Runnable, 35 CompletionItem, FileSymbol, Fold, FoldKind, HighlightedRange, LineIndex, Runnable,
@@ -43,20 +50,52 @@ impl std::fmt::Display for Canceled {
43impl std::error::Error for Canceled { 50impl std::error::Error for Canceled {
44} 51}
45 52
46#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 53#[derive(Default)]
47pub struct FileId(pub u32); 54pub struct AnalysisChange {
48 55 files_added: Vec<(FileId, String)>,
49#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 56 files_changed: Vec<(FileId, String)>,
50pub struct CrateId(pub u32); 57 files_removed: Vec<(FileId)>,
58 libraries_added: Vec<LibraryData>,
59 crate_graph: Option<CrateGraph>,
60 file_resolver: Option<FileResolverImp>,
61}
51 62
52#[derive(Debug, Clone, Default)] 63impl fmt::Debug for AnalysisChange {
53pub struct CrateGraph { 64 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
54 pub crate_roots: FxHashMap<CrateId, FileId>, 65 fmt.debug_struct("AnalysisChange")
66 .field("files_added", &self.files_added.len())
67 .field("files_changed", &self.files_changed.len())
68 .field("files_removed", &self.files_removed.len())
69 .field("libraries_added", &self.libraries_added.len())
70 .field("crate_graph", &self.crate_graph)
71 .field("file_resolver", &self.file_resolver)
72 .finish()
73 }
55} 74}
56 75
57pub trait FileResolver: Debug + Send + Sync + 'static { 76
58 fn file_stem(&self, file_id: FileId) -> String; 77impl AnalysisChange {
59 fn resolve(&self, file_id: FileId, path: &RelativePath) -> Option<FileId>; 78 pub fn new() -> AnalysisChange {
79 AnalysisChange::default()
80 }
81 pub fn add_file(&mut self, file_id: FileId, text: String) {
82 self.files_added.push((file_id, text))
83 }
84 pub fn change_file(&mut self, file_id: FileId, new_text: String) {
85 self.files_changed.push((file_id, new_text))
86 }
87 pub fn remove_file(&mut self, file_id: FileId) {
88 self.files_removed.push(file_id)
89 }
90 pub fn add_library(&mut self, data: LibraryData) {
91 self.libraries_added.push(data)
92 }
93 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
94 self.crate_graph = Some(graph);
95 }
96 pub fn set_file_resolver(&mut self, file_resolver: Arc<FileResolver>) {
97 self.file_resolver = Some(FileResolverImp::new(file_resolver));
98 }
60} 99}
61 100
62#[derive(Debug)] 101#[derive(Debug)]
@@ -75,20 +114,8 @@ impl AnalysisHost {
75 imp: self.imp.analysis(), 114 imp: self.imp.analysis(),
76 } 115 }
77 } 116 }
78 pub fn change_file(&mut self, file_id: FileId, text: Option<String>) { 117 pub fn apply_change(&mut self, change: AnalysisChange) {
79 self.change_files(::std::iter::once((file_id, text))); 118 self.imp.apply_change(change)
80 }
81 pub fn change_files(&mut self, mut changes: impl Iterator<Item = (FileId, Option<String>)>) {
82 self.imp.change_files(&mut changes)
83 }
84 pub fn set_file_resolver(&mut self, resolver: Arc<FileResolver>) {
85 self.imp.set_file_resolver(FileResolverImp::new(resolver));
86 }
87 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
88 self.imp.set_crate_graph(graph)
89 }
90 pub fn add_library(&mut self, data: LibraryData) {
91 self.imp.add_library(data.root)
92 } 119 }
93} 120}
94 121
@@ -266,14 +293,18 @@ impl Analysis {
266 293
267#[derive(Debug)] 294#[derive(Debug)]
268pub struct LibraryData { 295pub struct LibraryData {
269 root: roots::ReadonlySourceRoot, 296 files: Vec<(FileId, String)>,
297 file_resolver: FileResolverImp,
298 symbol_index: SymbolIndex,
270} 299}
271 300
272impl LibraryData { 301impl LibraryData {
273 pub fn prepare(files: Vec<(FileId, String)>, file_resolver: Arc<FileResolver>) -> LibraryData { 302 pub fn prepare(files: Vec<(FileId, String)>, file_resolver: Arc<FileResolver>) -> LibraryData {
274 let file_resolver = FileResolverImp::new(file_resolver); 303 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, text)| {
275 let root = roots::ReadonlySourceRoot::new(files, file_resolver); 304 let file = File::parse(text);
276 LibraryData { root } 305 (*file_id, file)
306 }));
307 LibraryData { files, file_resolver: FileResolverImp::new(file_resolver), symbol_index }
277 } 308 }
278} 309}
279 310
diff --git a/crates/ra_analysis/src/roots.rs b/crates/ra_analysis/src/roots.rs
deleted file mode 100644
index 1e9e613ac..000000000
--- a/crates/ra_analysis/src/roots.rs
+++ /dev/null
@@ -1,116 +0,0 @@
1use std::{sync::Arc};
2
3use rustc_hash::FxHashSet;
4use rayon::prelude::*;
5use salsa::Database;
6
7use crate::{
8 Cancelable,
9 db::{self, FilesDatabase, SyntaxDatabase},
10 imp::FileResolverImp,
11 symbol_index::SymbolIndex,
12 FileId,
13};
14
15pub(crate) trait SourceRoot {
16 fn contains(&self, file_id: FileId) -> bool;
17 fn db(&self) -> &db::RootDatabase;
18 fn symbols(&self, acc: &mut Vec<Arc<SymbolIndex>>) -> Cancelable<()>;
19}
20
21#[derive(Default, Debug, Clone)]
22pub(crate) struct WritableSourceRoot {
23 db: db::RootDatabase,
24}
25
26impl WritableSourceRoot {
27 pub fn apply_changes(
28 &mut self,
29 changes: &mut dyn Iterator<Item = (FileId, Option<String>)>,
30 file_resolver: Option<FileResolverImp>,
31 ) {
32 let mut changed = FxHashSet::default();
33 let mut removed = FxHashSet::default();
34 for (file_id, text) in changes {
35 match text {
36 None => {
37 removed.insert(file_id);
38 }
39 Some(text) => {
40 self.db
41 .query(db::FileTextQuery)
42 .set(file_id, Arc::new(text));
43 changed.insert(file_id);
44 }
45 }
46 }
47 let file_set = self.db.file_set();
48 let mut files: FxHashSet<FileId> = file_set.files.clone();
49 for file_id in removed {
50 files.remove(&file_id);
51 }
52 files.extend(changed);
53 let resolver = file_resolver.unwrap_or_else(|| file_set.resolver.clone());
54 self.db
55 .query(db::FileSetQuery)
56 .set((), Arc::new(db::FileSet { files, resolver }));
57 }
58}
59
60impl SourceRoot for WritableSourceRoot {
61 fn contains(&self, file_id: FileId) -> bool {
62 self.db.file_set().files.contains(&file_id)
63 }
64 fn db(&self) -> &db::RootDatabase {
65 &self.db
66 }
67 fn symbols<'a>(&'a self, acc: &mut Vec<Arc<SymbolIndex>>) -> Cancelable<()> {
68 for &file_id in self.db.file_set().files.iter() {
69 let symbols = self.db.file_symbols(file_id)?;
70 acc.push(symbols)
71 }
72 Ok(())
73 }
74}
75
76#[derive(Debug, Clone)]
77pub(crate) struct ReadonlySourceRoot {
78 db: db::RootDatabase,
79 symbol_index: Arc<SymbolIndex>,
80}
81
82impl ReadonlySourceRoot {
83 pub(crate) fn new(
84 files: Vec<(FileId, String)>,
85 resolver: FileResolverImp,
86 ) -> ReadonlySourceRoot {
87 let db = db::RootDatabase::default();
88 let mut file_ids = FxHashSet::default();
89 for (file_id, text) in files {
90 file_ids.insert(file_id);
91 db.query(db::FileTextQuery).set(file_id, Arc::new(text));
92 }
93
94 db.query(db::FileSetQuery)
95 .set((), Arc::new(db::FileSet { files: file_ids, resolver }));
96 let file_set = db.file_set();
97 let symbol_index =
98 SymbolIndex::for_files(file_set.files.par_iter()
99 .map_with(db.clone(), |db, &file_id| (file_id, db.file_syntax(file_id))));
100
101 ReadonlySourceRoot { db, symbol_index: Arc::new(symbol_index) }
102 }
103}
104
105impl SourceRoot for ReadonlySourceRoot {
106 fn contains(&self, file_id: FileId) -> bool {
107 self.db.file_set().files.contains(&file_id)
108 }
109 fn db(&self) -> &db::RootDatabase {
110 &self.db
111 }
112 fn symbols(&self, acc: &mut Vec<Arc<SymbolIndex>>) -> Cancelable<()> {
113 acc.push(Arc::clone(&self.symbol_index));
114 Ok(())
115 }
116}
diff --git a/crates/ra_analysis/src/symbol_index.rs b/crates/ra_analysis/src/symbol_index.rs
index e5c8d8870..5f302cbda 100644
--- a/crates/ra_analysis/src/symbol_index.rs
+++ b/crates/ra_analysis/src/symbol_index.rs
@@ -13,7 +13,7 @@ use rayon::prelude::*;
13 13
14use crate::{FileId, Query}; 14use crate::{FileId, Query};
15 15
16#[derive(Debug)] 16#[derive(Default, Debug)]
17pub(crate) struct SymbolIndex { 17pub(crate) struct SymbolIndex {
18 symbols: Vec<(FileId, FileSymbol)>, 18 symbols: Vec<(FileId, FileSymbol)>,
19 map: fst::Map, 19 map: fst::Map,
diff --git a/crates/ra_analysis/tests/tests.rs b/crates/ra_analysis/tests/tests.rs
index 52fae71ae..806e1fb34 100644
--- a/crates/ra_analysis/tests/tests.rs
+++ b/crates/ra_analysis/tests/tests.rs
@@ -5,15 +5,16 @@ extern crate relative_path;
5extern crate rustc_hash; 5extern crate rustc_hash;
6extern crate test_utils; 6extern crate test_utils;
7 7
8use std::sync::Arc; 8use std::{
9 sync::Arc,
10};
9 11
10use ra_syntax::TextRange; 12use ra_syntax::TextRange;
11use relative_path::{RelativePath, RelativePathBuf}; 13use relative_path::{RelativePath, RelativePathBuf};
12use rustc_hash::FxHashMap;
13use test_utils::{assert_eq_dbg, extract_offset}; 14use test_utils::{assert_eq_dbg, extract_offset};
14 15
15use ra_analysis::{ 16use ra_analysis::{
16 Analysis, AnalysisHost, CrateGraph, CrateId, FileId, FileResolver, FnDescriptor, 17 AnalysisChange, Analysis, AnalysisHost, CrateGraph, CrateId, FileId, FileResolver, FnDescriptor,
17}; 18};
18 19
19#[derive(Debug)] 20#[derive(Debug)]
@@ -45,14 +46,16 @@ impl FileResolver for FileMap {
45fn analysis_host(files: &[(&str, &str)]) -> AnalysisHost { 46fn analysis_host(files: &[(&str, &str)]) -> AnalysisHost {
46 let mut host = AnalysisHost::new(); 47 let mut host = AnalysisHost::new();
47 let mut file_map = Vec::new(); 48 let mut file_map = Vec::new();
49 let mut change = AnalysisChange::new();
48 for (id, &(path, contents)) in files.iter().enumerate() { 50 for (id, &(path, contents)) in files.iter().enumerate() {
49 let file_id = FileId((id + 1) as u32); 51 let file_id = FileId((id + 1) as u32);
50 assert!(path.starts_with('/')); 52 assert!(path.starts_with('/'));
51 let path = RelativePathBuf::from_path(&path[1..]).unwrap(); 53 let path = RelativePathBuf::from_path(&path[1..]).unwrap();
52 host.change_file(file_id, Some(contents.to_string())); 54 change.add_file(file_id, contents.to_string());
53 file_map.push((file_id, path)); 55 file_map.push((file_id, path));
54 } 56 }
55 host.set_file_resolver(Arc::new(FileMap(file_map))); 57 change.set_file_resolver(Arc::new(FileMap(file_map)));
58 host.apply_change(change);
56 host 59 host
57} 60}
58 61
@@ -126,17 +129,17 @@ fn test_resolve_crate_root() {
126 let snap = host.analysis(); 129 let snap = host.analysis();
127 assert!(snap.crate_for(FileId(2)).unwrap().is_empty()); 130 assert!(snap.crate_for(FileId(2)).unwrap().is_empty());
128 131
129 let crate_graph = CrateGraph { 132 let crate_graph = {
130 crate_roots: { 133 let mut g = CrateGraph::new();
131 let mut m = FxHashMap::default(); 134 g.add_crate_root(FileId(1));
132 m.insert(CrateId(1), FileId(1)); 135 g
133 m
134 },
135 }; 136 };
136 host.set_crate_graph(crate_graph); 137 let mut change = AnalysisChange::new();
138 change.set_crate_graph(crate_graph);
139 host.apply_change(change);
137 let snap = host.analysis(); 140 let snap = host.analysis();
138 141
139 assert_eq!(snap.crate_for(FileId(2)).unwrap(), vec![CrateId(1)],); 142 assert_eq!(snap.crate_for(FileId(2)).unwrap(), vec![CrateId(0)],);
140} 143}
141 144
142#[test] 145#[test]
diff --git a/crates/ra_lsp_server/src/main_loop/mod.rs b/crates/ra_lsp_server/src/main_loop/mod.rs
index e681062ca..9ddc3fd0b 100644
--- a/crates/ra_lsp_server/src/main_loop/mod.rs
+++ b/crates/ra_lsp_server/src/main_loop/mod.rs
@@ -8,7 +8,7 @@ use gen_lsp_server::{
8 handle_shutdown, ErrorCode, RawMessage, RawNotification, RawRequest, RawResponse, 8 handle_shutdown, ErrorCode, RawMessage, RawNotification, RawRequest, RawResponse,
9}; 9};
10use languageserver_types::NumberOrString; 10use languageserver_types::NumberOrString;
11use ra_analysis::{FileId, LibraryData}; 11use ra_analysis::{Canceled, FileId, LibraryData};
12use rayon::{self, ThreadPool}; 12use rayon::{self, ThreadPool};
13use rustc_hash::FxHashSet; 13use rustc_hash::FxHashSet;
14use serde::{de::DeserializeOwned, Serialize}; 14use serde::{de::DeserializeOwned, Serialize};
@@ -376,7 +376,7 @@ impl<'a> PoolDispatcher<'a> {
376 Err(e) => { 376 Err(e) => {
377 match e.downcast::<LspError>() { 377 match e.downcast::<LspError>() {
378 Ok(lsp_error) => RawResponse::err(id, lsp_error.code, lsp_error.message), 378 Ok(lsp_error) => RawResponse::err(id, lsp_error.code, lsp_error.message),
379 Err(e) => RawResponse::err(id, ErrorCode::InternalError as i32, e.to_string()) 379 Err(e) => RawResponse::err(id, ErrorCode::InternalError as i32, format!("{}\n{}", e, e.backtrace()))
380 } 380 }
381 } 381 }
382 }; 382 };
@@ -408,14 +408,22 @@ fn update_file_notifications_on_threadpool(
408 pool.spawn(move || { 408 pool.spawn(move || {
409 for file_id in subscriptions { 409 for file_id in subscriptions {
410 match handlers::publish_diagnostics(&world, file_id) { 410 match handlers::publish_diagnostics(&world, file_id) {
411 Err(e) => error!("failed to compute diagnostics: {:?}", e), 411 Err(e) => {
412 if !is_canceled(&e) {
413 error!("failed to compute diagnostics: {:?}", e);
414 }
415 },
412 Ok(params) => { 416 Ok(params) => {
413 let not = RawNotification::new::<req::PublishDiagnostics>(&params); 417 let not = RawNotification::new::<req::PublishDiagnostics>(&params);
414 sender.send(Task::Notify(not)); 418 sender.send(Task::Notify(not));
415 } 419 }
416 } 420 }
417 match handlers::publish_decorations(&world, file_id) { 421 match handlers::publish_decorations(&world, file_id) {
418 Err(e) => error!("failed to compute decorations: {:?}", e), 422 Err(e) => {
423 if !is_canceled(&e) {
424 error!("failed to compute decorations: {:?}", e);
425 }
426 },
419 Ok(params) => { 427 Ok(params) => {
420 let not = RawNotification::new::<req::PublishDecorations>(&params); 428 let not = RawNotification::new::<req::PublishDecorations>(&params);
421 sender.send(Task::Notify(not)) 429 sender.send(Task::Notify(not))
@@ -432,3 +440,7 @@ fn feedback(intrnal_mode: bool, msg: &str, sender: &Sender<RawMessage>) {
432 let not = RawNotification::new::<req::InternalFeedback>(&msg.to_string()); 440 let not = RawNotification::new::<req::InternalFeedback>(&msg.to_string());
433 sender.send(RawMessage::Notification(not)); 441 sender.send(RawMessage::Notification(not));
434} 442}
443
444fn is_canceled(e: &failure::Error) -> bool {
445 e.downcast_ref::<Canceled>().is_some()
446}
diff --git a/crates/ra_lsp_server/src/path_map.rs b/crates/ra_lsp_server/src/path_map.rs
index d32829382..d5957d673 100644
--- a/crates/ra_lsp_server/src/path_map.rs
+++ b/crates/ra_lsp_server/src/path_map.rs
@@ -1,4 +1,7 @@
1use std::path::{Component, Path, PathBuf}; 1use std::{
2 fmt,
3 path::{Component, Path, PathBuf},
4};
2 5
3use im; 6use im;
4use ra_analysis::{FileId, FileResolver}; 7use ra_analysis::{FileId, FileResolver};
@@ -10,7 +13,7 @@ pub enum Root {
10 Lib, 13 Lib,
11} 14}
12 15
13#[derive(Debug, Default, Clone)] 16#[derive(Default, Clone)]
14pub struct PathMap { 17pub struct PathMap {
15 next_id: u32, 18 next_id: u32,
16 path2id: im::HashMap<PathBuf, FileId>, 19 path2id: im::HashMap<PathBuf, FileId>,
@@ -18,19 +21,28 @@ pub struct PathMap {
18 id2root: im::HashMap<FileId, Root>, 21 id2root: im::HashMap<FileId, Root>,
19} 22}
20 23
24impl fmt::Debug for PathMap {
25 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26 f.write_str("PathMap { ... }")
27 }
28}
29
21impl PathMap { 30impl PathMap {
22 pub fn new() -> PathMap { 31 pub fn new() -> PathMap {
23 Default::default() 32 Default::default()
24 } 33 }
25 pub fn get_or_insert(&mut self, path: PathBuf, root: Root) -> FileId { 34 pub fn get_or_insert(&mut self, path: PathBuf, root: Root) -> (bool, FileId) {
26 self.path2id 35 let mut inserted = false;
36 let file_id = self.path2id
27 .get(path.as_path()) 37 .get(path.as_path())
28 .map(|&id| id) 38 .map(|&id| id)
29 .unwrap_or_else(|| { 39 .unwrap_or_else(|| {
40 inserted = true;
30 let id = self.new_file_id(); 41 let id = self.new_file_id();
31 self.insert(path, id, root); 42 self.insert(path, id, root);
32 id 43 id
33 }) 44 });
45 (inserted, file_id)
34 } 46 }
35 pub fn get_id(&self, path: &Path) -> Option<FileId> { 47 pub fn get_id(&self, path: &Path) -> Option<FileId> {
36 self.path2id.get(path).map(|&id| id) 48 self.path2id.get(path).map(|&id| id)
@@ -105,8 +117,8 @@ mod test {
105 #[test] 117 #[test]
106 fn test_resolve() { 118 fn test_resolve() {
107 let mut m = PathMap::new(); 119 let mut m = PathMap::new();
108 let id1 = m.get_or_insert(PathBuf::from("/foo"), Root::Workspace); 120 let (_, id1) = m.get_or_insert(PathBuf::from("/foo"), Root::Workspace);
109 let id2 = m.get_or_insert(PathBuf::from("/foo/bar.rs"), Root::Workspace); 121 let (_, id2) = m.get_or_insert(PathBuf::from("/foo/bar.rs"), Root::Workspace);
110 assert_eq!(m.resolve(id1, &RelativePath::new("bar.rs")), Some(id2),) 122 assert_eq!(m.resolve(id1, &RelativePath::new("bar.rs")), Some(id2),)
111 } 123 }
112} 124}
diff --git a/crates/ra_lsp_server/src/server_world.rs b/crates/ra_lsp_server/src/server_world.rs
index 69b2a1cd1..25986e230 100644
--- a/crates/ra_lsp_server/src/server_world.rs
+++ b/crates/ra_lsp_server/src/server_world.rs
@@ -5,7 +5,7 @@ use std::{
5}; 5};
6 6
7use languageserver_types::Url; 7use languageserver_types::Url;
8use ra_analysis::{Analysis, AnalysisHost, CrateGraph, CrateId, FileId, FileResolver, LibraryData}; 8use ra_analysis::{Analysis, AnalysisHost, AnalysisChange, CrateGraph, FileId, FileResolver, LibraryData};
9use rustc_hash::FxHashMap; 9use rustc_hash::FxHashMap;
10 10
11use crate::{ 11use crate::{
@@ -39,30 +39,40 @@ impl ServerWorldState {
39 } 39 }
40 } 40 }
41 pub fn apply_fs_changes(&mut self, events: Vec<FileEvent>) { 41 pub fn apply_fs_changes(&mut self, events: Vec<FileEvent>) {
42 let mut change = AnalysisChange::new();
43 let mut inserted = false;
42 { 44 {
43 let pm = &mut self.path_map; 45 let pm = &mut self.path_map;
44 let mm = &mut self.mem_map; 46 let mm = &mut self.mem_map;
45 let changes = events 47 events
46 .into_iter() 48 .into_iter()
47 .map(|event| { 49 .map(|event| {
48 let text = match event.kind { 50 let text = match event.kind {
49 FileEventKind::Add(text) => Some(text), 51 FileEventKind::Add(text) => text,
50 }; 52 };
51 (event.path, text) 53 (event.path, text)
52 }) 54 })
53 .map(|(path, text)| (pm.get_or_insert(path, Root::Workspace), text)) 55 .map(|(path, text)| {
54 .filter_map(|(id, text)| { 56 let (ins, file_id) = pm.get_or_insert(path, Root::Workspace);
55 if mm.contains_key(&id) { 57 inserted |= ins;
56 mm.insert(id, text); 58 (file_id, text)
59 })
60 .filter_map(|(file_id, text)| {
61 if mm.contains_key(&file_id) {
62 mm.insert(file_id, Some(text));
57 None 63 None
58 } else { 64 } else {
59 Some((id, text)) 65 Some((file_id, text))
60 } 66 }
67 })
68 .for_each(|(file_id, text)| {
69 change.add_file(file_id, text)
61 }); 70 });
62 self.analysis_host.change_files(changes);
63 } 71 }
64 self.analysis_host 72 if inserted {
65 .set_file_resolver(Arc::new(self.path_map.clone())); 73 change.set_file_resolver(Arc::new(self.path_map.clone()))
74 }
75 self.analysis_host.apply_change(change);
66 } 76 }
67 pub fn events_to_files( 77 pub fn events_to_files(
68 &mut self, 78 &mut self,
@@ -76,24 +86,31 @@ impl ServerWorldState {
76 let FileEventKind::Add(text) = event.kind; 86 let FileEventKind::Add(text) = event.kind;
77 (event.path, text) 87 (event.path, text)
78 }) 88 })
79 .map(|(path, text)| (pm.get_or_insert(path, Root::Lib), text)) 89 .map(|(path, text)| (pm.get_or_insert(path, Root::Lib).1, text))
80 .collect() 90 .collect()
81 }; 91 };
82 let resolver = Arc::new(self.path_map.clone()); 92 let resolver = Arc::new(self.path_map.clone());
83 (files, resolver) 93 (files, resolver)
84 } 94 }
85 pub fn add_lib(&mut self, data: LibraryData) { 95 pub fn add_lib(&mut self, data: LibraryData) {
86 self.analysis_host.add_library(data); 96 let mut change = AnalysisChange::new();
97 change.add_library(data);
98 self.analysis_host.apply_change(change);
87 } 99 }
88 100
89 pub fn add_mem_file(&mut self, path: PathBuf, text: String) -> FileId { 101 pub fn add_mem_file(&mut self, path: PathBuf, text: String) -> FileId {
90 let file_id = self.path_map.get_or_insert(path, Root::Workspace); 102 let (inserted, file_id) = self.path_map.get_or_insert(path, Root::Workspace);
91 self.analysis_host
92 .set_file_resolver(Arc::new(self.path_map.clone()));
93 self.mem_map.insert(file_id, None);
94 if self.path_map.get_root(file_id) != Root::Lib { 103 if self.path_map.get_root(file_id) != Root::Lib {
95 self.analysis_host.change_file(file_id, Some(text)); 104 let mut change = AnalysisChange::new();
105 if inserted {
106 change.add_file(file_id, text);
107 change.set_file_resolver(Arc::new(self.path_map.clone()));
108 } else {
109 change.change_file(file_id, text);
110 }
111 self.analysis_host.apply_change(change);
96 } 112 }
113 self.mem_map.insert(file_id, None);
97 file_id 114 file_id
98 } 115 }
99 116
@@ -103,7 +120,9 @@ impl ServerWorldState {
103 .get_id(path) 120 .get_id(path)
104 .ok_or_else(|| format_err!("change to unknown file: {}", path.display()))?; 121 .ok_or_else(|| format_err!("change to unknown file: {}", path.display()))?;
105 if self.path_map.get_root(file_id) != Root::Lib { 122 if self.path_map.get_root(file_id) != Root::Lib {
106 self.analysis_host.change_file(file_id, Some(text)); 123 let mut change = AnalysisChange::new();
124 change.change_file(file_id, text);
125 self.analysis_host.apply_change(change);
107 } 126 }
108 Ok(()) 127 Ok(())
109 } 128 }
@@ -120,12 +139,16 @@ impl ServerWorldState {
120 // Do this via file watcher ideally. 139 // Do this via file watcher ideally.
121 let text = fs::read_to_string(path).ok(); 140 let text = fs::read_to_string(path).ok();
122 if self.path_map.get_root(file_id) != Root::Lib { 141 if self.path_map.get_root(file_id) != Root::Lib {
123 self.analysis_host.change_file(file_id, text); 142 let mut change = AnalysisChange::new();
143 if let Some(text) = text {
144 change.change_file(file_id, text);
145 }
146 self.analysis_host.apply_change(change);
124 } 147 }
125 Ok(file_id) 148 Ok(file_id)
126 } 149 }
127 pub fn set_workspaces(&mut self, ws: Vec<CargoWorkspace>) { 150 pub fn set_workspaces(&mut self, ws: Vec<CargoWorkspace>) {
128 let mut crate_roots = FxHashMap::default(); 151 let mut crate_graph = CrateGraph::new();
129 ws.iter() 152 ws.iter()
130 .flat_map(|ws| { 153 .flat_map(|ws| {
131 ws.packages() 154 ws.packages()
@@ -134,13 +157,13 @@ impl ServerWorldState {
134 }) 157 })
135 .for_each(|root| { 158 .for_each(|root| {
136 if let Some(file_id) = self.path_map.get_id(root) { 159 if let Some(file_id) = self.path_map.get_id(root) {
137 let crate_id = CrateId(crate_roots.len() as u32); 160 crate_graph.add_crate_root(file_id);
138 crate_roots.insert(crate_id, file_id);
139 } 161 }
140 }); 162 });
141 let crate_graph = CrateGraph { crate_roots };
142 self.workspaces = Arc::new(ws); 163 self.workspaces = Arc::new(ws);
143 self.analysis_host.set_crate_graph(crate_graph); 164 let mut change = AnalysisChange::new();
165 change.set_crate_graph(crate_graph);
166 self.analysis_host.apply_change(change);
144 } 167 }
145 pub fn snapshot(&self) -> ServerWorld { 168 pub fn snapshot(&self) -> ServerWorld {
146 ServerWorld { 169 ServerWorld {