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