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