1use tree_sitter::{Node, Tree};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5pub enum SymbolKind {
6 Schema,
7 Table,
8 View,
9 MaterializedView,
10 Column,
11 Function,
12 Procedure,
13 Trigger,
14 Index,
15 Sequence,
16 Type,
17 Domain,
18 Extension,
19 Role,
20 Policy,
21 Publication,
22 Subscription,
23 ForeignTable,
24 Variable,
25 Cursor,
26}
27
28impl SymbolKind {
29 pub fn label(&self) -> &'static str {
30 match self {
31 Self::Schema => "schema",
32 Self::Table => "table",
33 Self::View => "view",
34 Self::MaterializedView => "materialized view",
35 Self::Column => "column",
36 Self::Function => "function",
37 Self::Procedure => "procedure",
38 Self::Trigger => "trigger",
39 Self::Index => "index",
40 Self::Sequence => "sequence",
41 Self::Type => "type",
42 Self::Domain => "domain",
43 Self::Extension => "extension",
44 Self::Role => "role",
45 Self::Policy => "policy",
46 Self::Publication => "publication",
47 Self::Subscription => "subscription",
48 Self::ForeignTable => "foreign table",
49 Self::Variable => "variable",
50 Self::Cursor => "cursor",
51 }
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Hash)]
57pub struct QualifiedName {
58 pub schema: Option<String>,
59 pub name: String,
60}
61
62impl QualifiedName {
63 pub fn new(name: String) -> Self {
64 Self { schema: None, name }
65 }
66
67 pub fn with_schema(schema: String, name: String) -> Self {
68 Self {
69 schema: Some(schema),
70 name,
71 }
72 }
73
74 pub fn display(&self) -> String {
75 match &self.schema {
76 Some(s) => format!("{s}.{}", self.name),
77 None => self.name.clone(),
78 }
79 }
80}
81
82#[derive(Debug, Clone)]
84pub struct Symbol {
85 pub kind: SymbolKind,
86 pub name: QualifiedName,
87 pub uri: String,
88 pub start_byte: usize,
90 pub end_byte: usize,
91 pub start_line: usize,
92 pub start_col: usize,
93 pub end_line: usize,
94 pub end_col: usize,
95 pub name_start_line: usize,
97 pub name_start_col: usize,
98 pub name_end_line: usize,
99 pub name_end_col: usize,
100 pub definition_text: String,
101 pub children: Vec<Symbol>,
102}
103
104#[derive(Debug, Clone)]
106pub struct SymbolRef {
107 pub name: QualifiedName,
109 pub uri: String,
111 pub start_byte: usize,
113 pub end_byte: usize,
114 pub start_line: usize,
116 pub start_col: usize,
117 pub end_line: usize,
118 pub end_col: usize,
119}
120
121pub fn extract_symbols(tree: &Tree, source: &str, uri: &str) -> Vec<Symbol> {
123 let mut symbols = Vec::new();
124 collect_definitions(tree.root_node(), source, uri, &mut symbols);
125 symbols
126}
127
128fn collect_definitions(node: Node, source: &str, uri: &str, symbols: &mut Vec<Symbol>) {
133 if let Some(symbol) = try_extract_definition(node, source, uri) {
134 symbols.push(symbol);
135 return; }
137
138 let mut cursor = node.walk();
139 for child in node.children(&mut cursor) {
140 collect_definitions(child, source, uri, symbols);
141 }
142}
143
144fn try_extract_definition(node: Node, source: &str, uri: &str) -> Option<Symbol> {
146 let result: Option<(SymbolKind, QualifiedName, Node)> = match node.kind() {
148 "CreateStmt" => find_descendant(node, "qualified_name").and_then(|n| {
149 extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Table, qn, n))
150 }),
151 "CreateMatViewStmt" => find_descendant(node, "qualified_name").and_then(|n| {
152 extract_qualified_name_node(n, source).map(|qn| (SymbolKind::MaterializedView, qn, n))
153 }),
154 "ViewStmt" => find_descendant(node, "qualified_name").and_then(|n| {
155 extract_qualified_name_node(n, source).map(|qn| (SymbolKind::View, qn, n))
156 }),
157 "CreateFunctionStmt" => {
158 let kind = if has_child_kind(node, "kw_procedure") {
159 SymbolKind::Procedure
160 } else {
161 SymbolKind::Function
162 };
163 find_descendant(node, "func_name")
164 .and_then(|n| extract_func_name(n, source).map(|qn| (kind, qn, n)))
165 }
166 "IndexStmt" => extract_name_or_col_id(node, source, SymbolKind::Index),
167 "CreateSeqStmt" => find_descendant(node, "qualified_name").and_then(|n| {
168 extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Sequence, qn, n))
169 }),
170 "CreateSchemaStmt" => find_descendant(node, "ColId")
171 .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Schema, qn, n))),
172 "CompositeTypeStmt" | "CreateEnumStmt" | "CreateRangeStmt" => {
173 find_descendant(node, "any_name")
174 .and_then(|n| {
175 extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Type, qn, n))
176 })
177 .or_else(|| {
178 find_descendant(node, "qualified_name").and_then(|n| {
179 extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Type, qn, n))
180 })
181 })
182 }
183 "CreateDomainStmt" => find_descendant(node, "any_name").and_then(|n| {
184 extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Domain, qn, n))
185 }),
186 "CreateExtensionStmt" => extract_name_or_col_id(node, source, SymbolKind::Extension),
187 "CreateTrigStmt" => extract_name_or_col_id(node, source, SymbolKind::Trigger),
188 "CreateRoleStmt" => find_descendant(node, "RoleId")
189 .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Role, qn, n)))
190 .or_else(|| {
191 find_descendant(node, "ColId")
192 .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Role, qn, n)))
193 }),
194 "CreatePolicyStmt" => find_descendant(node, "name")
195 .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Policy, qn, n))),
196 "CreatePublicationStmt" => find_descendant(node, "ColId")
197 .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Publication, qn, n))),
198 "CreateSubscriptionStmt" => find_descendant(node, "ColId")
199 .and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Subscription, qn, n))),
200 "CreateForeignTableStmt" => find_descendant(node, "qualified_name").and_then(|n| {
201 extract_qualified_name_node(n, source).map(|qn| (SymbolKind::ForeignTable, qn, n))
202 }),
203 _ => None,
204 };
205
206 let (kind, name, name_node) = result?;
207 let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
208
209 let mut symbol = Symbol {
210 kind,
211 name,
212 uri: uri.to_string(),
213 start_byte: node.start_byte(),
214 end_byte: node.end_byte(),
215 start_line: node.start_position().row,
216 start_col: node.start_position().column,
217 end_line: node.end_position().row,
218 end_col: node.end_position().column,
219 name_start_line: name_node.start_position().row,
220 name_start_col: name_node.start_position().column,
221 name_end_line: name_node.end_position().row,
222 name_end_col: name_node.end_position().column,
223 definition_text: def_text,
224 children: Vec::new(),
225 };
226
227 if kind == SymbolKind::Table {
228 symbol.children = extract_columns(node, source, uri);
229 }
230
231 Some(symbol)
232}
233
234fn extract_name_or_col_id<'a>(
236 node: Node<'a>,
237 source: &str,
238 kind: SymbolKind,
239) -> Option<(SymbolKind, QualifiedName, Node<'a>)> {
240 find_descendant(node, "name")
241 .and_then(|n| extract_leaf_name(n, source).map(|qn| (kind, qn, n)))
242 .or_else(|| {
243 find_descendant(node, "ColId")
244 .and_then(|n| extract_leaf_name(n, source).map(|qn| (kind, qn, n)))
245 })
246}
247
248fn extract_qualified_name_node(node: Node, source: &str) -> Option<QualifiedName> {
254 let mut first_name = None;
255 let mut indirection_name = None;
256
257 let mut cursor = node.walk();
258 for child in node.children(&mut cursor) {
259 match child.kind() {
260 "ColId" => {
261 first_name = leaf_text(child, source);
262 }
263 "indirection" => {
264 let mut ic = child.walk();
266 for indirection_child in child.children(&mut ic) {
267 if indirection_child.kind() == "indirection_el" {
268 let mut ec = indirection_child.walk();
269 for el_child in indirection_child.children(&mut ec) {
270 if el_child.kind() == "attr_name" {
271 indirection_name = leaf_text(el_child, source);
272 }
273 }
274 }
275 }
276 }
277 _ => {}
278 }
279 }
280
281 match (first_name, indirection_name) {
282 (Some(schema), Some(name)) => Some(QualifiedName::with_schema(schema, name)),
283 (Some(name), None) => Some(QualifiedName::new(name)),
284 _ => None,
285 }
286}
287
288pub fn extract_func_name(node: Node, source: &str) -> Option<QualifiedName> {
292 if let Some(indirection) = find_child(node, "indirection") {
294 let schema = find_child(node, "ColId").and_then(|n| leaf_text(n, source));
296 let mut name = None;
297 let mut ic = indirection.walk();
298 for child in indirection.children(&mut ic) {
299 if child.kind() == "indirection_el" {
300 let mut ec = child.walk();
301 for el_child in child.children(&mut ec) {
302 if el_child.kind() == "attr_name" {
303 name = leaf_text(el_child, source);
304 }
305 }
306 }
307 }
308 if let (Some(s), Some(n)) = (schema, name) {
309 return Some(QualifiedName::with_schema(s, n));
310 }
311 }
312
313 leaf_text(node, source).map(QualifiedName::new)
315}
316
317fn extract_leaf_name(node: Node, source: &str) -> Option<QualifiedName> {
319 leaf_text(node, source).map(QualifiedName::new)
320}
321
322pub fn leaf_text(node: Node, source: &str) -> Option<String> {
324 if node.child_count() == 0 {
326 let text = node.utf8_text(source.as_bytes()).ok()?;
327 return Some(text.trim().replace('"', ""));
328 }
329
330 let mut cursor = node.walk();
332 for child in node.children(&mut cursor) {
333 match child.kind() {
334 "identifier" => {
335 return child
336 .utf8_text(source.as_bytes())
337 .ok()
338 .map(|t| t.trim().replace('"', ""));
339 }
340 _ if child.kind().starts_with("kw_") => {
341 return child
342 .utf8_text(source.as_bytes())
343 .ok()
344 .map(|t| t.trim().to_string());
345 }
346 _ => {
347 if let Some(text) = leaf_text(child, source) {
348 return Some(text);
349 }
350 }
351 }
352 }
353 None
354}
355
356pub fn find_child<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
358 let mut cursor = node.walk();
359 node.children(&mut cursor).find(|c| c.kind() == kind)
360}
361
362fn find_descendant<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
364 if let Some(child) = find_child(node, kind) {
366 return Some(child);
367 }
368 let mut cursor = node.walk();
370 for child in node.children(&mut cursor) {
371 if let Some(grandchild) = find_child(child, kind) {
372 return Some(grandchild);
373 }
374 }
375 None
376}
377
378fn has_child_kind(node: Node, kind: &str) -> bool {
380 find_child(node, kind).is_some()
381}
382
383fn extract_columns(table_node: Node, source: &str, uri: &str) -> Vec<Symbol> {
385 let mut columns = Vec::new();
386 collect_column_defs(table_node, source, uri, &mut columns);
387 columns
388}
389
390fn collect_column_defs(node: Node, source: &str, uri: &str, columns: &mut Vec<Symbol>) {
391 if node.kind() == "columnDef" {
392 if let Some(col_id) = find_descendant(node, "ColId")
393 && let Some(name) = leaf_text(col_id, source)
394 {
395 let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
396 columns.push(Symbol {
397 kind: SymbolKind::Column,
398 name: QualifiedName::new(name),
399 uri: uri.to_string(),
400 start_byte: node.start_byte(),
401 end_byte: node.end_byte(),
402 start_line: node.start_position().row,
403 start_col: node.start_position().column,
404 end_line: node.end_position().row,
405 end_col: node.end_position().column,
406 name_start_line: col_id.start_position().row,
407 name_start_col: col_id.start_position().column,
408 name_end_line: col_id.end_position().row,
409 name_end_col: col_id.end_position().column,
410 definition_text: def_text,
411 children: Vec::new(),
412 });
413 }
414 return;
415 }
416
417 let mut cursor = node.walk();
418 for child in node.children(&mut cursor) {
419 collect_column_defs(child, source, uri, columns);
420 }
421}
422
423pub fn extract_references(tree: &Tree, source: &str, uri: &str) -> Vec<SymbolRef> {
425 let mut refs = Vec::new();
426 collect_references(tree.root_node(), source, uri, &mut refs);
427 refs
428}
429
430fn collect_references(node: Node, source: &str, uri: &str, refs: &mut Vec<SymbolRef>) {
431 match node.kind() {
432 "func_application" => {
433 if let Some(name_node) = find_descendant(node, "func_name")
437 && let Some(name) = extract_func_name(name_node, source)
438 {
439 refs.push(SymbolRef {
440 name,
441 uri: uri.to_string(),
442 start_byte: name_node.start_byte(),
443 end_byte: name_node.end_byte(),
444 start_line: name_node.start_position().row,
445 start_col: name_node.start_position().column,
446 end_line: name_node.end_position().row,
447 end_col: name_node.end_position().column,
448 });
449 }
450 }
452 "columnref" | "relation_expr" => {
453 let name = extract_qualified_name_node(node, source).or_else(|| {
454 find_descendant(node, "ColId").and_then(|n| extract_leaf_name(n, source))
455 });
456
457 if let Some(name) = name {
458 refs.push(SymbolRef {
459 name,
460 uri: uri.to_string(),
461 start_byte: node.start_byte(),
462 end_byte: node.end_byte(),
463 start_line: node.start_position().row,
464 start_col: node.start_position().column,
465 end_line: node.end_position().row,
466 end_col: node.end_position().column,
467 });
468 return;
469 }
470 }
471 _ => {}
472 }
473
474 let mut cursor = node.walk();
475 for child in node.children(&mut cursor) {
476 collect_references(child, source, uri, refs);
477 }
478}
479
480pub fn extract_plpgsql_symbols(
485 tree: &Tree,
486 source: &str,
487 uri: &str,
488 parent_start_line: usize,
489 parent_start_col: usize,
490) -> Vec<Symbol> {
491 let mut symbols = Vec::new();
492 collect_plpgsql_decls(
493 tree.root_node(),
494 source,
495 uri,
496 parent_start_line,
497 parent_start_col,
498 &mut symbols,
499 );
500 symbols
501}
502
503fn collect_plpgsql_decls(
504 node: Node,
505 source: &str,
506 uri: &str,
507 parent_start_line: usize,
508 parent_start_col: usize,
509 symbols: &mut Vec<Symbol>,
510) {
511 if node.kind() == "decl_statement" {
512 let name_node = find_child(node, "decl_varname");
513 let name = name_node.and_then(|n| leaf_text(n, source));
514 let type_text = find_child(node, "decl_datatype")
515 .and_then(|n| n.utf8_text(source.as_bytes()).ok())
516 .unwrap_or("")
517 .trim()
518 .to_string();
519
520 let is_cursor = find_child(node, "decl_cursor_query").is_some()
521 || type_text.to_uppercase().contains("CURSOR");
522
523 if let (Some(var_name), Some(name_node)) = (name, name_node) {
524 let kind = if is_cursor {
525 SymbolKind::Cursor
526 } else {
527 SymbolKind::Variable
528 };
529
530 let (start_line, start_col) = map_position(
531 node.start_position().row,
532 node.start_position().column,
533 parent_start_line,
534 parent_start_col,
535 );
536 let (end_line, end_col) = map_position(
537 node.end_position().row,
538 node.end_position().column,
539 parent_start_line,
540 parent_start_col,
541 );
542
543 let (name_sl, name_sc) = map_position(
544 name_node.start_position().row,
545 name_node.start_position().column,
546 parent_start_line,
547 parent_start_col,
548 );
549 let (name_el, name_ec) = map_position(
550 name_node.end_position().row,
551 name_node.end_position().column,
552 parent_start_line,
553 parent_start_col,
554 );
555
556 let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
557
558 symbols.push(Symbol {
559 kind,
560 name: QualifiedName::new(var_name),
561 uri: uri.to_string(),
562 start_byte: node.start_byte(),
563 end_byte: node.end_byte(),
564 start_line,
565 start_col,
566 end_line,
567 end_col,
568 name_start_line: name_sl,
569 name_start_col: name_sc,
570 name_end_line: name_el,
571 name_end_col: name_ec,
572 definition_text: def_text,
573 children: Vec::new(),
574 });
575 }
576 return;
577 }
578
579 let mut cursor = node.walk();
580 for child in node.children(&mut cursor) {
581 collect_plpgsql_decls(
582 child,
583 source,
584 uri,
585 parent_start_line,
586 parent_start_col,
587 symbols,
588 );
589 }
590}
591
592fn map_position(
594 local_line: usize,
595 local_col: usize,
596 parent_start_line: usize,
597 parent_start_col: usize,
598) -> (usize, usize) {
599 if local_line == 0 {
600 (parent_start_line, parent_start_col + local_col)
601 } else {
602 (parent_start_line + local_line, local_col)
603 }
604}
605
606#[cfg(test)]
607mod tests {
608 use postgres_lsp_parse::ParserPool;
609
610 use super::*;
611
612 fn parse_and_extract(sql: &str) -> Vec<Symbol> {
613 let pool = ParserPool::new();
614 let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
615 let tree = guard.parser_mut().parse(sql, None).unwrap();
616 extract_symbols(&tree, sql, "test.sql")
617 }
618
619 #[test]
620 fn extract_create_table() {
621 let symbols = parse_and_extract("CREATE TABLE users (id int, name text);");
622 assert_eq!(symbols.len(), 1);
623 assert_eq!(symbols[0].kind, SymbolKind::Table);
624 assert_eq!(symbols[0].name.name, "users");
625 assert_eq!(symbols[0].children.len(), 2);
626 assert_eq!(symbols[0].children[0].name.name, "id");
627 assert_eq!(symbols[0].children[1].name.name, "name");
628 }
629
630 #[test]
631 fn extract_create_function() {
632 let symbols = parse_and_extract(
633 "CREATE FUNCTION add(a int, b int) RETURNS int LANGUAGE sql AS 'SELECT a + b';",
634 );
635 assert_eq!(symbols.len(), 1);
636 assert_eq!(symbols[0].kind, SymbolKind::Function);
637 assert_eq!(symbols[0].name.name, "add");
638 }
639
640 #[test]
641 fn extract_schema_qualified() {
642 let symbols = parse_and_extract("CREATE TABLE public.users (id int);");
643 assert_eq!(symbols.len(), 1);
644 assert_eq!(symbols[0].name.schema.as_deref(), Some("public"));
645 assert_eq!(symbols[0].name.name, "users");
646 }
647
648 #[test]
649 fn extract_references_from_select() {
650 let pool = ParserPool::new();
651 let sql = "SELECT id, name FROM users WHERE id > 0;";
652 let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
653 let tree = guard.parser_mut().parse(sql, None).unwrap();
654 let refs = extract_references(&tree, sql, "test.sql");
655 assert!(!refs.is_empty(), "should find references in SELECT");
656 }
657
658 #[test]
659 fn extract_plpgsql_variables() {
660 let pool = ParserPool::new();
661 let plpgsql = "DECLARE\n v_count int;\n v_name text;\nBEGIN\n RETURN v_count;\nEND;";
662 let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::PlPgSql);
663 let tree = guard.parser_mut().parse(plpgsql, None).unwrap();
664 drop(guard);
665
666 let symbols = extract_plpgsql_symbols(&tree, plpgsql, "test.sql", 5, 0);
667 assert_eq!(symbols.len(), 2, "should find 2 variable declarations");
668 assert_eq!(symbols[0].kind, SymbolKind::Variable);
669 assert_eq!(symbols[0].name.name, "v_count");
670 assert_eq!(symbols[1].kind, SymbolKind::Variable);
671 assert_eq!(symbols[1].name.name, "v_name");
672 }
673
674 #[test]
675 fn plpgsql_variables_indexed_from_create_function() {
676 let pool = ParserPool::new();
677 let sql = r#"CREATE FUNCTION test() RETURNS int LANGUAGE plpgsql AS $$
678DECLARE
679 v_result int;
680BEGIN
681 v_result := 42;
682 RETURN v_result;
683END;
684$$;"#;
685 let doc = postgres_lsp_parse::Document::new("test.sql".into(), sql, &pool);
686 let tree = doc.tree().unwrap();
687 let injections = doc.injections();
688
689 let index = crate::index::WorkspaceIndex::new();
690 index.update_file("file:///test.sql", tree, sql, injections);
691
692 let funcs = index.find_definitions(SymbolKind::Function, "test");
694 assert_eq!(funcs.len(), 1);
695
696 let vars = index.find_definitions(SymbolKind::Variable, "v_result");
698 assert_eq!(vars.len(), 1, "PL/pgSQL variable should be indexed");
699 assert_eq!(vars[0].name.name, "v_result");
700 }
701}