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