-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindexing.rs
More file actions
205 lines (168 loc) · 5.78 KB
/
indexing.rs
File metadata and controls
205 lines (168 loc) · 5.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use crate::{
errors::Errors,
indexing::{local_graph::LocalGraph, rbs_indexer::RBSIndexer, ruby_indexer::RubyIndexer},
job_queue::{Job, JobQueue},
model::graph::Graph,
};
use crossbeam_channel::{Sender, unbounded};
use std::{ffi::OsStr, fs, path::PathBuf, sync::Arc};
use url::Url;
pub mod local_graph;
pub mod rbs_indexer;
pub mod ruby_indexer;
/// The language of a source document, used to dispatch to the appropriate indexer
pub enum LanguageId {
Ruby,
Rbs,
}
impl From<&OsStr> for LanguageId {
fn from(ext: &OsStr) -> Self {
if ext == "rbs" { Self::Rbs } else { Self::Ruby }
}
}
impl LanguageId {
/// Determines the language from an LSP language ID string.
///
/// # Errors
///
/// Returns an error if the language ID is not recognized.
pub fn from_language_id(language_id: &str) -> Result<Self, Errors> {
match language_id {
"ruby" => Ok(Self::Ruby),
"rbs" => Ok(Self::Rbs),
_ => Err(Errors::FileError(format!("Unsupported language_id `{language_id}`"))),
}
}
}
/// Job that indexes a single file
pub struct IndexingJob {
path: PathBuf,
local_graph_tx: Sender<LocalGraph>,
errors_tx: Sender<Errors>,
}
impl IndexingJob {
#[must_use]
pub fn new(path: PathBuf, local_graph_tx: Sender<LocalGraph>, errors_tx: Sender<Errors>) -> Self {
Self {
path,
local_graph_tx,
errors_tx,
}
}
fn send_error(&self, error: Errors) {
self.errors_tx
.send(error)
.expect("errors receiver dropped before run completion");
}
}
impl Job for IndexingJob {
fn run(&self) {
let Ok(source) = fs::read_to_string(&self.path) else {
self.send_error(Errors::FileError(format!(
"Failed to read file `{}`",
self.path.display()
)));
return;
};
let Ok(url) = Url::from_file_path(&self.path) else {
self.send_error(Errors::FileError(format!(
"Couldn't build URI from path `{}`",
self.path.display()
)));
return;
};
let language = self.path.extension().map_or(LanguageId::Ruby, LanguageId::from);
let local_graph = build_local_graph(url.to_string(), &source, &language);
self.local_graph_tx
.send(local_graph)
.expect("graph receiver dropped before merge");
}
}
/// Indexes a single source string in memory, dispatching to the appropriate indexer based on `language_id`.
pub fn index_source(graph: &mut Graph, uri: &str, source: &str, language_id: &LanguageId) {
let local_graph = build_local_graph(uri.to_string(), source, language_id);
graph.consume_document_changes(local_graph);
}
/// Indexes the given paths, reading the content from disk and populating the given `Graph` instance.
///
/// # Panics
///
/// Will panic if the graph cannot be wrapped in an Arc<Mutex<>>
pub fn index_files(graph: &mut Graph, paths: Vec<PathBuf>) -> Vec<Errors> {
let queue = Arc::new(JobQueue::new());
let (local_graphs_tx, local_graphs_rx) = unbounded();
let (errors_tx, errors_rx) = unbounded();
for path in paths {
queue.push(Box::new(IndexingJob::new(
path,
local_graphs_tx.clone(),
errors_tx.clone(),
)));
}
drop(local_graphs_tx);
drop(errors_tx);
JobQueue::run(&queue);
while let Ok(local_graph) = local_graphs_rx.recv() {
graph.consume_document_changes(local_graph);
}
errors_rx.iter().collect()
}
/// Indexes a source string using the appropriate indexer for the given language.
fn build_local_graph(uri: String, source: &str, language: &LanguageId) -> LocalGraph {
match language {
LanguageId::Ruby => {
let mut indexer = RubyIndexer::new(uri, source);
indexer.index();
indexer.local_graph()
}
LanguageId::Rbs => {
let mut indexer = RBSIndexer::new(uri, source);
indexer.index();
indexer.local_graph()
}
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
use crate::test_utils::Context;
use std::path::Path;
#[test]
fn index_relative_paths() {
let relative_path = Path::new("foo").join("bar.rb");
let context = Context::new();
context.touch(&relative_path);
let working_directory = std::env::current_dir().unwrap();
let absolute_path = context.absolute_path_to("foo/bar.rb");
let mut dots = PathBuf::from("..");
for _ in 0..working_directory.components().count() - 1 {
dots = dots.join("..");
}
let relative_to_pwd = &dots.join(absolute_path);
let mut graph = Graph::new();
let errors = index_files(&mut graph, vec![relative_to_pwd.clone()]);
assert!(errors.is_empty());
assert_eq!(graph.documents().len(), 1);
}
#[test]
fn from_language_id_unknown() {
let result = LanguageId::from_language_id("python");
assert!(result.is_err());
}
#[test]
fn updating_document_from_in_memory_source() {
let context = Context::new();
let path = context.absolute_path_to("foo/bar.rb");
context.write(&path, "class Foo; end");
let uri = Url::from_file_path(&path).unwrap().to_string();
let mut graph = Graph::new();
let errors = index_files(&mut graph, vec![path]);
assert!(errors.is_empty(), "Expected no errors, got: {errors:#?}");
assert_eq!(1, graph.definitions().len());
assert_eq!(1, graph.documents().len());
index_source(&mut graph, &uri, "", &LanguageId::Ruby);
assert_eq!(0, graph.definitions().len());
assert_eq!(1, graph.documents().len());
}
}