1 //! ide crate provides "ide-centric" APIs for the rust-analyzer. That is,
2 //! it generally operates with files and text ranges, and returns results as
3 //! Strings, suitable for displaying to the human.
4 //!
5 //! What powers this API are the `RootDatabase` struct, which defines a `salsa`
6 //! database, and the `hir` crate, where majority of the analysis happens.
7 //! However, IDE specific bits of the analysis (most notably completion) happen
8 //! in this crate.
9
10 // For proving that RootDatabase is RefUnwindSafe.
11 #![recursion_limit = "128"]
12 #![warn(rust_2018_idioms, unused_lifetimes, semicolon_in_expressions_from_macros)]
13
14 #[allow(unused)]
15 macro_rules! eprintln {
16 ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
17 }
18
19 #[cfg(test)]
20 mod fixture;
21
22 mod markup;
23 mod prime_caches;
24 mod navigation_target;
25
26 mod annotations;
27 mod call_hierarchy;
28 mod signature_help;
29 mod doc_links;
30 mod highlight_related;
31 mod expand_macro;
32 mod extend_selection;
33 mod file_structure;
34 mod folding_ranges;
35 mod goto_declaration;
36 mod goto_definition;
37 mod goto_implementation;
38 mod goto_type_definition;
39 mod hover;
40 mod inlay_hints;
41 mod join_lines;
42 mod markdown_remove;
43 mod matching_brace;
44 mod moniker;
45 mod move_item;
46 mod parent_module;
47 mod references;
48 mod rename;
49 mod runnables;
50 mod ssr;
51 mod static_index;
52 mod status;
53 mod syntax_highlighting;
54 mod syntax_tree;
55 mod typing;
56 mod view_crate_graph;
57 mod view_hir;
58 mod view_mir;
59 mod interpret_function;
60 mod view_item_tree;
61 mod shuffle_crate_graph;
62 mod fetch_crates;
63
64 use std::ffi::OsStr;
65
66 use cfg::CfgOptions;
67 use fetch_crates::CrateInfo;
68 use ide_db::{
69 base_db::{
70 salsa::{self, ParallelDatabase},
71 CrateOrigin, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
72 },
73 symbol_index, FxHashMap, FxIndexSet, LineIndexDatabase,
74 };
75 use syntax::SourceFile;
76 use triomphe::Arc;
77
78 use crate::navigation_target::{ToNav, TryToNav};
79
80 pub use crate::{
81 annotations::{Annotation, AnnotationConfig, AnnotationKind, AnnotationLocation},
82 call_hierarchy::CallItem,
83 expand_macro::ExpandedMacro,
84 file_structure::{StructureNode, StructureNodeKind},
85 folding_ranges::{Fold, FoldKind},
86 highlight_related::{HighlightRelatedConfig, HighlightedRange},
87 hover::{
88 HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult,
89 MemoryLayoutHoverConfig, MemoryLayoutHoverRenderKind,
90 },
91 inlay_hints::{
92 AdjustmentHints, AdjustmentHintsMode, ClosureReturnTypeHints, DiscriminantHints, InlayHint,
93 InlayHintLabel, InlayHintLabelPart, InlayHintPosition, InlayHintsConfig, InlayKind,
94 InlayTooltip, LifetimeElisionHints,
95 },
96 join_lines::JoinLinesConfig,
97 markup::Markup,
98 moniker::{MonikerDescriptorKind, MonikerKind, MonikerResult, PackageInformation},
99 move_item::Direction,
100 navigation_target::NavigationTarget,
101 prime_caches::ParallelPrimeCachesProgress,
102 references::ReferenceSearchResult,
103 rename::RenameError,
104 runnables::{Runnable, RunnableKind, TestId},
105 signature_help::SignatureHelp,
106 static_index::{StaticIndex, StaticIndexedFile, TokenId, TokenStaticData},
107 syntax_highlighting::{
108 tags::{Highlight, HlMod, HlMods, HlOperator, HlPunct, HlTag},
109 HighlightConfig, HlRange,
110 },
111 };
112 pub use hir::{Documentation, Semantics};
113 pub use ide_assists::{
114 Assist, AssistConfig, AssistId, AssistKind, AssistResolveStrategy, SingleResolve,
115 };
116 pub use ide_completion::{
117 CallableSnippets, CompletionConfig, CompletionItem, CompletionItemKind, CompletionRelevance,
118 Snippet, SnippetScope,
119 };
120 pub use ide_db::{
121 base_db::{
122 Cancelled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
123 SourceRoot, SourceRootId,
124 },
125 label::Label,
126 line_index::{LineCol, LineIndex},
127 search::{ReferenceCategory, SearchScope},
128 source_change::{FileSystemEdit, SourceChange},
129 symbol_index::Query,
130 RootDatabase, SymbolKind,
131 };
132 pub use ide_diagnostics::{Diagnostic, DiagnosticsConfig, ExprFillDefaultMode, Severity};
133 pub use ide_ssr::SsrError;
134 pub use syntax::{TextRange, TextSize};
135 pub use text_edit::{Indel, TextEdit};
136
137 pub type Cancellable<T> = Result<T, Cancelled>;
138
139 /// Info associated with a text range.
140 #[derive(Debug)]
141 pub struct RangeInfo<T> {
142 pub range: TextRange,
143 pub info: T,
144 }
145
146 impl<T> RangeInfo<T> {
new(range: TextRange, info: T) -> RangeInfo<T>147 pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
148 RangeInfo { range, info }
149 }
150 }
151
152 /// `AnalysisHost` stores the current state of the world.
153 #[derive(Debug)]
154 pub struct AnalysisHost {
155 db: RootDatabase,
156 }
157
158 impl AnalysisHost {
new(lru_capacity: Option<usize>) -> AnalysisHost159 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
160 AnalysisHost { db: RootDatabase::new(lru_capacity) }
161 }
162
update_lru_capacity(&mut self, lru_capacity: Option<usize>)163 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
164 self.db.update_parse_query_lru_capacity(lru_capacity);
165 }
166
update_lru_capacities(&mut self, lru_capacities: &FxHashMap<Box<str>, usize>)167 pub fn update_lru_capacities(&mut self, lru_capacities: &FxHashMap<Box<str>, usize>) {
168 self.db.update_lru_capacities(lru_capacities);
169 }
170
171 /// Returns a snapshot of the current state, which you can query for
172 /// semantic information.
analysis(&self) -> Analysis173 pub fn analysis(&self) -> Analysis {
174 Analysis { db: self.db.snapshot() }
175 }
176
177 /// Applies changes to the current state of the world. If there are
178 /// outstanding snapshots, they will be canceled.
apply_change(&mut self, change: Change)179 pub fn apply_change(&mut self, change: Change) {
180 self.db.apply_change(change)
181 }
182
183 /// NB: this clears the database
per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes, usize)>184 pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes, usize)> {
185 self.db.per_query_memory_usage()
186 }
request_cancellation(&mut self)187 pub fn request_cancellation(&mut self) {
188 self.db.request_cancellation();
189 }
raw_database(&self) -> &RootDatabase190 pub fn raw_database(&self) -> &RootDatabase {
191 &self.db
192 }
raw_database_mut(&mut self) -> &mut RootDatabase193 pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
194 &mut self.db
195 }
196
shuffle_crate_graph(&mut self)197 pub fn shuffle_crate_graph(&mut self) {
198 shuffle_crate_graph::shuffle_crate_graph(&mut self.db);
199 }
200 }
201
202 impl Default for AnalysisHost {
default() -> AnalysisHost203 fn default() -> AnalysisHost {
204 AnalysisHost::new(None)
205 }
206 }
207
208 /// Analysis is a snapshot of a world state at a moment in time. It is the main
209 /// entry point for asking semantic information about the world. When the world
210 /// state is advanced using `AnalysisHost::apply_change` method, all existing
211 /// `Analysis` are canceled (most method return `Err(Canceled)`).
212 #[derive(Debug)]
213 pub struct Analysis {
214 db: salsa::Snapshot<RootDatabase>,
215 }
216
217 // As a general design guideline, `Analysis` API are intended to be independent
218 // from the language server protocol. That is, when exposing some functionality
219 // we should think in terms of "what API makes most sense" and not in terms of
220 // "what types LSP uses". Although currently LSP is the only consumer of the
221 // API, the API should in theory be usable as a library, or via a different
222 // protocol.
223 impl Analysis {
224 // Creates an analysis instance for a single file, without any external
225 // dependencies, stdlib support or ability to apply changes. See
226 // `AnalysisHost` for creating a fully-featured analysis.
from_single_file(text: String) -> (Analysis, FileId)227 pub fn from_single_file(text: String) -> (Analysis, FileId) {
228 let mut host = AnalysisHost::default();
229 let file_id = FileId(0);
230 let mut file_set = FileSet::default();
231 file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
232 let source_root = SourceRoot::new_local(file_set);
233
234 let mut change = Change::new();
235 change.set_roots(vec![source_root]);
236 let mut crate_graph = CrateGraph::default();
237 // FIXME: cfg options
238 // Default to enable test for single file.
239 let mut cfg_options = CfgOptions::default();
240 cfg_options.insert_atom("test".into());
241 crate_graph.add_crate_root(
242 file_id,
243 Edition::CURRENT,
244 None,
245 None,
246 cfg_options.clone(),
247 None,
248 Env::default(),
249 false,
250 CrateOrigin::Local { repo: None, name: None },
251 Err("Analysis::from_single_file has no target layout".into()),
252 None,
253 );
254 change.change_file(file_id, Some(Arc::from(text)));
255 change.set_crate_graph(crate_graph);
256 host.apply_change(change);
257 (host.analysis(), file_id)
258 }
259
260 /// Debug info about the current state of the analysis.
status(&self, file_id: Option<FileId>) -> Cancellable<String>261 pub fn status(&self, file_id: Option<FileId>) -> Cancellable<String> {
262 self.with_db(|db| status::status(&*db, file_id))
263 }
264
parallel_prime_caches<F>(&self, num_worker_threads: u8, cb: F) -> Cancellable<()> where F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,265 pub fn parallel_prime_caches<F>(&self, num_worker_threads: u8, cb: F) -> Cancellable<()>
266 where
267 F: Fn(ParallelPrimeCachesProgress) + Sync + std::panic::UnwindSafe,
268 {
269 self.with_db(move |db| prime_caches::parallel_prime_caches(db, num_worker_threads, &cb))
270 }
271
272 /// Gets the text of the source file.
file_text(&self, file_id: FileId) -> Cancellable<Arc<str>>273 pub fn file_text(&self, file_id: FileId) -> Cancellable<Arc<str>> {
274 self.with_db(|db| db.file_text(file_id))
275 }
276
277 /// Gets the syntax tree of the file.
parse(&self, file_id: FileId) -> Cancellable<SourceFile>278 pub fn parse(&self, file_id: FileId) -> Cancellable<SourceFile> {
279 self.with_db(|db| db.parse(file_id).tree())
280 }
281
282 /// Returns true if this file belongs to an immutable library.
is_library_file(&self, file_id: FileId) -> Cancellable<bool>283 pub fn is_library_file(&self, file_id: FileId) -> Cancellable<bool> {
284 use ide_db::base_db::SourceDatabaseExt;
285 self.with_db(|db| db.source_root(db.file_source_root(file_id)).is_library)
286 }
287
288 /// Gets the file's `LineIndex`: data structure to convert between absolute
289 /// offsets and line/column representation.
file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>>290 pub fn file_line_index(&self, file_id: FileId) -> Cancellable<Arc<LineIndex>> {
291 self.with_db(|db| db.line_index(file_id))
292 }
293
294 /// Selects the next syntactic nodes encompassing the range.
extend_selection(&self, frange: FileRange) -> Cancellable<TextRange>295 pub fn extend_selection(&self, frange: FileRange) -> Cancellable<TextRange> {
296 self.with_db(|db| extend_selection::extend_selection(db, frange))
297 }
298
299 /// Returns position of the matching brace (all types of braces are
300 /// supported).
matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>>301 pub fn matching_brace(&self, position: FilePosition) -> Cancellable<Option<TextSize>> {
302 self.with_db(|db| {
303 let parse = db.parse(position.file_id);
304 let file = parse.tree();
305 matching_brace::matching_brace(&file, position.offset)
306 })
307 }
308
309 /// Returns a syntax tree represented as `String`, for debug purposes.
310 // FIXME: use a better name here.
syntax_tree( &self, file_id: FileId, text_range: Option<TextRange>, ) -> Cancellable<String>311 pub fn syntax_tree(
312 &self,
313 file_id: FileId,
314 text_range: Option<TextRange>,
315 ) -> Cancellable<String> {
316 self.with_db(|db| syntax_tree::syntax_tree(db, file_id, text_range))
317 }
318
view_hir(&self, position: FilePosition) -> Cancellable<String>319 pub fn view_hir(&self, position: FilePosition) -> Cancellable<String> {
320 self.with_db(|db| view_hir::view_hir(db, position))
321 }
322
view_mir(&self, position: FilePosition) -> Cancellable<String>323 pub fn view_mir(&self, position: FilePosition) -> Cancellable<String> {
324 self.with_db(|db| view_mir::view_mir(db, position))
325 }
326
interpret_function(&self, position: FilePosition) -> Cancellable<String>327 pub fn interpret_function(&self, position: FilePosition) -> Cancellable<String> {
328 self.with_db(|db| interpret_function::interpret_function(db, position))
329 }
330
view_item_tree(&self, file_id: FileId) -> Cancellable<String>331 pub fn view_item_tree(&self, file_id: FileId) -> Cancellable<String> {
332 self.with_db(|db| view_item_tree::view_item_tree(db, file_id))
333 }
334
335 /// Renders the crate graph to GraphViz "dot" syntax.
view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>>336 pub fn view_crate_graph(&self, full: bool) -> Cancellable<Result<String, String>> {
337 self.with_db(|db| view_crate_graph::view_crate_graph(db, full))
338 }
339
fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>>340 pub fn fetch_crates(&self) -> Cancellable<FxIndexSet<CrateInfo>> {
341 self.with_db(|db| fetch_crates::fetch_crates(db))
342 }
343
expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>>344 pub fn expand_macro(&self, position: FilePosition) -> Cancellable<Option<ExpandedMacro>> {
345 self.with_db(|db| expand_macro::expand_macro(db, position))
346 }
347
348 /// Returns an edit to remove all newlines in the range, cleaning up minor
349 /// stuff like trailing commas.
join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit>350 pub fn join_lines(&self, config: &JoinLinesConfig, frange: FileRange) -> Cancellable<TextEdit> {
351 self.with_db(|db| {
352 let parse = db.parse(frange.file_id);
353 join_lines::join_lines(config, &parse.tree(), frange.range)
354 })
355 }
356
357 /// Returns an edit which should be applied when opening a new line, fixing
358 /// up minor stuff like continuing the comment.
359 /// The edit will be a snippet (with `$0`).
on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>>360 pub fn on_enter(&self, position: FilePosition) -> Cancellable<Option<TextEdit>> {
361 self.with_db(|db| typing::on_enter(db, position))
362 }
363
364 /// Returns an edit which should be applied after a character was typed.
365 ///
366 /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
367 /// automatically.
on_char_typed( &self, position: FilePosition, char_typed: char, autoclose: bool, ) -> Cancellable<Option<SourceChange>>368 pub fn on_char_typed(
369 &self,
370 position: FilePosition,
371 char_typed: char,
372 autoclose: bool,
373 ) -> Cancellable<Option<SourceChange>> {
374 // Fast path to not even parse the file.
375 if !typing::TRIGGER_CHARS.contains(char_typed) {
376 return Ok(None);
377 }
378 if char_typed == '<' && !autoclose {
379 return Ok(None);
380 }
381
382 self.with_db(|db| typing::on_char_typed(db, position, char_typed))
383 }
384
385 /// Returns a tree representation of symbols in the file. Useful to draw a
386 /// file outline.
file_structure(&self, file_id: FileId) -> Cancellable<Vec<StructureNode>>387 pub fn file_structure(&self, file_id: FileId) -> Cancellable<Vec<StructureNode>> {
388 self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
389 }
390
391 /// Returns a list of the places in the file where type hints can be displayed.
inlay_hints( &self, config: &InlayHintsConfig, file_id: FileId, range: Option<TextRange>, ) -> Cancellable<Vec<InlayHint>>392 pub fn inlay_hints(
393 &self,
394 config: &InlayHintsConfig,
395 file_id: FileId,
396 range: Option<TextRange>,
397 ) -> Cancellable<Vec<InlayHint>> {
398 self.with_db(|db| inlay_hints::inlay_hints(db, file_id, range, config))
399 }
400
401 /// Returns the set of folding ranges.
folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>>402 pub fn folding_ranges(&self, file_id: FileId) -> Cancellable<Vec<Fold>> {
403 self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
404 }
405
406 /// Fuzzy searches for a symbol.
symbol_search(&self, query: Query) -> Cancellable<Vec<NavigationTarget>>407 pub fn symbol_search(&self, query: Query) -> Cancellable<Vec<NavigationTarget>> {
408 self.with_db(|db| {
409 symbol_index::world_symbols(db, query)
410 .into_iter() // xx: should we make this a par iter?
411 .filter_map(|s| s.try_to_nav(db))
412 .collect::<Vec<_>>()
413 })
414 }
415
416 /// Returns the definitions from the symbol at `position`.
goto_definition( &self, position: FilePosition, ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>>417 pub fn goto_definition(
418 &self,
419 position: FilePosition,
420 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
421 self.with_db(|db| goto_definition::goto_definition(db, position))
422 }
423
424 /// Returns the declaration from the symbol at `position`.
goto_declaration( &self, position: FilePosition, ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>>425 pub fn goto_declaration(
426 &self,
427 position: FilePosition,
428 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
429 self.with_db(|db| goto_declaration::goto_declaration(db, position))
430 }
431
432 /// Returns the impls from the symbol at `position`.
goto_implementation( &self, position: FilePosition, ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>>433 pub fn goto_implementation(
434 &self,
435 position: FilePosition,
436 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
437 self.with_db(|db| goto_implementation::goto_implementation(db, position))
438 }
439
440 /// Returns the type definitions for the symbol at `position`.
goto_type_definition( &self, position: FilePosition, ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>>441 pub fn goto_type_definition(
442 &self,
443 position: FilePosition,
444 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
445 self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
446 }
447
448 /// Finds all usages of the reference at point.
find_all_refs( &self, position: FilePosition, search_scope: Option<SearchScope>, ) -> Cancellable<Option<Vec<ReferenceSearchResult>>>449 pub fn find_all_refs(
450 &self,
451 position: FilePosition,
452 search_scope: Option<SearchScope>,
453 ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
454 self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
455 }
456
457 /// Returns a short text describing element at position.
hover( &self, config: &HoverConfig, range: FileRange, ) -> Cancellable<Option<RangeInfo<HoverResult>>>458 pub fn hover(
459 &self,
460 config: &HoverConfig,
461 range: FileRange,
462 ) -> Cancellable<Option<RangeInfo<HoverResult>>> {
463 self.with_db(|db| hover::hover(db, range, config))
464 }
465
466 /// Returns moniker of symbol at position.
moniker( &self, position: FilePosition, ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>>467 pub fn moniker(
468 &self,
469 position: FilePosition,
470 ) -> Cancellable<Option<RangeInfo<Vec<moniker::MonikerResult>>>> {
471 self.with_db(|db| moniker::moniker(db, position))
472 }
473
474 /// Returns URL(s) for the documentation of the symbol under the cursor.
475 /// # Arguments
476 /// * `position` - Position in the file.
477 /// * `target_dir` - Directory where the build output is storeda.
external_docs( &self, position: FilePosition, target_dir: Option<&OsStr>, sysroot: Option<&OsStr>, ) -> Cancellable<doc_links::DocumentationLinks>478 pub fn external_docs(
479 &self,
480 position: FilePosition,
481 target_dir: Option<&OsStr>,
482 sysroot: Option<&OsStr>,
483 ) -> Cancellable<doc_links::DocumentationLinks> {
484 self.with_db(|db| {
485 doc_links::external_docs(db, &position, target_dir, sysroot).unwrap_or_default()
486 })
487 }
488
489 /// Computes parameter information at the given position.
signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>>490 pub fn signature_help(&self, position: FilePosition) -> Cancellable<Option<SignatureHelp>> {
491 self.with_db(|db| signature_help::signature_help(db, position))
492 }
493
494 /// Computes call hierarchy candidates for the given file position.
call_hierarchy( &self, position: FilePosition, ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>>495 pub fn call_hierarchy(
496 &self,
497 position: FilePosition,
498 ) -> Cancellable<Option<RangeInfo<Vec<NavigationTarget>>>> {
499 self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
500 }
501
502 /// Computes incoming calls for the given file position.
incoming_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>>503 pub fn incoming_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
504 self.with_db(|db| call_hierarchy::incoming_calls(db, position))
505 }
506
507 /// Computes outgoing calls for the given file position.
outgoing_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>>508 pub fn outgoing_calls(&self, position: FilePosition) -> Cancellable<Option<Vec<CallItem>>> {
509 self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
510 }
511
512 /// Returns a `mod name;` declaration which created the current module.
parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>>513 pub fn parent_module(&self, position: FilePosition) -> Cancellable<Vec<NavigationTarget>> {
514 self.with_db(|db| parent_module::parent_module(db, position))
515 }
516
517 /// Returns crates this file belongs too.
crates_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>>518 pub fn crates_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
519 self.with_db(|db| parent_module::crates_for(db, file_id))
520 }
521
522 /// Returns crates this file belongs too.
transitive_rev_deps(&self, crate_id: CrateId) -> Cancellable<Vec<CrateId>>523 pub fn transitive_rev_deps(&self, crate_id: CrateId) -> Cancellable<Vec<CrateId>> {
524 self.with_db(|db| db.crate_graph().transitive_rev_deps(crate_id).collect())
525 }
526
527 /// Returns crates this file *might* belong too.
relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>>528 pub fn relevant_crates_for(&self, file_id: FileId) -> Cancellable<Vec<CrateId>> {
529 self.with_db(|db| db.relevant_crates(file_id).iter().copied().collect())
530 }
531
532 /// Returns the edition of the given crate.
crate_edition(&self, crate_id: CrateId) -> Cancellable<Edition>533 pub fn crate_edition(&self, crate_id: CrateId) -> Cancellable<Edition> {
534 self.with_db(|db| db.crate_graph()[crate_id].edition)
535 }
536
537 /// Returns true if this crate has `no_std` or `no_core` specified.
is_crate_no_std(&self, crate_id: CrateId) -> Cancellable<bool>538 pub fn is_crate_no_std(&self, crate_id: CrateId) -> Cancellable<bool> {
539 self.with_db(|db| hir::db::DefDatabase::crate_def_map(db, crate_id).is_no_std())
540 }
541
542 /// Returns the root file of the given crate.
crate_root(&self, crate_id: CrateId) -> Cancellable<FileId>543 pub fn crate_root(&self, crate_id: CrateId) -> Cancellable<FileId> {
544 self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
545 }
546
547 /// Returns the set of possible targets to run for the current file.
runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>>548 pub fn runnables(&self, file_id: FileId) -> Cancellable<Vec<Runnable>> {
549 self.with_db(|db| runnables::runnables(db, file_id))
550 }
551
552 /// Returns the set of tests for the given file position.
related_tests( &self, position: FilePosition, search_scope: Option<SearchScope>, ) -> Cancellable<Vec<Runnable>>553 pub fn related_tests(
554 &self,
555 position: FilePosition,
556 search_scope: Option<SearchScope>,
557 ) -> Cancellable<Vec<Runnable>> {
558 self.with_db(|db| runnables::related_tests(db, position, search_scope))
559 }
560
561 /// Computes syntax highlighting for the given file
highlight( &self, highlight_config: HighlightConfig, file_id: FileId, ) -> Cancellable<Vec<HlRange>>562 pub fn highlight(
563 &self,
564 highlight_config: HighlightConfig,
565 file_id: FileId,
566 ) -> Cancellable<Vec<HlRange>> {
567 self.with_db(|db| syntax_highlighting::highlight(db, highlight_config, file_id, None))
568 }
569
570 /// Computes all ranges to highlight for a given item in a file.
highlight_related( &self, config: HighlightRelatedConfig, position: FilePosition, ) -> Cancellable<Option<Vec<HighlightedRange>>>571 pub fn highlight_related(
572 &self,
573 config: HighlightRelatedConfig,
574 position: FilePosition,
575 ) -> Cancellable<Option<Vec<HighlightedRange>>> {
576 self.with_db(|db| {
577 highlight_related::highlight_related(&Semantics::new(db), config, position)
578 })
579 }
580
581 /// Computes syntax highlighting for the given file range.
highlight_range( &self, highlight_config: HighlightConfig, frange: FileRange, ) -> Cancellable<Vec<HlRange>>582 pub fn highlight_range(
583 &self,
584 highlight_config: HighlightConfig,
585 frange: FileRange,
586 ) -> Cancellable<Vec<HlRange>> {
587 self.with_db(|db| {
588 syntax_highlighting::highlight(db, highlight_config, frange.file_id, Some(frange.range))
589 })
590 }
591
592 /// Computes syntax highlighting for the given file.
highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String>593 pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancellable<String> {
594 self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
595 }
596
597 /// Computes completions at the given position.
completions( &self, config: &CompletionConfig, position: FilePosition, trigger_character: Option<char>, ) -> Cancellable<Option<Vec<CompletionItem>>>598 pub fn completions(
599 &self,
600 config: &CompletionConfig,
601 position: FilePosition,
602 trigger_character: Option<char>,
603 ) -> Cancellable<Option<Vec<CompletionItem>>> {
604 self.with_db(|db| {
605 ide_completion::completions(db, config, position, trigger_character).map(Into::into)
606 })
607 }
608
609 /// Resolves additional completion data at the position given.
resolve_completion_edits( &self, config: &CompletionConfig, position: FilePosition, imports: impl IntoIterator<Item = (String, String)> + std::panic::UnwindSafe, ) -> Cancellable<Vec<TextEdit>>610 pub fn resolve_completion_edits(
611 &self,
612 config: &CompletionConfig,
613 position: FilePosition,
614 imports: impl IntoIterator<Item = (String, String)> + std::panic::UnwindSafe,
615 ) -> Cancellable<Vec<TextEdit>> {
616 Ok(self
617 .with_db(|db| ide_completion::resolve_completion_edits(db, config, position, imports))?
618 .unwrap_or_default())
619 }
620
621 /// Computes the set of diagnostics for the given file.
diagnostics( &self, config: &DiagnosticsConfig, resolve: AssistResolveStrategy, file_id: FileId, ) -> Cancellable<Vec<Diagnostic>>622 pub fn diagnostics(
623 &self,
624 config: &DiagnosticsConfig,
625 resolve: AssistResolveStrategy,
626 file_id: FileId,
627 ) -> Cancellable<Vec<Diagnostic>> {
628 self.with_db(|db| ide_diagnostics::diagnostics(db, config, &resolve, file_id))
629 }
630
631 /// Convenience function to return assists + quick fixes for diagnostics
assists_with_fixes( &self, assist_config: &AssistConfig, diagnostics_config: &DiagnosticsConfig, resolve: AssistResolveStrategy, frange: FileRange, ) -> Cancellable<Vec<Assist>>632 pub fn assists_with_fixes(
633 &self,
634 assist_config: &AssistConfig,
635 diagnostics_config: &DiagnosticsConfig,
636 resolve: AssistResolveStrategy,
637 frange: FileRange,
638 ) -> Cancellable<Vec<Assist>> {
639 let include_fixes = match &assist_config.allowed {
640 Some(it) => it.iter().any(|&it| it == AssistKind::None || it == AssistKind::QuickFix),
641 None => true,
642 };
643
644 self.with_db(|db| {
645 let diagnostic_assists = if include_fixes {
646 ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
647 .into_iter()
648 .flat_map(|it| it.fixes.unwrap_or_default())
649 .filter(|it| it.target.intersect(frange.range).is_some())
650 .collect()
651 } else {
652 Vec::new()
653 };
654 let ssr_assists = ssr::ssr_assists(db, &resolve, frange);
655 let assists = ide_assists::assists(db, assist_config, resolve, frange);
656
657 let mut res = diagnostic_assists;
658 res.extend(ssr_assists.into_iter());
659 res.extend(assists.into_iter());
660
661 res
662 })
663 }
664
665 /// Returns the edit required to rename reference at the position to the new
666 /// name.
rename( &self, position: FilePosition, new_name: &str, ) -> Cancellable<Result<SourceChange, RenameError>>667 pub fn rename(
668 &self,
669 position: FilePosition,
670 new_name: &str,
671 ) -> Cancellable<Result<SourceChange, RenameError>> {
672 self.with_db(|db| rename::rename(db, position, new_name))
673 }
674
prepare_rename( &self, position: FilePosition, ) -> Cancellable<Result<RangeInfo<()>, RenameError>>675 pub fn prepare_rename(
676 &self,
677 position: FilePosition,
678 ) -> Cancellable<Result<RangeInfo<()>, RenameError>> {
679 self.with_db(|db| rename::prepare_rename(db, position))
680 }
681
will_rename_file( &self, file_id: FileId, new_name_stem: &str, ) -> Cancellable<Option<SourceChange>>682 pub fn will_rename_file(
683 &self,
684 file_id: FileId,
685 new_name_stem: &str,
686 ) -> Cancellable<Option<SourceChange>> {
687 self.with_db(|db| rename::will_rename_file(db, file_id, new_name_stem))
688 }
689
structural_search_replace( &self, query: &str, parse_only: bool, resolve_context: FilePosition, selections: Vec<FileRange>, ) -> Cancellable<Result<SourceChange, SsrError>>690 pub fn structural_search_replace(
691 &self,
692 query: &str,
693 parse_only: bool,
694 resolve_context: FilePosition,
695 selections: Vec<FileRange>,
696 ) -> Cancellable<Result<SourceChange, SsrError>> {
697 self.with_db(|db| {
698 let rule: ide_ssr::SsrRule = query.parse()?;
699 let mut match_finder =
700 ide_ssr::MatchFinder::in_context(db, resolve_context, selections)?;
701 match_finder.add_rule(rule)?;
702 let edits = if parse_only { Default::default() } else { match_finder.edits() };
703 Ok(SourceChange::from(edits))
704 })
705 }
706
annotations( &self, config: &AnnotationConfig, file_id: FileId, ) -> Cancellable<Vec<Annotation>>707 pub fn annotations(
708 &self,
709 config: &AnnotationConfig,
710 file_id: FileId,
711 ) -> Cancellable<Vec<Annotation>> {
712 self.with_db(|db| annotations::annotations(db, config, file_id))
713 }
714
resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation>715 pub fn resolve_annotation(&self, annotation: Annotation) -> Cancellable<Annotation> {
716 self.with_db(|db| annotations::resolve_annotation(db, annotation))
717 }
718
move_item( &self, range: FileRange, direction: Direction, ) -> Cancellable<Option<TextEdit>>719 pub fn move_item(
720 &self,
721 range: FileRange,
722 direction: Direction,
723 ) -> Cancellable<Option<TextEdit>> {
724 self.with_db(|db| move_item::move_item(db, range, direction))
725 }
726
727 /// Performs an operation on the database that may be canceled.
728 ///
729 /// rust-analyzer needs to be able to answer semantic questions about the
730 /// code while the code is being modified. A common problem is that a
731 /// long-running query is being calculated when a new change arrives.
732 ///
733 /// We can't just apply the change immediately: this will cause the pending
734 /// query to see inconsistent state (it will observe an absence of
735 /// repeatable read). So what we do is we **cancel** all pending queries
736 /// before applying the change.
737 ///
738 /// Salsa implements cancellation by unwinding with a special value and
739 /// catching it on the API boundary.
with_db<F, T>(&self, f: F) -> Cancellable<T> where F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,740 fn with_db<F, T>(&self, f: F) -> Cancellable<T>
741 where
742 F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
743 {
744 Cancelled::catch(|| f(&self.db))
745 }
746 }
747
748 #[test]
analysis_is_send()749 fn analysis_is_send() {
750 fn is_send<T: Send>() {}
751 is_send::<Analysis>();
752 }
753