]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_db/src/change.rs
Merge #4849
[rust.git] / crates / ra_ide_db / src / change.rs
1 //! Defines a unit of change that can applied to a state of IDE to get the next
2 //! state. Changes are transactional.
3
4 use std::{fmt, sync::Arc, time};
5
6 use ra_db::{
7     salsa::{Database, Durability, SweepStrategy},
8     CrateGraph, FileId, RelativePathBuf, SourceDatabase, SourceDatabaseExt, SourceRoot,
9     SourceRootId,
10 };
11 use ra_prof::{memory_usage, profile, Bytes};
12 use ra_syntax::SourceFile;
13 #[cfg(not(feature = "wasm"))]
14 use rayon::prelude::*;
15 use rustc_hash::FxHashMap;
16
17 use crate::{
18     symbol_index::{SymbolIndex, SymbolsDatabase},
19     RootDatabase,
20 };
21
22 #[derive(Default)]
23 pub struct AnalysisChange {
24     new_roots: Vec<(SourceRootId, bool)>,
25     roots_changed: FxHashMap<SourceRootId, RootChange>,
26     files_changed: Vec<(FileId, Arc<String>)>,
27     libraries_added: Vec<LibraryData>,
28     crate_graph: Option<CrateGraph>,
29 }
30
31 impl fmt::Debug for AnalysisChange {
32     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
33         let mut d = fmt.debug_struct("AnalysisChange");
34         if !self.new_roots.is_empty() {
35             d.field("new_roots", &self.new_roots);
36         }
37         if !self.roots_changed.is_empty() {
38             d.field("roots_changed", &self.roots_changed);
39         }
40         if !self.files_changed.is_empty() {
41             d.field("files_changed", &self.files_changed.len());
42         }
43         if !self.libraries_added.is_empty() {
44             d.field("libraries_added", &self.libraries_added.len());
45         }
46         if self.crate_graph.is_some() {
47             d.field("crate_graph", &self.crate_graph);
48         }
49         d.finish()
50     }
51 }
52
53 impl AnalysisChange {
54     pub fn new() -> AnalysisChange {
55         AnalysisChange::default()
56     }
57
58     pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
59         self.new_roots.push((root_id, is_local));
60     }
61
62     pub fn add_file(
63         &mut self,
64         root_id: SourceRootId,
65         file_id: FileId,
66         path: RelativePathBuf,
67         text: Arc<String>,
68     ) {
69         let file = AddFile { file_id, path, text };
70         self.roots_changed.entry(root_id).or_default().added.push(file);
71     }
72
73     pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
74         self.files_changed.push((file_id, new_text))
75     }
76
77     pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
78         let file = RemoveFile { file_id, path };
79         self.roots_changed.entry(root_id).or_default().removed.push(file);
80     }
81
82     pub fn add_library(&mut self, data: LibraryData) {
83         self.libraries_added.push(data)
84     }
85
86     pub fn set_crate_graph(&mut self, graph: CrateGraph) {
87         self.crate_graph = Some(graph);
88     }
89 }
90
91 #[derive(Debug)]
92 struct AddFile {
93     file_id: FileId,
94     path: RelativePathBuf,
95     text: Arc<String>,
96 }
97
98 #[derive(Debug)]
99 struct RemoveFile {
100     file_id: FileId,
101     path: RelativePathBuf,
102 }
103
104 #[derive(Default)]
105 struct RootChange {
106     added: Vec<AddFile>,
107     removed: Vec<RemoveFile>,
108 }
109
110 impl fmt::Debug for RootChange {
111     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
112         fmt.debug_struct("AnalysisChange")
113             .field("added", &self.added.len())
114             .field("removed", &self.removed.len())
115             .finish()
116     }
117 }
118
119 pub struct LibraryData {
120     root_id: SourceRootId,
121     root_change: RootChange,
122     symbol_index: SymbolIndex,
123 }
124
125 impl fmt::Debug for LibraryData {
126     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127         f.debug_struct("LibraryData")
128             .field("root_id", &self.root_id)
129             .field("root_change", &self.root_change)
130             .field("n_symbols", &self.symbol_index.len())
131             .finish()
132     }
133 }
134
135 impl LibraryData {
136     pub fn prepare(
137         root_id: SourceRootId,
138         files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
139     ) -> LibraryData {
140         let _p = profile("LibraryData::prepare");
141
142         #[cfg(not(feature = "wasm"))]
143         let iter = files.par_iter();
144         #[cfg(feature = "wasm")]
145         let iter = files.iter();
146
147         let symbol_index = SymbolIndex::for_files(iter.map(|(file_id, _, text)| {
148             let parse = SourceFile::parse(text);
149             (*file_id, parse)
150         }));
151         let mut root_change = RootChange::default();
152         root_change.added = files
153             .into_iter()
154             .map(|(file_id, path, text)| AddFile { file_id, path, text })
155             .collect();
156         LibraryData { root_id, root_change, symbol_index }
157     }
158 }
159
160 const GC_COOLDOWN: time::Duration = time::Duration::from_millis(100);
161
162 impl RootDatabase {
163     pub fn request_cancellation(&mut self) {
164         let _p = profile("RootDatabase::request_cancellation");
165         self.salsa_runtime_mut().synthetic_write(Durability::LOW);
166     }
167
168     pub fn apply_change(&mut self, change: AnalysisChange) {
169         let _p = profile("RootDatabase::apply_change");
170         self.request_cancellation();
171         log::info!("apply_change {:?}", change);
172         if !change.new_roots.is_empty() {
173             let mut local_roots = Vec::clone(&self.local_roots());
174             for (root_id, is_local) in change.new_roots {
175                 let root =
176                     if is_local { SourceRoot::new_local() } else { SourceRoot::new_library() };
177                 let durability = durability(&root);
178                 self.set_source_root_with_durability(root_id, Arc::new(root), durability);
179                 if is_local {
180                     local_roots.push(root_id);
181                 }
182             }
183             self.set_local_roots_with_durability(Arc::new(local_roots), Durability::HIGH);
184         }
185
186         for (root_id, root_change) in change.roots_changed {
187             self.apply_root_change(root_id, root_change);
188         }
189         for (file_id, text) in change.files_changed {
190             let source_root_id = self.file_source_root(file_id);
191             let source_root = self.source_root(source_root_id);
192             let durability = durability(&source_root);
193             self.set_file_text_with_durability(file_id, text, durability)
194         }
195         if !change.libraries_added.is_empty() {
196             let mut libraries = Vec::clone(&self.library_roots());
197             for library in change.libraries_added {
198                 libraries.push(library.root_id);
199                 self.set_source_root_with_durability(
200                     library.root_id,
201                     Arc::new(SourceRoot::new_library()),
202                     Durability::HIGH,
203                 );
204                 self.set_library_symbols_with_durability(
205                     library.root_id,
206                     Arc::new(library.symbol_index),
207                     Durability::HIGH,
208                 );
209                 self.apply_root_change(library.root_id, library.root_change);
210             }
211             self.set_library_roots_with_durability(Arc::new(libraries), Durability::HIGH);
212         }
213         if let Some(crate_graph) = change.crate_graph {
214             self.set_crate_graph_with_durability(Arc::new(crate_graph), Durability::HIGH)
215         }
216     }
217
218     fn apply_root_change(&mut self, root_id: SourceRootId, root_change: RootChange) {
219         let mut source_root = SourceRoot::clone(&self.source_root(root_id));
220         let durability = durability(&source_root);
221         for add_file in root_change.added {
222             self.set_file_text_with_durability(add_file.file_id, add_file.text, durability);
223             self.set_file_relative_path_with_durability(
224                 add_file.file_id,
225                 add_file.path.clone(),
226                 durability,
227             );
228             self.set_file_source_root_with_durability(add_file.file_id, root_id, durability);
229             source_root.insert_file(add_file.path, add_file.file_id);
230         }
231         for remove_file in root_change.removed {
232             self.set_file_text_with_durability(remove_file.file_id, Default::default(), durability);
233             source_root.remove_file(&remove_file.path);
234         }
235         self.set_source_root_with_durability(root_id, Arc::new(source_root), durability);
236     }
237
238     pub fn maybe_collect_garbage(&mut self) {
239         if cfg!(feature = "wasm") {
240             return;
241         }
242
243         if self.last_gc_check.elapsed() > GC_COOLDOWN {
244             self.last_gc_check = crate::wasm_shims::Instant::now();
245         }
246     }
247
248     pub fn collect_garbage(&mut self) {
249         if cfg!(feature = "wasm") {
250             return;
251         }
252
253         let _p = profile("RootDatabase::collect_garbage");
254         self.last_gc = crate::wasm_shims::Instant::now();
255
256         let sweep = SweepStrategy::default().discard_values().sweep_all_revisions();
257
258         self.query(ra_db::ParseQuery).sweep(sweep);
259         self.query(hir::db::ParseMacroQuery).sweep(sweep);
260
261         // Macros do take significant space, but less then the syntax trees
262         // self.query(hir::db::MacroDefQuery).sweep(sweep);
263         // self.query(hir::db::MacroArgQuery).sweep(sweep);
264         // self.query(hir::db::MacroExpandQuery).sweep(sweep);
265
266         self.query(hir::db::AstIdMapQuery).sweep(sweep);
267
268         self.query(hir::db::BodyWithSourceMapQuery).sweep(sweep);
269
270         self.query(hir::db::ExprScopesQuery).sweep(sweep);
271         self.query(hir::db::InferQueryQuery).sweep(sweep);
272         self.query(hir::db::BodyQuery).sweep(sweep);
273     }
274
275     pub fn per_query_memory_usage(&mut self) -> Vec<(String, Bytes)> {
276         let mut acc: Vec<(String, Bytes)> = vec![];
277         let sweep = SweepStrategy::default().discard_values().sweep_all_revisions();
278         macro_rules! sweep_each_query {
279             ($($q:path)*) => {$(
280                 let before = memory_usage().allocated;
281                 self.query($q).sweep(sweep);
282                 let after = memory_usage().allocated;
283                 let q: $q = Default::default();
284                 let name = format!("{:?}", q);
285                 acc.push((name, before - after));
286
287                 let before = memory_usage().allocated;
288                 self.query($q).sweep(sweep.discard_everything());
289                 let after = memory_usage().allocated;
290                 let q: $q = Default::default();
291                 let name = format!("{:?} (deps)", q);
292                 acc.push((name, before - after));
293             )*}
294         }
295         sweep_each_query![
296             // SourceDatabase
297             ra_db::ParseQuery
298             ra_db::SourceRootCratesQuery
299
300             // AstDatabase
301             hir::db::AstIdMapQuery
302             hir::db::InternMacroQuery
303             hir::db::MacroArgQuery
304             hir::db::MacroDefQuery
305             hir::db::ParseMacroQuery
306             hir::db::MacroExpandQuery
307             hir::db::InternEagerExpansionQuery
308
309             // DefDatabase
310             hir::db::RawItemsQuery
311             hir::db::CrateDefMapQueryQuery
312             hir::db::StructDataQuery
313             hir::db::UnionDataQuery
314             hir::db::EnumDataQuery
315             hir::db::ImplDataQuery
316             hir::db::TraitDataQuery
317             hir::db::TypeAliasDataQuery
318             hir::db::FunctionDataQuery
319             hir::db::ConstDataQuery
320             hir::db::StaticDataQuery
321             hir::db::BodyWithSourceMapQuery
322             hir::db::BodyQuery
323             hir::db::ExprScopesQuery
324             hir::db::GenericParamsQuery
325             hir::db::AttrsQuery
326             hir::db::ModuleLangItemsQuery
327             hir::db::CrateLangItemsQuery
328             hir::db::LangItemQuery
329             hir::db::DocumentationQuery
330             hir::db::ImportMapQuery
331
332             // InternDatabase
333             hir::db::InternFunctionQuery
334             hir::db::InternStructQuery
335             hir::db::InternUnionQuery
336             hir::db::InternEnumQuery
337             hir::db::InternConstQuery
338             hir::db::InternStaticQuery
339             hir::db::InternTraitQuery
340             hir::db::InternTypeAliasQuery
341             hir::db::InternImplQuery
342
343             // HirDatabase
344             hir::db::InferQueryQuery
345             hir::db::TyQuery
346             hir::db::ValueTyQuery
347             hir::db::ImplSelfTyQuery
348             hir::db::ImplTraitQuery
349             hir::db::FieldTypesQuery
350             hir::db::CallableItemSignatureQuery
351             hir::db::GenericPredicatesForParamQuery
352             hir::db::GenericPredicatesQuery
353             hir::db::GenericDefaultsQuery
354             hir::db::ImplsInCrateQuery
355             hir::db::ImplsForTraitQuery
356             hir::db::InternTypeCtorQuery
357             hir::db::InternTypeParamIdQuery
358             hir::db::InternChalkImplQuery
359             hir::db::InternAssocTyValueQuery
360             hir::db::AssociatedTyDataQuery
361             hir::db::TraitDatumQuery
362             hir::db::StructDatumQuery
363             hir::db::ImplDatumQuery
364             hir::db::AssociatedTyValueQuery
365             hir::db::TraitSolveQuery
366             hir::db::ReturnTypeImplTraitsQuery
367
368             // SymbolsDatabase
369             crate::symbol_index::FileSymbolsQuery
370
371             // LineIndexDatabase
372             crate::LineIndexQuery
373         ];
374         acc.sort_by_key(|it| std::cmp::Reverse(it.1));
375         acc
376     }
377 }
378
379 fn durability(source_root: &SourceRoot) -> Durability {
380     if source_root.is_library {
381         Durability::HIGH
382     } else {
383         Durability::LOW
384     }
385 }