]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide_api/src/lib.rs
Move type inlay hint truncation to language server
[rust.git] / crates / ra_ide_api / src / lib.rs
1 //! ra_ide_api 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 `ra_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 mod db;
14 pub mod mock_analysis;
15 mod symbol_index;
16 mod change;
17 mod source_change;
18 mod feature_flags;
19
20 mod status;
21 mod completion;
22 mod runnables;
23 mod goto_definition;
24 mod goto_type_definition;
25 mod extend_selection;
26 mod hover;
27 mod call_info;
28 mod syntax_highlighting;
29 mod parent_module;
30 mod references;
31 mod impls;
32 mod assists;
33 mod diagnostics;
34 mod syntax_tree;
35 mod folding_ranges;
36 mod line_index;
37 mod line_index_utils;
38 mod join_lines;
39 mod typing;
40 mod matching_brace;
41 mod display;
42 mod inlay_hints;
43 mod wasm_shims;
44 mod expand;
45
46 #[cfg(test)]
47 mod marks;
48 #[cfg(test)]
49 mod test_utils;
50
51 use std::sync::Arc;
52
53 use ra_cfg::CfgOptions;
54 use ra_db::{
55     salsa::{self, ParallelDatabase},
56     CheckCanceled, FileLoader, SourceDatabase,
57 };
58 use ra_syntax::{SourceFile, TextRange, TextUnit};
59
60 use crate::{db::LineIndexDatabase, display::ToNav, symbol_index::FileSymbol};
61
62 pub use crate::{
63     assists::{Assist, AssistId},
64     change::{AnalysisChange, LibraryData},
65     completion::{CompletionItem, CompletionItemKind, InsertTextFormat},
66     diagnostics::Severity,
67     display::{file_structure, FunctionSignature, NavigationTarget, StructureNode},
68     feature_flags::FeatureFlags,
69     folding_ranges::{Fold, FoldKind},
70     hover::HoverResult,
71     inlay_hints::{InlayHint, InlayKind},
72     line_index::{LineCol, LineIndex},
73     line_index_utils::translate_offset_with_edit,
74     references::{ReferenceSearchResult, SearchScope},
75     runnables::{Runnable, RunnableKind},
76     source_change::{FileSystemEdit, SourceChange, SourceFileEdit},
77     syntax_highlighting::HighlightedRange,
78 };
79
80 pub use hir::Documentation;
81 pub use ra_db::{
82     Canceled, CrateGraph, CrateId, Edition, FileId, FilePosition, FileRange, SourceRootId,
83 };
84
85 pub type Cancelable<T> = Result<T, Canceled>;
86
87 #[derive(Debug)]
88 pub struct Diagnostic {
89     pub message: String,
90     pub range: TextRange,
91     pub fix: Option<SourceChange>,
92     pub severity: Severity,
93 }
94
95 #[derive(Debug)]
96 pub struct Query {
97     query: String,
98     lowercased: String,
99     only_types: bool,
100     libs: bool,
101     exact: bool,
102     limit: usize,
103 }
104
105 impl Query {
106     pub fn new(query: String) -> Query {
107         let lowercased = query.to_lowercase();
108         Query {
109             query,
110             lowercased,
111             only_types: false,
112             libs: false,
113             exact: false,
114             limit: usize::max_value(),
115         }
116     }
117
118     pub fn only_types(&mut self) {
119         self.only_types = true;
120     }
121
122     pub fn libs(&mut self) {
123         self.libs = true;
124     }
125
126     pub fn exact(&mut self) {
127         self.exact = true;
128     }
129
130     pub fn limit(&mut self, limit: usize) {
131         self.limit = limit
132     }
133 }
134
135 /// Info associated with a text range.
136 #[derive(Debug)]
137 pub struct RangeInfo<T> {
138     pub range: TextRange,
139     pub info: T,
140 }
141
142 impl<T> RangeInfo<T> {
143     pub fn new(range: TextRange, info: T) -> RangeInfo<T> {
144         RangeInfo { range, info }
145     }
146 }
147
148 /// Contains information about a call site. Specifically the
149 /// `FunctionSignature`and current parameter.
150 #[derive(Debug)]
151 pub struct CallInfo {
152     pub signature: FunctionSignature,
153     pub active_parameter: Option<usize>,
154 }
155
156 /// `AnalysisHost` stores the current state of the world.
157 #[derive(Debug)]
158 pub struct AnalysisHost {
159     db: db::RootDatabase,
160 }
161
162 impl Default for AnalysisHost {
163     fn default() -> AnalysisHost {
164         AnalysisHost::new(None, FeatureFlags::default())
165     }
166 }
167
168 impl AnalysisHost {
169     pub fn new(lru_capcity: Option<usize>, feature_flags: FeatureFlags) -> AnalysisHost {
170         AnalysisHost { db: db::RootDatabase::new(lru_capcity, feature_flags) }
171     }
172     /// Returns a snapshot of the current state, which you can query for
173     /// semantic information.
174     pub fn analysis(&self) -> Analysis {
175         Analysis { db: self.db.snapshot() }
176     }
177
178     pub fn feature_flags(&self) -> &FeatureFlags {
179         &self.db.feature_flags
180     }
181
182     /// Applies changes to the current state of the world. If there are
183     /// outstanding snapshots, they will be canceled.
184     pub fn apply_change(&mut self, change: AnalysisChange) {
185         self.db.apply_change(change)
186     }
187
188     pub fn maybe_collect_garbage(&mut self) {
189         self.db.maybe_collect_garbage();
190     }
191
192     pub fn collect_garbage(&mut self) {
193         self.db.collect_garbage();
194     }
195     /// NB: this clears the database
196     pub fn per_query_memory_usage(&mut self) -> Vec<(String, ra_prof::Bytes)> {
197         self.db.per_query_memory_usage()
198     }
199     pub fn raw_database(
200         &self,
201     ) -> &(impl hir::db::HirDatabase + salsa::Database + ra_db::SourceDatabaseExt) {
202         &self.db
203     }
204     pub fn raw_database_mut(
205         &mut self,
206     ) -> &mut (impl hir::db::HirDatabase + salsa::Database + ra_db::SourceDatabaseExt) {
207         &mut self.db
208     }
209 }
210
211 /// Analysis is a snapshot of a world state at a moment in time. It is the main
212 /// entry point for asking semantic information about the world. When the world
213 /// state is advanced using `AnalysisHost::apply_change` method, all existing
214 /// `Analysis` are canceled (most method return `Err(Canceled)`).
215 #[derive(Debug)]
216 pub struct Analysis {
217     db: salsa::Snapshot<db::RootDatabase>,
218 }
219
220 // As a general design guideline, `Analysis` API are intended to be independent
221 // from the language server protocol. That is, when exposing some functionality
222 // we should think in terms of "what API makes most sense" and not in terms of
223 // "what types LSP uses". Although currently LSP is the only consumer of the
224 // API, the API should in theory be usable as a library, or via a different
225 // protocol.
226 impl Analysis {
227     // Creates an analysis instance for a single file, without any extenal
228     // dependencies, stdlib support or ability to apply changes. See
229     // `AnalysisHost` for creating a fully-featured analysis.
230     pub fn from_single_file(text: String) -> (Analysis, FileId) {
231         let mut host = AnalysisHost::default();
232         let source_root = SourceRootId(0);
233         let mut change = AnalysisChange::new();
234         change.add_root(source_root, true);
235         let mut crate_graph = CrateGraph::default();
236         let file_id = FileId(0);
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(file_id, Edition::Edition2018, cfg_options);
242         change.add_file(source_root, file_id, "main.rs".into(), Arc::new(text));
243         change.set_crate_graph(crate_graph);
244         host.apply_change(change);
245         (host.analysis(), file_id)
246     }
247
248     /// Features for Analysis.
249     pub fn feature_flags(&self) -> &FeatureFlags {
250         &self.db.feature_flags
251     }
252
253     /// Debug info about the current state of the analysis.
254     pub fn status(&self) -> Cancelable<String> {
255         self.with_db(|db| status::status(&*db))
256     }
257
258     /// Gets the text of the source file.
259     pub fn file_text(&self, file_id: FileId) -> Cancelable<Arc<String>> {
260         self.with_db(|db| db.file_text(file_id))
261     }
262
263     /// Gets the syntax tree of the file.
264     pub fn parse(&self, file_id: FileId) -> Cancelable<SourceFile> {
265         self.with_db(|db| db.parse(file_id).tree())
266     }
267
268     /// Gets the file's `LineIndex`: data structure to convert between absolute
269     /// offsets and line/column representation.
270     pub fn file_line_index(&self, file_id: FileId) -> Cancelable<Arc<LineIndex>> {
271         self.with_db(|db| db.line_index(file_id))
272     }
273
274     /// Selects the next syntactic nodes encompassing the range.
275     pub fn extend_selection(&self, frange: FileRange) -> Cancelable<TextRange> {
276         self.with_db(|db| extend_selection::extend_selection(db, frange))
277     }
278
279     /// Returns position of the matching brace (all types of braces are
280     /// supported).
281     pub fn matching_brace(&self, position: FilePosition) -> Cancelable<Option<TextUnit>> {
282         self.with_db(|db| {
283             let parse = db.parse(position.file_id);
284             let file = parse.tree();
285             matching_brace::matching_brace(&file, position.offset)
286         })
287     }
288
289     /// Returns a syntax tree represented as `String`, for debug purposes.
290     // FIXME: use a better name here.
291     pub fn syntax_tree(
292         &self,
293         file_id: FileId,
294         text_range: Option<TextRange>,
295     ) -> Cancelable<String> {
296         self.with_db(|db| syntax_tree::syntax_tree(&db, file_id, text_range))
297     }
298
299     /// Returns an edit to remove all newlines in the range, cleaning up minor
300     /// stuff like trailing commas.
301     pub fn join_lines(&self, frange: FileRange) -> Cancelable<SourceChange> {
302         self.with_db(|db| {
303             let parse = db.parse(frange.file_id);
304             let file_edit = SourceFileEdit {
305                 file_id: frange.file_id,
306                 edit: join_lines::join_lines(&parse.tree(), frange.range),
307             };
308             SourceChange::source_file_edit("join lines", file_edit)
309         })
310     }
311
312     /// Returns an edit which should be applied when opening a new line, fixing
313     /// up minor stuff like continuing the comment.
314     pub fn on_enter(&self, position: FilePosition) -> Cancelable<Option<SourceChange>> {
315         self.with_db(|db| typing::on_enter(&db, position))
316     }
317
318     /// Returns an edit which should be applied after a character was typed.
319     ///
320     /// This is useful for some on-the-fly fixups, like adding `;` to `let =`
321     /// automatically.
322     pub fn on_char_typed(
323         &self,
324         position: FilePosition,
325         char_typed: char,
326     ) -> Cancelable<Option<SourceChange>> {
327         // Fast path to not even parse the file.
328         if !typing::TRIGGER_CHARS.contains(char_typed) {
329             return Ok(None);
330         }
331         self.with_db(|db| typing::on_char_typed(&db, position, char_typed))
332     }
333
334     /// Returns a tree representation of symbols in the file. Useful to draw a
335     /// file outline.
336     pub fn file_structure(&self, file_id: FileId) -> Cancelable<Vec<StructureNode>> {
337         self.with_db(|db| file_structure(&db.parse(file_id).tree()))
338     }
339
340     /// Returns a list of the places in the file where type hints can be displayed.
341     pub fn inlay_hints(
342         &self,
343         file_id: FileId,
344         max_inlay_hint_length: Option<usize>,
345     ) -> Cancelable<Vec<InlayHint>> {
346         self.with_db(|db| {
347             inlay_hints::inlay_hints(db, file_id, &db.parse(file_id).tree(), max_inlay_hint_length)
348         })
349     }
350
351     /// Returns the set of folding ranges.
352     pub fn folding_ranges(&self, file_id: FileId) -> Cancelable<Vec<Fold>> {
353         self.with_db(|db| folding_ranges::folding_ranges(&db.parse(file_id).tree()))
354     }
355
356     /// Fuzzy searches for a symbol.
357     pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
358         self.with_db(|db| {
359             symbol_index::world_symbols(db, query)
360                 .into_iter()
361                 .map(|s| s.to_nav(db))
362                 .collect::<Vec<_>>()
363         })
364     }
365
366     /// Returns the definitions from the symbol at `position`.
367     pub fn goto_definition(
368         &self,
369         position: FilePosition,
370     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
371         self.with_db(|db| goto_definition::goto_definition(db, position))
372     }
373
374     /// Returns the impls from the symbol at `position`.
375     pub fn goto_implementation(
376         &self,
377         position: FilePosition,
378     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
379         self.with_db(|db| impls::goto_implementation(db, position))
380     }
381
382     /// Returns the type definitions for the symbol at `position`.
383     pub fn goto_type_definition(
384         &self,
385         position: FilePosition,
386     ) -> Cancelable<Option<RangeInfo<Vec<NavigationTarget>>>> {
387         self.with_db(|db| goto_type_definition::goto_type_definition(db, position))
388     }
389
390     /// Finds all usages of the reference at point.
391     pub fn find_all_refs(
392         &self,
393         position: FilePosition,
394         search_scope: Option<SearchScope>,
395     ) -> Cancelable<Option<ReferenceSearchResult>> {
396         self.with_db(|db| references::find_all_refs(db, position, search_scope).map(|it| it.info))
397     }
398
399     /// Returns a short text describing element at position.
400     pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<HoverResult>>> {
401         self.with_db(|db| hover::hover(db, position))
402     }
403
404     /// Computes parameter information for the given call expression.
405     pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
406         self.with_db(|db| call_info::call_info(db, position))
407     }
408
409     /// Returns a `mod name;` declaration which created the current module.
410     pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
411         self.with_db(|db| parent_module::parent_module(db, position))
412     }
413
414     /// Returns crates this file belongs too.
415     pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
416         self.with_db(|db| parent_module::crate_for(db, file_id))
417     }
418
419     /// Returns the root file of the given crate.
420     pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
421         self.with_db(|db| db.crate_graph().crate_root(crate_id))
422     }
423
424     /// Returns the set of possible targets to run for the current file.
425     pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
426         self.with_db(|db| runnables::runnables(db, file_id))
427     }
428
429     /// Computes syntax highlighting for the given file.
430     pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
431         self.with_db(|db| syntax_highlighting::highlight(db, file_id))
432     }
433
434     /// Computes syntax highlighting for the given file.
435     pub fn highlight_as_html(&self, file_id: FileId, rainbow: bool) -> Cancelable<String> {
436         self.with_db(|db| syntax_highlighting::highlight_as_html(db, file_id, rainbow))
437     }
438
439     /// Computes completions at the given position.
440     pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
441         self.with_db(|db| completion::completions(db, position).map(Into::into))
442     }
443
444     /// Computes assists (aka code actions aka intentions) for the given
445     /// position.
446     pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<Assist>> {
447         self.with_db(|db| assists::assists(db, frange))
448     }
449
450     /// Computes the set of diagnostics for the given file.
451     pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
452         self.with_db(|db| diagnostics::diagnostics(db, file_id))
453     }
454
455     /// Computes the type of the expression at the given position.
456     pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
457         self.with_db(|db| hover::type_of(db, frange))
458     }
459
460     /// Returns the edit required to rename reference at the position to the new
461     /// name.
462     pub fn rename(
463         &self,
464         position: FilePosition,
465         new_name: &str,
466     ) -> Cancelable<Option<RangeInfo<SourceChange>>> {
467         self.with_db(|db| references::rename(db, position, new_name))
468     }
469
470     /// Performs an operation on that may be Canceled.
471     fn with_db<F: FnOnce(&db::RootDatabase) -> T + std::panic::UnwindSafe, T>(
472         &self,
473         f: F,
474     ) -> Cancelable<T> {
475         self.db.catch_canceled(f)
476     }
477 }
478
479 #[test]
480 fn analysis_is_send() {
481     fn is_send<T: Send>() {}
482     is_send::<Analysis>();
483 }