]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/lib.rs
b600178ee15982b6074d9295661a22b059804407
[rust.git] / crates / ide / src / lib.rs
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
13 #[allow(unused)]
14 macro_rules! eprintln {
15     ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
16 }
17
18 #[cfg(test)]
19 mod fixture;
20
21 mod markup;
22 mod prime_caches;
23 mod display;
24
25 mod annotations;
26 mod call_hierarchy;
27 mod diagnostics;
28 mod expand_macro;
29 mod extend_selection;
30 mod file_structure;
31 mod folding_ranges;
32 mod goto_definition;
33 mod goto_implementation;
34 mod goto_type_definition;
35 mod view_hir;
36 mod hover;
37 mod inlay_hints;
38 mod join_lines;
39 mod matching_brace;
40 mod parent_module;
41 mod references;
42 mod fn_references;
43 mod runnables;
44 mod status;
45 mod syntax_highlighting;
46 mod syntax_tree;
47 mod typing;
48 mod markdown_remove;
49 mod doc_links;
50
51 use std::sync::Arc;
52
53 use cfg::CfgOptions;
54 use ide_db::base_db::{
55     salsa::{self, ParallelDatabase},
56     CheckCanceled, Env, FileLoader, FileSet, SourceDatabase, VfsPath,
57 };
58 use ide_db::{
59     symbol_index::{self, FileSymbol},
60     LineIndexDatabase,
61 };
62 use syntax::SourceFile;
63
64 use crate::display::ToNav;
65
66 pub use crate::{
67     annotations::{Annotation, AnnotationConfig, AnnotationKind},
68     call_hierarchy::CallItem,
69     diagnostics::{Diagnostic, DiagnosticsConfig, Fix, Severity},
70     display::navigation_target::NavigationTarget,
71     expand_macro::ExpandedMacro,
72     file_structure::StructureNode,
73     folding_ranges::{Fold, FoldKind},
74     hover::{HoverAction, HoverConfig, HoverGotoTypeData, HoverResult},
75     inlay_hints::{InlayHint, InlayHintsConfig, InlayKind},
76     markup::Markup,
77     prime_caches::PrimeCachesProgress,
78     references::{rename::RenameError, ReferenceSearchResult},
79     runnables::{Runnable, RunnableKind, TestId},
80     syntax_highlighting::{
81         tags::{Highlight, HlMod, HlMods, HlPunct, HlTag},
82         HlRange,
83     },
84 };
85 pub use hir::{Documentation, Semantics};
86 pub use ide_assists::{Assist, AssistConfig, AssistId, AssistKind};
87 pub use ide_completion::{
88     CompletionConfig, CompletionItem, CompletionItemKind, CompletionScore, ImportEdit,
89     InsertTextFormat,
90 };
91 pub use ide_db::{
92     base_db::{
93         Canceled, Change, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange,
94         SourceRoot, SourceRootId,
95     },
96     call_info::CallInfo,
97     label::Label,
98     line_index::{LineCol, LineColUtf16, LineIndex},
99     search::{ReferenceAccess, SearchScope},
100     source_change::{FileSystemEdit, SourceChange},
101     symbol_index::Query,
102     RootDatabase,
103 };
104 pub use ide_ssr::SsrError;
105 pub use syntax::{TextRange, TextSize};
106 pub use text_edit::{Indel, TextEdit};
107
108 pub type Cancelable<T> = Result<T, Canceled>;
109
110 /// Info associated with a text range.
111 #[derive(Debug)]
112 pub struct RangeInfo<T> {
113     pub range: TextRange,
114     pub info: T,
115 }
116
117 impl<T> RangeInfo<T> {
118     pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
119         RangeInfo { range, info }
120     }
121 }
122
123 /// `AnalysisHost` stores the current state of the world.
124 #[derive(Debug)]
125 pub struct AnalysisHost {
126     db: RootDatabase,
127 }
128
129 impl AnalysisHost {
130     pub fn new(lru_capacity: Option<usize>) -> AnalysisHost {
131         AnalysisHost { db: RootDatabase::new(lru_capacity) }
132     }
133
134     pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
135         self.db.update_lru_capacity(lru_capacity);
136     }
137
138     /// Returns a snapshot of the current state, which you can query for
139     /// semantic information.
140     pub fn analysis(&self) -> Analysis {
141         Analysis { db: self.db.snapshot() }
142     }
143
144     /// Applies changes to the current state of the world. If there are
145     /// outstanding snapshots, they will be canceled.
146     pub fn apply_change(&mut self, change: Change) {
147         self.db.apply_change(change)
148     }
149
150     pub fn collect_garbage(&mut self) {
151         self.db.collect_garbage();
152     }
153     /// NB: this clears the database
154     pub fn per_query_memory_usage(&mut self) -> Vec<(String, profile::Bytes)> {
155         self.db.per_query_memory_usage()
156     }
157     pub fn request_cancellation(&mut self) {
158         self.db.request_cancellation();
159     }
160     pub fn raw_database(&self) -> &RootDatabase {
161         &self.db
162     }
163     pub fn raw_database_mut(&mut self) -> &mut RootDatabase {
164         &mut self.db
165     }
166 }
167
168 impl Default for AnalysisHost {
169     fn default() -> AnalysisHost {
170         AnalysisHost::new(None)
171     }
172 }
173
174 /// Analysis is a snapshot of a world state at a moment in time. It is the main
175 /// entry point for asking semantic information about the world. When the world
176 /// state is advanced using `AnalysisHost::apply_change` method, all existing
177 /// `Analysis` are canceled (most method return `Err(Canceled)`).
178 #[derive(Debug)]
179 pub struct Analysis {
180     db: salsa::Snapshot<RootDatabase>,
181 }
182
183 // As a general design guideline, `Analysis` API are intended to be independent
184 // from the language server protocol. That is, when exposing some functionality
185 // we should think in terms of "what API makes most sense" and not in terms of
186 // "what types LSP uses". Although currently LSP is the only consumer of the
187 // API, the API should in theory be usable as a library, or via a different
188 // protocol.
189 impl Analysis {
190     // Creates an analysis instance for a single file, without any extenal
191     // dependencies, stdlib support or ability to apply changes. See
192     // `AnalysisHost` for creating a fully-featured analysis.
193     pub fn from_single_file(text: String) -> (Analysis, FileId) {
194         let mut host = AnalysisHost::default();
195         let file_id = FileId(0);
196         let mut file_set = FileSet::default();
197         file_set.insert(file_id, VfsPath::new_virtual_path("/main.rs".to_string()));
198         let source_root = SourceRoot::new_local(file_set);
199
200         let mut change = Change::new();
201         change.set_roots(vec![source_root]);
202         let mut crate_graph = CrateGraph::default();
203         // FIXME: cfg options
204         // Default to enable test for single file.
205         let mut cfg_options = CfgOptions::default();
206         cfg_options.insert_atom("test".into());
207         crate_graph.add_crate_root(
208             file_id,
209             Edition::Edition2018,
210             None,
211             cfg_options,
212             Env::default(),
213             Default::default(),
214         );
215         change.change_file(file_id, Some(Arc::new(text)));
216         change.set_crate_graph(crate_graph);
217         host.apply_change(change);
218         (host.analysis(), file_id)
219     }
220
221     /// Debug info about the current state of the analysis.
222     pub fn status(&self, file_id: Option<FileId>) -> Cancelable<String> {
223         self.with_db(|db| status::status(&*db, file_id))
224     }
225
226     pub fn prime_caches<F>(&self, cb: F) -> Cancelable<()>
227     where
228         F: Fn(PrimeCachesProgress) + Sync + std::panic::UnwindSafe,
229     {
230         self.with_db(move |db| prime_caches::prime_caches(db, &cb))
231     }
232
233     /// Gets the text of the source file.
234     pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
235         self.with_db(|db| db.file_text(file_id))
236     }
237
238     /// Gets the syntax tree of the file.
239     pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
240         self.with_db(|db| db.parse(file_id).tree())
241     }
242
243     /// Gets the file's `LineIndex`: data structure to convert between absolute
244     /// offsets and line/column representation.
245     pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
246         self.with_db(|db| db.line_index(file_id))
247     }
248
249     /// Selects the next syntactic nodes encompassing the range.
250     pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
251         self.with_db(|db| extend_selection::extend_selection(db, frange))
252     }
253
254     /// Returns position of the matching brace (all types of braces are
255     /// supported).
256     pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextSize>> {
257         self.with_db(|db| {
258             let parse = db.parse(position.file_id);
259             let file = parse.tree();
260             matching_brace::matching_brace(&file, position.offset)
261         })
262     }
263
264     /// Returns a syntax tree represented as `String`, for debug purposes.
265     // FIXME: use a better name here.
266     pub fn syntax_tree(
267         &self,
268         file_id: FileId,
269         text_range: Option<TextRange>,
270     ) -> Cancelable<String> {
271         self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
272     }
273
274     pub fn view_hir(&self, position: FilePosition) -> Cancelable<String> {
275         self.with_db(|db| view_hir::view_hir(&db, position))
276     }
277
278     pub fn expand_macro(&self, position: FilePosition) -> Cancelable<Option<ExpandedMacro>> {
279         self.with_db(|db| expand_macro::expand_macro(db, position))
280     }
281
282     /// Returns an edit to remove all newlines in the range, cleaning up minor
283     /// stuff like trailing commas.
284     pub fn join_lines(&self, frange: FileRange) -> Cancelable<TextEdit> {
285         self.with_db(|db| {
286             let parse = db.parse(frange.file_id);
287             join_lines::join_lines(&parse.tree(), frange.range)
288         })
289     }
290
291     /// Returns an edit which should be applied when opening a new line, fixing
292     /// up minor stuff like continuing the comment.
293     /// The edit will be a snippet (with `$0`).
294     pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<TextEdit>> {
295         self.with_db(|db| typing::on_enter(&db, position))
296     }
297
298     /// Returns an edit which should be applied after a character was typed.
299     ///
300     /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
301     /// automatically.
302     pub fn on_char_typed(
303         &self,
304         position: FilePosition,
305         char_typed: char,
306     ) -> Cancelable<Option<SourceChange>> {
307         // Fast path to not even parse the file.
308         if !typing::TRIGGER_CHARS.contains(char_typed) {
309             return Ok(None);
310         }
311         self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
312     }
313
314     /// Returns a tree representation of symbols in the file. Useful to draw a
315     /// file outline.
316     pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
317         self.with_db(|db| file_structure::file_structure(&db.parse(file_id).tree()))
318     }
319
320     /// Returns a list of the places in the file where type hints can be displayed.
321     pub fn inlay_hints(
322         &self,
323         file_id: FileId,
324         config: &InlayHintsConfig,
325     ) -> Cancelable<Vec<InlayHint>> {
326         self.with_db(|db| inlay_hints::inlay_hints(db, file_id, config))
327     }
328
329     /// Returns the set of folding ranges.
330     pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
331         self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
332     }
333
334     /// Fuzzy searches for a symbol.
335     pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
336         self.with_db(|db| {
337             symbol_index::world_symbols(db, query)
338                 .into_iter()
339                 .map(|s| s.to_nav(db))
340                 .collect::<Vec<_>>()
341         })
342     }
343
344     /// Returns the definitions from the symbol at `position`.
345     pub fn goto_definition(
346         &self,
347         position: FilePosition,
348     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
349         self.with_db(|db| goto_definition::goto_definition(db, position))
350     }
351
352     /// Returns the impls from the symbol at `position`.
353     pub fn goto_implementation(
354         &self,
355         position: FilePosition,
356     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
357         self.with_db(|db| goto_implementation::goto_implementation(db, position))
358     }
359
360     /// Returns the type definitions for the symbol at `position`.
361     pub fn goto_type_definition(
362         &self,
363         position: FilePosition,
364     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
365         self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
366     }
367
368     /// Finds all usages of the reference at point.
369     pub fn find_all_refs(
370         &self,
371         position: FilePosition,
372         search_scope: Option<SearchScope>,
373     ) -> Cancelable<Option<ReferenceSearchResult>> {
374         self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
375     }
376
377     /// Finds all methods and free functions for the file. Does not return tests!
378     pub fn find_all_methods(&self, file_id: FileId) -> Cancelable<Vec<FileRange>> {
379         self.with_db(|db| fn_references::find_all_methods(db, file_id))
380     }
381
382     /// Returns a short text describing element at position.
383     pub fn hover(
384         &self,
385         position: FilePosition,
386         links_in_hover: bool,
387         markdown: bool,
388     ) -> Cancelable<Option<RangeInfo<HoverResult>>> {
389         self.with_db(|db| hover::hover(db, position, links_in_hover, markdown))
390     }
391
392     /// Return URL(s) for the documentation of the symbol under the cursor.
393     pub fn external_docs(
394         &self,
395         position: FilePosition,
396     ) -> Cancelable<Option<doc_links::DocumentationLink>> {
397         self.with_db(|db| doc_links::external_docs(db, &position))
398     }
399
400     /// Computes parameter information for the given call expression.
401     pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
402         self.with_db(|db| ide_db::call_info::call_info(db, position))
403     }
404
405     /// Computes call hierarchy candidates for the given file position.
406     pub fn call_hierarchy(
407         &self,
408         position: FilePosition,
409     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
410         self.with_db(|db| call_hierarchy::call_hierarchy(db, position))
411     }
412
413     /// Computes incoming calls for the given file position.
414     pub fn incoming_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
415         self.with_db(|db| call_hierarchy::incoming_calls(db, position))
416     }
417
418     /// Computes incoming calls for the given file position.
419     pub fn outgoing_calls(&self, position: FilePosition) -> Cancelable<Option<Vec<CallItem>>> {
420         self.with_db(|db| call_hierarchy::outgoing_calls(db, position))
421     }
422
423     /// Returns a `mod name;` declaration which created the current module.
424     pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
425         self.with_db(|db| parent_module::parent_module(db, position))
426     }
427
428     /// Returns crates this file belongs too.
429     pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
430         self.with_db(|db| parent_module::crate_for(db, file_id))
431     }
432
433     /// Returns the edition of the given crate.
434     pub fn crate_edition(&self, crate_id: CrateId) -> Cancelable<Edition> {
435         self.with_db(|db| db.crate_graph()[crate_id].edition)
436     }
437
438     /// Returns the root file of the given crate.
439     pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
440         self.with_db(|db| db.crate_graph()[crate_id].root_file_id)
441     }
442
443     /// Returns the set of possible targets to run for the current file.
444     pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
445         self.with_db(|db| runnables::runnables(db, file_id))
446     }
447
448     /// Computes syntax highlighting for the given file
449     pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HlRange>> {
450         self.with_db(|db| syntax_highlighting::highlight(db, file_id, None, false))
451     }
452
453     /// Computes syntax highlighting for the given file range.
454     pub fn highlight_range(&self, frange: FileRange) -> Cancelable<Vec<HlRange>> {
455         self.with_db(|db| {
456             syntax_highlighting::highlight(db, frange.file_id, Some(frange.range), false)
457         })
458     }
459
460     /// Computes syntax highlighting for the given file.
461     pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
462         self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
463     }
464
465     /// Computes completions at the given position.
466     pub fn completions(
467         &self,
468         config: &CompletionConfig,
469         position: FilePosition,
470     ) -> Cancelable<Option<Vec<CompletionItem>>> {
471         self.with_db(|db| ide_completion::completions(db, config, position).map(Into::into))
472     }
473
474     /// Resolves additional completion data at the position given.
475     pub fn resolve_completion_edits(
476         &self,
477         config: &CompletionConfig,
478         position: FilePosition,
479         full_import_path: &str,
480         imported_name: String,
481         import_for_trait_assoc_item: bool,
482     ) -> Cancelable<Vec<TextEdit>> {
483         Ok(self
484             .with_db(|db| {
485                 ide_completion::resolve_completion_edits(
486                     db,
487                     config,
488                     position,
489                     full_import_path,
490                     imported_name,
491                     import_for_trait_assoc_item,
492                 )
493             })?
494             .unwrap_or_default())
495     }
496
497     /// Computes assists (aka code actions aka intentions) for the given
498     /// position. If `resolve == false`, computes enough info to show the
499     /// lightbulb list in the editor, but doesn't compute actual edits, to
500     /// improve performance.
501     pub fn assists(
502         &self,
503         config: &AssistConfig,
504         resolve: bool,
505         frange: FileRange,
506     ) -> Cancelable<Vec<Assist>> {
507         self.with_db(|db| Assist::get(db, config, resolve, frange))
508     }
509
510     /// Computes the set of diagnostics for the given file.
511     pub fn diagnostics(
512         &self,
513         config: &DiagnosticsConfig,
514         file_id: FileId,
515     ) -> Cancelable<Vec<Diagnostic>> {
516         self.with_db(|db| diagnostics::diagnostics(db, config, file_id))
517     }
518
519     /// Returns the edit required to rename reference at the position to the new
520     /// name.
521     pub fn rename(
522         &self,
523         position: FilePosition,
524         new_name: &str,
525     ) -> Cancelable<Result<SourceChange, RenameError>> {
526         self.with_db(|db| references::rename::rename(db, position, new_name))
527     }
528
529     pub fn prepare_rename(
530         &self,
531         position: FilePosition,
532     ) -> Cancelable<Result<RangeInfo<()>, RenameError>> {
533         self.with_db(|db| references::rename::prepare_rename(db, position))
534     }
535
536     pub fn will_rename_file(
537         &self,
538         file_id: FileId,
539         new_name_stem: &str,
540     ) -> Cancelable<Option<SourceChange>> {
541         self.with_db(|db| references::rename::will_rename_file(db, file_id, new_name_stem))
542     }
543
544     pub fn structural_search_replace(
545         &self,
546         query: &str,
547         parse_only: bool,
548         resolve_context: FilePosition,
549         selections: Vec<FileRange>,
550     ) -> Cancelable<Result<SourceChange, SsrError>> {
551         self.with_db(|db| {
552             let rule: ide_ssr::SsrRule = query.parse()?;
553             let mut match_finder =
554                 ide_ssr::MatchFinder::in_context(db, resolve_context, selections);
555             match_finder.add_rule(rule)?;
556             let edits = if parse_only { Default::default() } else { match_finder.edits() };
557             Ok(SourceChange::from(edits))
558         })
559     }
560
561     pub fn annotations(
562         &self,
563         file_id: FileId,
564         config: AnnotationConfig,
565     ) -> Cancelable<Vec<Annotation>> {
566         self.with_db(|db| annotations::annotations(db, file_id, config))
567     }
568
569     pub fn resolve_annotation(&self, annotation: Annotation) -> Cancelable<Annotation> {
570         self.with_db(|db| annotations::resolve_annotation(db, annotation))
571     }
572
573     /// Performs an operation on that may be Canceled.
574     fn with_db<F, T>(&self, f: F) -> Cancelable<T>
575     where
576         F: FnOnce(&RootDatabase) -> T + std::panic::UnwindSafe,
577     {
578         self.db.catch_canceled(f)
579     }
580 }
581
582 #[test]
583 fn analysis_is_send() {
584     fn is_send<T: Send>() {}
585     is_send::<Analysis>();
586 }