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},
19 DebugData, RootDatabase,
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,
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);
38 if !self.roots_changed.is_empty() {
39 d.field("roots_changed", &self.roots_changed);
41 if !self.files_changed.is_empty() {
42 d.field("files_changed", &self.files_changed.len());
44 if !self.libraries_added.is_empty() {
45 d.field("libraries_added", &self.libraries_added.len());
47 if self.crate_graph.is_some() {
48 d.field("crate_graph", &self.crate_graph);
55 pub fn new() -> AnalysisChange {
56 AnalysisChange::default()
59 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
60 self.new_roots.push((root_id, is_local));
65 root_id: SourceRootId,
67 path: RelativePathBuf,
70 let file = AddFile { file_id, path, text };
71 self.roots_changed.entry(root_id).or_default().added.push(file);
74 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
75 self.files_changed.push((file_id, new_text))
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);
83 pub fn add_library(&mut self, data: LibraryData) {
84 self.libraries_added.push(data)
87 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
88 self.crate_graph = Some(graph);
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);
99 path: RelativePathBuf,
106 path: RelativePathBuf,
112 removed: Vec<RemoveFile>,
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())
124 pub struct LibraryData {
125 root_id: SourceRootId,
126 root_change: RootChange,
127 symbol_index: SymbolIndex,
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())
142 root_id: SourceRootId,
143 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
145 let _p = profile("LibraryData::prepare");
147 #[cfg(not(feature = "wasm"))]
148 let iter = files.par_iter();
149 #[cfg(feature = "wasm")]
150 let iter = files.iter();
152 let symbol_index = SymbolIndex::for_files(iter.map(|(file_id, _, text)| {
153 let parse = SourceFile::parse(text);
156 let mut root_change = RootChange::default();
157 root_change.added = files
159 .map(|(file_id, path, text)| AddFile { file_id, path, text })
161 LibraryData { root_id, root_change, symbol_index }
165 const GC_COOLDOWN: time::Duration = time::Duration::from_millis(100);
168 pub fn request_cancellation(&mut self) {
169 let _p = profile("RootDatabase::request_cancellation");
170 self.salsa_runtime_mut().synthetic_write(Durability::LOW);
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 {
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);
185 local_roots.push(root_id);
188 self.set_local_roots_with_durability(Arc::new(local_roots), Durability::HIGH);
191 for (root_id, root_change) in change.roots_changed {
192 self.apply_root_change(root_id, root_change);
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)
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(
206 Arc::new(SourceRoot::new_library()),
209 self.set_library_symbols_with_durability(
211 Arc::new(library.symbol_index),
214 self.apply_root_change(library.root_id, library.root_change);
216 self.set_library_roots_with_durability(Arc::new(libraries), Durability::HIGH);
218 if let Some(crate_graph) = change.crate_graph {
219 self.set_crate_graph_with_durability(Arc::new(crate_graph), Durability::HIGH)
222 Arc::make_mut(&mut self.debug_data).merge(change.debug_data)
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(
232 add_file.path.clone(),
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);
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);
242 self.set_source_root_with_durability(root_id, Arc::new(source_root), durability);
245 pub fn maybe_collect_garbage(&mut self) {
246 if cfg!(feature = "wasm") {
250 if self.last_gc_check.elapsed() > GC_COOLDOWN {
251 self.last_gc_check = crate::wasm_shims::Instant::now();
255 pub fn collect_garbage(&mut self) {
256 if cfg!(feature = "wasm") {
260 let _p = profile("RootDatabase::collect_garbage");
261 self.last_gc = crate::wasm_shims::Instant::now();
263 let sweep = SweepStrategy::default().discard_values().sweep_all_revisions();
265 self.query(ra_db::ParseQuery).sweep(sweep);
266 self.query(hir::db::ParseMacroQuery).sweep(sweep);
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);
273 self.query(hir::db::AstIdMapQuery).sweep(sweep);
275 self.query(hir::db::BodyWithSourceMapQuery).sweep(sweep);
277 self.query(hir::db::ExprScopesQuery).sweep(sweep);
278 self.query(hir::db::InferQueryQuery).sweep(sweep);
279 self.query(hir::db::BodyQuery).sweep(sweep);
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 {
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));
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));
305 ra_db::SourceRootCratesQuery
308 hir::db::AstIdMapQuery
309 hir::db::InternMacroQuery
310 hir::db::MacroArgQuery
311 hir::db::MacroDefQuery
312 hir::db::ParseMacroQuery
313 hir::db::MacroExpandQuery
316 hir::db::RawItemsQuery
317 hir::db::CrateDefMapQueryQuery
318 hir::db::StructDataQuery
319 hir::db::UnionDataQuery
320 hir::db::EnumDataQuery
321 hir::db::ImplDataQuery
322 hir::db::TraitDataQuery
323 hir::db::TypeAliasDataQuery
324 hir::db::FunctionDataQuery
325 hir::db::ConstDataQuery
326 hir::db::StaticDataQuery
327 hir::db::BodyWithSourceMapQuery
329 hir::db::ExprScopesQuery
330 hir::db::GenericParamsQuery
332 hir::db::ModuleLangItemsQuery
333 hir::db::CrateLangItemsQuery
334 hir::db::LangItemQuery
335 hir::db::DocumentationQuery
338 hir::db::InternFunctionQuery
339 hir::db::InternStructQuery
340 hir::db::InternUnionQuery
341 hir::db::InternEnumQuery
342 hir::db::InternConstQuery
343 hir::db::InternStaticQuery
344 hir::db::InternTraitQuery
345 hir::db::InternTypeAliasQuery
346 hir::db::InternImplQuery
349 hir::db::InferQueryQuery
351 hir::db::ValueTyQuery
352 hir::db::ImplSelfTyQuery
353 hir::db::ImplTraitQuery
354 hir::db::FieldTypesQuery
355 hir::db::CallableItemSignatureQuery
356 hir::db::GenericPredicatesForParamQuery
357 hir::db::GenericPredicatesQuery
358 hir::db::GenericDefaultsQuery
359 hir::db::ImplsInCrateQuery
360 hir::db::ImplsForTraitQuery
361 hir::db::InternTypeCtorQuery
362 hir::db::InternChalkImplQuery
363 hir::db::InternAssocTyValueQuery
364 hir::db::AssociatedTyDataQuery
365 hir::db::AssociatedTyValueQuery
366 hir::db::TraitSolveQuery
367 hir::db::TraitDatumQuery
368 hir::db::StructDatumQuery
369 hir::db::ImplDatumQuery
371 acc.sort_by_key(|it| std::cmp::Reverse(it.1));
376 fn durability(source_root: &SourceRoot) -> Durability {
377 if source_root.is_library {