peeker 1.1.0

A CLI tool for extracting code structure using Tree-sitter
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
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>,
}

#[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,
}

#[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);

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

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);

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

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)
}