herolib-code 0.3.13

Code analysis and parsing utilities for Rust source files
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
//! Rust source code parser using the `syn` crate.
//!
//! This module parses Rust source files and extracts information about
//! enums, structs, and their associated methods.

use std::fs;
use std::path::Path;

use proc_macro2::Span;
use quote::ToTokens;
use syn::{
    Attribute, Fields, GenericParam, Generics, ImplItem, Item, ItemEnum, ItemImpl, ItemStruct,
    Type, Visibility as SynVisibility,
};

use super::error::{ParseError, ParseResult};
use super::types::{
    CodeBase, EnumInfo, EnumVariant, FieldInfo, FileInfo, MethodInfo, ParameterInfo, Receiver,
    StructInfo, Visibility,
};

/// Parses Rust source files and extracts code structure information.
pub struct RustParser {
    /// Whether to include private items.
    include_private: bool,
}

impl Default for RustParser {
    fn default() -> Self {
        Self::new()
    }
}

impl RustParser {
    /// Creates a new RustParser with default settings.
    pub fn new() -> Self {
        Self {
            include_private: true,
        }
    }

    /// Sets whether to include private items in the output.
    pub fn include_private(mut self, include: bool) -> Self {
        self.include_private = include;
        self
    }

    /// Parses a single Rust source file.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the Rust source file.
    ///
    /// # Returns
    ///
    /// A CodeBase containing all parsed elements from the file.
    pub fn parse_file<P: AsRef<Path>>(&self, path: P) -> ParseResult<CodeBase> {
        let path = path.as_ref();
        let content = fs::read_to_string(path).map_err(|e| ParseError::FileRead {
            path: path.to_path_buf(),
            source: e,
        })?;

        self.parse_source(&content, path.to_string_lossy().to_string())
    }

    /// Parses Rust source code from a string.
    ///
    /// # Arguments
    ///
    /// * `source` - The Rust source code as a string.
    /// * `file_path` - The path to use for error messages and file references.
    ///
    /// # Returns
    ///
    /// A CodeBase containing all parsed elements.
    pub fn parse_source(&self, source: &str, file_path: String) -> ParseResult<CodeBase> {
        let syntax = syn::parse_file(source).map_err(|e| ParseError::SyntaxError {
            path: file_path.clone().into(),
            message: e.to_string(),
        })?;

        let mut codebase = CodeBase::new();
        let mut structs: Vec<StructInfo> = Vec::new();
        let mut enums: Vec<EnumInfo> = Vec::new();

        // First pass: collect all structs and enums
        for item in &syntax.items {
            match item {
                Item::Struct(item_struct) => {
                    if let Some(struct_info) = self.parse_struct(item_struct, &file_path) {
                        structs.push(struct_info);
                    }
                }
                Item::Enum(item_enum) => {
                    if let Some(enum_info) = self.parse_enum(item_enum, &file_path) {
                        enums.push(enum_info);
                    }
                }
                _ => {}
            }
        }

        // Second pass: collect impl blocks and attach methods to structs
        for item in &syntax.items {
            if let Item::Impl(item_impl) = item {
                self.process_impl_block(item_impl, &file_path, &mut structs);
            }
        }

        // Update file info
        codebase.files.push(FileInfo {
            path: file_path,
            enum_count: enums.len(),
            struct_count: structs.len(),
        });

        codebase.enums = enums;
        codebase.structs = structs;

        Ok(codebase)
    }

    /// Parses a struct item.
    fn parse_struct(&self, item: &ItemStruct, file_path: &str) -> Option<StructInfo> {
        let visibility = self.parse_visibility(&item.vis);

        if !self.include_private && visibility == Visibility::Private {
            return None;
        }

        let doc_comment = self.extract_doc_comment(&item.attrs);
        let (derives, attributes) = self.extract_attributes(&item.attrs);
        let generics = self.parse_generics(&item.generics);
        let fields = self.parse_fields(&item.fields);

        Some(StructInfo {
            name: item.ident.to_string(),
            doc_comment,
            file_path: file_path.to_string(),
            line_number: self.get_line_number(item.ident.span()),
            visibility,
            generics,
            derives,
            attributes,
            fields,
            methods: Vec::new(),
        })
    }

    /// Parses an enum item.
    fn parse_enum(&self, item: &ItemEnum, file_path: &str) -> Option<EnumInfo> {
        let visibility = self.parse_visibility(&item.vis);

        if !self.include_private && visibility == Visibility::Private {
            return None;
        }

        let doc_comment = self.extract_doc_comment(&item.attrs);
        let (derives, attributes) = self.extract_attributes(&item.attrs);
        let generics = self.parse_generics(&item.generics);

        let variants: Vec<EnumVariant> = item
            .variants
            .iter()
            .map(|v| {
                let variant_doc = self.extract_doc_comment(&v.attrs);
                let fields = self.parse_fields(&v.fields);
                let discriminant = v
                    .discriminant
                    .as_ref()
                    .map(|(_, expr)| expr.to_token_stream().to_string());

                EnumVariant {
                    name: v.ident.to_string(),
                    doc_comment: variant_doc,
                    fields,
                    discriminant,
                }
            })
            .collect();

        Some(EnumInfo {
            name: item.ident.to_string(),
            doc_comment,
            file_path: file_path.to_string(),
            line_number: self.get_line_number(item.ident.span()),
            visibility,
            generics,
            derives,
            attributes,
            variants,
        })
    }

    /// Processes an impl block and attaches methods to the corresponding struct.
    fn process_impl_block(
        &self,
        item_impl: &ItemImpl,
        file_path: &str,
        structs: &mut [StructInfo],
    ) {
        // Only process inherent impls (not trait impls)
        if item_impl.trait_.is_some() {
            return;
        }

        // Get the type name being implemented
        let type_name = match &*item_impl.self_ty {
            Type::Path(type_path) => type_path
                .path
                .segments
                .last()
                .map(|seg| seg.ident.to_string()),
            _ => None,
        };

        let Some(type_name) = type_name else {
            return;
        };

        // Find the corresponding struct
        let Some(struct_info) = structs.iter_mut().find(|s| s.name == type_name) else {
            return;
        };

        // Parse methods from the impl block
        for item in &item_impl.items {
            if let ImplItem::Fn(method) = item {
                let visibility = self.parse_visibility(&method.vis);

                if !self.include_private && visibility == Visibility::Private {
                    continue;
                }

                let doc_comment = self.extract_doc_comment(&method.attrs);
                let generics = self.parse_generics(&method.sig.generics);

                // Parse receiver (self parameter)
                let receiver = method.sig.receiver().map(|recv| {
                    if recv.reference.is_some() {
                        if recv.mutability.is_some() {
                            Receiver::RefMut
                        } else {
                            Receiver::Ref
                        }
                    } else {
                        Receiver::Value
                    }
                });

                // Parse parameters (excluding self)
                let parameters: Vec<ParameterInfo> = method
                    .sig
                    .inputs
                    .iter()
                    .filter_map(|arg| {
                        if let syn::FnArg::Typed(pat_type) = arg {
                            let name = pat_type.pat.to_token_stream().to_string();
                            let ty = pat_type.ty.to_token_stream().to_string();
                            Some(ParameterInfo { name, ty })
                        } else {
                            None
                        }
                    })
                    .collect();

                // Parse return type
                let return_type = match &method.sig.output {
                    syn::ReturnType::Default => None,
                    syn::ReturnType::Type(_, ty) => Some(ty.to_token_stream().to_string()),
                };

                let method_info = MethodInfo {
                    name: method.sig.ident.to_string(),
                    doc_comment,
                    file_path: file_path.to_string(),
                    line_number: self.get_line_number(method.sig.ident.span()),
                    visibility,
                    is_async: method.sig.asyncness.is_some(),
                    is_const: method.sig.constness.is_some(),
                    is_unsafe: method.sig.unsafety.is_some(),
                    generics,
                    parameters,
                    return_type,
                    receiver,
                };

                struct_info.methods.push(method_info);
            }
        }
    }

    /// Parses visibility from syn's Visibility type.
    fn parse_visibility(&self, vis: &SynVisibility) -> Visibility {
        match vis {
            SynVisibility::Public(_) => Visibility::Public,
            SynVisibility::Restricted(restricted) => {
                let path = restricted.path.to_token_stream().to_string();
                if path == "crate" {
                    Visibility::Crate
                } else if path == "super" {
                    Visibility::Super
                } else {
                    Visibility::Restricted(path)
                }
            }
            SynVisibility::Inherited => Visibility::Private,
        }
    }

    /// Extracts doc comments from attributes.
    fn extract_doc_comment(&self, attrs: &[Attribute]) -> Option<String> {
        let doc_lines: Vec<String> = attrs
            .iter()
            .filter_map(|attr| {
                if attr.path().is_ident("doc") {
                    if let syn::Meta::NameValue(meta) = &attr.meta {
                        if let syn::Expr::Lit(expr_lit) = &meta.value {
                            if let syn::Lit::Str(lit_str) = &expr_lit.lit {
                                return Some(lit_str.value().trim().to_string());
                            }
                        }
                    }
                }
                None
            })
            .collect();

        if doc_lines.is_empty() {
            None
        } else {
            Some(doc_lines.join("\n"))
        }
    }

    /// Extracts derive macros and other attributes.
    fn extract_attributes(&self, attrs: &[Attribute]) -> (Vec<String>, Vec<String>) {
        let mut derives = Vec::new();
        let mut other_attrs = Vec::new();

        for attr in attrs {
            if attr.path().is_ident("doc") {
                continue; // Skip doc comments
            }

            if attr.path().is_ident("derive") {
                // Extract derive macro names
                if let Ok(meta) = attr.meta.require_list() {
                    let tokens = meta.tokens.to_string();
                    // Parse comma-separated derive names
                    for derive_name in tokens.split(',') {
                        let name = derive_name.trim();
                        if !name.is_empty() {
                            derives.push(name.to_string());
                        }
                    }
                }
            } else {
                // Store other attributes as strings
                other_attrs.push(attr.to_token_stream().to_string());
            }
        }

        (derives, other_attrs)
    }

    /// Parses generic parameters.
    fn parse_generics(&self, generics: &Generics) -> Vec<String> {
        generics
            .params
            .iter()
            .map(|param| match param {
                GenericParam::Type(type_param) => type_param.ident.to_string(),
                GenericParam::Lifetime(lifetime) => lifetime.lifetime.to_string(),
                GenericParam::Const(const_param) => {
                    format!("const {}", const_param.ident)
                }
            })
            .collect()
    }

    /// Parses struct/enum fields.
    fn parse_fields(&self, fields: &Fields) -> Vec<FieldInfo> {
        match fields {
            Fields::Named(named) => named
                .named
                .iter()
                .map(|f| {
                    let doc_comment = self.extract_doc_comment(&f.attrs);
                    let (_, attributes) = self.extract_attributes(&f.attrs);

                    FieldInfo {
                        name: f.ident.as_ref().map(|i| i.to_string()),
                        ty: f.ty.to_token_stream().to_string(),
                        doc_comment,
                        visibility: self.parse_visibility(&f.vis),
                        attributes,
                    }
                })
                .collect(),
            Fields::Unnamed(unnamed) => unnamed
                .unnamed
                .iter()
                .enumerate()
                .map(|(idx, f)| {
                    let doc_comment = self.extract_doc_comment(&f.attrs);
                    let (_, attributes) = self.extract_attributes(&f.attrs);

                    FieldInfo {
                        name: Some(format!("{}", idx)),
                        ty: f.ty.to_token_stream().to_string(),
                        doc_comment,
                        visibility: self.parse_visibility(&f.vis),
                        attributes,
                    }
                })
                .collect(),
            Fields::Unit => Vec::new(),
        }
    }

    /// Gets the line number from a span.
    fn get_line_number(&self, span: Span) -> usize {
        span.start().line
    }
}

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

    #[test]
    fn test_parse_simple_struct() {
        let source = r#"
/// A simple test struct.
pub struct TestStruct {
    /// The name field.
    pub name: String,
    /// The age field.
    age: u32,
}
"#;

        let parser = RustParser::new();
        let codebase = parser.parse_source(source, "test.rs".to_string()).unwrap();

        assert_eq!(codebase.structs.len(), 1);
        let s = &codebase.structs[0];
        assert_eq!(s.name, "TestStruct");
        assert!(s
            .doc_comment
            .as_ref()
            .unwrap()
            .contains("simple test struct"));
        assert_eq!(s.visibility, Visibility::Public);
        assert_eq!(s.fields.len(), 2);
        assert_eq!(s.fields[0].name, Some("name".to_string()));
        assert_eq!(s.fields[1].name, Some("age".to_string()));
    }

    #[test]
    fn test_parse_enum() {
        let source = r#"
/// Status enum.
#[derive(Debug, Clone)]
pub enum Status {
    /// Active status.
    Active,
    /// Inactive with reason.
    Inactive(String),
    /// Custom status.
    Custom { code: u32, message: String },
}
"#;

        let parser = RustParser::new();
        let codebase = parser.parse_source(source, "test.rs".to_string()).unwrap();

        assert_eq!(codebase.enums.len(), 1);
        let e = &codebase.enums[0];
        assert_eq!(e.name, "Status");
        assert!(e.derives.contains(&"Debug".to_string()));
        assert!(e.derives.contains(&"Clone".to_string()));
        assert_eq!(e.variants.len(), 3);
        assert_eq!(e.variants[0].name, "Active");
        assert_eq!(e.variants[1].name, "Inactive");
        assert_eq!(e.variants[2].name, "Custom");
    }

    #[test]
    fn test_parse_methods() {
        let source = r#"
pub struct Calculator {
    value: i32,
}

impl Calculator {
    /// Creates a new calculator.
    pub fn new() -> Self {
        Self { value: 0 }
    }

    /// Adds a value.
    pub fn add(&mut self, n: i32) {
        self.value += n;
    }

    /// Gets the current value.
    pub fn value(&self) -> i32 {
        self.value
    }
}
"#;

        let parser = RustParser::new();
        let codebase = parser.parse_source(source, "test.rs".to_string()).unwrap();

        assert_eq!(codebase.structs.len(), 1);
        let s = &codebase.structs[0];
        assert_eq!(s.methods.len(), 3);

        let new_method = s.methods.iter().find(|m| m.name == "new").unwrap();
        assert!(new_method.receiver.is_none());
        assert!(new_method.return_type.is_some());

        let add_method = s.methods.iter().find(|m| m.name == "add").unwrap();
        assert!(matches!(add_method.receiver, Some(Receiver::RefMut)));
        assert_eq!(add_method.parameters.len(), 1);

        let value_method = s.methods.iter().find(|m| m.name == "value").unwrap();
        assert!(matches!(value_method.receiver, Some(Receiver::Ref)));
    }

    #[test]
    fn test_parse_generics() {
        let source = r#"
pub struct Container<T, U> {
    first: T,
    second: U,
}
"#;

        let parser = RustParser::new();
        let codebase = parser.parse_source(source, "test.rs".to_string()).unwrap();

        assert_eq!(codebase.structs.len(), 1);
        let s = &codebase.structs[0];
        assert_eq!(s.generics, vec!["T", "U"]);
    }

    #[test]
    fn test_exclude_private() {
        let source = r#"
pub struct Public {}
struct Private {}
"#;

        let parser = RustParser::new().include_private(false);
        let codebase = parser.parse_source(source, "test.rs".to_string()).unwrap();

        assert_eq!(codebase.structs.len(), 1);
        assert_eq!(codebase.structs[0].name, "Public");
    }
}