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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// 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/>.

//! AST traversal utilities for LSP features.
//!
//! This module provides functions for finding nodes at positions,
//! collecting node paths, and other AST analysis tasks.

use crate::ast::{AstNode, ObjectEntry, Span};

/// A path through the AST from root to a specific node.
///
/// Each entry contains a reference to a node and context about
/// how it was reached (key name or array index).
#[derive(Debug, Clone)]
pub struct NodePathEntry<'a> {
    /// The AST node at this position in the path
    pub node: &'a AstNode,
    /// If this node is an object entry value, the key name
    pub key: Option<&'a str>,
    /// If this node is an array item, the index
    pub index: Option<usize>,
}

impl<'a> NodePathEntry<'a> {
    /// Create a new path entry for a root or standalone node.
    pub fn root(node: &'a AstNode) -> Self {
        Self { node, key: None, index: None }
    }

    /// Create a new path entry for an object entry value.
    pub fn with_key(node: &'a AstNode, key: &'a str) -> Self {
        Self { node, key: Some(key), index: None }
    }

    /// Create a new path entry for an array item.
    pub fn with_index(node: &'a AstNode, index: usize) -> Self {
        Self { node, key: None, index: Some(index) }
    }
}

/// Result of finding a node at a position.
#[derive(Debug)]
pub struct NodeAtPosition<'a> {
    /// Path from root to the found node
    pub path: Vec<NodePathEntry<'a>>,
    /// The innermost node containing the position
    pub node: &'a AstNode,
    /// If position is on an object key, the entry info
    pub on_key: Option<&'a ObjectEntry>,
}

/// Find the AST node at a given position.
///
/// Returns the path from root to the most specific node containing
/// the position, along with context about whether the position is
/// on a key or value.
///
/// # Arguments
/// * `root` - The root AST node (typically Document)
/// * `line` - 0-indexed line number
/// * `column` - 0-indexed column (UTF-8 bytes)
/// * `offset` - Byte offset from start of document
///
/// # Returns
/// `Some(NodeAtPosition)` if a node contains the position, `None` otherwise
pub fn find_node_at_position(
    root: &AstNode,
    line: u32,
    column: u32,
    offset: u32,
) -> Option<NodeAtPosition<'_>> {
    let pos = crate::ast::Position::new(line, column, offset);

    if !root.span().contains(pos) {
        return None;
    }

    let mut path = vec![NodePathEntry::root(root)];
    let mut current = root;
    let mut on_key: Option<&ObjectEntry> = None;

    loop {
        match current {
            AstNode::Document { children, .. } => {
                if let Some(child) = find_child_containing(children, pos) {
                    path.push(NodePathEntry::root(child));
                    current = child;
                } else {
                    break;
                }
            }
            AstNode::Object { entries, .. } => {
                if let Some((entry, is_on_key)) = find_entry_containing(entries, pos) {
                    if is_on_key {
                        on_key = Some(entry);
                        break;
                    }
                    path.push(NodePathEntry::with_key(&entry.value, &entry.key));
                    current = &entry.value;
                } else {
                    break;
                }
            }
            AstNode::Array { items, .. } => {
                if let Some((idx, item)) = find_item_containing(items, pos) {
                    path.push(NodePathEntry::with_index(item, idx));
                    current = item;
                } else {
                    break;
                }
            }
            // Leaf nodes - stop here
            AstNode::String { .. }
            | AstNode::Number { .. }
            | AstNode::Bool { .. }
            | AstNode::Null { .. }
            | AstNode::Reference { .. } => break,
        }
    }

    Some(NodeAtPosition { path, node: current, on_key })
}

/// Find a child node containing the position.
fn find_child_containing(children: &[AstNode], pos: crate::ast::Position) -> Option<&AstNode> {
    children.iter().find(|child| child.span().contains(pos))
}

/// Find an object entry containing the position.
/// Returns the entry and whether the position is on the key (true) or value (false).
fn find_entry_containing(
    entries: &[ObjectEntry],
    pos: crate::ast::Position,
) -> Option<(&ObjectEntry, bool)> {
    for entry in entries {
        // Check if on the key
        if entry.key_span.contains(pos) {
            return Some((entry, true));
        }
        // Check if on the value
        if entry.value.span().contains(pos) {
            return Some((entry, false));
        }
    }
    None
}

/// Find an array item containing the position.
/// Returns the index and reference to the item.
fn find_item_containing(items: &[AstNode], pos: crate::ast::Position) -> Option<(usize, &AstNode)> {
    items.iter().enumerate().find(|(_, item)| item.span().contains(pos))
}

/// Collect all keys from sibling entries in an object.
///
/// # Arguments
/// * `entries` - The object entries
/// * `exclude_key` - Optional key to exclude (e.g., the key being completed)
///
/// # Returns
/// Vector of sibling key names
pub fn collect_sibling_keys<'a>(
    entries: &'a [ObjectEntry],
    exclude_key: Option<&str>,
) -> Vec<&'a str> {
    entries.iter().map(|e| e.key.as_str()).filter(|k| exclude_key != Some(*k)).collect()
}

/// Collect all keys from a node path (parent objects).
///
/// # Arguments
/// * `path` - The node path from root
///
/// # Returns
/// Vector of keys from ancestor objects
pub fn collect_parent_keys<'a>(path: &'a [NodePathEntry<'a>]) -> Vec<&'a str> {
    let mut keys = Vec::new();

    for entry in path {
        if let AstNode::Object { entries, .. } = entry.node {
            for obj_entry in entries {
                keys.push(obj_entry.key.as_str());
            }
        }
    }

    keys
}

/// Build a dot-separated key path from the node path.
pub fn build_key_path(path: &[NodePathEntry<'_>]) -> String {
    let keys: Vec<&str> = path.iter().filter_map(|entry| entry.key).collect();
    keys.join(".")
}

/// Find all definitions of a key within an object.
///
/// Used for go-to-definition when duplicate keys exist.
///
/// # Arguments
/// * `entries` - The object entries to search
/// * `key_name` - The key to find
///
/// # Returns
/// Vector of spans where the key is defined
pub fn find_key_definitions<'a>(entries: &'a [ObjectEntry], key_name: &str) -> Vec<&'a Span> {
    entries.iter().filter(|e| e.key == key_name).map(|e| &e.key_span).collect()
}

/// Collect all keys with their spans from an AST.
///
/// Recursively traverses the entire AST and collects every object key
/// with its corresponding span. Used by find references and rename features.
///
/// # Arguments
/// * `ast` - The root AST node to traverse
///
/// # Returns
/// Vector of (key_name, key_span) tuples for all keys in the tree
pub fn collect_all_keys(ast: &AstNode) -> Vec<(String, Span)> {
    let mut keys = Vec::new();
    collect_keys_recursive(ast, &mut keys);
    keys
}

/// Helper function for recursive key collection.
fn collect_keys_recursive(node: &AstNode, keys: &mut Vec<(String, Span)>) {
    match node {
        AstNode::Document { children, .. } => {
            for child in children {
                collect_keys_recursive(child, keys);
            }
        }
        AstNode::Object { entries, .. } => {
            for entry in entries {
                keys.push((entry.key.clone(), entry.key_span));
                collect_keys_recursive(&entry.value, keys);
            }
        }
        AstNode::Array { items, .. } => {
            for item in items {
                collect_keys_recursive(item, keys);
            }
        }
        // Leaf nodes - no keys to collect
        AstNode::String { .. }
        | AstNode::Number { .. }
        | AstNode::Bool { .. }
        | AstNode::Null { .. }
        | AstNode::Reference { .. } => {}
    }
}

/// Pre-computed line offset index for O(1) offset lookups.
///
/// Stores the byte offset of each line start, enabling fast
/// conversion from (line, column) to byte offset.
#[derive(Debug, Clone)]
pub struct LineIndex {
    offsets: Vec<u32>,
}

impl LineIndex {
    /// Build a line index from source text.
    pub fn new(source: &str) -> Self {
        let mut offsets = vec![0u32];
        for (i, ch) in source.char_indices() {
            if ch == '\n' {
                offsets.push(i as u32 + 1);
            }
        }
        Self { offsets }
    }

    /// Get the byte offset for a (line, column) position.
    #[inline]
    pub fn offset(&self, line: u32, column: u32) -> Option<u32> {
        let line_start = self.offsets.get(line as usize)?;
        Some(line_start.saturating_add(column))
    }
}

/// Calculate byte offset from line and column position.
///
/// Converts a (line, column) position into a byte offset in the source text.
/// This is necessary because Rust's string indexing uses byte offsets, while
/// LSP uses line/column positions.
///
/// # Arguments
///
/// * `source` - The document text
/// * `line` - 0-based line number
/// * `column` - 0-based UTF-8 column (character offset, not byte offset)
///
/// # Returns
///
/// Byte offset from start of document, or `None` if position is out of bounds.
///
/// # Performance Note
///
/// Prefer `LineIndex::offset()` for repeated lookups. This function does an
/// O(N) scan and is intended for one-off use.
pub fn calculate_offset(source: &str, line: u32, column: u32) -> Option<u32> {
    LineIndex::new(source).offset(line, column)
}

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

    #[test]
    fn test_find_node_at_root() {
        let source = "name: Alice";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        let result = find_node_at_position(&ast, 0, 0, 0);
        assert!(result.is_some());
    }

    #[test]
    fn test_find_node_on_key() {
        let source = "name: Alice";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        // Position on "name" key
        let result = find_node_at_position(&ast, 0, 2, 2);
        assert!(result.is_some());
        let result = result.unwrap();
        assert!(result.on_key.is_some());
        assert_eq!(result.on_key.unwrap().key, "name");
    }

    #[test]
    fn test_find_node_on_value() {
        let source = "name: Alice";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        // Position on "Alice" value (after ": ")
        let result = find_node_at_position(&ast, 0, 6, 6);
        assert!(result.is_some());
        let result = result.unwrap();
        assert!(result.on_key.is_none());
        matches!(result.node, AstNode::String { .. });
    }

    #[test]
    fn test_collect_sibling_keys() {
        let source = "name: Alice
age: 30
city: Boston";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        if let AstNode::Document { children, .. } = &ast
            && let Some(AstNode::Object { entries, .. }) = children.first()
        {
            let keys = collect_sibling_keys(entries, None);
            assert_eq!(keys.len(), 3);
            assert!(keys.contains(&"name"));
            assert!(keys.contains(&"age"));
            assert!(keys.contains(&"city"));
        }
    }

    #[test]
    fn test_find_key_definitions_unique() {
        let source = "name: Alice\nage: 30";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        if let AstNode::Document { children, .. } = &ast
            && let Some(AstNode::Object { entries, .. }) = children.first()
        {
            let defs = find_key_definitions(entries, "name");
            assert_eq!(defs.len(), 1);
        }
    }

    #[test]
    fn test_collect_all_keys_empty() {
        // Test with empty document
        let source = "";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        let keys = collect_all_keys(&ast);
        assert_eq!(keys.len(), 0);
    }

    #[test]
    fn test_collect_all_keys_single_object() {
        // Test with single object
        let source = "name: Alice\nage: 30";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        let keys = collect_all_keys(&ast);
        assert_eq!(keys.len(), 2);

        let key_names: Vec<&str> = keys.iter().map(|(k, _)| k.as_str()).collect();
        assert!(key_names.contains(&"name"));
        assert!(key_names.contains(&"age"));
    }

    #[test]
    fn test_collect_all_keys_nested_objects() {
        // Test with nested objects
        let source = r"
user:
  name: Alice
  address:
    city: Boston
    zip: 02101
";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        let keys = collect_all_keys(&ast);
        assert_eq!(keys.len(), 5); // user, name, address, city, zip

        let key_names: Vec<&str> = keys.iter().map(|(k, _)| k.as_str()).collect();
        assert!(key_names.contains(&"user"));
        assert!(key_names.contains(&"name"));
        assert!(key_names.contains(&"address"));
        assert!(key_names.contains(&"city"));
        assert!(key_names.contains(&"zip"));
    }

    #[test]
    fn test_collect_all_keys_with_arrays() {
        // Test with tabular array containing objects
        let source = "users[2]{id,name}:\n  1,Alice\n  2,Bob";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        let keys = collect_all_keys(&ast);

        // Should find: users (1), id (2), name (2) = 5 keys total
        assert_eq!(keys.len(), 5);

        let key_names: Vec<&str> = keys.iter().map(|(k, _)| k.as_str()).collect();
        assert!(key_names.contains(&"users"));
        assert_eq!(key_names.iter().filter(|&&k| k == "id").count(), 2);
        assert_eq!(key_names.iter().filter(|&&k| k == "name").count(), 2);
    }

    #[test]
    fn test_collect_all_keys_preserves_spans() {
        // Test that spans are correctly preserved
        let source = "name: Alice";
        let (ast, _) = parse_with_errors(source);
        let ast = ast.expect("should parse");

        let keys = collect_all_keys(&ast);
        assert_eq!(keys.len(), 1);

        let (key_name, span) = &keys[0];
        assert_eq!(key_name, "name");
        // Verify span points to the key position
        assert_eq!(span.start.line, 0);
        assert_eq!(span.start.column, 0);
    }
}