toon-lsp 0.7.21

Language Server Protocol implementation for TOON (Token-Oriented Object Notation)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2024-2025 w0wl0lxd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Rename symbol support for TOON keys.
//!
//! This module provides functionality to validate and rename object keys
//! throughout the document, which is used by the LSP `textDocument/rename`
//! and `textDocument/prepareRename` features.

use crate::ast::{AstNode, Span};
use crate::lsp::ast_utils::{calculate_offset, collect_all_keys, find_node_at_position};

/// Result of prepare-rename validation.
///
/// Returned by [`prepare_rename`] to indicate that a rename operation
/// is valid at the cursor position. The LSP client uses this information
/// to show a rename dialog with the current key name as the default.
///
/// # Fields
///
/// * `range` - The span of the key identifier to be renamed
/// * `placeholder` - The current key name to show in the rename dialog
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrepareRenameResult {
    /// Range of the key to rename
    pub range: Span,
    /// Current key name as placeholder/default
    pub placeholder: String,
}

/// A single text replacement for rename.
///
/// Represents one edit operation to apply when renaming a key. When a key
/// appears multiple times in a document, each occurrence generates a separate
/// `RenameEdit`.
///
/// # Fields
///
/// * `span` - The location of the key occurrence to replace
/// * `new_text` - The new key name to insert
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenameEdit {
    /// Range to replace
    pub span: Span,
    /// New key name
    pub new_text: String,
}

/// Validate if rename is possible at the given position.
///
/// Called by the LSP server to check if the cursor is positioned on a symbol
/// that can be renamed. Returns the range and current name if valid, or `None`
/// if the cursor is on a value or whitespace.
///
/// # Arguments
///
/// * `ast` - The parsed AST root node
/// * `text` - The original document text
/// * `line` - 0-based line number of cursor position
/// * `col` - 0-based UTF-8 column of cursor position
///
/// # Returns
///
/// `Some(PrepareRenameResult)` if cursor is on a key (renameable), `None` otherwise.
///
/// # Examples
///
/// ```
/// # use toon_lsp::lsp::rename::prepare_rename;
/// # use toon_lsp::parser::parse_with_errors;
/// let source = "name: Alice";
/// let (ast, _) = parse_with_errors(source);
/// let result = prepare_rename(&ast.unwrap(), source, 0, 2); // On "name"
/// assert!(result.is_some());
/// assert_eq!(result.unwrap().placeholder, "name");
/// ```
pub fn prepare_rename(
    ast: &AstNode,
    text: &str,
    line: u32,
    col: u32,
) -> Option<PrepareRenameResult> {
    // Calculate offset
    let offset = calculate_offset(text, line, col)?;

    // Use find_node_at_position to locate cursor
    let node_at_pos = find_node_at_position(ast, line, col, offset)?;

    // Check if on_key is Some
    let entry = node_at_pos.on_key?;

    // Return span and key name if on a key
    Some(PrepareRenameResult { range: entry.key_span, placeholder: entry.key.clone() })
}

/// Generate edits to rename a key at the given position.
///
/// Finds all occurrences of the key at the cursor position and generates
/// edit operations to rename them all to the new name. This ensures that
/// all uses of the key are updated consistently.
///
/// # Arguments
///
/// * `ast` - The parsed AST root node
/// * `text` - The original document text
/// * `line` - 0-based line number of cursor position
/// * `col` - 0-based UTF-8 column of cursor position
/// * `new_name` - The new key name to use
///
/// # Returns
///
/// Vector of [`RenameEdit`] for all occurrences of the key, sorted by position.
/// Returns empty vector if cursor is not on a key.
///
/// # Examples
///
/// ```
/// # use toon_lsp::lsp::rename::rename_key;
/// # use toon_lsp::parser::parse_with_errors;
/// let source = "id: 1\ndata:\n  id: 2";
/// let (ast, _) = parse_with_errors(source);
/// let edits = rename_key(&ast.unwrap(), source, 0, 0, "identifier");
/// assert_eq!(edits.len(), 2); // Both "id" keys renamed
/// ```
pub fn rename_key(
    ast: &AstNode,
    text: &str,
    line: u32,
    col: u32,
    new_name: &str,
) -> Vec<RenameEdit> {
    // Calculate offset
    let offset = match calculate_offset(text, line, col) {
        Some(o) => o,
        None => return Vec::new(),
    };

    // Find the node at cursor position
    let node_at_pos = match find_node_at_position(ast, line, col, offset) {
        Some(node) => node,
        None => return Vec::new(),
    };

    // Make sure we are actually on a key to start the rename
    let entry = match node_at_pos.on_key {
        Some(e) => e,
        None => return Vec::new(),
    };

    let key_name = &entry.key;

    // Compute parent path and fully qualified key path
    let parent_path = crate::lsp::ast_utils::build_key_path(&node_at_pos.path);
    let key_path = if parent_path.is_empty() {
        key_name.clone()
    } else {
        format!("{}.{}", parent_path, key_name)
    };

    let new_key_path = if parent_path.is_empty() {
        new_name.to_string()
    } else {
        format!("{}.{}", parent_path, new_name)
    };

    // Use collect_all_keys to get all keys with spans
    let all_keys = collect_all_keys(ast);

    // Filter for exact key name matches and create RenameEdit for each key
    let mut edits: Vec<RenameEdit> = all_keys
        .into_iter()
        .filter(|(k, _)| k == key_name) // Exact match only
        .map(|(_, span)| RenameEdit { span, new_text: new_name.to_string() })
        .collect();

    // Now find and rename all references pointing to this key
    let mut references = Vec::new();
    collect_references_recursive(ast, &mut references);

    for (path, span) in references {
        if path == key_path {
            edits.push(RenameEdit { span, new_text: format!("${{{}}}", new_key_path) });
        } else if path.starts_with(&format!("{}.", key_path)) {
            let suffix = &path[key_path.len()..];
            let resolved_new_path = format!("{}{}", new_key_path, suffix);
            edits.push(RenameEdit { span, new_text: format!("${{{}}}", resolved_new_path) });
        }
    }

    // Sort by position for consistent ordering
    edits.sort_by(|a, b| {
        a.span
            .start
            .line
            .cmp(&b.span.start.line)
            .then(a.span.start.column.cmp(&b.span.start.column))
    });

    edits
}

/// Helper function to recursively collect all Reference nodes from the AST.
fn collect_references_recursive(node: &AstNode, references: &mut Vec<(String, Span)>) {
    match node {
        AstNode::Document { children, .. } => {
            for child in children {
                collect_references_recursive(child, references);
            }
        }
        AstNode::Object { entries, .. } => {
            for entry in entries {
                collect_references_recursive(&entry.value, references);
            }
        }
        AstNode::Array { items, .. } => {
            for item in items {
                collect_references_recursive(item, references);
            }
        }
        AstNode::Reference { path, span, is_env, .. } if !is_env => {
            references.push((path.clone(), *span));
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_with_errors;

    // Test prepare_rename validates cursor is on key
    #[test]
    fn test_prepare_rename_on_key() {
        let source = "name: Alice";
        let (ast, errors) = parse_with_errors(source);
        assert!(errors.is_empty(), "Parse should succeed");
        let ast = ast.expect("AST should be present");

        // Position on "name" (line 0, col 1 - middle of "name")
        let result = prepare_rename(&ast, source, 0, 1);
        assert!(result.is_some(), "Should validate rename on key");
        assert_eq!(result.unwrap().placeholder, "name");
    }

    // Test prepare_rename returns range and placeholder
    #[test]
    fn test_prepare_rename_range_and_placeholder() {
        let source = "username: bob";
        let (ast, errors) = parse_with_errors(source);
        assert!(errors.is_empty(), "Parse should succeed");
        let ast = ast.expect("AST should be present");

        // Position on "username" (line 0, col 4)
        let result = prepare_rename(&ast, source, 0, 4);
        assert!(result.is_some(), "Should return prepare result");
        let result = result.unwrap();

        // Range should cover "username" (cols 0-8)
        assert_eq!(result.placeholder, "username");
        assert_eq!(result.range.start.column, 0);
        assert_eq!(result.range.end.column, 8);
    }

    // Test prepare_rename rejects cursor on value
    #[test]
    fn test_prepare_rename_on_value_rejected() {
        let source = "name: Alice";
        let (ast, errors) = parse_with_errors(source);
        assert!(errors.is_empty(), "Parse should succeed");
        let ast = ast.expect("AST should be present");

        // Position on "Alice" (value) - line 0, col 7
        let result = prepare_rename(&ast, source, 0, 7);
        assert!(result.is_none(), "Should reject rename on value");
    }

    // Test rename_key updates all occurrences
    #[test]
    fn test_rename_updates_all_occurrences() {
        let source = "id: 1\ndata:\n  id: 2";
        let (ast, errors) = parse_with_errors(source);
        assert!(errors.is_empty(), "Parse should succeed");
        let ast = ast.expect("AST should be present");

        // Position on first "id" (line 0, col 0)
        let edits = rename_key(&ast, source, 0, 0, "identifier");

        // Should return 2 edits: both "id" keys
        assert_eq!(edits.len(), 2, "Should rename all occurrences");
        assert_eq!(edits[0].new_text, "identifier");
        assert_eq!(edits[1].new_text, "identifier");
    }

    // Test rename preserves document validity
    #[test]
    fn test_rename_preserves_validity() {
        let source = "key: value";
        let (ast, errors) = parse_with_errors(source);
        assert!(errors.is_empty(), "Parse should succeed");
        let ast = ast.expect("AST should be present");

        // Rename "key" to "new_key"
        let edits = rename_key(&ast, source, 0, 0, "new_key");
        assert_eq!(edits.len(), 1, "Should have one edit");

        // Apply edits and verify document still parses
        let new_doc = apply_edits(source, &edits);
        assert_eq!(new_doc, "new_key: value");

        // Verify it parses without errors
        let (new_ast, new_errors) = parse_with_errors(&new_doc);
        assert!(new_errors.is_empty(), "Renamed document should parse");
        assert!(new_ast.is_some(), "Should have AST after rename");
    }

    // Test rename handles special characters
    #[test]
    fn test_rename_special_characters() {
        // Test with underscore (valid in TOON keys)
        let source = "my_key: value";
        let (ast, errors) = parse_with_errors(source);
        assert!(errors.is_empty(), "Parse should succeed");
        let ast = ast.expect("AST should be present");

        // Rename "my_key" to "my_new_key"
        let edits = rename_key(&ast, source, 0, 0, "my_new_key");
        assert_eq!(edits.len(), 1, "Should have one edit");
        assert_eq!(edits[0].new_text, "my_new_key");

        // Verify edit span covers the original key
        assert_eq!(edits[0].span.start.column, 0);
        assert_eq!(edits[0].span.end.column, 6); // "my_key" is 6 chars
    }

    // Test rename warns when creating duplicate keys at same level
    #[test]
    fn test_rename_duplicate_key_warning() {
        let source = "name: Alice\nage: 30";
        let (ast, errors) = parse_with_errors(source);
        assert!(errors.is_empty(), "Parse should succeed");
        let ast = ast.expect("AST should be present");

        // Renaming "age" (line 1, col 0) to "name" would create duplicate
        // Function should still return edits (LSP handler can add warning)
        let edits = rename_key(&ast, source, 1, 0, "name");
        assert_eq!(edits.len(), 1, "Should return edit even if creating duplicate");
        assert_eq!(edits[0].new_text, "name");

        // Apply and verify it creates duplicate (valid TOON but semantically questionable)
        let new_doc = apply_edits(source, &edits);
        assert!(new_doc.contains("name: Alice"));
        assert!(new_doc.contains("name: 30"));
    }

    #[test]
    fn test_rename_updates_references() {
        let source = "db:\n  port: 5432\nservice:\n  db_port: ${db.port}";
        let (ast, errors) = parse_with_errors(source);
        assert!(errors.is_empty(), "Parse should succeed");
        let ast = ast.expect("AST should be present");

        // Rename "port" (line 1, col 2) to "number"
        let edits = rename_key(&ast, source, 1, 2, "number");
        assert_eq!(edits.len(), 2, "Should have two edits (key + reference)");

        // Check key rename edit
        assert_eq!(edits[0].new_text, "number");
        assert_eq!(edits[0].span.start.line, 1);

        // Check reference rename edit
        assert_eq!(edits[1].new_text, "${db.number}");
        assert_eq!(edits[1].span.start.line, 3);

        // Apply edits and verify the references are updated
        let new_doc = apply_edits(source, &edits);
        assert_eq!(new_doc, "db:\n  number: 5432\nservice:\n  db_port: ${db.number}");
    }

    /// Helper function to apply edits to source text.
    fn apply_edits(source: &str, edits: &[RenameEdit]) -> String {
        // Sort edits by position (reverse order to apply from end to start)
        let mut sorted_edits = edits.to_vec();
        sorted_edits.sort_by_key(|e| std::cmp::Reverse(e.span.start.offset));

        let mut result = source.to_string();
        for edit in sorted_edits {
            let start = edit.span.start.offset as usize;
            let end = edit.span.end.offset as usize;
            result.replace_range(start..end, &edit.new_text);
        }

        result
    }
}