use tree_sitter::{Node, Tree};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SymbolKind {
Schema,
Table,
View,
MaterializedView,
Column,
Function,
Procedure,
Trigger,
Index,
Sequence,
Type,
Domain,
Extension,
Role,
Policy,
Publication,
Subscription,
ForeignTable,
Variable,
Cursor,
}
impl SymbolKind {
pub fn label(&self) -> &'static str {
match self {
Self::Schema => "schema",
Self::Table => "table",
Self::View => "view",
Self::MaterializedView => "materialized view",
Self::Column => "column",
Self::Function => "function",
Self::Procedure => "procedure",
Self::Trigger => "trigger",
Self::Index => "index",
Self::Sequence => "sequence",
Self::Type => "type",
Self::Domain => "domain",
Self::Extension => "extension",
Self::Role => "role",
Self::Policy => "policy",
Self::Publication => "publication",
Self::Subscription => "subscription",
Self::ForeignTable => "foreign table",
Self::Variable => "variable",
Self::Cursor => "cursor",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct QualifiedName {
pub schema: Option<String>,
pub name: String,
}
impl QualifiedName {
pub fn new(name: String) -> Self {
Self { schema: None, name }
}
pub fn with_schema(schema: String, name: String) -> Self {
Self {
schema: Some(schema),
name,
}
}
pub fn display(&self) -> String {
match &self.schema {
Some(s) => format!("{s}.{}", self.name),
None => self.name.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct Symbol {
pub kind: SymbolKind,
pub name: QualifiedName,
pub uri: String,
pub start_byte: usize,
pub end_byte: usize,
pub start_line: usize,
pub start_col: usize,
pub end_line: usize,
pub end_col: usize,
pub name_start_line: usize,
pub name_start_col: usize,
pub name_end_line: usize,
pub name_end_col: usize,
pub definition_text: String,
pub children: Vec<Symbol>,
}
#[derive(Debug, Clone)]
pub struct SymbolRef {
pub name: QualifiedName,
pub uri: String,
pub start_byte: usize,
pub end_byte: usize,
pub start_line: usize,
pub start_col: usize,
pub end_line: usize,
pub end_col: usize,
}
pub fn extract_symbols(tree: &Tree, source: &str, uri: &str) -> Vec<Symbol> {
let mut symbols = Vec::new();
collect_definitions(tree.root_node(), source, uri, &mut symbols);
symbols
}
fn collect_definitions(node: Node, source: &str, uri: &str, symbols: &mut Vec<Symbol>) {
if let Some(symbol) = try_extract_definition(node, source, uri) {
symbols.push(symbol);
return; }
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
collect_definitions(child, source, uri, symbols);
}
}
fn try_extract_definition(node: Node, source: &str, uri: &str) -> Option<Symbol> {
let result: Option<(SymbolKind, QualifiedName, Node)> = match node.kind() {
"CreateStmt" => find_descendant(node, "qualified_name").and_then(|n| {
extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Table, qn, n))
}),
"CreateMatViewStmt" => find_descendant(node, "qualified_name").and_then(|n| {
extract_qualified_name_node(n, source).map(|qn| (SymbolKind::MaterializedView, qn, n))
}),
"ViewStmt" => find_descendant(node, "qualified_name").and_then(|n| {
extract_qualified_name_node(n, source).map(|qn| (SymbolKind::View, qn, n))
}),
"CreateFunctionStmt" => {
let kind = if has_child_kind(node, "kw_procedure") {
SymbolKind::Procedure
} else {
SymbolKind::Function
};
find_descendant(node, "func_name")
.and_then(|n| extract_func_name(n, source).map(|qn| (kind, qn, n)))
}
"IndexStmt" => extract_name_or_col_id(node, source, SymbolKind::Index),
"CreateSeqStmt" => find_descendant(node, "qualified_name").and_then(|n| {
extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Sequence, qn, n))
}),
"CreateSchemaStmt" => find_descendant(node, "ColId")
.and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Schema, qn, n))),
"CompositeTypeStmt" | "CreateEnumStmt" | "CreateRangeStmt" => {
find_descendant(node, "any_name")
.and_then(|n| {
extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Type, qn, n))
})
.or_else(|| {
find_descendant(node, "qualified_name").and_then(|n| {
extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Type, qn, n))
})
})
}
"CreateDomainStmt" => find_descendant(node, "any_name").and_then(|n| {
extract_qualified_name_node(n, source).map(|qn| (SymbolKind::Domain, qn, n))
}),
"CreateExtensionStmt" => extract_name_or_col_id(node, source, SymbolKind::Extension),
"CreateTrigStmt" => extract_name_or_col_id(node, source, SymbolKind::Trigger),
"CreateRoleStmt" => find_descendant(node, "RoleId")
.and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Role, qn, n)))
.or_else(|| {
find_descendant(node, "ColId")
.and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Role, qn, n)))
}),
"CreatePolicyStmt" => find_descendant(node, "name")
.and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Policy, qn, n))),
"CreatePublicationStmt" => find_descendant(node, "ColId")
.and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Publication, qn, n))),
"CreateSubscriptionStmt" => find_descendant(node, "ColId")
.and_then(|n| extract_leaf_name(n, source).map(|qn| (SymbolKind::Subscription, qn, n))),
"CreateForeignTableStmt" => find_descendant(node, "qualified_name").and_then(|n| {
extract_qualified_name_node(n, source).map(|qn| (SymbolKind::ForeignTable, qn, n))
}),
_ => None,
};
let (kind, name, name_node) = result?;
let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
let mut symbol = Symbol {
kind,
name,
uri: uri.to_string(),
start_byte: node.start_byte(),
end_byte: node.end_byte(),
start_line: node.start_position().row,
start_col: node.start_position().column,
end_line: node.end_position().row,
end_col: node.end_position().column,
name_start_line: name_node.start_position().row,
name_start_col: name_node.start_position().column,
name_end_line: name_node.end_position().row,
name_end_col: name_node.end_position().column,
definition_text: def_text,
children: Vec::new(),
};
if kind == SymbolKind::Table {
symbol.children = extract_columns(node, source, uri);
}
Some(symbol)
}
fn extract_name_or_col_id<'a>(
node: Node<'a>,
source: &str,
kind: SymbolKind,
) -> Option<(SymbolKind, QualifiedName, Node<'a>)> {
find_descendant(node, "name")
.and_then(|n| extract_leaf_name(n, source).map(|qn| (kind, qn, n)))
.or_else(|| {
find_descendant(node, "ColId")
.and_then(|n| extract_leaf_name(n, source).map(|qn| (kind, qn, n)))
})
}
fn extract_qualified_name_node(node: Node, source: &str) -> Option<QualifiedName> {
let mut first_name = None;
let mut indirection_name = None;
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"ColId" => {
first_name = leaf_text(child, source);
}
"indirection" => {
let mut ic = child.walk();
for indirection_child in child.children(&mut ic) {
if indirection_child.kind() == "indirection_el" {
let mut ec = indirection_child.walk();
for el_child in indirection_child.children(&mut ec) {
if el_child.kind() == "attr_name" {
indirection_name = leaf_text(el_child, source);
}
}
}
}
}
_ => {}
}
}
match (first_name, indirection_name) {
(Some(schema), Some(name)) => Some(QualifiedName::with_schema(schema, name)),
(Some(name), None) => Some(QualifiedName::new(name)),
_ => None,
}
}
pub fn extract_func_name(node: Node, source: &str) -> Option<QualifiedName> {
if let Some(indirection) = find_child(node, "indirection") {
let schema = find_child(node, "ColId").and_then(|n| leaf_text(n, source));
let mut name = None;
let mut ic = indirection.walk();
for child in indirection.children(&mut ic) {
if child.kind() == "indirection_el" {
let mut ec = child.walk();
for el_child in child.children(&mut ec) {
if el_child.kind() == "attr_name" {
name = leaf_text(el_child, source);
}
}
}
}
if let (Some(s), Some(n)) = (schema, name) {
return Some(QualifiedName::with_schema(s, n));
}
}
leaf_text(node, source).map(QualifiedName::new)
}
fn extract_leaf_name(node: Node, source: &str) -> Option<QualifiedName> {
leaf_text(node, source).map(QualifiedName::new)
}
pub fn leaf_text(node: Node, source: &str) -> Option<String> {
if node.child_count() == 0 {
let text = node.utf8_text(source.as_bytes()).ok()?;
return Some(text.trim().replace('"', ""));
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
match child.kind() {
"identifier" => {
return child
.utf8_text(source.as_bytes())
.ok()
.map(|t| t.trim().replace('"', ""));
}
_ if child.kind().starts_with("kw_") => {
return child
.utf8_text(source.as_bytes())
.ok()
.map(|t| t.trim().to_string());
}
_ => {
if let Some(text) = leaf_text(child, source) {
return Some(text);
}
}
}
}
None
}
pub fn find_child<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
let mut cursor = node.walk();
node.children(&mut cursor).find(|c| c.kind() == kind)
}
fn find_descendant<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
if let Some(child) = find_child(node, kind) {
return Some(child);
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if let Some(grandchild) = find_child(child, kind) {
return Some(grandchild);
}
}
None
}
fn has_child_kind(node: Node, kind: &str) -> bool {
find_child(node, kind).is_some()
}
fn extract_columns(table_node: Node, source: &str, uri: &str) -> Vec<Symbol> {
let mut columns = Vec::new();
collect_column_defs(table_node, source, uri, &mut columns);
columns
}
fn collect_column_defs(node: Node, source: &str, uri: &str, columns: &mut Vec<Symbol>) {
if node.kind() == "columnDef" {
if let Some(col_id) = find_descendant(node, "ColId")
&& let Some(name) = leaf_text(col_id, source)
{
let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
columns.push(Symbol {
kind: SymbolKind::Column,
name: QualifiedName::new(name),
uri: uri.to_string(),
start_byte: node.start_byte(),
end_byte: node.end_byte(),
start_line: node.start_position().row,
start_col: node.start_position().column,
end_line: node.end_position().row,
end_col: node.end_position().column,
name_start_line: col_id.start_position().row,
name_start_col: col_id.start_position().column,
name_end_line: col_id.end_position().row,
name_end_col: col_id.end_position().column,
definition_text: def_text,
children: Vec::new(),
});
}
return;
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
collect_column_defs(child, source, uri, columns);
}
}
pub fn extract_references(tree: &Tree, source: &str, uri: &str) -> Vec<SymbolRef> {
let mut refs = Vec::new();
collect_references(tree.root_node(), source, uri, &mut refs);
refs
}
fn collect_references(node: Node, source: &str, uri: &str, refs: &mut Vec<SymbolRef>) {
match node.kind() {
"func_application" => {
if let Some(name_node) = find_descendant(node, "func_name")
&& let Some(name) = extract_func_name(name_node, source)
{
refs.push(SymbolRef {
name,
uri: uri.to_string(),
start_byte: name_node.start_byte(),
end_byte: name_node.end_byte(),
start_line: name_node.start_position().row,
start_col: name_node.start_position().column,
end_line: name_node.end_position().row,
end_col: name_node.end_position().column,
});
}
}
"columnref" | "relation_expr" => {
let name = extract_qualified_name_node(node, source).or_else(|| {
find_descendant(node, "ColId").and_then(|n| extract_leaf_name(n, source))
});
if let Some(name) = name {
refs.push(SymbolRef {
name,
uri: uri.to_string(),
start_byte: node.start_byte(),
end_byte: node.end_byte(),
start_line: node.start_position().row,
start_col: node.start_position().column,
end_line: node.end_position().row,
end_col: node.end_position().column,
});
return;
}
}
_ => {}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
collect_references(child, source, uri, refs);
}
}
pub fn extract_plpgsql_symbols(
tree: &Tree,
source: &str,
uri: &str,
parent_start_line: usize,
parent_start_col: usize,
) -> Vec<Symbol> {
let mut symbols = Vec::new();
collect_plpgsql_decls(
tree.root_node(),
source,
uri,
parent_start_line,
parent_start_col,
&mut symbols,
);
symbols
}
fn collect_plpgsql_decls(
node: Node,
source: &str,
uri: &str,
parent_start_line: usize,
parent_start_col: usize,
symbols: &mut Vec<Symbol>,
) {
if node.kind() == "decl_statement" {
let name_node = find_child(node, "decl_varname");
let name = name_node.and_then(|n| leaf_text(n, source));
let type_text = find_child(node, "decl_datatype")
.and_then(|n| n.utf8_text(source.as_bytes()).ok())
.unwrap_or("")
.trim()
.to_string();
let is_cursor = find_child(node, "decl_cursor_query").is_some()
|| type_text.to_uppercase().contains("CURSOR");
if let (Some(var_name), Some(name_node)) = (name, name_node) {
let kind = if is_cursor {
SymbolKind::Cursor
} else {
SymbolKind::Variable
};
let (start_line, start_col) = map_position(
node.start_position().row,
node.start_position().column,
parent_start_line,
parent_start_col,
);
let (end_line, end_col) = map_position(
node.end_position().row,
node.end_position().column,
parent_start_line,
parent_start_col,
);
let (name_sl, name_sc) = map_position(
name_node.start_position().row,
name_node.start_position().column,
parent_start_line,
parent_start_col,
);
let (name_el, name_ec) = map_position(
name_node.end_position().row,
name_node.end_position().column,
parent_start_line,
parent_start_col,
);
let def_text = node.utf8_text(source.as_bytes()).unwrap_or("").to_string();
symbols.push(Symbol {
kind,
name: QualifiedName::new(var_name),
uri: uri.to_string(),
start_byte: node.start_byte(),
end_byte: node.end_byte(),
start_line,
start_col,
end_line,
end_col,
name_start_line: name_sl,
name_start_col: name_sc,
name_end_line: name_el,
name_end_col: name_ec,
definition_text: def_text,
children: Vec::new(),
});
}
return;
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
collect_plpgsql_decls(
child,
source,
uri,
parent_start_line,
parent_start_col,
symbols,
);
}
}
fn map_position(
local_line: usize,
local_col: usize,
parent_start_line: usize,
parent_start_col: usize,
) -> (usize, usize) {
if local_line == 0 {
(parent_start_line, parent_start_col + local_col)
} else {
(parent_start_line + local_line, local_col)
}
}
#[cfg(test)]
mod tests {
use postgres_lsp_parse::ParserPool;
use super::*;
fn parse_and_extract(sql: &str) -> Vec<Symbol> {
let pool = ParserPool::new();
let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
let tree = guard.parser_mut().parse(sql, None).unwrap();
extract_symbols(&tree, sql, "test.sql")
}
#[test]
fn extract_create_table() {
let symbols = parse_and_extract("CREATE TABLE users (id int, name text);");
assert_eq!(symbols.len(), 1);
assert_eq!(symbols[0].kind, SymbolKind::Table);
assert_eq!(symbols[0].name.name, "users");
assert_eq!(symbols[0].children.len(), 2);
assert_eq!(symbols[0].children[0].name.name, "id");
assert_eq!(symbols[0].children[1].name.name, "name");
}
#[test]
fn extract_create_function() {
let symbols = parse_and_extract(
"CREATE FUNCTION add(a int, b int) RETURNS int LANGUAGE sql AS 'SELECT a + b';",
);
assert_eq!(symbols.len(), 1);
assert_eq!(symbols[0].kind, SymbolKind::Function);
assert_eq!(symbols[0].name.name, "add");
}
#[test]
fn extract_schema_qualified() {
let symbols = parse_and_extract("CREATE TABLE public.users (id int);");
assert_eq!(symbols.len(), 1);
assert_eq!(symbols[0].name.schema.as_deref(), Some("public"));
assert_eq!(symbols[0].name.name, "users");
}
#[test]
fn extract_references_from_select() {
let pool = ParserPool::new();
let sql = "SELECT id, name FROM users WHERE id > 0;";
let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
let tree = guard.parser_mut().parse(sql, None).unwrap();
let refs = extract_references(&tree, sql, "test.sql");
assert!(!refs.is_empty(), "should find references in SELECT");
}
#[test]
fn extract_plpgsql_variables() {
let pool = ParserPool::new();
let plpgsql = "DECLARE\n v_count int;\n v_name text;\nBEGIN\n RETURN v_count;\nEND;";
let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::PlPgSql);
let tree = guard.parser_mut().parse(plpgsql, None).unwrap();
drop(guard);
let symbols = extract_plpgsql_symbols(&tree, plpgsql, "test.sql", 5, 0);
assert_eq!(symbols.len(), 2, "should find 2 variable declarations");
assert_eq!(symbols[0].kind, SymbolKind::Variable);
assert_eq!(symbols[0].name.name, "v_count");
assert_eq!(symbols[1].kind, SymbolKind::Variable);
assert_eq!(symbols[1].name.name, "v_name");
}
#[test]
fn plpgsql_variables_indexed_from_create_function() {
let pool = ParserPool::new();
let sql = r#"CREATE FUNCTION test() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
v_result int;
BEGIN
v_result := 42;
RETURN v_result;
END;
$$;"#;
let doc = postgres_lsp_parse::Document::new("test.sql".into(), sql, &pool);
let tree = doc.tree().unwrap();
let injections = doc.injections();
let index = crate::index::WorkspaceIndex::new();
index.update_file("file:///test.sql", tree, sql, injections);
let funcs = index.find_definitions(SymbolKind::Function, "test");
assert_eq!(funcs.len(), 1);
let vars = index.find_definitions(SymbolKind::Variable, "v_result");
assert_eq!(vars.len(), 1, "PL/pgSQL variable should be indexed");
assert_eq!(vars[0].name.name, "v_result");
}
}