batless 0.5.0

A non-blocking, LLM-friendly code viewer inspired by bat
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! AST-based code summarization using tree-sitter
//!
//! This module provides robust, syntax-aware code summarization by parsing
//! the source code into an Abstract Syntax Tree (AST) and extracting
//! relevant nodes based on the summary level.

use crate::summary::SummaryLevel;
use crate::summary_item::SummaryItem;
use std::ops::ControlFlow;
use std::time::{Duration, Instant};
// use streaming_iterator::StreamingIterator; // Removed
use tree_sitter::{ParseOptions, Parser, Query, QueryCursor, StreamingIterator}; // Added StreamingIterator

/// Maximum time allowed for tree-sitter parsing before aborting.
const PARSE_TIMEOUT: Duration = Duration::from_millis(500);

/// AST-based summary extractor
pub struct AstSummarizer;

impl AstSummarizer {
    /// Parse content with a timeout to prevent hangs on pathological inputs.
    /// Returns `None` if parsing fails or times out.
    fn parse_with_timeout(parser: &mut Parser, content: &str) -> Option<tree_sitter::Tree> {
        Self::parse_with_deadline(parser, content, PARSE_TIMEOUT)
    }

    /// Parse content with a configurable timeout duration.
    /// Returns `None` if parsing fails or the deadline is exceeded.
    fn parse_with_deadline(
        parser: &mut Parser,
        content: &str,
        timeout: Duration,
    ) -> Option<tree_sitter::Tree> {
        let deadline = Instant::now() + timeout;
        let bytes = content.as_bytes();
        let len = bytes.len();
        let mut progress = |_: &_| {
            if Instant::now() >= deadline {
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        };
        let mut options = ParseOptions::new().progress_callback(&mut progress);
        parser.parse_with_options(
            &mut |i, _| {
                if i < len {
                    &bytes[i..]
                } else {
                    &[]
                }
            },
            None,
            Some(options.reborrow()),
        )
    }

    /// Extract a summary of important code structures using AST parsing
    pub fn extract_summary(
        content: &str,
        language: Option<&str>,
        level: SummaryLevel,
    ) -> Vec<SummaryItem> {
        if !level.is_enabled() {
            return Vec::new();
        }

        match language {
            Some("Rust") => Self::summarize_rust(content, level),
            Some("Python") => Self::summarize_python(content, level),
            Some("JavaScript" | "JSX") => Self::summarize_javascript(content, level),
            Some("TypeScript" | "TSX") => Self::summarize_typescript(content, level),
            // Fallback to empty for unsupported languages (caller should handle fallback to regex)
            _ => Vec::new(),
        }
    }

    fn summarize_rust(content: &str, level: SummaryLevel) -> Vec<SummaryItem> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .expect("Error loading Rust grammar");

        let Some(tree) = Self::parse_with_timeout(&mut parser, content) else {
            return Vec::new();
        };
        let root_node = tree.root_node();

        let query_string = match level {
            SummaryLevel::Minimal => {
                "(function_item name: (identifier) @name) @function
                 (struct_item name: (type_identifier) @name) @struct
                 (enum_item name: (type_identifier) @name) @enum
                 (impl_item) @impl"
            }
            SummaryLevel::Standard => {
                "(function_item name: (identifier) @name) @function
                 (struct_item name: (type_identifier) @name) @struct
                 (enum_item name: (type_identifier) @name) @enum
                 (impl_item) @impl
                 (trait_item name: (type_identifier) @name) @trait
                 (mod_item name: (identifier) @name) @mod
                 (use_declaration) @use"
            }
            SummaryLevel::Detailed => {
                "(function_item name: (identifier) @name) @function
                 (struct_item name: (type_identifier) @name) @struct
                 (enum_item name: (type_identifier) @name) @enum
                 (impl_item) @impl
                 (trait_item name: (type_identifier) @name) @trait
                 (mod_item name: (identifier) @name) @mod
                 (macro_definition name: (identifier) @name) @macro
                 (use_declaration) @use
                 (let_declaration) @let
                 (const_item) @const
                 (static_item) @static"
            }
            SummaryLevel::None => return Vec::new(),
        };

        let query = Query::new(&tree_sitter_rust::LANGUAGE.into(), query_string)
            .expect("Error compiling query");

        let capture_names = query.capture_names().to_vec();
        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(&query, root_node, content.as_bytes());

        let lines: Vec<&str> = content.lines().collect();
        // BTreeMap<start_line, (kind, end_line)> — first write wins per line
        let mut line_items: std::collections::BTreeMap<usize, (String, usize)> =
            std::collections::BTreeMap::new();

        while let Some(m) = matches.next() {
            // Use @name capture's row when present — it lands on the declaration line,
            // not on any preceding decorator whose span is included in the outer node
            let name_row = m
                .captures
                .iter()
                .find(|c| capture_names[c.index as usize] == "name")
                .map(|c| c.node.start_position().row);
            for capture in m.captures {
                let kind = &capture_names[capture.index as usize];
                if *kind == "name" {
                    continue;
                }
                let start_line = name_row.unwrap_or_else(|| capture.node.start_position().row);
                let end_line = capture.node.end_position().row;
                line_items
                    .entry(start_line)
                    .or_insert_with(|| (kind.to_string(), end_line));
            }
        }

        line_items
            .into_iter()
            .filter_map(|(idx, (kind, end_row))| {
                lines
                    .get(idx)
                    .map(|&line| SummaryItem::new(line, idx + 1, Some(end_row + 1), kind))
            })
            .collect()
    }

    fn summarize_python(content: &str, level: SummaryLevel) -> Vec<SummaryItem> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_python::LANGUAGE.into())
            .expect("Error loading Python grammar");

        let Some(tree) = Self::parse_with_timeout(&mut parser, content) else {
            return Vec::new();
        };
        let root_node = tree.root_node();

        let query_string = match level {
            SummaryLevel::Minimal => {
                "(function_definition name: (identifier) @name) @function
                 (class_definition name: (identifier) @name) @class"
            }
            SummaryLevel::Standard => {
                "(function_definition name: (identifier) @name) @function
                 (class_definition name: (identifier) @name) @class
                 (import_statement) @import
                 (import_from_statement) @import_from
                 (decorated_definition) @decorator"
            }
            SummaryLevel::Detailed => {
                "(function_definition name: (identifier) @name) @function
                 (class_definition name: (identifier) @name) @class
                 (import_statement) @import
                 (import_from_statement) @import_from
                 (decorated_definition) @decorator
                 (assignment left: (identifier) @name) @assignment
                 (global_statement) @global
                 (nonlocal_statement) @nonlocal"
            }
            SummaryLevel::None => return Vec::new(),
        };

        let query = Query::new(&tree_sitter_python::LANGUAGE.into(), query_string)
            .expect("Error compiling query");

        let capture_names = query.capture_names().to_vec();
        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(&query, root_node, content.as_bytes());

        let lines: Vec<&str> = content.lines().collect();
        let mut line_items: std::collections::BTreeMap<usize, (String, usize)> =
            std::collections::BTreeMap::new();

        while let Some(m) = matches.next() {
            // Use @name capture's row when present — it lands on the declaration line,
            // not on any preceding decorator whose span is included in the outer node
            let name_row = m
                .captures
                .iter()
                .find(|c| capture_names[c.index as usize] == "name")
                .map(|c| c.node.start_position().row);
            for capture in m.captures {
                let kind = &capture_names[capture.index as usize];
                if *kind == "name" {
                    continue;
                }
                let start_line = name_row.unwrap_or_else(|| capture.node.start_position().row);
                let end_line = capture.node.end_position().row;
                line_items
                    .entry(start_line)
                    .or_insert_with(|| (kind.to_string(), end_line));
            }
        }

        line_items
            .into_iter()
            .filter_map(|(idx, (kind, end_row))| {
                lines
                    .get(idx)
                    .map(|&line| SummaryItem::new(line, idx + 1, Some(end_row + 1), kind))
            })
            .collect()
    }

    fn summarize_javascript(content: &str, level: SummaryLevel) -> Vec<SummaryItem> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_javascript::LANGUAGE.into())
            .expect("Error loading JavaScript grammar");

        let Some(tree) = Self::parse_with_timeout(&mut parser, content) else {
            return Vec::new();
        };
        let root_node = tree.root_node();

        let query_string = match level {
            SummaryLevel::Minimal => {
                "(function_declaration name: (identifier) @name) @function
                 (class_declaration name: (identifier) @name) @class
                 (arrow_function) @arrow"
            }
            SummaryLevel::Standard => {
                "(function_declaration name: (identifier) @name) @function
                 (class_declaration name: (identifier) @name) @class
                 (method_definition name: (property_identifier) @name) @method
                 (arrow_function) @arrow
                 (export_statement) @export
                 (import_statement) @import"
            }
            SummaryLevel::Detailed => {
                "(function_declaration name: (identifier) @name) @function
                 (class_declaration name: (identifier) @name) @class
                 (method_definition name: (property_identifier) @name) @method
                 (arrow_function) @arrow
                 (export_statement) @export
                 (import_statement) @import
                 (variable_declarator name: (identifier) @name) @var
                 (lexical_declaration) @const"
            }
            SummaryLevel::None => return Vec::new(),
        };

        let query = Query::new(&tree_sitter_javascript::LANGUAGE.into(), query_string)
            .expect("Error compiling query");

        let capture_names = query.capture_names().to_vec();
        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(&query, root_node, content.as_bytes());

        let lines: Vec<&str> = content.lines().collect();
        let mut line_items: std::collections::BTreeMap<usize, (String, usize)> =
            std::collections::BTreeMap::new();

        while let Some(m) = matches.next() {
            // Use @name capture's row when present — it lands on the declaration line,
            // not on any preceding decorator whose span is included in the outer node
            let name_row = m
                .captures
                .iter()
                .find(|c| capture_names[c.index as usize] == "name")
                .map(|c| c.node.start_position().row);
            for capture in m.captures {
                let kind = &capture_names[capture.index as usize];
                if *kind == "name" {
                    continue;
                }
                let start_line = name_row.unwrap_or_else(|| capture.node.start_position().row);
                let end_line = capture.node.end_position().row;
                line_items
                    .entry(start_line)
                    .or_insert_with(|| (kind.to_string(), end_line));
            }
        }

        line_items
            .into_iter()
            .filter_map(|(idx, (kind, end_row))| {
                lines
                    .get(idx)
                    .map(|&line| SummaryItem::new(line, idx + 1, Some(end_row + 1), kind))
            })
            .collect()
    }

    fn summarize_typescript(content: &str, level: SummaryLevel) -> Vec<SummaryItem> {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into())
            .expect("Error loading TypeScript grammar");

        let Some(tree) = Self::parse_with_timeout(&mut parser, content) else {
            return Vec::new();
        };
        let root_node = tree.root_node();

        let query_string = match level {
            SummaryLevel::Minimal => {
                "(function_declaration name: (identifier) @name) @function
                 (class_declaration name: (type_identifier) @name) @class
                 (interface_declaration name: (type_identifier) @name) @interface
                 (arrow_function) @arrow"
            }
            SummaryLevel::Standard => {
                "(function_declaration name: (identifier) @name) @function
                 (class_declaration name: (type_identifier) @name) @class
                 (interface_declaration name: (type_identifier) @name) @interface
                 (type_alias_declaration name: (type_identifier) @name) @type
                 (method_definition name: (property_identifier) @name) @method
                 (arrow_function) @arrow
                 (export_statement) @export
                 (import_statement) @import"
            }
            SummaryLevel::Detailed => {
                "(function_declaration name: (identifier) @name) @function
                 (class_declaration name: (type_identifier) @name) @class
                 (interface_declaration name: (type_identifier) @name) @interface
                 (type_alias_declaration name: (type_identifier) @name) @type
                 (enum_declaration name: (identifier) @name) @enum
                 (method_definition name: (property_identifier) @name) @method
                 (arrow_function) @arrow
                 (export_statement) @export
                 (import_statement) @import
                 (variable_declarator name: (identifier) @name) @var
                 (lexical_declaration) @const"
            }
            SummaryLevel::None => return Vec::new(),
        };

        let query = Query::new(
            &tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
            query_string,
        )
        .expect("Error compiling query");

        let capture_names = query.capture_names().to_vec();
        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(&query, root_node, content.as_bytes());

        let lines: Vec<&str> = content.lines().collect();
        let mut line_items: std::collections::BTreeMap<usize, (String, usize)> =
            std::collections::BTreeMap::new();

        while let Some(m) = matches.next() {
            // Use @name capture's row when present — it lands on the declaration line,
            // not on any preceding decorator whose span is included in the outer node
            let name_row = m
                .captures
                .iter()
                .find(|c| capture_names[c.index as usize] == "name")
                .map(|c| c.node.start_position().row);
            for capture in m.captures {
                let kind = &capture_names[capture.index as usize];
                if *kind == "name" {
                    continue;
                }
                let start_line = name_row.unwrap_or_else(|| capture.node.start_position().row);
                let end_line = capture.node.end_position().row;
                line_items
                    .entry(start_line)
                    .or_insert_with(|| (kind.to_string(), end_line));
            }
        }

        line_items
            .into_iter()
            .filter_map(|(idx, (kind, end_row))| {
                lines
                    .get(idx)
                    .map(|&line| SummaryItem::new(line, idx + 1, Some(end_row + 1), kind))
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write as _;

    use super::*;

    #[test]
    fn test_empty_input_all_languages() {
        for lang in &["Rust", "Python", "JavaScript", "TypeScript"] {
            let result = AstSummarizer::extract_summary("", Some(lang), SummaryLevel::Standard);
            assert!(
                result.is_empty(),
                "Empty input should produce empty summary for {lang}"
            );
        }
    }

    #[test]
    fn test_unsupported_language_returns_empty() {
        let result =
            AstSummarizer::extract_summary("some code", Some("Haskell"), SummaryLevel::Standard);
        assert!(result.is_empty());
    }

    #[test]
    fn test_none_language_returns_empty() {
        let result = AstSummarizer::extract_summary("fn main() {}", None, SummaryLevel::Standard);
        assert!(result.is_empty());
    }

    #[test]
    fn test_none_level_returns_empty() {
        let result =
            AstSummarizer::extract_summary("fn main() {}", Some("Rust"), SummaryLevel::None);
        assert!(result.is_empty());
    }

    #[test]
    fn test_binary_content_does_not_panic() {
        let binary = "\x00\x01\x02binary\x00data\x7f";
        for lang in &["Rust", "Python", "JavaScript", "TypeScript"] {
            // Should not panic, just return empty or partial results
            let _ = AstSummarizer::extract_summary(binary, Some(lang), SummaryLevel::Standard);
        }
    }

    #[test]
    fn test_malformed_rust_does_not_panic() {
        let bad = "fn {{ struct {{ impl {";
        let result = AstSummarizer::extract_summary(bad, Some("Rust"), SummaryLevel::Standard);
        // May return partial results or empty; should not panic
        let _ = result;
    }

    #[test]
    fn test_malformed_python_does_not_panic() {
        let bad = "def def class (((";
        let _ = AstSummarizer::extract_summary(bad, Some("Python"), SummaryLevel::Standard);
    }

    #[test]
    fn test_rust_minimal_level() {
        let code = "use std::io;\nfn main() {}\nstruct S {}\nenum E {}\ntrait T {}\nmod m {}";
        let result = AstSummarizer::extract_summary(code, Some("Rust"), SummaryLevel::Minimal);
        assert!(result.iter().any(|l| l.line.contains("fn main")));
        assert!(result.iter().any(|l| l.line.contains("struct S")));
        assert!(result.iter().any(|l| l.line.contains("enum E")));
        // Minimal should NOT include trait or mod
        assert!(!result.iter().any(|l| l.line.contains("trait T")));
        assert!(!result.iter().any(|l| l.line.contains("mod m")));
    }

    #[test]
    fn test_rust_detailed_includes_use_and_const() {
        let code = "use std::io;\nconst X: i32 = 1;\nstatic Y: i32 = 2;\nfn f() {}";
        let result = AstSummarizer::extract_summary(code, Some("Rust"), SummaryLevel::Detailed);
        assert!(result.iter().any(|l| l.line.contains("use std::io")));
        assert!(result.iter().any(|l| l.line.contains("const X")));
        assert!(result.iter().any(|l| l.line.contains("static Y")));
    }

    #[test]
    fn test_python_minimal_level() {
        let code = "import os\ndef foo():\n    pass\nclass Bar:\n    pass";
        let result = AstSummarizer::extract_summary(code, Some("Python"), SummaryLevel::Minimal);
        assert!(result.iter().any(|l| l.line.contains("def foo")));
        assert!(result.iter().any(|l| l.line.contains("class Bar")));
        // Minimal should NOT include imports
        assert!(!result.iter().any(|l| l.line.contains("import os")));
    }

    #[test]
    fn test_javascript_detects_classes_and_functions() {
        let code = "function hello() {}\nclass World {}\nconst x = () => {};";
        let result =
            AstSummarizer::extract_summary(code, Some("JavaScript"), SummaryLevel::Standard);
        assert!(result.iter().any(|l| l.line.contains("function hello")));
        assert!(result.iter().any(|l| l.line.contains("class World")));
    }

    #[test]
    fn test_typescript_detects_interfaces() {
        let code = "interface User { name: string; }\nfunction greet(u: User) {}";
        let result =
            AstSummarizer::extract_summary(code, Some("TypeScript"), SummaryLevel::Standard);
        assert!(result.iter().any(|l| l.line.contains("interface User")));
        assert!(result.iter().any(|l| l.line.contains("function greet")));
    }

    #[test]
    fn test_jsx_uses_javascript_parser() {
        let code = "function App() { return <div/>; }";
        let result = AstSummarizer::extract_summary(code, Some("JSX"), SummaryLevel::Standard);
        assert!(result.iter().any(|l| l.line.contains("function App")));
    }

    #[test]
    fn test_tsx_uses_typescript_parser() {
        // TSX is routed through the TypeScript parser, so pure TS syntax works
        let code = "function App(): string { return 'hello'; }";
        let result = AstSummarizer::extract_summary(code, Some("TSX"), SummaryLevel::Standard);
        assert!(result.iter().any(|l| l.line.contains("function App")));
    }

    #[test]
    fn test_very_long_single_line() {
        let code = format!("fn {}() {{}}", "a".repeat(10_000));
        let result = AstSummarizer::extract_summary(&code, Some("Rust"), SummaryLevel::Standard);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_whitespace_only_input() {
        let result =
            AstSummarizer::extract_summary("   \n\n\t\t\n  ", Some("Rust"), SummaryLevel::Standard);
        assert!(result.is_empty());
    }

    #[test]
    fn test_parse_with_timeout_returns_tree_for_valid_code() {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .unwrap();
        let tree = AstSummarizer::parse_with_timeout(&mut parser, "fn main() {}");
        assert!(tree.is_some(), "Valid code should parse successfully");
        let tree = tree.unwrap();
        assert_eq!(tree.root_node().kind(), "source_file");
    }

    #[test]
    fn test_parse_with_timeout_handles_empty_content() {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .unwrap();
        let tree = AstSummarizer::parse_with_timeout(&mut parser, "");
        assert!(tree.is_some(), "Empty content should still produce a tree");
    }

    #[test]
    fn test_parse_with_timeout_handles_invalid_syntax() {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .unwrap();
        // Tree-sitter produces partial trees for invalid syntax (doesn't return None)
        let tree = AstSummarizer::parse_with_timeout(&mut parser, "{{{{{{");
        assert!(tree.is_some());
        assert!(tree.unwrap().root_node().has_error());
    }

    #[test]
    fn test_parse_with_timeout_all_languages() {
        let languages: Vec<(&str, tree_sitter::Language)> = vec![
            ("Rust", tree_sitter_rust::LANGUAGE.into()),
            ("Python", tree_sitter_python::LANGUAGE.into()),
            ("JavaScript", tree_sitter_javascript::LANGUAGE.into()),
            (
                "TypeScript",
                tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
            ),
        ];
        let snippets = [
            ("Rust", "fn hello() {} struct S {}"),
            ("Python", "def hello():\n    pass"),
            ("JavaScript", "function hello() {}"),
            ("TypeScript", "function hello(): void {}"),
        ];
        for ((name, lang), (_, snippet)) in languages.iter().zip(snippets.iter()) {
            let mut parser = Parser::new();
            parser.set_language(lang).unwrap();
            let tree = AstSummarizer::parse_with_timeout(&mut parser, snippet);
            assert!(
                tree.is_some(),
                "parse_with_timeout should succeed for {name}"
            );
        }
    }

    #[test]
    fn test_parse_with_zero_timeout_aborts() {
        let mut parser = Parser::new();
        parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .unwrap();
        // Generate a large input so tree-sitter invokes the progress callback
        // before finishing. A zero-duration deadline is already in the past,
        // so the callback should return Break and cancel parsing.
        let mut large_input = String::new();
        for i in 0..1000 {
            writeln!(large_input, "fn func_{i}(x: i32) -> i32 {{ x + {i} }}").unwrap();
        }
        let tree = AstSummarizer::parse_with_deadline(&mut parser, &large_input, Duration::ZERO);
        assert!(
            tree.is_none(),
            "Zero timeout should abort parsing and return None"
        );
    }
}