Skip to main content

postgres_lsp_parse/
document.rs

1use ropey::Rope;
2use tree_sitter::{InputEdit, Point, Tree};
3
4use crate::injection::{self, InjectedRegion};
5use crate::parser::{Language, ParserPool};
6
7/// A parsed SQL or PL/pgSQL document with incremental edit support.
8///
9/// Maintains the source text, the primary parse tree, and any injected
10/// PL/pgSQL regions found within CREATE FUNCTION bodies.
11pub struct Document {
12    uri: String,
13    language: Language,
14    rope: Rope,
15    tree: Option<Tree>,
16    injections: Vec<InjectedRegion>,
17}
18
19impl Document {
20    /// Create a new document by parsing the given source text.
21    pub fn new(uri: String, text: &str, pool: &ParserPool) -> Self {
22        let language = detect_language(&uri);
23        let rope = Rope::from_str(text);
24        let mut guard = pool.acquire(language);
25        let tree = guard.parser_mut().parse(text, None);
26        drop(guard);
27
28        let injections = tree
29            .as_ref()
30            .map(|t| injection::extract_plpgsql_bodies(t, text, pool))
31            .unwrap_or_default();
32
33        Self {
34            uri,
35            language,
36            rope,
37            tree,
38            injections,
39        }
40    }
41
42    /// Apply a full-text replacement and re-parse.
43    pub fn replace_full(&mut self, new_text: &str, pool: &ParserPool) {
44        self.rope = Rope::from_str(new_text);
45        let mut guard = pool.acquire(self.language);
46        self.tree = guard.parser_mut().parse(new_text, None);
47        drop(guard);
48
49        self.injections = self
50            .tree
51            .as_ref()
52            .map(|t| injection::extract_plpgsql_bodies(t, new_text, pool))
53            .unwrap_or_default();
54    }
55
56    /// Apply an incremental edit (LSP-style line/col range) and re-parse.
57    ///
58    /// `start_line`/`start_col` and `end_line`/`end_col` are 0-based.
59    /// `new_text` is the replacement text for the range.
60    pub fn apply_edit(
61        &mut self,
62        start_line: usize,
63        start_col: usize,
64        end_line: usize,
65        end_col: usize,
66        new_text: &str,
67        pool: &ParserPool,
68    ) {
69        let start_byte = self.position_to_byte(start_line, start_col);
70        let old_end_byte = self.position_to_byte(end_line, end_col).max(start_byte);
71
72        // Compute the old positions before the rope changes. The range
73        // refers to the old text, so its lines can be past the end of the
74        // new text (for example, after a format edit removes lines).
75        // Point.column must be byte offsets, not UTF-16 code units.
76        let start_position = self.byte_to_point(start_byte);
77        let old_end_position = self.byte_to_point(old_end_byte);
78
79        // Apply the edit to the rope.
80        let start_char = self.rope.byte_to_char(start_byte);
81        let end_char = self.rope.byte_to_char(old_end_byte);
82        self.rope.remove(start_char..end_char);
83        self.rope.insert(start_char, new_text);
84
85        let new_end_byte = start_byte + new_text.len();
86        let new_end_position = self.byte_to_point(new_end_byte);
87
88        // Inform tree-sitter about the edit for incremental re-parsing.
89        if let Some(ref mut tree) = self.tree {
90            tree.edit(&InputEdit {
91                start_byte,
92                old_end_byte,
93                new_end_byte,
94                start_position,
95                old_end_position,
96                new_end_position,
97            });
98        }
99
100        // Re-parse incrementally.
101        let source = self.text();
102        let mut guard = pool.acquire(self.language);
103        self.tree = guard.parser_mut().parse(&source, self.tree.as_ref());
104        drop(guard);
105
106        self.injections = self
107            .tree
108            .as_ref()
109            .map(|t| injection::extract_plpgsql_bodies(t, &source, pool))
110            .unwrap_or_default();
111    }
112
113    pub fn uri(&self) -> &str {
114        &self.uri
115    }
116
117    pub fn language(&self) -> Language {
118        self.language
119    }
120
121    pub fn tree(&self) -> Option<&Tree> {
122        self.tree.as_ref()
123    }
124
125    /// Get the injected PL/pgSQL regions (function bodies).
126    pub fn injections(&self) -> &[InjectedRegion] {
127        &self.injections
128    }
129
130    /// Get the full source text as a String.
131    pub fn text(&self) -> String {
132        self.rope.to_string()
133    }
134
135    /// Get the underlying rope.
136    pub fn rope(&self) -> &Rope {
137        &self.rope
138    }
139
140    /// Get the LSP position of the end of the document as a 0-based
141    /// (line, utf16_col) pair.
142    pub fn end_position(&self) -> (usize, usize) {
143        let last_line = self.rope.len_lines() - 1;
144        let col = self.rope.line(last_line).chars().map(char::len_utf16).sum();
145        (last_line, col)
146    }
147
148    /// Convert a 0-based (line, utf16_col) to a byte offset.
149    ///
150    /// LSP uses UTF-16 code units for character positions, so we must
151    /// convert from UTF-16 units to byte offsets within the line.
152    fn position_to_byte(&self, line: usize, utf16_col: usize) -> usize {
153        // The position comes from the client. A line past the end maps to
154        // the end of the document, and a column past the end of the line
155        // maps to the end of the line, as the LSP specification requires.
156        let Some(line_text) = self.rope.get_line(line) else {
157            return self.rope.len_bytes();
158        };
159        let line_start = self.rope.line_to_byte(line);
160        let mut utf16_count = 0;
161        let mut byte_offset = 0;
162        for ch in line_text.chars() {
163            if utf16_count >= utf16_col || ch == '\n' || ch == '\r' {
164                break;
165            }
166            utf16_count += ch.len_utf16();
167            byte_offset += ch.len_utf8();
168        }
169        line_start + byte_offset
170    }
171
172    /// Convert a byte offset in the current rope to a tree-sitter point.
173    ///
174    /// Tree-sitter counts only LF as a line break. Ropey also counts CR,
175    /// U+2028 and other separators, so we do not use the rope line index.
176    // ponytail: O(n) scan per call, the re-parse after each edit is O(n) too.
177    fn byte_to_point(&self, byte: usize) -> Point {
178        let mut point = Point { row: 0, column: 0 };
179        for chunk in self.rope.byte_slice(..byte).chunks() {
180            for b in chunk.bytes() {
181                if b == b'\n' {
182                    point.row += 1;
183                    point.column = 0;
184                } else {
185                    point.column += 1;
186                }
187            }
188        }
189        point
190    }
191
192    /// Collect all ERROR and MISSING nodes from the parse tree and injected regions.
193    pub fn errors(&self) -> Vec<ParseError> {
194        let Some(tree) = &self.tree else {
195            return vec![];
196        };
197        let mut errors = Vec::new();
198        collect_errors(tree.root_node(), &mut errors);
199
200        // Collect errors from injected PL/pgSQL regions.
201        let source = self.text();
202        for region in &self.injections {
203            let mut injection_errors = Vec::new();
204            collect_errors(region.tree.root_node(), &mut injection_errors);
205
206            // Map injection-local positions to parent document positions.
207            let (parent_line, parent_col) = region.parent_position(&source);
208
209            for mut err in injection_errors {
210                if err.start_line == 0 {
211                    err.start_col += parent_col;
212                }
213                if err.end_line == 0 {
214                    err.end_col += parent_col;
215                }
216                err.start_line += parent_line;
217                err.end_line += parent_line;
218                errors.push(err);
219            }
220        }
221
222        errors
223    }
224}
225
226/// A parse error with position information.
227#[derive(Debug, Clone)]
228pub struct ParseError {
229    pub start_line: usize,
230    pub start_col: usize,
231    pub end_line: usize,
232    pub end_col: usize,
233    pub message: String,
234}
235
236fn collect_errors(node: tree_sitter::Node, errors: &mut Vec<ParseError>) {
237    if node.is_error() {
238        errors.push(ParseError {
239            start_line: node.start_position().row,
240            start_col: node.start_position().column,
241            end_line: node.end_position().row,
242            end_col: node.end_position().column,
243            message: format!("Syntax error: unexpected `{}`", node.kind()),
244        });
245    } else if node.is_missing() {
246        errors.push(ParseError {
247            start_line: node.start_position().row,
248            start_col: node.start_position().column,
249            end_line: node.end_position().row,
250            end_col: node.end_position().column,
251            message: format!("Missing `{}`", node.kind()),
252        });
253    }
254
255    let mut cursor = node.walk();
256    for child in node.children(&mut cursor) {
257        collect_errors(child, errors);
258    }
259}
260
261/// Detect the language from a file URI or path.
262fn detect_language(uri: &str) -> Language {
263    if uri.ends_with(".plpgsql") || uri.ends_with(".plsql") {
264        Language::PlPgSql
265    } else {
266        // Default to PostgreSQL SQL for .sql and everything else.
267        Language::Postgres
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn parse_simple_select() {
277        let pool = ParserPool::new();
278        let doc = Document::new("test.sql".into(), "SELECT 1;", &pool);
279        assert!(doc.tree().is_some());
280        assert!(doc.errors().is_empty());
281    }
282
283    #[test]
284    fn parse_error_reported() {
285        let pool = ParserPool::new();
286        let doc = Document::new("test.sql".into(), "SELECTZ 1;", &pool);
287        let errors = doc.errors();
288        assert!(!errors.is_empty(), "expected parse errors for invalid SQL");
289    }
290
291    #[test]
292    fn incremental_edit() {
293        let pool = ParserPool::new();
294        let mut doc = Document::new("test.sql".into(), "SELECT 1;", &pool);
295
296        // Change "1" to "42"
297        doc.apply_edit(0, 7, 0, 8, "42", &pool);
298        assert_eq!(doc.text(), "SELECT 42;");
299        assert!(doc.tree().is_some());
300        assert!(doc.errors().is_empty());
301    }
302
303    #[test]
304    fn full_replace() {
305        let pool = ParserPool::new();
306        let mut doc = Document::new("test.sql".into(), "SELECT 1;", &pool);
307        doc.replace_full("INSERT INTO t VALUES (1);", &pool);
308        assert_eq!(doc.text(), "INSERT INTO t VALUES (1);");
309        assert!(doc.tree().is_some());
310    }
311
312    #[test]
313    fn multiline_edit() {
314        let pool = ParserPool::new();
315        let mut doc = Document::new("test.sql".into(), "SELECT\n  1\nFROM\n  t;", &pool);
316        // Replace "1" with "a, b"
317        doc.apply_edit(1, 2, 1, 3, "a, b", &pool);
318        assert_eq!(doc.text(), "SELECT\n  a, b\nFROM\n  t;");
319        assert!(doc.tree().is_some());
320    }
321
322    #[test]
323    fn detect_language_from_extension() {
324        assert_eq!(detect_language("file.sql"), Language::Postgres);
325        assert_eq!(detect_language("file.plpgsql"), Language::PlPgSql);
326        assert_eq!(detect_language("file.plsql"), Language::PlPgSql);
327        assert_eq!(
328            detect_language("file:///path/to/schema.sql"),
329            Language::Postgres
330        );
331    }
332
333    #[test]
334    fn plpgsql_injections_detected() {
335        let pool = ParserPool::new();
336        let sql = r#"CREATE FUNCTION test() RETURNS void LANGUAGE plpgsql AS $$
337BEGIN
338  RAISE NOTICE 'hello';
339END;
340$$;"#;
341        let doc = Document::new("test.sql".into(), sql, &pool);
342        assert!(doc.tree().is_some());
343        assert!(
344            !doc.injections().is_empty(),
345            "should detect PL/pgSQL injection"
346        );
347        assert!(doc.injections()[0].text.contains("BEGIN"));
348    }
349
350    #[test]
351    fn no_injections_in_plain_sql() {
352        let pool = ParserPool::new();
353        let doc = Document::new("test.sql".into(), "SELECT 1;", &pool);
354        assert!(doc.injections().is_empty());
355    }
356
357    /// Regression test for issue #8. A client applies a whole-document
358    /// format edit and then sends the edit back as an incremental change.
359    /// The range uses line numbers of the old text, which has more lines
360    /// than the new text.
361    #[test]
362    fn edit_that_removes_lines() {
363        let pool = ParserPool::new();
364        let old: String = (0..12).map(|i| format!("SELECT {i};\n")).collect();
365        let mut doc = Document::new("test.sql".into(), &old, &pool);
366        assert_eq!(doc.rope().len_lines(), 13);
367
368        let new: String = (0..8).map(|i| format!("SELECT {i};\n")).collect();
369        doc.apply_edit(0, 0, 12, 0, &new, &pool);
370        assert_eq!(doc.text(), new);
371        assert!(doc.errors().is_empty());
372    }
373
374    #[test]
375    fn edit_that_removes_lines_crlf() {
376        let pool = ParserPool::new();
377        let old: String = (0..12).map(|i| format!("SELECT {i};\r\n")).collect();
378        let mut doc = Document::new("test.sql".into(), &old, &pool);
379
380        let new: String = (0..8).map(|i| format!("SELECT {i};\r\n")).collect();
381        doc.apply_edit(0, 0, 12, 0, &new, &pool);
382        assert_eq!(doc.text(), new);
383        assert!(doc.errors().is_empty());
384    }
385
386    #[test]
387    fn edit_that_removes_lines_in_middle() {
388        let pool = ParserPool::new();
389        let mut doc = Document::new("test.sql".into(), "SELECT\n  a,\n  b,\n  c\nFROM t;", &pool);
390        doc.apply_edit(1, 0, 4, 0, "  x\n", &pool);
391        assert_eq!(doc.text(), "SELECT\n  x\nFROM t;");
392        assert!(doc.errors().is_empty());
393    }
394
395    #[test]
396    fn edit_with_positions_past_end_does_not_panic() {
397        let pool = ParserPool::new();
398        let mut doc = Document::new("test.sql".into(), "SELECT 1;\n", &pool);
399        // Line past the end clamps to the end of the document.
400        doc.apply_edit(50, 0, 99, 7, "SELECT 2;", &pool);
401        assert_eq!(doc.text(), "SELECT 1;\nSELECT 2;");
402        // Column past the end of a line clamps to the end of that line.
403        doc.apply_edit(0, 100, 0, 200, " -- x", &pool);
404        assert_eq!(doc.text(), "SELECT 1; -- x\nSELECT 2;");
405        // A start after the end does not panic.
406        doc.apply_edit(1, 5, 0, 0, "", &pool);
407        assert!(doc.tree().is_some());
408    }
409
410    #[test]
411    fn end_position() {
412        let pool = ParserPool::new();
413        let doc = Document::new("test.sql".into(), "", &pool);
414        assert_eq!(doc.end_position(), (0, 0));
415        let doc = Document::new("test.sql".into(), "SELECT 1;\n", &pool);
416        assert_eq!(doc.end_position(), (1, 0));
417        let doc = Document::new("test.sql".into(), "SELECT 1;\r\nSELECT 'é😀';", &pool);
418        // UTF-16 length of the last line: "SELECT 'é😀';" is 13 code units.
419        assert_eq!(doc.end_position(), (1, 13));
420    }
421
422    /// Ropey counts a bare CR and U+2028 as line breaks, but tree-sitter
423    /// counts only LF. Tree-sitter points must count only LF.
424    #[test]
425    fn byte_to_point_counts_only_lf() {
426        let pool = ParserPool::new();
427        let mut doc = Document::new("test.sql".into(), "SELECT 1;\n", &pool);
428        doc.apply_edit(1, 0, 1, 0, "SELECT 'a\rb\u{2028}c';\nSELECT 2;", &pool);
429        let text = doc.text();
430        assert_eq!(doc.byte_to_point(text.len()), Point { row: 2, column: 9 });
431        let tree = doc.tree().unwrap();
432        assert_eq!(tree.root_node().end_position(), Point { row: 2, column: 9 });
433    }
434}