rustledger-lsp 0.21.0

Language Server Protocol implementation for Beancount
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
//! Call hierarchy handler for navigating account-transaction relationships.
//!
//! In beancount semantics:
//! - An account is like a "function"
//! - A transaction "calls" an account when it has a posting to that account
//! - Incoming calls: transactions that post TO this account
//! - Outgoing calls: from a transaction, the other accounts it touches

use lsp_types::{
    CallHierarchyIncomingCall, CallHierarchyIncomingCallsParams, CallHierarchyItem,
    CallHierarchyOutgoingCall, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
    Position, Range, SymbolKind, Uri,
};
use rustledger_core::{Directive, SYNTHESIZED_FILE_ID};
use rustledger_parser::ParseResult;
use std::collections::HashMap;

use super::utils::{LineIndex, PositionEncoding, get_word_at_position, is_account_like};

/// Handle a prepare call hierarchy request.
/// Returns the account at the cursor position as a CallHierarchyItem.
pub fn handle_prepare_call_hierarchy(
    params: &CallHierarchyPrepareParams,
    source: &str,
    parse_result: &ParseResult,
    uri: &Uri,
    encoding: PositionEncoding,
) -> Option<Vec<CallHierarchyItem>> {
    let position = params.text_document_position_params.position;
    let line_idx = position.line as usize;
    let lines: Vec<&str> = source.lines().collect();
    let line = lines.get(line_idx)?;

    // Get the word at the cursor position
    let (word, start, end) = get_word_at_position(line, position.character as usize, encoding)?;

    // Check if it's an account
    if !is_account_like(&word) {
        return None;
    }

    // Verify the account exists in the parse result
    if !account_exists(&word, parse_result) {
        return None;
    }

    let item = CallHierarchyItem {
        name: word.clone(),
        kind: SymbolKind::FUNCTION, // Use Function for "callable" semantics
        tags: None,
        detail: Some("Account".to_string()),
        uri: uri.clone(),
        range: Range {
            start: Position::new(position.line, start as u32),
            end: Position::new(position.line, end as u32),
        },
        selection_range: Range {
            start: Position::new(position.line, start as u32),
            end: Position::new(position.line, end as u32),
        },
        data: Some(serde_json::json!({ "account": word })),
    };

    Some(vec![item])
}

/// Handle incoming calls request.
/// Returns all transactions that post to this account.
pub fn handle_incoming_calls(
    params: &CallHierarchyIncomingCallsParams,
    source: &str,
    parse_result: &ParseResult,
    uri: &Uri,
    encoding: PositionEncoding,
) -> Option<Vec<CallHierarchyIncomingCall>> {
    let account = params
        .item
        .data
        .as_ref()
        .and_then(|v| v.get("account"))
        .and_then(|v| v.as_str())
        .unwrap_or(&params.item.name);

    let mut calls: Vec<CallHierarchyIncomingCall> = Vec::new();
    let line_index = LineIndex::new(source, encoding);

    // Find all transactions that reference this account
    for spanned in &parse_result.directives {
        if let Directive::Transaction(txn) = &spanned.value {
            let posting_indices: Vec<usize> = txn
                .postings
                .iter()
                .enumerate()
                .filter(|(_, p)| p.account.as_ref() == account)
                .map(|(i, _)| i)
                .collect();

            if posting_indices.is_empty() {
                continue;
            }

            // Get transaction location
            let (txn_line, _) = line_index.offset_to_position(spanned.span.start);

            // Build transaction description
            let description = format!("{} {} \"{}\"", txn.date, txn.flag, txn.narration.as_ref());

            // Find the ranges where this account appears in the
            // transaction. Per-posting span lookup (see #1142): the
            // prior `txn_line + 1 + idx` arithmetic broke for
            // transactions with interleaved posting-level metadata.
            let from_ranges: Vec<Range> = posting_indices
                .iter()
                .filter_map(|&idx| {
                    let sp = txn.postings.get(idx)?;
                    if sp.file_id == SYNTHESIZED_FILE_ID {
                        return None;
                    }
                    let (posting_line, _) = line_index.offset_to_position(sp.span.start);
                    let line_text = line_index.line_text(posting_line)?;
                    let col = line_text.find(account)?;
                    // Route both endpoints through the index so the
                    // emitted columns are in the negotiated encoding
                    // (byte offsets under UTF-8, UTF-16 code units
                    // under UTF-16). Pre-round-19 emitted `col as u32`
                    // directly — a UTF-16-negotiated client interpreted
                    // the UTF-8 byte offset as a UTF-16 code-unit
                    // count and misaligned every non-ASCII line.
                    let start = line_index.byte_in_line_to_position(posting_line, col)?;
                    let end =
                        line_index.byte_in_line_to_position(posting_line, col + account.len())?;
                    Some(Range { start, end })
                })
                .collect();

            if from_ranges.is_empty() {
                continue;
            }

            // Compute the transaction's full source range from the
            // outer directive span. The prior heuristic of
            // `txn_line + postings.len() + 1` under-counted lines
            // whenever the transaction had interleaved metadata or
            // pre-posting comments (same root cause as #1142).
            //
            // `spanned.span.end` is an *exclusive* byte offset that
            // typically already points at the start of the next line
            // (the parser consumes the trailing newline). Use the
            // resulting (line, col) directly; only normalize to the
            // next line when the end column is non-zero (i.e. the
            // span ends mid-line and the LSP range needs to round up).
            let (txn_end_line, txn_end_col) = line_index.offset_to_position(spanned.span.end);
            let normalized_end_line = if txn_end_col == 0 {
                txn_end_line
            } else {
                txn_end_line.saturating_add(1)
            };
            let txn_item = CallHierarchyItem {
                name: description,
                kind: SymbolKind::EVENT, // Use Event for transactions
                tags: None,
                detail: Some(format!("{} postings", txn.postings.len())),
                uri: uri.clone(),
                range: Range {
                    start: Position::new(txn_line, 0),
                    end: Position::new(normalized_end_line, 0),
                },
                selection_range: Range {
                    start: Position::new(txn_line, 0),
                    end: Position::new(txn_line, 10), // Just the date portion
                },
                data: Some(serde_json::json!({
                    "type": "transaction",
                    "line": txn_line
                })),
            };

            calls.push(CallHierarchyIncomingCall {
                from: txn_item,
                from_ranges,
            });
        }
    }

    if calls.is_empty() { None } else { Some(calls) }
}

/// Handle outgoing calls request.
/// For an account: returns nothing (accounts don't "call" other things).
/// For a transaction (identified by data): returns all accounts it posts to.
pub fn handle_outgoing_calls(
    params: &CallHierarchyOutgoingCallsParams,
    source: &str,
    parse_result: &ParseResult,
    uri: &Uri,
    encoding: PositionEncoding,
) -> Option<Vec<CallHierarchyOutgoingCall>> {
    // Check if this is a transaction
    let data = params.item.data.as_ref()?;
    let item_type = data.get("type").and_then(|v| v.as_str())?;

    if item_type != "transaction" {
        // Accounts don't have outgoing calls
        return None;
    }

    let txn_line = data.get("line").and_then(|v| v.as_u64())? as u32;
    let line_index = LineIndex::new(source, encoding);

    // Find the transaction at this line
    for spanned in &parse_result.directives {
        if let Directive::Transaction(txn) = &spanned.value {
            let (line, _) = line_index.offset_to_position(spanned.span.start);

            if line != txn_line {
                continue;
            }

            // Collect unique accounts from postings
            let mut account_postings: HashMap<String, Vec<usize>> = HashMap::new();

            for (idx, posting) in txn.postings.iter().enumerate() {
                let account = posting.account.to_string();
                account_postings.entry(account).or_default().push(idx);
            }

            let calls: Vec<CallHierarchyOutgoingCall> = account_postings
                .into_iter()
                .filter_map(|(account, indices)| {
                    // Find where this account is defined (open directive)
                    let account_location =
                        find_account_definition(parse_result, &line_index, &account);
                    let (_acc_line, acc_range) = match account_location {
                        Some(loc) => loc,
                        None => {
                            // Fallback: use first posting location, looked
                            // up via its span (see #1142).
                            let sp = txn.postings.get(indices[0])?;
                            if sp.file_id == SYNTHESIZED_FILE_ID {
                                return None;
                            }
                            let (posting_line, _) = line_index.offset_to_position(sp.span.start);
                            let line_text = line_index.line_text(posting_line)?;
                            let col = line_text.find(&account)?;
                            let start = line_index.byte_in_line_to_position(posting_line, col)?;
                            let end = line_index
                                .byte_in_line_to_position(posting_line, col + account.len())?;
                            (posting_line, Range { start, end })
                        }
                    };

                    // Ranges where this account is "called" from the
                    // transaction (per-posting span lookup, see #1142).
                    let from_ranges: Vec<Range> = indices
                        .iter()
                        .filter_map(|&idx| {
                            let sp = txn.postings.get(idx)?;
                            if sp.file_id == SYNTHESIZED_FILE_ID {
                                return None;
                            }
                            let (posting_line, _) = line_index.offset_to_position(sp.span.start);
                            let line_text = line_index.line_text(posting_line)?;
                            let col = line_text.find(&account)?;
                            let start = line_index.byte_in_line_to_position(posting_line, col)?;
                            let end = line_index
                                .byte_in_line_to_position(posting_line, col + account.len())?;
                            Some(Range { start, end })
                        })
                        .collect();

                    let account_item = CallHierarchyItem {
                        name: account.clone(),
                        kind: SymbolKind::FUNCTION,
                        tags: None,
                        detail: Some("Account".to_string()),
                        uri: uri.clone(),
                        range: acc_range,
                        selection_range: acc_range,
                        data: Some(serde_json::json!({ "account": account })),
                    };

                    Some(CallHierarchyOutgoingCall {
                        to: account_item,
                        from_ranges,
                    })
                })
                .collect();

            return if calls.is_empty() { None } else { Some(calls) };
        }
    }

    None
}

/// Find where an account is defined (open directive).
fn find_account_definition(
    parse_result: &ParseResult,
    line_index: &LineIndex<'_>,
    account: &str,
) -> Option<(u32, Range)> {
    for spanned in &parse_result.directives {
        if let Directive::Open(open) = &spanned.value
            && open.account.as_ref() == account
        {
            let (line, _) = line_index.offset_to_position(spanned.span.start);
            let line_text = line_index.line_text(line)?;
            let col = line_text.find(account)?;
            let start = line_index.byte_in_line_to_position(line, col)?;
            let end = line_index.byte_in_line_to_position(line, col + account.len())?;
            return Some((line, Range { start, end }));
        }
    }
    None
}

/// Check if an account exists in the parse result.
fn account_exists(account: &str, parse_result: &ParseResult) -> bool {
    for spanned in &parse_result.directives {
        match &spanned.value {
            Directive::Open(open) if open.account.as_ref() == account => return true,
            Directive::Close(close) if close.account.as_ref() == account => return true,
            Directive::Balance(bal) if bal.account.as_ref() == account => return true,
            Directive::Transaction(txn)
                if txn.postings.iter().any(|p| p.account.as_ref() == account) =>
            {
                return true;
            }
            _ => {}
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustledger_parser::parse;

    #[test]
    fn test_prepare_call_hierarchy() {
        let source = r#"2024-01-01 open Assets:Bank:Checking USD
2024-01-15 * "Coffee"
  Assets:Bank:Checking  -5.00 USD
  Expenses:Food
"#;
        let result = parse(source);
        let uri: Uri = "file:///test.beancount".parse().unwrap();

        let params = CallHierarchyPrepareParams {
            text_document_position_params: lsp_types::TextDocumentPositionParams {
                text_document: lsp_types::TextDocumentIdentifier { uri: uri.clone() },
                position: Position::new(0, 20), // On "Assets:Bank:Checking"
            },
            work_done_progress_params: Default::default(),
        };

        let items =
            handle_prepare_call_hierarchy(&params, source, &result, &uri, PositionEncoding::Utf16);
        assert!(items.is_some());

        let items = items.unwrap();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].name, "Assets:Bank:Checking");
        assert_eq!(items[0].kind, SymbolKind::FUNCTION);
    }

    #[test]
    fn test_incoming_calls() {
        let source = r#"2024-01-01 open Assets:Bank:Checking USD
2024-01-15 * "Coffee"
  Assets:Bank:Checking  -5.00 USD
  Expenses:Food
2024-01-16 * "Lunch"
  Assets:Bank:Checking  -10.00 USD
  Expenses:Food
"#;
        let result = parse(source);
        let uri: Uri = "file:///test.beancount".parse().unwrap();

        let item = CallHierarchyItem {
            name: "Assets:Bank:Checking".to_string(),
            kind: SymbolKind::FUNCTION,
            tags: None,
            detail: Some("Account".to_string()),
            uri: uri.clone(),
            range: Range::default(),
            selection_range: Range::default(),
            data: Some(serde_json::json!({ "account": "Assets:Bank:Checking" })),
        };

        let params = CallHierarchyIncomingCallsParams {
            item,
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let calls = handle_incoming_calls(&params, source, &result, &uri, PositionEncoding::Utf16);
        assert!(calls.is_some());

        let calls = calls.unwrap();
        assert_eq!(calls.len(), 2); // Two transactions reference this account
    }

    #[test]
    fn test_outgoing_calls_from_transaction() {
        let source = r#"2024-01-01 open Assets:Bank:Checking USD
2024-01-01 open Expenses:Food
2024-01-15 * "Coffee"
  Assets:Bank:Checking  -5.00 USD
  Expenses:Food
"#;
        let result = parse(source);
        let uri: Uri = "file:///test.beancount".parse().unwrap();

        let item = CallHierarchyItem {
            name: "2024-01-15 * \"Coffee\"".to_string(),
            kind: SymbolKind::EVENT,
            tags: None,
            detail: None,
            uri: uri.clone(),
            range: Range::default(),
            selection_range: Range::default(),
            data: Some(serde_json::json!({
                "type": "transaction",
                "line": 2
            })),
        };

        let params = CallHierarchyOutgoingCallsParams {
            item,
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let calls = handle_outgoing_calls(&params, source, &result, &uri, PositionEncoding::Utf16);
        assert!(calls.is_some());

        let calls = calls.unwrap();
        assert_eq!(calls.len(), 2); // Two accounts in this transaction
    }
}