aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api/src/lib.rs
diff options
context:
space:
mode:
authorbors[bot] <bors[bot]@users.noreply.github.com>2019-01-08 19:48:48 +0000
committerbors[bot] <bors[bot]@users.noreply.github.com>2019-01-08 19:48:48 +0000
commit46f74e33ca53a7897e9020d3de75cc76a6b89d79 (patch)
tree2bc001c8ecf58b49ac9a0da1f20d5644ce29fb3a /crates/ra_ide_api/src/lib.rs
parent4f4f7933b1b7ff34f8633b1686b18b2d1b994c47 (diff)
parent0c62b1bb7a49bf527780ce1f8cade5eb4fbfdb2d (diff)
Merge #471
471: rename crates to match reality r=matklad a=matklad Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates/ra_ide_api/src/lib.rs')
-rw-r--r--crates/ra_ide_api/src/lib.rs515
1 files changed, 515 insertions, 0 deletions
diff --git a/crates/ra_ide_api/src/lib.rs b/crates/ra_ide_api/src/lib.rs
new file mode 100644
index 000000000..7e9ca2034
--- /dev/null
+++ b/crates/ra_ide_api/src/lib.rs
@@ -0,0 +1,515 @@
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//! The sibling `ra_ide_api_light` handles thouse bits of IDE functionality
11//! which are restricted to a single file and need only syntax.
12macro_rules! ctry {
13 ($expr:expr) => {
14 match $expr {
15 None => return Ok(None),
16 Some(it) => it,
17 }
18 };
19}
20
21mod completion;
22mod db;
23mod goto_defenition;
24mod imp;
25pub mod mock_analysis;
26mod runnables;
27mod symbol_index;
28
29mod extend_selection;
30mod hover;
31mod call_info;
32mod syntax_highlighting;
33
34use std::{fmt, sync::Arc};
35
36use ra_syntax::{SmolStr, SourceFile, TreePtr, SyntaxKind, TextRange, TextUnit};
37use ra_text_edit::TextEdit;
38use ra_db::{SyntaxDatabase, FilesDatabase, LocalSyntaxPtr};
39use rayon::prelude::*;
40use relative_path::RelativePathBuf;
41use rustc_hash::FxHashMap;
42use salsa::ParallelDatabase;
43
44use crate::{
45 symbol_index::{FileSymbol, SymbolIndex},
46 db::LineIndexDatabase,
47};
48
49pub use crate::{
50 completion::{CompletionItem, CompletionItemKind, InsertText},
51 runnables::{Runnable, RunnableKind},
52};
53pub use ra_ide_api_light::{
54 Fold, FoldKind, HighlightedRange, Severity, StructureNode,
55 LineIndex, LineCol, translate_offset_with_edit,
56};
57pub use ra_db::{
58 Cancelable, Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId
59};
60
61#[derive(Default)]
62pub struct AnalysisChange {
63 new_roots: Vec<(SourceRootId, bool)>,
64 roots_changed: FxHashMap<SourceRootId, RootChange>,
65 files_changed: Vec<(FileId, Arc<String>)>,
66 libraries_added: Vec<LibraryData>,
67 crate_graph: Option<CrateGraph>,
68}
69
70#[derive(Default)]
71struct RootChange {
72 added: Vec<AddFile>,
73 removed: Vec<RemoveFile>,
74}
75
76#[derive(Debug)]
77struct AddFile {
78 file_id: FileId,
79 path: RelativePathBuf,
80 text: Arc<String>,
81}
82
83#[derive(Debug)]
84struct RemoveFile {
85 file_id: FileId,
86 path: RelativePathBuf,
87}
88
89impl fmt::Debug for AnalysisChange {
90 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
91 let mut d = fmt.debug_struct("AnalysisChange");
92 if !self.new_roots.is_empty() {
93 d.field("new_roots", &self.new_roots);
94 }
95 if !self.roots_changed.is_empty() {
96 d.field("roots_changed", &self.roots_changed);
97 }
98 if !self.files_changed.is_empty() {
99 d.field("files_changed", &self.files_changed.len());
100 }
101 if !self.libraries_added.is_empty() {
102 d.field("libraries_added", &self.libraries_added.len());
103 }
104 if !self.crate_graph.is_some() {
105 d.field("crate_graph", &self.crate_graph);
106 }
107 d.finish()
108 }
109}
110
111impl fmt::Debug for RootChange {
112 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
113 fmt.debug_struct("AnalysisChange")
114 .field("added", &self.added.len())
115 .field("removed", &self.removed.len())
116 .finish()
117 }
118}
119
120impl AnalysisChange {
121 pub fn new() -> AnalysisChange {
122 AnalysisChange::default()
123 }
124 pub fn add_root(&mut self, root_id: SourceRootId, is_local: bool) {
125 self.new_roots.push((root_id, is_local));
126 }
127 pub fn add_file(
128 &mut self,
129 root_id: SourceRootId,
130 file_id: FileId,
131 path: RelativePathBuf,
132 text: Arc<String>,
133 ) {
134 let file = AddFile {
135 file_id,
136 path,
137 text,
138 };
139 self.roots_changed
140 .entry(root_id)
141 .or_default()
142 .added
143 .push(file);
144 }
145 pub fn change_file(&mut self, file_id: FileId, new_text: Arc<String>) {
146 self.files_changed.push((file_id, new_text))
147 }
148 pub fn remove_file(&mut self, root_id: SourceRootId, file_id: FileId, path: RelativePathBuf) {
149 let file = RemoveFile { file_id, path };
150 self.roots_changed
151 .entry(root_id)
152 .or_default()
153 .removed
154 .push(file);
155 }
156 pub fn add_library(&mut self, data: LibraryData) {
157 self.libraries_added.push(data)
158 }
159 pub fn set_crate_graph(&mut self, graph: CrateGraph) {
160 self.crate_graph = Some(graph);
161 }
162}
163
164#[derive(Debug)]
165pub struct SourceChange {
166 pub label: String,
167 pub source_file_edits: Vec<SourceFileEdit>,
168 pub file_system_edits: Vec<FileSystemEdit>,
169 pub cursor_position: Option<FilePosition>,
170}
171
172#[derive(Debug)]
173pub struct SourceFileEdit {
174 pub file_id: FileId,
175 pub edit: TextEdit,
176}
177
178#[derive(Debug)]
179pub enum FileSystemEdit {
180 CreateFile {
181 source_root: SourceRootId,
182 path: RelativePathBuf,
183 },
184 MoveFile {
185 src: FileId,
186 dst_source_root: SourceRootId,
187 dst_path: RelativePathBuf,
188 },
189}
190
191#[derive(Debug)]
192pub struct Diagnostic {
193 pub message: String,
194 pub range: TextRange,
195 pub fix: Option<SourceChange>,
196 pub severity: Severity,
197}
198
199#[derive(Debug)]
200pub struct Query {
201 query: String,
202 lowercased: String,
203 only_types: bool,
204 libs: bool,
205 exact: bool,
206 limit: usize,
207}
208
209impl Query {
210 pub fn new(query: String) -> Query {
211 let lowercased = query.to_lowercase();
212 Query {
213 query,
214 lowercased,
215 only_types: false,
216 libs: false,
217 exact: false,
218 limit: usize::max_value(),
219 }
220 }
221 pub fn only_types(&mut self) {
222 self.only_types = true;
223 }
224 pub fn libs(&mut self) {
225 self.libs = true;
226 }
227 pub fn exact(&mut self) {
228 self.exact = true;
229 }
230 pub fn limit(&mut self, limit: usize) {
231 self.limit = limit
232 }
233}
234
235/// `NavigationTarget` represents and element in the editor's UI whihc you can
236/// click on to navigate to a particular piece of code.
237///
238/// Typically, a `NavigationTarget` corresponds to some element in the source
239/// code, like a function or a struct, but this is not strictly required.
240#[derive(Debug, Clone)]
241pub struct NavigationTarget {
242 file_id: FileId,
243 name: SmolStr,
244 kind: SyntaxKind,
245 range: TextRange,
246 // Should be DefId ideally
247 ptr: Option<LocalSyntaxPtr>,
248}
249
250impl NavigationTarget {
251 fn from_symbol(symbol: FileSymbol) -> NavigationTarget {
252 NavigationTarget {
253 file_id: symbol.file_id,
254 name: symbol.name.clone(),
255 kind: symbol.ptr.kind(),
256 range: symbol.ptr.range(),
257 ptr: Some(symbol.ptr.clone()),
258 }
259 }
260 pub fn name(&self) -> &SmolStr {
261 &self.name
262 }
263 pub fn kind(&self) -> SyntaxKind {
264 self.kind
265 }
266 pub fn file_id(&self) -> FileId {
267 self.file_id
268 }
269 pub fn range(&self) -> TextRange {
270 self.range
271 }
272}
273
274#[derive(Debug)]
275pub struct RangeInfo<T> {
276 pub range: TextRange,
277 pub info: T,
278}
279
280impl<T> RangeInfo<T> {
281 fn new(range: TextRange, info: T) -> RangeInfo<T> {
282 RangeInfo { range, info }
283 }
284}
285
286#[derive(Debug)]
287pub struct CallInfo {
288 pub label: String,
289 pub doc: Option<String>,
290 pub parameters: Vec<String>,
291 pub active_parameter: Option<usize>,
292}
293
294/// `AnalysisHost` stores the current state of the world.
295#[derive(Debug, Default)]
296pub struct AnalysisHost {
297 db: db::RootDatabase,
298}
299
300impl AnalysisHost {
301 /// Returns a snapshot of the current state, which you can query for
302 /// semantic information.
303 pub fn analysis(&self) -> Analysis {
304 Analysis {
305 db: self.db.snapshot(),
306 }
307 }
308 /// Applies changes to the current state of the world. If there are
309 /// outstanding snapshots, they will be canceled.
310 pub fn apply_change(&mut self, change: AnalysisChange) {
311 self.db.apply_change(change)
312 }
313}
314
315/// Analysis is a snapshot of a world state at a moment in time. It is the main
316/// entry point for asking semantic information about the world. When the world
317/// state is advanced using `AnalysisHost::apply_change` method, all existing
318/// `Analysis` are canceled (most method return `Err(Canceled)`).
319#[derive(Debug)]
320pub struct Analysis {
321 db: salsa::Snapshot<db::RootDatabase>,
322}
323
324impl Analysis {
325 /// Gets the text of the source file.
326 pub fn file_text(&self, file_id: FileId) -> Arc<String> {
327 self.db.file_text(file_id)
328 }
329 /// Gets the syntax tree of the file.
330 pub fn file_syntax(&self, file_id: FileId) -> TreePtr<SourceFile> {
331 self.db.source_file(file_id).clone()
332 }
333 /// Gets the file's `LineIndex`: data structure to convert between absolute
334 /// offsets and line/column representation.
335 pub fn file_line_index(&self, file_id: FileId) -> Arc<LineIndex> {
336 self.db.line_index(file_id)
337 }
338 /// Selects the next syntactic nodes encopasing the range.
339 pub fn extend_selection(&self, frange: FileRange) -> TextRange {
340 extend_selection::extend_selection(&self.db, frange)
341 }
342 /// Returns position of the mathcing brace (all types of braces are
343 /// supported).
344 pub fn matching_brace(&self, file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
345 ra_ide_api_light::matching_brace(file, offset)
346 }
347 /// Returns a syntax tree represented as `String`, for debug purposes.
348 // FIXME: use a better name here.
349 pub fn syntax_tree(&self, file_id: FileId) -> String {
350 let file = self.db.source_file(file_id);
351 ra_ide_api_light::syntax_tree(&file)
352 }
353 /// Returns an edit to remove all newlines in the range, cleaning up minor
354 /// stuff like trailing commas.
355 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
356 let file = self.db.source_file(frange.file_id);
357 SourceChange::from_local_edit(
358 frange.file_id,
359 ra_ide_api_light::join_lines(&file, frange.range),
360 )
361 }
362 /// Returns an edit which should be applied when opening a new line, fixing
363 /// up minor stuff like continuing the comment.
364 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
365 let file = self.db.source_file(position.file_id);
366 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
367 Some(SourceChange::from_local_edit(position.file_id, edit))
368 }
369 /// Returns an edit which should be applied after `=` was typed. Primarily,
370 /// this works when adding `let =`.
371 // FIXME: use a snippet completion instead of this hack here.
372 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
373 let file = self.db.source_file(position.file_id);
374 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?;
375 Some(SourceChange::from_local_edit(position.file_id, edit))
376 }
377 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
378 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
379 let file = self.db.source_file(position.file_id);
380 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
381 Some(SourceChange::from_local_edit(position.file_id, edit))
382 }
383 /// Returns a tree representation of symbols in the file. Useful to draw a
384 /// file outline.
385 pub fn file_structure(&self, file_id: FileId) -> Vec<StructureNode> {
386 let file = self.db.source_file(file_id);
387 ra_ide_api_light::file_structure(&file)
388 }
389 /// Returns the set of folding ranges.
390 pub fn folding_ranges(&self, file_id: FileId) -> Vec<Fold> {
391 let file = self.db.source_file(file_id);
392 ra_ide_api_light::folding_ranges(&file)
393 }
394 /// Fuzzy searches for a symbol.
395 pub fn symbol_search(&self, query: Query) -> Cancelable<Vec<NavigationTarget>> {
396 let res = symbol_index::world_symbols(&*self.db, query)?
397 .into_iter()
398 .map(NavigationTarget::from_symbol)
399 .collect();
400 Ok(res)
401 }
402 pub fn goto_defenition(
403 &self,
404 position: FilePosition,
405 ) -> Cancelable<Option<Vec<NavigationTarget>>> {
406 goto_defenition::goto_defenition(&*self.db, position)
407 }
408 /// Finds all usages of the reference at point.
409 pub fn find_all_refs(&self, position: FilePosition) -> Cancelable<Vec<(FileId, TextRange)>> {
410 self.db.find_all_refs(position)
411 }
412 /// Returns a short text descrbing element at position.
413 pub fn hover(&self, position: FilePosition) -> Cancelable<Option<RangeInfo<String>>> {
414 hover::hover(&*self.db, position)
415 }
416 /// Computes parameter information for the given call expression.
417 pub fn call_info(&self, position: FilePosition) -> Cancelable<Option<CallInfo>> {
418 call_info::call_info(&*self.db, position)
419 }
420 /// Returns a `mod name;` declaration which created the current module.
421 pub fn parent_module(&self, position: FilePosition) -> Cancelable<Vec<NavigationTarget>> {
422 self.db.parent_module(position)
423 }
424 /// Returns crates this file belongs too.
425 pub fn crate_for(&self, file_id: FileId) -> Cancelable<Vec<CrateId>> {
426 self.db.crate_for(file_id)
427 }
428 /// Returns the root file of the given crate.
429 pub fn crate_root(&self, crate_id: CrateId) -> Cancelable<FileId> {
430 Ok(self.db.crate_graph().crate_root(crate_id))
431 }
432 /// Returns the set of possible targets to run for the current file.
433 pub fn runnables(&self, file_id: FileId) -> Cancelable<Vec<Runnable>> {
434 runnables::runnables(&*self.db, file_id)
435 }
436 /// Computes syntax highlighting for the given file.
437 pub fn highlight(&self, file_id: FileId) -> Cancelable<Vec<HighlightedRange>> {
438 syntax_highlighting::highlight(&*self.db, file_id)
439 }
440 /// Computes completions at the given position.
441 pub fn completions(&self, position: FilePosition) -> Cancelable<Option<Vec<CompletionItem>>> {
442 let completions = completion::completions(&self.db, position)?;
443 Ok(completions.map(|it| it.into()))
444 }
445 /// Computes assists (aks code actons aka intentions) for the given
446 /// position.
447 pub fn assists(&self, frange: FileRange) -> Cancelable<Vec<SourceChange>> {
448 Ok(self.db.assists(frange))
449 }
450 /// Computes the set of diagnostics for the given file.
451 pub fn diagnostics(&self, file_id: FileId) -> Cancelable<Vec<Diagnostic>> {
452 self.db.diagnostics(file_id)
453 }
454 /// Computes the type of the expression at the given position.
455 pub fn type_of(&self, frange: FileRange) -> Cancelable<Option<String>> {
456 hover::type_of(&*self.db, frange)
457 }
458 /// Returns the edit required to rename reference at the position to the new
459 /// name.
460 pub fn rename(
461 &self,
462 position: FilePosition,
463 new_name: &str,
464 ) -> Cancelable<Vec<SourceFileEdit>> {
465 self.db.rename(position, new_name)
466 }
467}
468
469pub struct LibraryData {
470 root_id: SourceRootId,
471 root_change: RootChange,
472 symbol_index: SymbolIndex,
473}
474
475impl fmt::Debug for LibraryData {
476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
477 f.debug_struct("LibraryData")
478 .field("root_id", &self.root_id)
479 .field("root_change", &self.root_change)
480 .field("n_symbols", &self.symbol_index.len())
481 .finish()
482 }
483}
484
485impl LibraryData {
486 pub fn prepare(
487 root_id: SourceRootId,
488 files: Vec<(FileId, RelativePathBuf, Arc<String>)>,
489 ) -> LibraryData {
490 let symbol_index = SymbolIndex::for_files(files.par_iter().map(|(file_id, _, text)| {
491 let file = SourceFile::parse(text);
492 (*file_id, file)
493 }));
494 let mut root_change = RootChange::default();
495 root_change.added = files
496 .into_iter()
497 .map(|(file_id, path, text)| AddFile {
498 file_id,
499 path,
500 text,
501 })
502 .collect();
503 LibraryData {
504 root_id,
505 root_change,
506 symbol_index,
507 }
508 }
509}
510
511#[test]
512fn analysis_is_send() {
513 fn is_send<T: Send>() {}
514 is_send::<Analysis>();
515}