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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use arret_syntax::span::Span;

#[derive(Debug)]
pub struct Document {
    version: i32,
    text: String,
    line_offsets: Vec<usize>,
}

fn line_offsets_for_str(source: &str) -> Vec<usize> {
    std::iter::once(0)
        .chain(source.match_indices('\n').map(|(i, _)| i + 1))
        .collect()
}

impl Document {
    pub fn new(version: i32, text: String) -> Document {
        Document {
            version,
            line_offsets: line_offsets_for_str(&text),
            text,
        }
    }

    /// Returns a new instance of the document with specified range replaced
    pub fn with_range_edit(
        &self,
        new_version: i32,
        range: lsp_types::Range,
        new_range_text: &str,
    ) -> Result<Document, ()> {
        let start_offset = if let Some(start_offset) = self.position_to_offset(range.start) {
            start_offset
        } else {
            return Err(());
        };

        let end_offset = self.position_to_offset(range.end);

        // Rebuild the new text
        let mut new_text = self.text[..start_offset].to_string() + new_range_text;
        if let Some(end_offset) = end_offset {
            new_text += &self.text[end_offset..];
        }

        // Preserve the line offsets from before the edit
        let mut new_line_offsets = (&self.line_offsets[..=range.start.line as usize]).to_vec();

        // Add the line offsets inside the new range
        new_line_offsets.extend(
            new_range_text
                .match_indices('\n')
                .map(|(i, _)| i + start_offset + 1),
        );

        if let Some(end_offset) = end_offset {
            // Shift the remaining offsets to account for the size of the new range
            let previous_len = end_offset - start_offset;
            new_line_offsets.extend(
                self.line_offsets[range.end.line as usize + 1..]
                    .iter()
                    .map(|i| i + new_range_text.len() - previous_len),
            )
        }

        Ok(Document {
            version: new_version,
            line_offsets: new_line_offsets,
            text: new_text,
        })
    }

    /// Returns the document version
    pub fn version(&self) -> i32 {
        self.version
    }

    /// Returns the document text
    pub fn text(&self) -> &str {
        self.text.as_ref()
    }

    /// Returns an LSP `Range` for the given `arret-syntax` S`pan`
    pub fn span_to_range(&self, span: Span) -> lsp_types::Range {
        lsp_types::Range {
            start: self.offset_to_position(span.start() as usize),
            end: self.offset_to_position(span.end() as usize),
        }
    }

    /// Returns the position for the given byte offset
    pub fn offset_to_position(&self, offset: usize) -> lsp_types::Position {
        let line = match self
            .line_offsets
            .binary_search_by(|line_start| line_start.cmp(&offset))
        {
            Ok(line) => line,
            Err(line) => line - 1,
        };

        let line_start = self.line_offsets[line];
        let character: usize = self.text[line_start..offset]
            .chars()
            .map(|c| c.len_utf16())
            .sum();

        lsp_types::Position {
            line: line as u32,
            character: character as u32,
        }
    }

    /// Returns the byte offset for the given position
    fn position_to_offset(&self, position: lsp_types::Position) -> Option<usize> {
        // Lines are already computed
        let line_offset = *self.line_offsets.get(position.line as usize)?;

        if position.character == 0 {
            return Some(line_offset);
        }

        let mut utf16_chars_remaining = position.character as usize;

        for (char_offset, c) in self.text[line_offset..].char_indices() {
            utf16_chars_remaining -= c.len_utf16();

            if utf16_chars_remaining == 0 {
                return Some(line_offset + char_offset + c.len_utf8());
            }
        }

        // Ran out of string
        None
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn assert_consistency(doc: &Document) {
        assert_eq!(line_offsets_for_str(&doc.text), doc.line_offsets);
    }

    #[test]
    fn test_positions() {
        let doc = Document::new(1, "Hello 💣\nNext line\n".into());

        assert_eq!(
            lsp_types::Position {
                line: 0,
                character: 0
            },
            doc.offset_to_position(0)
        );

        assert_eq!(
            lsp_types::Position {
                line: 0,
                character: 6
            },
            doc.offset_to_position(6)
        );

        assert_eq!(
            lsp_types::Position {
                line: 0,
                character: 8
            },
            doc.offset_to_position(10)
        );

        assert_eq!(
            lsp_types::Position {
                line: 1,
                character: 0
            },
            doc.offset_to_position(11)
        );

        assert_eq!(
            lsp_types::Position {
                line: 2,
                character: 0
            },
            doc.offset_to_position(21)
        );
    }

    #[test]
    fn test_append_to_empty() {
        let doc = Document::new(1, "".into())
            .with_range_edit(
                2,
                lsp_types::Range {
                    start: lsp_types::Position {
                        line: 0,
                        character: 0,
                    },
                    end: lsp_types::Position {
                        line: 0,
                        character: 7,
                    },
                },
                "abc-123",
            )
            .unwrap();

        assert_eq!(&doc.text, "abc-123");
        assert_consistency(&doc);
    }

    #[test]
    fn test_append_to_line() {
        let doc = Document::new(1, "Hello".into())
            .with_range_edit(
                2,
                lsp_types::Range {
                    start: lsp_types::Position {
                        line: 0,
                        character: 5,
                    },
                    end: lsp_types::Position {
                        line: 0,
                        character: 5,
                    },
                },
                ", world!",
            )
            .unwrap();

        assert_eq!(&doc.text, "Hello, world!");
        assert_consistency(&doc);
    }

    #[test]
    fn test_erase_all() {
        let doc = Document::new(1, "abc-123".into())
            .with_range_edit(
                2,
                lsp_types::Range {
                    start: lsp_types::Position {
                        line: 0,
                        character: 0,
                    },
                    end: lsp_types::Position {
                        line: 0,
                        character: 7,
                    },
                },
                "",
            )
            .unwrap();

        assert_eq!(&doc.text, "");
        assert_consistency(&doc);
    }

    #[test]
    fn test_replace_line() {
        let doc = Document::new(1, "hello\nnebraska\n".into())
            .with_range_edit(
                2,
                lsp_types::Range {
                    start: lsp_types::Position {
                        line: 1,
                        character: 0,
                    },
                    end: lsp_types::Position {
                        line: 1,
                        character: 8,
                    },
                },
                "world",
            )
            .unwrap();

        assert_eq!(&doc.text, "hello\nworld\n");
        assert_consistency(&doc);
    }

    #[test]
    fn test_insert_line() {
        let doc = Document::new(1, "hello\nworld\n".into())
            .with_range_edit(
                2,
                lsp_types::Range {
                    start: lsp_types::Position {
                        line: 1,
                        character: 0,
                    },
                    end: lsp_types::Position {
                        line: 1,
                        character: 0,
                    },
                },
                "entire\n",
            )
            .unwrap();

        assert_eq!(&doc.text, "hello\nentire\nworld\n");
        assert_consistency(&doc);
    }

    #[test]
    fn test_delete_line() {
        let doc = Document::new(1, "hello\nentire\nworld\n".into())
            .with_range_edit(
                2,
                lsp_types::Range {
                    start: lsp_types::Position {
                        line: 1,
                        character: 0,
                    },
                    end: lsp_types::Position {
                        line: 2,
                        character: 0,
                    },
                },
                "",
            )
            .unwrap();

        assert_eq!(&doc.text, "hello\nworld\n");
        assert_consistency(&doc);
    }

    #[test]
    fn test_delete_utf16() {
        let doc = Document::new(1, "Defuse 💣 me".into())
            .with_range_edit(
                2,
                lsp_types::Range {
                    start: lsp_types::Position {
                        line: 0,
                        character: 7,
                    },
                    end: lsp_types::Position {
                        line: 0,
                        character: 10,
                    },
                },
                "",
            )
            .unwrap();

        assert_eq!(&doc.text, "Defuse me");
        assert_consistency(&doc);
    }
}