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 len = self.rope.len_bytes();
70        let start_byte = self.position_to_byte(start_line, start_col).min(len);
71        let old_end_byte = self.position_to_byte(end_line, end_col).min(len);
72
73        // Apply the edit to the rope.
74        let start_char = self.rope.byte_to_char(start_byte);
75        let end_char = self.rope.byte_to_char(old_end_byte);
76        self.rope.remove(start_char..end_char);
77        self.rope.insert(start_char, new_text);
78
79        let new_end_byte = start_byte + new_text.len();
80        let new_end_line = self.rope.byte_to_line(new_end_byte);
81        let new_end_col = new_end_byte - self.rope.line_to_byte(new_end_line);
82
83        // Inform tree-sitter about the edit for incremental re-parsing.
84        // Point.column must be byte offsets, not UTF-16 code units.
85        let start_byte_col = start_byte - self.rope.line_to_byte(start_line);
86        let old_end_byte_col = old_end_byte - self.rope.line_to_byte(end_line);
87        if let Some(ref mut tree) = self.tree {
88            tree.edit(&InputEdit {
89                start_byte,
90                old_end_byte,
91                new_end_byte,
92                start_position: Point {
93                    row: start_line,
94                    column: start_byte_col,
95                },
96                old_end_position: Point {
97                    row: end_line,
98                    column: old_end_byte_col,
99                },
100                new_end_position: Point {
101                    row: new_end_line,
102                    column: new_end_col,
103                },
104            });
105        }
106
107        // Re-parse incrementally.
108        let source = self.text();
109        let mut guard = pool.acquire(self.language);
110        self.tree = guard.parser_mut().parse(&source, self.tree.as_ref());
111        drop(guard);
112
113        self.injections = self
114            .tree
115            .as_ref()
116            .map(|t| injection::extract_plpgsql_bodies(t, &source, pool))
117            .unwrap_or_default();
118    }
119
120    pub fn uri(&self) -> &str {
121        &self.uri
122    }
123
124    pub fn language(&self) -> Language {
125        self.language
126    }
127
128    pub fn tree(&self) -> Option<&Tree> {
129        self.tree.as_ref()
130    }
131
132    /// Get the injected PL/pgSQL regions (function bodies).
133    pub fn injections(&self) -> &[InjectedRegion] {
134        &self.injections
135    }
136
137    /// Get the full source text as a String.
138    pub fn text(&self) -> String {
139        self.rope.to_string()
140    }
141
142    /// Get the underlying rope.
143    pub fn rope(&self) -> &Rope {
144        &self.rope
145    }
146
147    /// Convert a 0-based (line, utf16_col) to a byte offset.
148    ///
149    /// LSP uses UTF-16 code units for character positions, so we must
150    /// convert from UTF-16 units to byte offsets within the line.
151    fn position_to_byte(&self, line: usize, utf16_col: usize) -> usize {
152        let line_start = self.rope.line_to_byte(line);
153        let line_text = self.rope.line(line);
154        let mut utf16_count = 0;
155        let mut byte_offset = 0;
156        for ch in line_text.chars() {
157            if utf16_count >= utf16_col {
158                break;
159            }
160            utf16_count += ch.len_utf16();
161            byte_offset += ch.len_utf8();
162        }
163        line_start + byte_offset
164    }
165
166    /// Collect all ERROR and MISSING nodes from the parse tree and injected regions.
167    pub fn errors(&self) -> Vec<ParseError> {
168        let Some(tree) = &self.tree else {
169            return vec![];
170        };
171        let mut errors = Vec::new();
172        collect_errors(tree.root_node(), &mut errors);
173
174        // Collect errors from injected PL/pgSQL regions.
175        let source = self.text();
176        for region in &self.injections {
177            let mut injection_errors = Vec::new();
178            collect_errors(region.tree.root_node(), &mut injection_errors);
179
180            // Map injection-local positions to parent document positions.
181            let (parent_line, parent_col) = region.parent_position(&source);
182
183            for mut err in injection_errors {
184                if err.start_line == 0 {
185                    err.start_col += parent_col;
186                }
187                if err.end_line == 0 {
188                    err.end_col += parent_col;
189                }
190                err.start_line += parent_line;
191                err.end_line += parent_line;
192                errors.push(err);
193            }
194        }
195
196        errors
197    }
198}
199
200/// A parse error with position information.
201#[derive(Debug, Clone)]
202pub struct ParseError {
203    pub start_line: usize,
204    pub start_col: usize,
205    pub end_line: usize,
206    pub end_col: usize,
207    pub message: String,
208}
209
210fn collect_errors(node: tree_sitter::Node, errors: &mut Vec<ParseError>) {
211    if node.is_error() {
212        errors.push(ParseError {
213            start_line: node.start_position().row,
214            start_col: node.start_position().column,
215            end_line: node.end_position().row,
216            end_col: node.end_position().column,
217            message: format!("Syntax error: unexpected `{}`", node.kind()),
218        });
219    } else if node.is_missing() {
220        errors.push(ParseError {
221            start_line: node.start_position().row,
222            start_col: node.start_position().column,
223            end_line: node.end_position().row,
224            end_col: node.end_position().column,
225            message: format!("Missing `{}`", node.kind()),
226        });
227    }
228
229    let mut cursor = node.walk();
230    for child in node.children(&mut cursor) {
231        collect_errors(child, errors);
232    }
233}
234
235/// Detect the language from a file URI or path.
236fn detect_language(uri: &str) -> Language {
237    if uri.ends_with(".plpgsql") || uri.ends_with(".plsql") {
238        Language::PlPgSql
239    } else {
240        // Default to PostgreSQL SQL for .sql and everything else.
241        Language::Postgres
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn parse_simple_select() {
251        let pool = ParserPool::new();
252        let doc = Document::new("test.sql".into(), "SELECT 1;", &pool);
253        assert!(doc.tree().is_some());
254        assert!(doc.errors().is_empty());
255    }
256
257    #[test]
258    fn parse_error_reported() {
259        let pool = ParserPool::new();
260        let doc = Document::new("test.sql".into(), "SELECTZ 1;", &pool);
261        let errors = doc.errors();
262        assert!(!errors.is_empty(), "expected parse errors for invalid SQL");
263    }
264
265    #[test]
266    fn incremental_edit() {
267        let pool = ParserPool::new();
268        let mut doc = Document::new("test.sql".into(), "SELECT 1;", &pool);
269
270        // Change "1" to "42"
271        doc.apply_edit(0, 7, 0, 8, "42", &pool);
272        assert_eq!(doc.text(), "SELECT 42;");
273        assert!(doc.tree().is_some());
274        assert!(doc.errors().is_empty());
275    }
276
277    #[test]
278    fn full_replace() {
279        let pool = ParserPool::new();
280        let mut doc = Document::new("test.sql".into(), "SELECT 1;", &pool);
281        doc.replace_full("INSERT INTO t VALUES (1);", &pool);
282        assert_eq!(doc.text(), "INSERT INTO t VALUES (1);");
283        assert!(doc.tree().is_some());
284    }
285
286    #[test]
287    fn multiline_edit() {
288        let pool = ParserPool::new();
289        let mut doc = Document::new("test.sql".into(), "SELECT\n  1\nFROM\n  t;", &pool);
290        // Replace "1" with "a, b"
291        doc.apply_edit(1, 2, 1, 3, "a, b", &pool);
292        assert_eq!(doc.text(), "SELECT\n  a, b\nFROM\n  t;");
293        assert!(doc.tree().is_some());
294    }
295
296    #[test]
297    fn detect_language_from_extension() {
298        assert_eq!(detect_language("file.sql"), Language::Postgres);
299        assert_eq!(detect_language("file.plpgsql"), Language::PlPgSql);
300        assert_eq!(detect_language("file.plsql"), Language::PlPgSql);
301        assert_eq!(
302            detect_language("file:///path/to/schema.sql"),
303            Language::Postgres
304        );
305    }
306
307    #[test]
308    fn plpgsql_injections_detected() {
309        let pool = ParserPool::new();
310        let sql = r#"CREATE FUNCTION test() RETURNS void LANGUAGE plpgsql AS $$
311BEGIN
312  RAISE NOTICE 'hello';
313END;
314$$;"#;
315        let doc = Document::new("test.sql".into(), sql, &pool);
316        assert!(doc.tree().is_some());
317        assert!(
318            !doc.injections().is_empty(),
319            "should detect PL/pgSQL injection"
320        );
321        assert!(doc.injections()[0].text.contains("BEGIN"));
322    }
323
324    #[test]
325    fn no_injections_in_plain_sql() {
326        let pool = ParserPool::new();
327        let doc = Document::new("test.sql".into(), "SELECT 1;", &pool);
328        assert!(doc.injections().is_empty());
329    }
330}