1 //! Defines a unit of change that can applied to a state of IDE to get the next
2 //! state. Changes are transactional.
4 use std::{fmt, sync::Arc, time};
7 salsa::{Database, Durability, SweepStrategy},
8 CrateGraph, FileId, RelativePathBuf, SourceDatabase, SourceDatabaseExt, SourceRoot,
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;
18 symbol_index::{SymbolIndex, SymbolsDatabase},
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>,
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);
37 if !self.roots_changed.is_empty() {
38 d.field("roots_changed", &self.roots_changed);
40 if !self.files_changed.is_empty() {
41 d.field("files_changed", &self.files_changed.len());
43 if !self.libraries_added.is_empty() {
44 d.field("libraries_added", &self.libraries_added.len());
46 if self.crate_graph.is_some() {
47 d.field("crate_graph", &self.crate_graph);
54 pub fn new() -> AnalysisChange {
55 AnalysisChange::default()
58 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
59 self.new_roots.push((root_id, is_local));
64 root_id: SourceRootId,
66 path: RelativePathBuf,
69 let file = AddFile { file_id, path, text };
70 self.roots_changed.entry(root_id).or_default().added.push(file);
73 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
74 self.files_changed.push((file_id, new_text))
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);
82 pub fn add_library(&mut self, data: LibraryData) {
83 self.libraries_added.push(data)
86 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
87 self.crate_graph = Some(graph);
94 path: RelativePathBuf,
101 path: RelativePathBuf,
107 removed: Vec<RemoveFile>,
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())
119 pub struct LibraryData {
120 root_id: SourceRootId,
121 root_change: RootChange,
122 symbol_index: SymbolIndex,
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())
137 root_id: SourceRootId,
138 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
140 let _p = profile("LibraryData::prepare");
142 #[cfg(not(feature = "wasm"))]
143 let iter = files.par_iter();
144 #[cfg(feature = "wasm")]
145 let iter = files.iter();
147 let symbol_index = SymbolIndex::for_files(iter.map(|(file_id, _, text)| {
148 let parse = SourceFile::parse(text);
151 let mut root_change = RootChange::default();
152 root_change.added = files
154 .map(|(file_id, path, text)| AddFile { file_id, path, text })
156 LibraryData { root_id, root_change, symbol_index }
160 const GC_COOLDOWN: time::Duration = time::Duration::from_millis(100);
163 pub fn request_cancellation(&mut self) {
164 let _p = profile("RootDatabase::request_cancellation");
165 self.salsa_runtime_mut().synthetic_write(Durability::LOW);
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 {
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);
180 local_roots.push(root_id);
183 self.set_local_roots_with_durability(Arc::new(local_roots), Durability::HIGH);
186 for (root_id, root_change) in change.roots_changed {
187 self.apply_root_change(root_id, root_change);
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)
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(
201 Arc::new(SourceRoot::new_library()),
204 self.set_library_symbols_with_durability(
206 Arc::new(library.symbol_index),
209 self.apply_root_change(library.root_id, library.root_change);
211 self.set_library_roots_with_durability(Arc::new(libraries), Durability::HIGH);
213 if let Some(crate_graph) = change.crate_graph {
214 self.set_crate_graph_with_durability(Arc::new(crate_graph), Durability::HIGH)
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(
225 add_file.path.clone(),
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);
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);
235 self.set_source_root_with_durability(root_id, Arc::new(source_root), durability);
238 pub fn maybe_collect_garbage(&mut self) {
239 if cfg!(feature = "wasm") {
243 if self.last_gc_check.elapsed() > GC_COOLDOWN {
244 self.last_gc_check = crate::wasm_shims::Instant::now();
248 pub fn collect_garbage(&mut self) {
249 if cfg!(feature = "wasm") {
253 let _p = profile("RootDatabase::collect_garbage");
254 self.last_gc = crate::wasm_shims::Instant::now();
256 let sweep = SweepStrategy::default().discard_values().sweep_all_revisions();
258 self.query(ra_db::ParseQuery).sweep(sweep);
259 self.query(hir::db::ParseMacroQuery).sweep(sweep);
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);
266 self.query(hir::db::AstIdMapQuery).sweep(sweep);
268 self.query(hir::db::BodyWithSourceMapQuery).sweep(sweep);
270 self.query(hir::db::ExprScopesQuery).sweep(sweep);
271 self.query(hir::db::InferQueryQuery).sweep(sweep);
272 self.query(hir::db::BodyQuery).sweep(sweep);
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 {
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));
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));
298 ra_db::SourceRootCratesQuery
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
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
323 hir::db::ExprScopesQuery
324 hir::db::GenericParamsQuery
326 hir::db::ModuleLangItemsQuery
327 hir::db::CrateLangItemsQuery
328 hir::db::LangItemQuery
329 hir::db::DocumentationQuery
330 hir::db::ImportMapQuery
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
344 hir::db::InferQueryQuery
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
369 crate::symbol_index::FileSymbolsQuery
372 crate::LineIndexQuery
374 acc.sort_by_key(|it| std::cmp::Reverse(it.1));
379 fn durability(source_root: &SourceRoot) -> Durability {
380 if source_root.is_library {