Skip to main content

postgres_lsp_analysis/
signature.rs

1use tree_sitter::Node;
2
3use crate::index::WorkspaceIndex;
4use crate::resolve;
5use crate::symbols::{self, QualifiedName, Symbol, SymbolKind};
6
7/// A parameter extracted from a function definition.
8#[derive(Debug, Clone)]
9pub struct ParamInfo {
10    pub name: Option<String>,
11    pub type_name: String,
12}
13
14impl ParamInfo {
15    pub fn label(&self) -> String {
16        match &self.name {
17            Some(name) => format!("{name} {}", self.type_name),
18            None => self.type_name.clone(),
19        }
20    }
21}
22
23/// Signature information for a function.
24#[derive(Debug, Clone)]
25pub struct SignatureInfo {
26    pub name: String,
27    pub params: Vec<ParamInfo>,
28    pub return_type: Option<String>,
29}
30
31impl SignatureInfo {
32    pub fn label(&self) -> String {
33        let params = self
34            .params
35            .iter()
36            .map(|p| p.label())
37            .collect::<Vec<_>>()
38            .join(", ");
39        match &self.return_type {
40            Some(ret) => format!("{}({}) -> {}", self.name, params, ret),
41            None => format!("{}({})", self.name, params),
42        }
43    }
44}
45
46/// Extract parameter information from a function definition's source text
47/// by re-parsing its definition tree.
48pub fn extract_signature(
49    symbol: &Symbol,
50    pool: &postgres_lsp_parse::ParserPool,
51) -> Option<SignatureInfo> {
52    if symbol.kind != SymbolKind::Function && symbol.kind != SymbolKind::Procedure {
53        return None;
54    }
55
56    let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
57    let tree = guard.parser_mut().parse(&symbol.definition_text, None)?;
58    let root = tree.root_node();
59
60    let func_stmt = find_node_by_kind(root, "CreateFunctionStmt")?;
61
62    let params = extract_params(func_stmt, &symbol.definition_text);
63    let return_type = extract_return_type(func_stmt, &symbol.definition_text);
64
65    Some(SignatureInfo {
66        name: symbol.name.display(),
67        params,
68        return_type,
69    })
70}
71
72/// Find the enclosing func_application node and determine the active parameter index.
73///
74/// Uses a tree-sitter Point (row, byte_column) for cursor position.
75/// Returns `(qualified_name, active_param_index)`.
76pub fn find_active_function_call(
77    tree: &tree_sitter::Tree,
78    source: &str,
79    row: usize,
80    byte_col: usize,
81) -> Option<(QualifiedName, usize)> {
82    let point = tree_sitter::Point {
83        row,
84        column: byte_col,
85    };
86    let cursor_node = tree.root_node().descendant_for_point_range(point, point)?;
87    let cursor_byte = cursor_node.start_byte();
88
89    // Walk up to find the nearest func_application.
90    let mut current = Some(cursor_node);
91    while let Some(n) = current {
92        if n.kind() == "func_application" {
93            let name_node = symbols::find_child(n, "func_name")?;
94            let qname = symbols::extract_func_name(name_node, source)?;
95            let param_index = count_commas_before(n, cursor_byte);
96            return Some((qname, param_index));
97        }
98        current = n.parent();
99    }
100    None
101}
102
103/// Look up signature help for a function call at the given position.
104pub fn signature_help(
105    index: &WorkspaceIndex,
106    pool: &postgres_lsp_parse::ParserPool,
107    tree: &tree_sitter::Tree,
108    source: &str,
109    row: usize,
110    byte_col: usize,
111) -> Option<(SignatureInfo, usize)> {
112    let (name, active_param) = find_active_function_call(tree, source, row, byte_col)?;
113    let defs = resolve::resolve_name(index, &name);
114
115    let func_sym = defs
116        .iter()
117        .find(|s| s.kind == SymbolKind::Function || s.kind == SymbolKind::Procedure)?;
118
119    let sig = extract_signature(func_sym, pool)?;
120    Some((sig, active_param))
121}
122
123/// Count commas before the byte offset within a func_application's argument list.
124/// Iterates only the direct children of func_arg_list — no deep recursion needed.
125fn count_commas_before(func_app: Node, byte_offset: usize) -> usize {
126    // func_arg_list is a left-recursive list; commas are direct children.
127    fn count_in_list(node: Node, byte_offset: usize) -> usize {
128        let mut count = 0;
129        let mut cursor = node.walk();
130        for child in node.children(&mut cursor) {
131            if child.kind() == "," && child.start_byte() < byte_offset {
132                count += 1;
133            } else if child.kind() == "func_arg_list" {
134                count += count_in_list(child, byte_offset);
135            }
136        }
137        count
138    }
139
140    let mut cursor = func_app.walk();
141    for child in func_app.children(&mut cursor) {
142        if child.kind() == "func_arg_list" {
143            return count_in_list(child, byte_offset);
144        }
145    }
146    0
147}
148
149/// Extract parameters from a CreateFunctionStmt node.
150fn extract_params(func_stmt: Node, source: &str) -> Vec<ParamInfo> {
151    let mut params = Vec::new();
152    collect_params(func_stmt, source, &mut params);
153    params
154}
155
156fn collect_params(node: Node, source: &str, params: &mut Vec<ParamInfo>) {
157    if node.kind() == "func_arg" {
158        let param_name =
159            symbols::find_child(node, "param_name").and_then(|n| symbols::leaf_text(n, source));
160        let type_name = symbols::find_child(node, "func_type")
161            .map(|n| node_full_text(n, source))
162            .unwrap_or_else(|| "unknown".to_string());
163        params.push(ParamInfo {
164            name: param_name,
165            type_name,
166        });
167        return;
168    }
169
170    let mut cursor = node.walk();
171    for child in node.children(&mut cursor) {
172        collect_params(child, source, params);
173    }
174}
175
176/// Extract the return type from a CreateFunctionStmt.
177fn extract_return_type(func_stmt: Node, source: &str) -> Option<String> {
178    let func_return = find_node_by_kind(func_stmt, "func_return")?;
179    let func_type = find_node_by_kind(func_return, "func_type")?;
180    Some(node_full_text(func_type, source))
181}
182
183/// Get the full text of a node, preserving multi-token types like
184/// `double precision`, `timestamp with time zone`, `numeric(10,2)`, etc.
185fn node_full_text(node: Node, source: &str) -> String {
186    node.utf8_text(source.as_bytes())
187        .unwrap_or("unknown")
188        .trim()
189        .to_string()
190}
191
192fn find_node_by_kind<'a>(node: Node<'a>, kind: &str) -> Option<Node<'a>> {
193    if node.kind() == kind {
194        return Some(node);
195    }
196    let mut cursor = node.walk();
197    for child in node.children(&mut cursor) {
198        if let Some(found) = find_node_by_kind(child, kind) {
199            return Some(found);
200        }
201    }
202    None
203}
204
205#[cfg(test)]
206mod tests {
207    use postgres_lsp_parse::ParserPool;
208
209    use super::*;
210
211    fn make_index_with_func() -> (WorkspaceIndex, String) {
212        let pool = ParserPool::new();
213        let sql = "CREATE FUNCTION my_func(a int, b text, c int) RETURNS void LANGUAGE sql AS 'SELECT 1';";
214        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
215        let tree = guard.parser_mut().parse(sql, None).unwrap();
216        drop(guard);
217
218        let index = WorkspaceIndex::new();
219        index.update_file("file:///test.sql", &tree, sql, &[]);
220        (index, sql.to_string())
221    }
222
223    #[test]
224    fn extract_signature_from_function() {
225        let pool = ParserPool::new();
226        let (index, _) = make_index_with_func();
227        let syms = index.find_definitions(SymbolKind::Function, "my_func");
228        assert_eq!(syms.len(), 1);
229
230        let sig = extract_signature(&syms[0], &pool).unwrap();
231        assert_eq!(sig.name, "my_func");
232        assert_eq!(sig.params.len(), 3);
233        assert_eq!(sig.params[0].name.as_deref(), Some("a"));
234        assert_eq!(sig.params[0].type_name, "int");
235        assert_eq!(sig.params[1].name.as_deref(), Some("b"));
236        assert_eq!(sig.params[1].type_name, "text");
237        assert_eq!(sig.params[2].name.as_deref(), Some("c"));
238        assert_eq!(sig.params[2].type_name, "int");
239        assert!(sig.return_type.is_some());
240    }
241
242    #[test]
243    fn find_active_param_first() {
244        let pool = ParserPool::new();
245        let sql = "SELECT my_func(1, 'hello', 42);";
246        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
247        let tree = guard.parser_mut().parse(sql, None).unwrap();
248        drop(guard);
249
250        // Cursor inside first argument (byte column 15 = position of "1")
251        let result = find_active_function_call(&tree, sql, 0, 15);
252        assert!(result.is_some());
253        let (name, idx) = result.unwrap();
254        assert_eq!(name.display(), "my_func");
255        assert_eq!(idx, 0);
256    }
257
258    #[test]
259    fn find_active_param_second() {
260        let pool = ParserPool::new();
261        let sql = "SELECT my_func(1, 'hello', 42);";
262        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
263        let tree = guard.parser_mut().parse(sql, None).unwrap();
264        drop(guard);
265
266        // Cursor inside second argument (byte column 19 = inside "'hello'")
267        let result = find_active_function_call(&tree, sql, 0, 19);
268        assert!(result.is_some());
269        let (name, idx) = result.unwrap();
270        assert_eq!(name.display(), "my_func");
271        assert_eq!(idx, 1);
272    }
273
274    #[test]
275    fn find_active_param_third() {
276        let pool = ParserPool::new();
277        let sql = "SELECT my_func(1, 'hello', 42);";
278        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
279        let tree = guard.parser_mut().parse(sql, None).unwrap();
280        drop(guard);
281
282        // Cursor inside third argument (byte column 27 = position of "42")
283        let result = find_active_function_call(&tree, sql, 0, 27);
284        assert!(result.is_some());
285        let (name, idx) = result.unwrap();
286        assert_eq!(name.display(), "my_func");
287        assert_eq!(idx, 2);
288    }
289
290    #[test]
291    fn signature_help_full() {
292        let pool = ParserPool::new();
293        let (index, _) = make_index_with_func();
294
295        let call_sql = "SELECT my_func(1, 'hello', 42);";
296        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
297        let tree = guard.parser_mut().parse(call_sql, None).unwrap();
298        drop(guard);
299
300        // Cursor at second argument (byte column 19)
301        let result = signature_help(&index, &pool, &tree, call_sql, 0, 19);
302        assert!(result.is_some());
303        let (sig, active) = result.unwrap();
304        assert_eq!(sig.name, "my_func");
305        assert_eq!(sig.params.len(), 3);
306        assert_eq!(active, 1);
307    }
308
309    #[test]
310    fn no_signature_outside_function_call() {
311        let pool = ParserPool::new();
312        let sql = "SELECT 1;";
313        let mut guard = pool.acquire(postgres_lsp_parse::parser::Language::Postgres);
314        let tree = guard.parser_mut().parse(sql, None).unwrap();
315        drop(guard);
316
317        let index = WorkspaceIndex::new();
318        let result = signature_help(&index, &pool, &tree, sql, 0, 7);
319        assert!(result.is_none());
320    }
321}