Skip to main content

postgres_lsp_parse/
injection.rs

1use tree_sitter::{Node, Tree};
2
3use crate::parser::{Language, ParserPool};
4
5/// An injected parse region — a sub-tree parsed with a different language.
6///
7/// For example, a PL/pgSQL function body inside a CREATE FUNCTION statement
8/// is parsed with the plpgsql grammar, and SQL expressions within PL/pgSQL
9/// are injected back with the postgres grammar.
10#[derive(Debug)]
11pub struct InjectedRegion {
12    /// Byte offset of this region within the parent document.
13    pub parent_start_byte: usize,
14    /// The language of the injected region.
15    pub language: Language,
16    /// The parse tree for the injected content.
17    pub tree: Tree,
18    /// The source text of the injected region.
19    pub text: String,
20}
21
22impl InjectedRegion {
23    /// Convert a byte offset within this injected region to the parent document offset.
24    pub fn to_parent_byte(&self, local_byte: usize) -> usize {
25        self.parent_start_byte + local_byte
26    }
27
28    /// Compute the (line, column) of this region's start within the parent document.
29    pub fn parent_position(&self, source: &str) -> (usize, usize) {
30        let parent_line = source[..self.parent_start_byte].matches('\n').count();
31        let parent_col = self.parent_start_byte
32            - source[..self.parent_start_byte]
33                .rfind('\n')
34                .map(|p| p + 1)
35                .unwrap_or(0);
36        (parent_line, parent_col)
37    }
38
39    /// Convert a parent document byte offset to a local offset within this region.
40    /// Returns None if the parent offset is outside this region.
41    pub fn to_local_byte(&self, parent_byte: usize) -> Option<usize> {
42        if parent_byte >= self.parent_start_byte
43            && parent_byte < self.parent_start_byte + self.text.len()
44        {
45            Some(parent_byte - self.parent_start_byte)
46        } else {
47            None
48        }
49    }
50}
51
52/// Find dollar-quoted string bodies in CREATE FUNCTION/PROCEDURE statements
53/// and parse them with the PL/pgSQL grammar.
54///
55/// This handles the first level of injection: SQL -> PL/pgSQL.
56pub fn extract_plpgsql_bodies(tree: &Tree, source: &str, pool: &ParserPool) -> Vec<InjectedRegion> {
57    let mut regions = Vec::new();
58    find_dollar_quoted_bodies(tree.root_node(), source, pool, &mut regions);
59    regions
60}
61
62fn find_dollar_quoted_bodies(
63    node: Node,
64    source: &str,
65    pool: &ParserPool,
66    regions: &mut Vec<InjectedRegion>,
67) {
68    // Look for dollar_quoted_string nodes inside function/procedure definitions
69    // that have LANGUAGE plpgsql.
70    if node.kind() == "dollar_quoted_string"
71        && is_plpgsql_function_body(node, source)
72        && let Some(body) = extract_dollar_quote_content(node, source)
73    {
74        let mut guard = pool.acquire(Language::PlPgSql);
75        if let Some(tree) = guard.parser_mut().parse(&body.text, None) {
76            regions.push(InjectedRegion {
77                parent_start_byte: body.start_byte,
78                language: Language::PlPgSql,
79                tree,
80                text: body.text,
81            });
82        }
83    }
84
85    let mut cursor = node.walk();
86    for child in node.children(&mut cursor) {
87        find_dollar_quoted_bodies(child, source, pool, regions);
88    }
89}
90
91/// Check if a dollar_quoted_string node is the function body in the AS clause
92/// of a CreateFunctionStmt whose LANGUAGE is plpgsql.
93///
94/// Expected tree path: dollar_quoted_string → Sconst → func_as →
95/// createfunc_opt_item (with kw_as) → createfunc_opt_list → ... → CreateFunctionStmt
96fn is_plpgsql_function_body(node: Node, source: &str) -> bool {
97    // Walk up to verify the node is inside a func_as (the AS clause body).
98    let func_stmt = {
99        let mut current = node.parent();
100        let mut found_func_as = false;
101        let mut result = None;
102        while let Some(p) = current {
103            if p.kind() == "func_as" {
104                found_func_as = true;
105            }
106            if p.kind() == "CreateFunctionStmt" {
107                if found_func_as {
108                    result = Some(p);
109                }
110                break;
111            }
112            current = p.parent();
113        }
114        result
115    };
116
117    let Some(stmt) = func_stmt else {
118        return false;
119    };
120
121    // Find the LANGUAGE option structurally in the CreateFunctionStmt.
122    has_language_plpgsql(stmt, source)
123}
124
125/// Check if a CreateFunctionStmt has LANGUAGE plpgsql by walking its
126/// createfunc_opt_item children looking for kw_language followed by
127/// a NonReservedWord_or_Sconst containing "plpgsql".
128fn has_language_plpgsql(stmt: Node, source: &str) -> bool {
129    fn check_opt_items(node: Node, source: &str) -> bool {
130        if node.kind() == "createfunc_opt_item" {
131            let mut found_language = false;
132            let mut cursor = node.walk();
133            for child in node.children(&mut cursor) {
134                if child.kind() == "kw_language" {
135                    found_language = true;
136                }
137                if found_language
138                    && (child.kind() == "NonReservedWord_or_Sconst"
139                        || child.kind() == "NonReservedWord"
140                        || child.kind() == "identifier")
141                {
142                    let text = child.utf8_text(source.as_bytes()).unwrap_or("");
143                    // Recurse into wrapper nodes to find the leaf identifier.
144                    let lang = extract_leaf_text(child, source).unwrap_or(text);
145                    if lang.eq_ignore_ascii_case("plpgsql") {
146                        return true;
147                    }
148                }
149            }
150            return false;
151        }
152        let mut cursor = node.walk();
153        for child in node.children(&mut cursor) {
154            if check_opt_items(child, source) {
155                return true;
156            }
157        }
158        false
159    }
160    check_opt_items(stmt, source)
161}
162
163/// Extract the deepest leaf text from a node (finds identifier or keyword).
164fn extract_leaf_text<'a>(node: Node<'a>, source: &'a str) -> Option<&'a str> {
165    if node.child_count() == 0 {
166        return node.utf8_text(source.as_bytes()).ok();
167    }
168    let mut cursor = node.walk();
169    for child in node.children(&mut cursor) {
170        if let Some(text) = extract_leaf_text(child, source) {
171            return Some(text);
172        }
173    }
174    None
175}
176
177struct DollarQuoteContent {
178    start_byte: usize,
179    text: String,
180}
181
182/// Extract the content between dollar-quote delimiters.
183/// E.g., `$$BEGIN ... END;$$` -> `BEGIN ... END;`
184///
185/// Note: `rfind` is safe here because tree-sitter already parsed the outer
186/// `dollar_quoted_string` node boundary. Any nested dollar-quotes with
187/// different tags (e.g., `$inner$...$inner$`) will be part of the content.
188fn extract_dollar_quote_content(node: Node, source: &str) -> Option<DollarQuoteContent> {
189    let full = node.utf8_text(source.as_bytes()).ok()?;
190
191    // Find the opening delimiter ($$, $tag$, etc.)
192    let first_dollar = full.find('$')?;
193    let delim_end = full[first_dollar + 1..].find('$')? + first_dollar + 2;
194    let delimiter = &full[first_dollar..delim_end];
195
196    // Find the closing delimiter (last occurrence, which is the outer close)
197    let content_start = delim_end;
198    let content_end = full.rfind(delimiter)?;
199    if content_end <= content_start {
200        return None;
201    }
202
203    let text = full[content_start..content_end].to_string();
204    let start_byte = node.start_byte() + content_start;
205
206    Some(DollarQuoteContent { start_byte, text })
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn extract_plpgsql_from_create_function() {
215        let pool = ParserPool::new();
216        let source = r#"CREATE FUNCTION test() RETURNS void LANGUAGE plpgsql AS $$
217BEGIN
218  RAISE NOTICE 'hello';
219END;
220$$;"#;
221
222        let mut guard = pool.acquire(Language::Postgres);
223        let tree = guard.parser_mut().parse(source, None).unwrap();
224        drop(guard);
225
226        let regions = extract_plpgsql_bodies(&tree, source, &pool);
227        assert!(!regions.is_empty(), "should find PL/pgSQL body");
228        assert_eq!(regions[0].language, Language::PlPgSql);
229        assert!(regions[0].text.contains("BEGIN"));
230        assert!(regions[0].text.contains("RAISE NOTICE"));
231    }
232
233    #[test]
234    fn offset_mapping() {
235        let region = InjectedRegion {
236            parent_start_byte: 100,
237            language: Language::PlPgSql,
238            tree: {
239                let pool = ParserPool::new();
240                let mut guard = pool.acquire(Language::PlPgSql);
241                guard.parser_mut().parse("BEGIN\nEND;", None).unwrap()
242            },
243            text: "BEGIN\nEND;".to_string(),
244        };
245
246        assert_eq!(region.to_parent_byte(0), 100);
247        assert_eq!(region.to_parent_byte(5), 105);
248        assert_eq!(region.to_local_byte(100), Some(0));
249        assert_eq!(region.to_local_byte(105), Some(5));
250        assert_eq!(region.to_local_byte(99), None);
251        assert_eq!(region.to_local_byte(110), None);
252    }
253
254    #[test]
255    fn dollar_quoted_set_value_not_injected() {
256        let pool = ParserPool::new();
257        let source = "SET search_path = $$public$$;";
258
259        let mut guard = pool.acquire(Language::Postgres);
260        let tree = guard.parser_mut().parse(source, None).unwrap();
261        drop(guard);
262
263        let regions = extract_plpgsql_bodies(&tree, source, &pool);
264        assert!(
265            regions.is_empty(),
266            "dollar-quoted SET value should not be treated as PL/pgSQL"
267        );
268    }
269
270    #[test]
271    fn sql_language_function_not_injected() {
272        let pool = ParserPool::new();
273        // Function whose body mentions "LANGUAGE plpgsql" in a string but
274        // whose actual LANGUAGE is sql — should NOT be treated as PL/pgSQL.
275        let source =
276            r#"CREATE FUNCTION test() RETURNS text LANGUAGE sql AS $$SELECT 'LANGUAGE plpgsql'$$;"#;
277
278        let mut guard = pool.acquire(Language::Postgres);
279        let tree = guard.parser_mut().parse(source, None).unwrap();
280        drop(guard);
281
282        let regions = extract_plpgsql_bodies(&tree, source, &pool);
283        assert!(
284            regions.is_empty(),
285            "LANGUAGE sql function should not be treated as PL/pgSQL"
286        );
287    }
288}