forked from SpaceManiac/SpacemanDMM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocument.rs
269 lines (233 loc) · 8.44 KB
/
document.rs
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//! Utilities for managing the text document synchronization facilities of the
//! language server protocol.
#![allow(dead_code)]
use std::io::{self, Read, BufRead};
use std::borrow::Cow;
use std::collections::HashMap;
use std::rc::Rc;
use url::Url;
use jsonrpc;
use lsp_types::{TextDocumentItem, TextDocumentIdentifier,
VersionedTextDocumentIdentifier, TextDocumentContentChangeEvent};
use super::{invalid_request, url_to_path};
/// A store for the contents of currently-open documents, with appropriate
/// fallback for documents which are not currently open.
#[derive(Default)]
pub struct DocumentStore {
map: HashMap<Url, Document>,
}
impl DocumentStore {
pub fn open(&mut self, doc: TextDocumentItem) -> Result<(), jsonrpc::Error> {
match self.map.insert(doc.uri.clone(), Document::new(doc.version, doc.text)) {
None => Ok(()),
Some(_) => Err(invalid_request(format!("opened twice: {}", doc.uri))),
}
}
pub fn close(&mut self, id: TextDocumentIdentifier) -> Result<Url, jsonrpc::Error> {
match self.map.remove(&id.uri) {
Some(_) => Ok(id.uri),
None => Err(invalid_request(format!("cannot close non-opened: {}", id.uri))),
}
}
pub fn change(
&mut self,
doc_id: VersionedTextDocumentIdentifier,
changes: Vec<TextDocumentContentChangeEvent>,
) -> Result<Url, jsonrpc::Error> {
// "If a versioned text document identifier is sent from the server to
// the client and the file is not open in the editor (the server has
// not received an open notification before) the server can send `null`
// to indicate that the version is known and the content on disk is the
// truth (as speced with document content ownership)."
let new_version = match doc_id.version {
Some(version) => version,
None => return Err(invalid_request("document version is missing")),
};
let document = match self.map.get_mut(&doc_id.uri) {
Some(doc) => doc,
None => return Err(invalid_request(format!("cannot change non-opened: {}", doc_id.uri))),
};
if new_version < document.version {
eprintln!("new_version: {} < document_version: {}", new_version, document.version);
return Err(invalid_request("document version numbers shouldn't go backwards"));
}
document.version = new_version;
// Make an effort to apply all changes, even if one failed.
let mut result = Ok(doc_id.uri);
for change in changes {
if let Err(e) = document.change(change) {
result = Err(e);
}
}
result
}
pub fn get_contents<'a>(&'a self, url: &Url) -> io::Result<Cow<'a, str>> {
if let Some(document) = self.map.get(url) {
return Ok(Cow::Borrowed(&document.text));
}
if let Ok(path) = url_to_path(url) {
let mut text = String::new();
let mut file = std::fs::File::open(path)?;
file.read_to_string(&mut text)?;
return Ok(Cow::Owned(text));
}
Err(io::Error::new(io::ErrorKind::NotFound,
format!("URL not opened and schema is not 'file': {}", url)))
}
pub fn read(&self, url: &Url) -> io::Result<Box<dyn io::Read>> {
if let Some(document) = self.map.get(url) {
return Ok(Box::new(Cursor::new(document.text.clone())) as Box<dyn io::Read>);
}
if let Ok(path) = url_to_path(url) {
let file = std::fs::File::open(path)?;
return Ok(Box::new(file) as Box<dyn io::Read>);
}
Err(io::Error::new(io::ErrorKind::NotFound,
format!("URL not opened and schema is not 'file': {}", url)))
}
}
/// The internal representation of document contents received from the client.
struct Document {
version: i64,
text: Rc<String>,
}
impl Document {
fn new(version: i64, text: String) -> Document {
Document {
version,
text: Rc::new(text),
}
}
fn change(&mut self, change: TextDocumentContentChangeEvent) -> Result<(), jsonrpc::Error> {
// rangeLength is deprecated: https://github.com/Microsoft/language-server-protocol/issues/9
let range = match change.range {
Some(range) => range,
_ => {
// "If range and rangeLength are omitted the new text is
// considered to be the full content of the document."
self.text = Rc::new(change.text);
return Ok(());
}
};
let start_pos = total_offset(&self.text, range.start.line, range.start.character)?;
let end_pos = total_offset(&self.text, range.end.line, range.end.character)?;
Rc::make_mut(&mut self.text).replace_range(start_pos..end_pos, &change.text);
Ok(())
}
}
/// Find the offset into the given text at which the given zero-indexed line
/// number begins.
fn line_offset(text: &str, line_number: u64) -> Result<usize, jsonrpc::Error> {
// Hopefully this logic isn't too far off.
let mut start_pos = 0;
for _ in 0..line_number {
match text[start_pos..].find('\n') {
Some(next_pos) => start_pos += next_pos + 1,
None => return Err(invalid_request("line number apparently out of range")),
}
}
Ok(start_pos)
}
fn total_offset(text: &str, line: u64, mut character: u64) -> Result<usize, jsonrpc::Error> {
let start = line_offset(text, line)?;
// column is measured in UTF-16 code units, which is really inconvenient.
let mut chars = text[start..].chars();
while character > 0 {
if let Some(ch) = chars.next() {
character = character.saturating_sub(ch.len_utf16() as u64);
} else {
break
}
}
Ok(text.len() - chars.as_str().len())
}
// Reverse of the above.
pub fn offset_to_position(text: &str, offset: usize) -> lsp_types::Position {
let mut line = 0;
let mut line_start = 0;
loop {
match text[line_start..].find('\n') {
Some(next_pos) if line_start + next_pos < offset => line_start += next_pos + 1,
_ => break,
}
line += 1;
}
let mut character = 0;
for ch in text[line_start..offset].chars() {
character += ch.len_utf16() as u64;
}
lsp_types::Position { line, character }
}
pub fn get_range(text: &str, range: lsp_types::Range) -> Result<&str, jsonrpc::Error> {
Ok(&text[
total_offset(text, range.start.line, range.start.character)?
..total_offset(text, range.end.line, range.end.character)?
])
}
pub fn find_word(text: &str, offset: usize) -> &str {
// go left as far as we can
let mut start = offset;
loop {
let mut start_next = start - 1;
while !text.is_char_boundary(start_next) {
start_next -= 1;
}
if !text[start_next..start].chars().next().map_or(false, is_ident) {
break;
}
start = start_next;
}
// go right as far as we can
let mut end = offset;
loop {
let mut end_next = end + 1;
while !text.is_char_boundary(end_next) {
end_next += 1;
}
if !text[end..end_next].chars().next().map_or(false, is_ident) {
break;
}
end = end_next;
}
if start == end {
""
} else {
&text[start..end]
}
}
fn is_ident(ch: char) -> bool {
(ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'
}
/// An adaptation of `std::io::Cursor` which works on an `Rc<String>`, which
/// sadly does not satisfy `AsRef<u8>`.
struct Cursor {
inner: Rc<String>,
pos: u64,
}
impl Cursor {
fn new(inner: Rc<String>) -> Cursor {
Cursor { inner, pos: 0 }
}
}
impl Read for Cursor {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let n = Read::read(&mut self.fill_buf()?, buf)?;
self.pos += n as u64;
Ok(n)
}
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
let n = buf.len();
Read::read_exact(&mut self.fill_buf()?, buf)?;
self.pos += n as u64;
Ok(())
}
}
impl BufRead for Cursor {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
let amt = std::cmp::min(self.pos, self.inner.as_ref().len() as u64);
Ok(&self.inner.as_bytes()[(amt as usize)..])
}
fn consume(&mut self, amt: usize) {
self.pos += amt as u64;
}
}