Skip to main content

logicaffeine_lsp/
signature_help.rs

1use lsp_types::{
2    ParameterInformation, ParameterLabel, Position, SignatureHelp, SignatureInformation,
3};
4
5use logicaffeine_language::token::TokenType;
6
7use crate::document::DocumentState;
8use crate::index::DefinitionKind;
9
10/// Handle signature help request.
11///
12/// When the cursor is inside a `Call` expression, find the function definition
13/// and show parameter names/types.
14pub fn signature_help(doc: &DocumentState, position: Position) -> Option<SignatureHelp> {
15    let offset = doc.line_index.offset(position);
16
17    // Scan backwards from cursor to find a Call token
18    let call_token = doc
19        .tokens
20        .iter()
21        .rev()
22        .find(|t| t.span.end <= offset && matches!(t.kind, TokenType::Call))?;
23
24    // Find the function name token (should be right after Call or after "with")
25    let call_idx = doc
26        .tokens
27        .iter()
28        .position(|t| t.span == call_token.span && t.kind == call_token.kind)?;
29
30    // The function name should follow Call
31    let func_name_token = doc.tokens.get(call_idx + 1)?;
32    let func_name = doc
33        .source
34        .get(func_name_token.span.start..func_name_token.span.end)?;
35
36    // Look up the function definition; stdlib prelude names answer when the
37    // document defines nothing by that name.
38    let defs = doc.symbol_index.definitions_of(func_name);
39    let func_def = defs.iter().find(|d| d.kind == DefinitionKind::Function);
40    let (detail, documentation) = match func_def {
41        Some(def) => (def.detail.clone()?, def.doc.clone()),
42        None => {
43            let entry = crate::stdlib_docs::stdlib_doc(func_name).filter(|e| !e.is_type)?;
44            (
45                entry.signature.trim_start_matches("## ").to_string(),
46                entry.doc.clone(),
47            )
48        }
49    };
50    let detail = &detail;
51
52    // Count parameter separators after Call to determine active parameter.
53    // "with" introduces the parameter list, only "and" and "," separate params.
54    let active_param = doc.tokens[call_idx..]
55        .iter()
56        .take_while(|t| t.span.start < offset)
57        .filter(|t| {
58            matches!(t.kind, TokenType::Comma)
59                || doc
60                    .source
61                    .get(t.span.start..t.span.end)
62                    .map(|s| s == "and")
63                    .unwrap_or(false)
64        })
65        .count();
66
67    // Extract parameters from the function's signature detail string
68    let params: Vec<ParameterInformation> = extract_params_from_signature(detail)
69        .into_iter()
70        .map(|(name, ty)| ParameterInformation {
71            label: ParameterLabel::Simple(name.clone()),
72            documentation: Some(lsp_types::Documentation::String(format!(
73                "{}: {}",
74                name, ty
75            ))),
76        })
77        .collect();
78
79    Some(SignatureHelp {
80        signatures: vec![SignatureInformation {
81            label: detail.clone(),
82            documentation: documentation.map(|d| {
83                lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
84                    kind: lsp_types::MarkupKind::Markdown,
85                    value: d,
86                })
87            }),
88            parameters: if params.is_empty() {
89                None
90            } else {
91                Some(params)
92            },
93            active_parameter: Some(active_param as u32),
94        }],
95        active_signature: Some(0),
96        active_parameter: Some(active_param as u32),
97    })
98}
99
100/// Extract parameter names and types from a function signature detail string.
101///
102/// Handles both the comma style (`"To name(a: Int, b: Int) -> Ret"`) and the
103/// stdlib's prepositional groups (`"To native f (a: Int) and (b: Int) -> R"`):
104/// every parenthesized group before the arrow contributes its parameters.
105fn extract_params_from_signature(detail: &str) -> Vec<(String, String)> {
106    let head = detail.split("->").next().unwrap_or(detail);
107    let mut params = Vec::new();
108    let mut rest = head;
109    while let Some(open) = rest.find('(') {
110        let Some(close) = rest[open + 1..].find(')') else {
111            break;
112        };
113        let group = &rest[open + 1..open + 1 + close];
114        for part in group.split(',') {
115            let part = part.trim();
116            if part.is_empty() {
117                continue;
118            }
119            let mut split = part.splitn(2, ':');
120            let Some(name) = split.next().map(|s| s.trim().to_string()) else {
121                continue;
122            };
123            let ty = split
124                .next()
125                .map(|s| s.trim().to_string())
126                .unwrap_or_else(|| "auto".to_string());
127            params.push((name, ty));
128        }
129        rest = &rest[open + 1 + close + 1..];
130    }
131    params
132}
133
134#[cfg(test)]
135#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/signature_help/tests.rs"]
136mod tests;