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