postgres_lsp_parse/
injection.rs1use tree_sitter::{Node, Tree};
2
3use crate::parser::{Language, ParserPool};
4
5#[derive(Debug)]
11pub struct InjectedRegion {
12 pub parent_start_byte: usize,
14 pub language: Language,
16 pub tree: Tree,
18 pub text: String,
20}
21
22impl InjectedRegion {
23 pub fn to_parent_byte(&self, local_byte: usize) -> usize {
25 self.parent_start_byte + local_byte
26 }
27
28 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 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
52pub 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 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
91fn is_plpgsql_function_body(node: Node, source: &str) -> bool {
97 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 has_language_plpgsql(stmt, source)
123}
124
125fn 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 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
163fn 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
182fn extract_dollar_quote_content(node: Node, source: &str) -> Option<DollarQuoteContent> {
189 let full = node.utf8_text(source.as_bytes()).ok()?;
190
191 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 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 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}