Skip to main content

postgres_lsp_analysis/
code_actions.rs

1use tree_sitter::Node;
2
3/// A code action produced by the analysis layer.
4#[derive(Debug, Clone)]
5pub struct CodeAction {
6    pub title: String,
7    pub kind: CodeActionKind,
8    pub edit: TextEditAction,
9}
10
11#[derive(Debug, Clone)]
12pub enum CodeActionKind {
13    QuickFix,
14    RefactorRewrite,
15}
16
17/// A single text edit for a code action.
18#[derive(Debug, Clone)]
19pub struct TextEditAction {
20    pub start_line: usize,
21    pub start_col: usize,
22    pub end_line: usize,
23    pub end_col: usize,
24    pub new_text: String,
25}
26
27/// Compute code actions for a given cursor range in the document.
28pub fn compute_code_actions(
29    tree: &tree_sitter::Tree,
30    source: &str,
31    start_line: usize,
32    start_col: usize,
33    end_line: usize,
34    end_col: usize,
35) -> Vec<CodeAction> {
36    let mut actions = Vec::new();
37
38    // 1. Add missing semicolon — look for MISSING nodes in the range.
39    collect_missing_semicolons(
40        tree.root_node(),
41        (start_line, start_col),
42        (end_line, end_col),
43        &mut actions,
44    );
45
46    // 2. Uppercase keyword at cursor — if the cursor is on a lowercase keyword.
47    if let Some(node) = tree.root_node().descendant_for_point_range(
48        tree_sitter::Point {
49            row: start_line,
50            column: start_col,
51        },
52        tree_sitter::Point {
53            row: end_line,
54            column: end_col,
55        },
56    ) && let Some(action) = uppercase_keyword_action(node, source)
57    {
58        actions.push(action);
59    }
60
61    actions
62}
63
64/// Find MISSING `;` nodes within the requested range and offer to insert them.
65fn collect_missing_semicolons(
66    node: Node,
67    start: (usize, usize),
68    end: (usize, usize),
69    actions: &mut Vec<CodeAction>,
70) {
71    if node.is_missing() && node.kind() == ";" {
72        let line = node.start_position().row;
73        let col = node.start_position().column;
74        if (line, col) >= start && (line, col) <= end {
75            actions.push(CodeAction {
76                title: "Add missing semicolon".to_string(),
77                kind: CodeActionKind::QuickFix,
78                edit: TextEditAction {
79                    start_line: line,
80                    start_col: col,
81                    end_line: line,
82                    end_col: col,
83                    new_text: ";".to_string(),
84                },
85            });
86        }
87    }
88
89    let mut cursor = node.walk();
90    for child in node.children(&mut cursor) {
91        collect_missing_semicolons(child, start, end, actions);
92    }
93}
94
95/// If the cursor is on a keyword node that is lowercase, offer to uppercase it.
96fn uppercase_keyword_action(node: Node, source: &str) -> Option<CodeAction> {
97    if !node.kind().starts_with("kw_") {
98        return None;
99    }
100
101    let text = node.utf8_text(source.as_bytes()).ok()?;
102    let upper = text.to_uppercase();
103
104    // Only offer if the text isn't already uppercase.
105    if text == upper {
106        return None;
107    }
108
109    Some(CodeAction {
110        title: format!("Uppercase keyword: {text} → {upper}"),
111        kind: CodeActionKind::RefactorRewrite,
112        edit: TextEditAction {
113            start_line: node.start_position().row,
114            start_col: node.start_position().column,
115            end_line: node.end_position().row,
116            end_col: node.end_position().column,
117            new_text: upper,
118        },
119    })
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    fn parse(sql: &str) -> tree_sitter::Tree {
127        let mut parser = tree_sitter::Parser::new();
128        let lang: tree_sitter::Language = tree_sitter_postgres::LANGUAGE.into();
129        parser.set_language(&lang).unwrap();
130        parser.parse(sql, None).unwrap()
131    }
132
133    #[test]
134    fn missing_semicolon_action() {
135        // Two statements without semicolons trigger errors in tree-sitter-postgres.
136        let sql = "SELECT 1\nSELECT 2;";
137        let tree = parse(sql);
138        assert!(
139            tree.root_node().has_error(),
140            "grammar should report error for missing separator"
141        );
142        let actions = compute_code_actions(&tree, sql, 0, 0, 1, 9);
143        // If the grammar emits MISSING `;` nodes, we should get a quick fix.
144        // If it emits ERROR nodes instead, the list may be empty, which is
145        // acceptable — the grammar controls which node types appear.
146        for action in &actions {
147            if action.title == "Add missing semicolon" {
148                assert_eq!(action.edit.new_text, ";");
149                assert!(matches!(action.kind, CodeActionKind::QuickFix));
150            }
151        }
152    }
153
154    #[test]
155    fn uppercase_keyword_action_for_lowercase() {
156        let sql = "select 1;";
157        let tree = parse(sql);
158        // Cursor on "select" (byte col 0-6)
159        let actions = compute_code_actions(&tree, sql, 0, 0, 0, 0);
160        let kw_actions: Vec<_> = actions
161            .iter()
162            .filter(|a| a.title.contains("Uppercase"))
163            .collect();
164        assert!(!kw_actions.is_empty(), "should offer to uppercase 'select'");
165        assert_eq!(kw_actions[0].edit.new_text, "SELECT");
166    }
167
168    #[test]
169    fn no_uppercase_action_for_already_upper() {
170        let sql = "SELECT 1;";
171        let tree = parse(sql);
172        let actions = compute_code_actions(&tree, sql, 0, 0, 0, 0);
173        let kw_actions: Vec<_> = actions
174            .iter()
175            .filter(|a| a.title.contains("Uppercase"))
176            .collect();
177        assert!(
178            kw_actions.is_empty(),
179            "should not offer uppercase for already-uppercase keyword"
180        );
181    }
182
183    #[test]
184    fn no_actions_for_valid_sql() {
185        let sql = "SELECT 1;";
186        let tree = parse(sql);
187        let actions = compute_code_actions(&tree, sql, 0, 7, 0, 7);
188        // Should have no quick fixes (valid SQL, cursor on "1")
189        let fixes: Vec<_> = actions
190            .iter()
191            .filter(|a| matches!(a.kind, CodeActionKind::QuickFix))
192            .collect();
193        assert!(fixes.is_empty(), "no quick fixes for valid SQL");
194    }
195}