peeker 1.2.0

A library and CLI tool for extracting code structure using Tree-sitter
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
use anyhow::Result;
use serde::Serialize;
use tree_sitter::{Node, Parser, Tree};

use crate::languages::{LanguageConfig, get_language_config};

#[derive(Debug, Clone, Serialize, Default)]
pub struct CodeStructure {
    pub imports: Vec<Import>,
    pub structs: Vec<StructDef>,
    pub functions: Vec<FunctionDef>,
    pub traits: Vec<TraitDef>,
    pub enums: Vec<EnumDef>,
}

impl CodeStructure {
    pub fn exports_only(&self) -> CodeStructure {
        CodeStructure {
            imports: self.imports.clone(),
            structs: self
                .structs
                .iter()
                .filter(|s| s.is_public)
                .cloned()
                .collect(),
            functions: self
                .functions
                .iter()
                .filter(|f| f.is_public)
                .cloned()
                .collect(),
            traits: self
                .traits
                .iter()
                .filter(|t| t.is_public)
                .cloned()
                .collect(),
            enums: self.enums.iter().filter(|e| e.is_public).cloned().collect(),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct Import {
    pub name: String,
    pub line: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct StructDef {
    pub name: String,
    pub is_public: bool,
    pub start_line: usize,
    pub end_line: usize,
    pub fields: Vec<FieldDef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub doc_comment: Option<String>,
}

impl StructDef {
    /// Returns a signature string suitable for embedding/semantic search.
    /// Example output: "pub struct Foo { x: i32, y: String }"
    pub fn signature_string(&self) -> String {
        let visibility = if self.is_public { "pub " } else { "" };

        if self.fields.is_empty() {
            format!("{}struct {}", visibility, self.name)
        } else {
            let fields: Vec<String> = self
                .fields
                .iter()
                .map(|f| {
                    let field_vis = if f.is_public { "pub " } else { "" };
                    format!("{}{}: {}", field_vis, f.name, f.type_name)
                })
                .collect();
            format!(
                "{}struct {} {{ {} }}",
                visibility,
                self.name,
                fields.join(", ")
            )
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct FieldDef {
    pub name: String,
    pub type_name: String,
    pub is_public: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct FunctionDef {
    pub name: String,
    pub is_public: bool,
    pub is_async: bool,
    pub params: Vec<String>,
    pub return_type: Option<String>,
    pub start_line: usize,
    pub end_line: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub doc_comment: Option<String>,
}

impl FunctionDef {
    /// Returns a signature string suitable for embedding/semantic search.
    /// Example output: "pub async fn foo(x: i32, y: String) -> Result<()>"
    pub fn signature_string(&self) -> String {
        let mut parts = Vec::new();

        if self.is_public {
            parts.push("pub");
        }
        if self.is_async {
            parts.push("async");
        }
        parts.push("fn");

        let params = self.params.join(", ");
        let name_and_params = format!("{}({})", self.name, params);

        let signature = if let Some(ref ret) = self.return_type {
            format!("{} {} -> {}", parts.join(" "), name_and_params, ret)
        } else {
            format!("{} {}", parts.join(" "), name_and_params)
        };

        signature
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct TraitDef {
    pub name: String,
    pub is_public: bool,
    pub start_line: usize,
    pub end_line: usize,
}

#[derive(Debug, Clone, Serialize)]
pub struct EnumDef {
    pub name: String,
    pub is_public: bool,
    pub start_line: usize,
    pub end_line: usize,
    pub variants: Vec<String>,
}

pub fn parse_file(source: &str, extension: &str) -> Result<CodeStructure> {
    let config = get_language_config(extension)?;

    let mut parser = Parser::new();
    parser.set_language(&config.language)?;

    let tree = parser
        .parse(source, None)
        .ok_or_else(|| anyhow::anyhow!("Failed to parse file"))?;

    extract_structure(&tree, source, &config)
}

fn extract_structure(tree: &Tree, source: &str, config: &LanguageConfig) -> Result<CodeStructure> {
    let mut structure = CodeStructure::default();
    let root = tree.root_node();

    extract_from_node(root, source, config, &mut structure);

    Ok(structure)
}

fn extract_from_node(
    node: Node,
    source: &str,
    config: &LanguageConfig,
    structure: &mut CodeStructure,
) {
    let kind = node.kind();

    // Check for imports
    if config.import_kinds.contains(&kind) {
        if let Some(import) = extract_import(node, source, config) {
            structure.imports.push(import);
        }
    }

    // Check for structs/classes
    if config.struct_kinds.contains(&kind) {
        if let Some(struct_def) = extract_struct(node, source, config) {
            structure.structs.push(struct_def);
        }
    }

    // Check for functions
    if config.function_kinds.contains(&kind) {
        if let Some(func_def) = extract_function(node, source, config) {
            structure.functions.push(func_def);
        }
    }

    // Check for traits/interfaces
    if config.trait_kinds.contains(&kind) {
        if let Some(trait_def) = extract_trait(node, source, config) {
            structure.traits.push(trait_def);
        }
    }

    // Check for enums
    if config.enum_kinds.contains(&kind) {
        if let Some(enum_def) = extract_enum(node, source, config) {
            structure.enums.push(enum_def);
        }
    }

    // Recurse into children
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        extract_from_node(child, source, config, structure);
    }
}

fn extract_import(node: Node, source: &str, _config: &LanguageConfig) -> Option<Import> {
    let text = node.utf8_text(source.as_bytes()).ok()?;
    let line = node.start_position().row + 1;

    // Clean up the import text
    let name = text.lines().next().unwrap_or(text).trim().to_string();

    Some(Import { name, line })
}

fn extract_struct(node: Node, source: &str, config: &LanguageConfig) -> Option<StructDef> {
    let name = find_child_by_field(node, "name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string())?;

    let is_public = check_visibility(node, source, config);
    let start_line = node.start_position().row + 1;
    let end_line = node.end_position().row + 1;

    let fields = extract_fields(node, source, config);
    let doc_comment = extract_doc_comment(node, source, config);

    Some(StructDef {
        name,
        is_public,
        start_line,
        end_line,
        fields,
        doc_comment,
    })
}

fn extract_fields(node: Node, source: &str, config: &LanguageConfig) -> Vec<FieldDef> {
    let mut fields = Vec::new();
    let mut cursor = node.walk();

    for child in node.children(&mut cursor) {
        if config.field_kinds.contains(&child.kind()) {
            if let Some(field) = extract_single_field(child, source, config) {
                fields.push(field);
            }
        }
        // Also check nested children (e.g., field_declaration_list)
        let mut inner_cursor = child.walk();
        for inner in child.children(&mut inner_cursor) {
            if config.field_kinds.contains(&inner.kind()) {
                if let Some(field) = extract_single_field(inner, source, config) {
                    fields.push(field);
                }
            }
        }
    }

    fields
}

fn extract_single_field(node: Node, source: &str, config: &LanguageConfig) -> Option<FieldDef> {
    let name = find_child_by_field(node, "name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string())?;

    let type_name = find_child_by_field(node, "type")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string())
        .unwrap_or_else(|| "unknown".to_string());

    let is_public = check_visibility(node, source, config);

    Some(FieldDef {
        name,
        type_name,
        is_public,
    })
}

fn extract_function(node: Node, source: &str, config: &LanguageConfig) -> Option<FunctionDef> {
    let name = find_child_by_field(node, "name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string())?;

    let is_public = check_visibility(node, source, config);
    let is_async = check_async(node, source);
    let start_line = node.start_position().row + 1;
    let end_line = node.end_position().row + 1;

    let params = extract_parameters(node, source, config);
    let return_type = extract_return_type(node, source, config);
    let doc_comment = extract_doc_comment(node, source, config);

    Some(FunctionDef {
        name,
        is_public,
        is_async,
        params,
        return_type,
        start_line,
        end_line,
        doc_comment,
    })
}

fn extract_parameters(node: Node, source: &str, config: &LanguageConfig) -> Vec<String> {
    let mut params = Vec::new();

    if let Some(params_node) = find_child_by_field(node, "parameters") {
        let mut cursor = params_node.walk();
        for child in params_node.children(&mut cursor) {
            if config.param_kinds.contains(&child.kind()) {
                // Try to get parameter name
                if let Some(name_node) = find_child_by_field(child, "pattern")
                    .or_else(|| find_child_by_field(child, "name"))
                {
                    if let Ok(name) = name_node.utf8_text(source.as_bytes()) {
                        // Try to get type
                        let type_str = find_child_by_field(child, "type")
                            .and_then(|t| t.utf8_text(source.as_bytes()).ok())
                            .map(|t| format!(": {}", t))
                            .unwrap_or_default();
                        params.push(format!("{}{}", name, type_str));
                    }
                } else if let Ok(text) = child.utf8_text(source.as_bytes()) {
                    // Fallback: use full text
                    let text = text.trim();
                    if !text.is_empty() && text != "," {
                        params.push(text.to_string());
                    }
                }
            }
        }
    }

    params
}

fn extract_return_type(node: Node, source: &str, _config: &LanguageConfig) -> Option<String> {
    find_child_by_field(node, "return_type")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.trim_start_matches("->").trim().to_string())
}

fn extract_trait(node: Node, source: &str, config: &LanguageConfig) -> Option<TraitDef> {
    let name = find_child_by_field(node, "name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string())?;

    let is_public = check_visibility(node, source, config);
    let start_line = node.start_position().row + 1;
    let end_line = node.end_position().row + 1;

    Some(TraitDef {
        name,
        is_public,
        start_line,
        end_line,
    })
}

fn extract_enum(node: Node, source: &str, config: &LanguageConfig) -> Option<EnumDef> {
    let name = find_child_by_field(node, "name")
        .and_then(|n| n.utf8_text(source.as_bytes()).ok())
        .map(|s| s.to_string())?;

    let is_public = check_visibility(node, source, config);
    let start_line = node.start_position().row + 1;
    let end_line = node.end_position().row + 1;

    let variants = extract_enum_variants(node, source, config);

    Some(EnumDef {
        name,
        is_public,
        start_line,
        end_line,
        variants,
    })
}

fn extract_enum_variants(node: Node, source: &str, config: &LanguageConfig) -> Vec<String> {
    let mut variants = Vec::new();
    let mut cursor = node.walk();

    fn collect_variants(
        node: Node,
        source: &str,
        config: &LanguageConfig,
        variants: &mut Vec<String>,
    ) {
        if config.enum_variant_kinds.contains(&node.kind()) {
            if let Some(name_node) = find_child_by_field(node, "name") {
                if let Ok(name) = name_node.utf8_text(source.as_bytes()) {
                    variants.push(name.to_string());
                }
            } else if let Ok(text) = node.utf8_text(source.as_bytes()) {
                // Some languages have simpler variant structures
                let text = text.trim();
                if !text.is_empty() {
                    variants.push(text.to_string());
                }
            }
        }

        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            collect_variants(child, source, config, variants);
        }
    }

    for child in node.children(&mut cursor) {
        collect_variants(child, source, config, &mut variants);
    }

    variants
}

fn check_visibility(node: Node, source: &str, config: &LanguageConfig) -> bool {
    // Check for visibility modifier as a child
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "visibility_modifier" {
            if let Ok(text) = child.utf8_text(source.as_bytes()) {
                return text.contains("pub");
            }
        }
        // Python: check for decorators or naming conventions
        if child.kind() == "decorator" {
            if let Ok(text) = child.utf8_text(source.as_bytes()) {
                if text.contains("export") || text.contains("public") {
                    return true;
                }
            }
        }
    }

    // TypeScript/JavaScript: check for export keyword
    if let Some(parent) = node.parent() {
        if parent.kind() == "export_statement" {
            return true;
        }
    }

    // Check previous sibling for export
    if let Some(prev) = node.prev_sibling() {
        if prev.kind() == "export" || prev.kind() == "export_statement" {
            return true;
        }
    }

    // Language-specific defaults
    match config.name {
        "python" => {
            // Python: items not starting with _ are considered public
            if let Some(name_node) = find_child_by_field(node, "name") {
                if let Ok(name) = name_node.utf8_text(source.as_bytes()) {
                    return !name.starts_with('_');
                }
            }
            true
        }
        "typescript" | "javascript" => false, // Need explicit export
        _ => false,
    }
}

fn check_async(node: Node, source: &str) -> bool {
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "async" {
            return true;
        }
    }

    // Also check the node text for async keyword
    if let Ok(text) = node.utf8_text(source.as_bytes()) {
        return text.trim_start().starts_with("async");
    }

    false
}

fn find_child_by_field<'a>(node: Node<'a>, field_name: &str) -> Option<Node<'a>> {
    node.child_by_field_name(field_name)
}

/// Extracts doc comments/docstrings that appear immediately before a node.
/// Supports:
/// - Rust: `///` doc comments and `/** */` block doc comments
/// - Python: Docstrings (first string literal in function/class body)
/// - JS/TS: `/** */` JSDoc comments
/// - Go: `//` comments immediately preceding
/// - Java: `/** */` Javadoc comments
fn extract_doc_comment(node: Node, source: &str, config: &LanguageConfig) -> Option<String> {
    // For Python, docstrings are inside the function/class body
    if config.name == "python" {
        return extract_python_docstring(node, source);
    }

    // For other languages, look for comments immediately preceding the node
    // For JS/TS, we may need to look at the parent if it's an export_statement
    let search_node = if let Some(parent) = node.parent() {
        if parent.kind() == "export_statement" {
            parent
        } else {
            node
        }
    } else {
        node
    };

    let mut comments = Vec::new();
    let mut current = search_node.prev_sibling();

    while let Some(sibling) = current {
        let kind = sibling.kind();

        // Check if this is a comment node
        if is_comment_node(kind) {
            if let Ok(text) = sibling.utf8_text(source.as_bytes()) {
                comments.push(text.to_string());
            }
            current = sibling.prev_sibling();
        } else if kind == "attribute_item" || kind == "decorator" {
            // Skip attributes/decorators and continue looking for comments
            current = sibling.prev_sibling();
        } else {
            // Hit something that's not a comment or attribute, stop
            break;
        }
    }

    if comments.is_empty() {
        return None;
    }

    // Reverse to get comments in original order
    comments.reverse();

    // Clean and join the comments
    let cleaned: Vec<String> = comments.iter().map(|c| clean_comment(c, config)).collect();

    Some(cleaned.join("\n"))
}

/// Check if a node kind represents a comment
fn is_comment_node(kind: &str) -> bool {
    matches!(
        kind,
        "line_comment"
            | "block_comment"
            | "comment"
            | "doc_comment"
            | "documentation_comment"
            | "string_content"
    )
}

/// Extract Python docstring from function/class body
fn extract_python_docstring(node: Node, source: &str) -> Option<String> {
    // Find the body of the function/class
    let body = find_child_by_field(node, "body")?;

    // Get the first statement in the body
    let mut cursor = body.walk();
    for child in body.children(&mut cursor) {
        // Look for expression_statement containing a string
        if child.kind() == "expression_statement" {
            let mut inner_cursor = child.walk();
            for inner in child.children(&mut inner_cursor) {
                if inner.kind() == "string" || inner.kind() == "concatenated_string" {
                    if let Ok(text) = inner.utf8_text(source.as_bytes()) {
                        return Some(clean_python_docstring(text));
                    }
                }
            }
        }
        // Only check the first statement
        break;
    }

    None
}

/// Clean a Python docstring by removing quotes and normalizing
fn clean_python_docstring(text: &str) -> String {
    let trimmed = text.trim();

    // Remove triple quotes
    let content = if trimmed.starts_with("\"\"\"") && trimmed.ends_with("\"\"\"") {
        &trimmed[3..trimmed.len() - 3]
    } else if trimmed.starts_with("'''") && trimmed.ends_with("'''") {
        &trimmed[3..trimmed.len() - 3]
    } else if trimmed.starts_with('"') && trimmed.ends_with('"') {
        &trimmed[1..trimmed.len() - 1]
    } else if trimmed.starts_with('\'') && trimmed.ends_with('\'') {
        &trimmed[1..trimmed.len() - 1]
    } else {
        trimmed
    };

    content.trim().to_string()
}

/// Clean a comment by removing comment markers
fn clean_comment(text: &str, config: &LanguageConfig) -> String {
    let trimmed = text.trim();

    // Handle different comment styles based on language
    match config.name {
        "rust" => clean_rust_comment(trimmed),
        "go" => clean_go_comment(trimmed),
        "java" | "typescript" | "javascript" | "c" | "cpp" => clean_c_style_comment(trimmed),
        _ => clean_c_style_comment(trimmed),
    }
}

/// Clean Rust doc comments (/// and /** */)
fn clean_rust_comment(text: &str) -> String {
    if text.starts_with("///") {
        // Line doc comment
        text.strip_prefix("///")
            .unwrap_or(text)
            .trim_start()
            .to_string()
    } else if text.starts_with("//!") {
        // Inner doc comment
        text.strip_prefix("//!")
            .unwrap_or(text)
            .trim_start()
            .to_string()
    } else if text.starts_with("/**") && text.ends_with("*/") {
        // Block doc comment
        clean_block_comment(text)
    } else if text.starts_with("//") {
        // Regular line comment
        text.strip_prefix("//")
            .unwrap_or(text)
            .trim_start()
            .to_string()
    } else {
        text.to_string()
    }
}

/// Clean Go comments (// style)
fn clean_go_comment(text: &str) -> String {
    if text.starts_with("//") {
        text.strip_prefix("//")
            .unwrap_or(text)
            .trim_start()
            .to_string()
    } else if text.starts_with("/*") && text.ends_with("*/") {
        clean_block_comment(text)
    } else {
        text.to_string()
    }
}

/// Clean C-style comments (// and /* */)
fn clean_c_style_comment(text: &str) -> String {
    if text.starts_with("/**") && text.ends_with("*/") {
        // JSDoc/Javadoc style
        clean_block_comment(text)
    } else if text.starts_with("/*") && text.ends_with("*/") {
        // Regular block comment
        clean_block_comment(text)
    } else if text.starts_with("//") {
        text.strip_prefix("//")
            .unwrap_or(text)
            .trim_start()
            .to_string()
    } else {
        text.to_string()
    }
}

/// Clean a block comment by removing /* */ markers and * prefixes
fn clean_block_comment(text: &str) -> String {
    let content = text
        .strip_prefix("/**")
        .or_else(|| text.strip_prefix("/*"))
        .unwrap_or(text)
        .strip_suffix("*/")
        .unwrap_or(text)
        .trim();

    // Handle multi-line block comments with * prefix on each line
    let lines: Vec<&str> = content
        .lines()
        .map(|line| {
            let trimmed = line.trim();
            trimmed.strip_prefix('*').unwrap_or(trimmed).trim()
        })
        .collect();

    lines.join("\n").trim().to_string()
}