pmat 3.15.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
#![allow(unused)]
#![cfg_attr(coverage_nightly, coverage(off))]
//! Enhanced AST visitor that preserves real source locations and qualified names
//!
//! This module provides an enhanced visitor that extracts actual AST information
//! instead of generating placeholders, enabling MCP tools to query precise
//! code locations and symbol names.

use crate::services::context::AstItem;
use std::path::{Path, PathBuf};
use syn::spanned::Spanned;
use syn::visit::Visit;
use syn::{ItemEnum, ItemFn, ItemImpl, ItemMod, ItemStruct, ItemTrait, ItemUse, Visibility};

/// Enhanced AST visitor that preserves real source information
pub struct EnhancedAstVisitor {
    items: Vec<AstItem>,

    file_path: PathBuf,
    module_path: Vec<String>,
}

impl EnhancedAstVisitor {
    /// Creates a new enhanced visitor for a given file
    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
    pub fn new(file_path: &Path) -> Self {
        Self {
            items: Vec::new(),
            file_path: file_path.to_path_buf(),
            module_path: vec![],
        }
    }

    /// Extracts all AST items with real source information
    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn extract_items(mut self, syntax_tree: &syn::File) -> Vec<AstItem> {
        self.visit_file(syntax_tree);
        self.items
    }

    /// Gets visibility as a string
    fn get_visibility(&self, vis: &Visibility) -> String {
        match vis {
            Visibility::Public(_) => "pub".to_string(),
            Visibility::Restricted(r) => {
                if r.path.is_ident("crate") {
                    "pub(crate)".to_string()
                } else if r.path.is_ident("super") {
                    "pub(super)".to_string()
                } else if r.path.is_ident("self") {
                    "pub(self)".to_string()
                } else {
                    #[cfg(feature = "rust-ast")]
                    {
                        format!("pub(in {})", quote::quote!(#r.path))
                    }
                    #[cfg(not(feature = "rust-ast"))]
                    {
                        format!("pub(in {:?})", r.path)
                    }
                }
            }
            Visibility::Inherited => "private".to_string(),
        }
    }

    /// Gets line number from a span debug representation
    fn get_line_from_span_debug(&self, span_debug: &str) -> usize {
        // Extract line number from debug representation if available
        // Format is typically "Span { start: Loc { line: X, ... }, ... }"
        if let Some(line_start) = span_debug.find("line: ") {
            let line_str = &span_debug[line_start + 6..];
            if let Some(comma_pos) = line_str.find(',') {
                if let Ok(line) = line_str[..comma_pos].parse::<usize>() {
                    return line;
                }
            }
        }

        // Fallback to sequential numbering
        self.items.len() + 1
    }

    /// Gets line number from a Spanned item
    fn get_line<S: Spanned>(&self, item: &S) -> usize {
        // In real proc_macro2, spans don't carry line info by default
        // We'll use a heuristic based on the span's debug representation
        // For production, we'd integrate with proc_macro2's unstable features
        // or use a source map approach
        let span = item.span();
        let debug_str = format!("{span:?}");
        self.get_line_from_span_debug(&debug_str)
    }

    /// Creates a qualified name for the current module context
    fn get_qualified_name(&self, name: &str) -> String {
        if self.module_path.is_empty() {
            name.to_string()
        } else {
            format!("{}::{}", self.module_path.join("::"), name)
        }
    }
}

impl<'ast> Visit<'ast> for EnhancedAstVisitor {
    fn visit_item_fn(&mut self, node: &'ast ItemFn) {
        let name = self.get_qualified_name(&node.sig.ident.to_string());
        let visibility = self.get_visibility(&node.vis);
        let is_async = node.sig.asyncness.is_some();
        let line = self.get_line(node);

        self.items.push(AstItem::Function {
            name,
            visibility,
            is_async,
            line,
        });

        syn::visit::visit_item_fn(self, node);
    }

    fn visit_item_struct(&mut self, node: &'ast ItemStruct) {
        let name = self.get_qualified_name(&node.ident.to_string());
        let visibility = self.get_visibility(&node.vis);
        let fields_count = node.fields.len();
        let line = self.get_line(node);

        // Extract derives
        let mut derives = Vec::new();
        for attr in &node.attrs {
            if attr.path().is_ident("derive") {
                if let Ok(syn::Meta::List(meta_list)) = attr.parse_args::<syn::Meta>() {
                    // Extract derive macro names
                    #[cfg(feature = "rust-ast")]
                    {
                        let tokens = quote::quote!(#meta_list);
                        let derive_str = tokens.to_string();
                        derives.push(derive_str);
                    }
                    #[cfg(not(feature = "rust-ast"))]
                    {
                        let derive_str = format!("{:?}", meta_list);
                        derives.push(derive_str);
                    }
                }
            }
        }

        self.items.push(AstItem::Struct {
            name,
            visibility,
            fields_count,
            derives,
            line,
        });

        syn::visit::visit_item_struct(self, node);
    }

    fn visit_item_enum(&mut self, node: &'ast ItemEnum) {
        let name = self.get_qualified_name(&node.ident.to_string());
        let visibility = self.get_visibility(&node.vis);
        let variants_count = node.variants.len();
        let line = self.get_line(node);

        self.items.push(AstItem::Enum {
            name,
            visibility,
            variants_count,
            line,
        });

        syn::visit::visit_item_enum(self, node);
    }

    fn visit_item_trait(&mut self, node: &'ast ItemTrait) {
        let name = self.get_qualified_name(&node.ident.to_string());
        let visibility = self.get_visibility(&node.vis);
        let line = self.get_line(node);

        self.items.push(AstItem::Trait {
            name,
            visibility,
            line,
        });

        syn::visit::visit_item_trait(self, node);
    }

    fn visit_item_impl(&mut self, node: &'ast ItemImpl) {
        #[cfg(feature = "rust-ast")]
        let type_name = quote::quote!(#node.self_ty).to_string();
        #[cfg(not(feature = "rust-ast"))]
        let type_name = format!("{:?}", node.self_ty);
        #[cfg(feature = "rust-ast")]
        let trait_name = node
            .trait_
            .as_ref()
            .map(|(_, path, _)| quote::quote!(#path).to_string());
        #[cfg(not(feature = "rust-ast"))]
        let trait_name = node
            .trait_
            .as_ref()
            .map(|(_, path, _)| format!("{:?}", path));
        let line = self.get_line(node);

        self.items.push(AstItem::Impl {
            type_name,
            trait_name,
            line,
        });

        syn::visit::visit_item_impl(self, node);
    }

    fn visit_item_mod(&mut self, node: &'ast ItemMod) {
        let name = node.ident.to_string();
        let visibility = self.get_visibility(&node.vis);
        let line = self.get_line(node);

        self.items.push(AstItem::Module {
            name: self.get_qualified_name(&name),
            visibility,
            line,
        });

        // Track module path for nested items
        self.module_path.push(name);
        syn::visit::visit_item_mod(self, node);
        self.module_path.pop();
    }

    fn visit_item_use(&mut self, node: &'ast ItemUse) {
        #[cfg(feature = "rust-ast")]
        let path = quote::quote!(#node.tree).to_string();
        #[cfg(not(feature = "rust-ast"))]
        let path = format!("{:?}", node.tree);
        let line = self.get_line(node);

        self.items.push(AstItem::Use { path, line });

        syn::visit::visit_item_use(self, node);
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;

    /// Test enhanced visitor extracts real function names
    #[test]
    fn test_extract_real_function_names() {
        let code = r#"
            /// Calculate complexity.
            pub fn calculate_complexity() -> u32 { 42 }
            async fn process_data(input: &str) -> Result<String, Error> { Ok(input.to_string()) }
            pub(crate) fn helper_function() {}
        "#;

        let syntax = syn::parse_file(code).unwrap();
        let visitor = EnhancedAstVisitor::new(Path::new("test.rs"));
        let items = visitor.extract_items(&syntax);

        assert_eq!(items.len(), 3);

        // Verify real names are extracted
        match &items[0] {
            AstItem::Function {
                name,
                visibility,
                is_async,
                ..
            } => {
                assert_eq!(name, "calculate_complexity");
                assert_eq!(visibility, "pub");
                assert!(!is_async);
            }
            _ => panic!("Expected Function"),
        }

        match &items[1] {
            AstItem::Function {
                name,
                visibility,
                is_async,
                ..
            } => {
                assert_eq!(name, "process_data");
                assert_eq!(visibility, "private");
                assert!(is_async);
            }
            _ => panic!("Expected Function"),
        }
    }

    /// Test enhanced visitor preserves module hierarchy
    #[test]
    fn test_preserve_module_hierarchy() {
        let code = r#"
            mod services {
                #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
                /// Service function.
                pub fn service_function() {}

                mod internal {
                    fn internal_helper() {}
                }
            }
        "#;

        let syntax = syn::parse_file(code).unwrap();
        let visitor = EnhancedAstVisitor::new(Path::new("test.rs"));
        let items = visitor.extract_items(&syntax);

        // Find the service_function
        let service_fn = items.iter().find(|item| {
            matches!(item, AstItem::Function { name, .. } if name.contains("service_function"))
        });

        assert!(service_fn.is_some());
        if let Some(AstItem::Function { name, .. }) = service_fn {
            assert_eq!(name, "services::service_function");
        }
    }

    /// Test enhanced visitor extracts struct information
    #[test]
    fn test_extract_struct_details() {
        let code = r#"
            #[derive(Debug, Clone)]
            /// Configuration.
            pub struct Configuration {
                pub name: String,
                value: u32,
                internal: bool,
            }
        "#;

        let syntax = syn::parse_file(code).unwrap();
        let visitor = EnhancedAstVisitor::new(Path::new("test.rs"));
        let items = visitor.extract_items(&syntax);

        assert_eq!(items.len(), 1);
        match &items[0] {
            AstItem::Struct {
                name,
                visibility,
                fields_count,
                ..
            } => {
                assert_eq!(name, "Configuration");
                assert_eq!(visibility, "pub");
                assert_eq!(*fields_count, 3);
            }
            _ => panic!("Expected Struct"),
        }
    }

    /// Test enhanced visitor handles complex visibility modifiers
    #[test]
    fn test_visibility_modifiers() {
        let code = r#"
            #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
            /// Public fn.
            pub fn public_fn() {}
            pub(crate) fn crate_fn() {}
            pub(super) fn super_fn() {}
            fn private_fn() {}
        "#;

        let syntax = syn::parse_file(code).unwrap();
        let visitor = EnhancedAstVisitor::new(Path::new("test.rs"));
        let items = visitor.extract_items(&syntax);

        let visibilities: Vec<String> = items
            .iter()
            .filter_map(|item| match item {
                AstItem::Function { visibility, .. } => Some(visibility.clone()),
                _ => None,
            })
            .collect();

        assert_eq!(
            visibilities,
            vec!["pub", "pub(crate)", "pub(super)", "private"]
        );
    }
}

/// Property tests for enhanced AST visitor
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// Property: visitor always produces valid AST items
        #[test]
        fn visitor_produces_valid_items(seed in 0u64..1000) {
            // Generate deterministic test code based on seed
            let code = generate_test_code(seed);

            if let Ok(syntax) = syn::parse_file(&code) {
                let visitor = EnhancedAstVisitor::new(Path::new("test.rs"));
                let items = visitor.extract_items(&syntax);

                // All items should have non-empty names
                for item in &items {
                    match item {
                        AstItem::Function { name, .. } |
                        AstItem::Struct { name, .. } |
                        AstItem::Enum { name, .. } |
                        AstItem::Trait { name, .. } |
                        AstItem::Module { name, .. } => {
                            prop_assert!(!name.is_empty());
                        }
                        AstItem::Impl { type_name, .. } => {
                            prop_assert!(!type_name.is_empty());
                        }
                        AstItem::Use { path, .. } => {
                            prop_assert!(!path.is_empty());
                        }
                        _ => {}
                    }
                }
            }
        }

        /// Property: qualified names preserve module hierarchy
        #[test]
        fn qualified_names_preserve_hierarchy(module_depth in 0usize..5) {
            let code = generate_nested_modules(module_depth);

            if let Ok(syntax) = syn::parse_file(&code) {
                let visitor = EnhancedAstVisitor::new(Path::new("test.rs"));
                let items = visitor.extract_items(&syntax);

                // Functions in nested modules should have qualified names
                for item in &items {
                    if let AstItem::Function { name, .. } = item {
                        let separators = name.matches("::").count();
                        prop_assert!(separators <= module_depth);
                    }
                }
            }
        }
    }

    fn generate_test_code(seed: u64) -> String {
        let fn_count = (seed % 5) + 1;
        let mut code = String::new();

        for i in 0..fn_count {
            code.push_str(&format!("fn function_{}() {{}}\n", i));
        }

        if seed % 3 == 0 {
            code.push_str("pub struct TestStruct { field: u32 }\n");
        }

        if seed % 5 == 0 {
            code.push_str("enum TestEnum { Variant1, Variant2 }\n");
        }

        code
    }

    fn generate_nested_modules(depth: usize) -> String {
        let mut code = String::new();
        let mut indent = String::new();

        for i in 0..depth {
            code.push_str(&format!("{}mod level_{} {{\n", indent, i));
            indent.push_str("    ");
        }

        code.push_str(&format!("{}fn nested_function() {{}}\n", indent));

        for _ in 0..depth {
            indent.truncate(indent.len().saturating_sub(4));
            code.push_str(&format!("{}}}\n", indent));
        }

        code
    }
}