pmat 3.14.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
// CAstVisitor implementation: constructor, source analysis, and all extraction methods.
// This file is included into c.rs and shares its module scope (no `use` imports here).

#[cfg(feature = "c-ast")]
impl CAstVisitor {
    /// Creates a new C AST visitor
    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
    pub fn new(file_path: &Path) -> Self {
        // Check if file is a header file
        let is_header = file_path.extension().map(|ext| ext == "h").unwrap_or(false);

        Self {
            items: Vec::new(),
            _file_path: file_path.to_path_buf(),
            current_scope: Vec::new(),
            is_header,
        }
    }

    /// Analyzes C source code and extracts AST items (complexity ≤10)
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn analyze_c_source(mut self, source: &str) -> Result<Vec<AstItem>, String> {
        if source.trim().is_empty() {
            return Ok(vec![]);
        }

        self.extract_function_declarations(source)?;
        self.extract_struct_declarations(source)?;
        self.extract_enum_declarations(source)?;
        self.extract_typedef_declarations(source)?;
        self.extract_global_variables(source)?;

        Ok(self.items)
    }

    /// Extracts function declarations (complexity ≤10)
    fn extract_function_declarations(&mut self, source: &str) -> Result<(), String> {
        let mut in_function = false;
        let mut brace_depth = 0;
        let mut current_function_name = String::new();
        let mut has_static_modifier = false;
        let mut _has_inline_modifier = false;
        let mut in_multiline_comment = false; // BUG-009 FIX: Track multiline comment state

        // Mark them as used
        let _ = &current_function_name;
        let _ = &has_static_modifier;

        for (line_num, line) in source.lines().enumerate() {
            let trimmed = line.trim();

            // BUG-009 FIX: Handle multiline comment state
            // Check if we're entering a multiline comment
            if trimmed.contains("/*") {
                in_multiline_comment = true;
            }

            // Check if we're exiting a multiline comment
            if trimmed.contains("*/") {
                in_multiline_comment = false;
                continue; // Skip the line with the closing comment
            }

            // Skip if we're inside a multiline comment
            if in_multiline_comment {
                continue;
            }

            // Skip single-line comments and preprocessor directives
            if trimmed.starts_with("//") || trimmed.starts_with("/*") || trimmed.starts_with("#") {
                continue;
            }

            // Check for function declaration
            if !in_function && self.is_function_declaration(trimmed) {
                // Check modifiers
                has_static_modifier = trimmed.contains("static ");
                _has_inline_modifier = trimmed.contains("inline ");

                if let Ok(name) = self.extract_function_name(trimmed) {
                    current_function_name = name;

                    // Only add function if it has a body (not just a declaration)
                    if trimmed.contains("{") {
                        self.items.push(AstItem::Function {
                            name: current_function_name.clone(),
                            visibility: if has_static_modifier {
                                "private"
                            } else {
                                "public"
                            }
                            .to_string(),
                            is_async: false,
                            line: line_num + 1,
                        });
                        in_function = true;
                    }
                }
            }

            // Track brace depth to know when we exit the function
            brace_depth += trimmed.chars().filter(|&c| c == '{').count() as i32;
            brace_depth -= trimmed.chars().filter(|&c| c == '}').count() as i32;

            if in_function && brace_depth == 0 {
                in_function = false;
                let _ = &has_static_modifier; // Mark as used
                _has_inline_modifier = false;
            }
        }
        Ok(())
    }

    /// Extracts struct declarations (complexity ≤10)
    fn extract_struct_declarations(&mut self, source: &str) -> Result<(), String> {
        let mut in_struct = false;
        let mut brace_depth = 0;
        let mut struct_start_line = 0;
        let mut current_struct_name = String::new();
        let mut fields_count = 0;

        for (line_num, line) in source.lines().enumerate() {
            let trimmed = line.trim();

            // Check for struct declaration (but not function return types)
            if !in_struct && trimmed.starts_with("struct ") {
                // Skip if this is a function (has parentheses before brace)
                let has_function_params = trimmed.contains("(")
                    && trimmed.find("(").unwrap_or(usize::MAX)
                        < trimmed.find("{").unwrap_or(usize::MAX);

                if !has_function_params {
                    if let Some(name) = self.extract_struct_name(trimmed) {
                        current_struct_name = name;
                        struct_start_line = line_num + 1;

                        // Check if struct definition has opening brace
                        if trimmed.contains("{") {
                            in_struct = true;
                            fields_count = 0;
                        }
                    }
                }
            }

            // Count fields when in a struct
            if in_struct
                && !trimmed.is_empty()
                && !trimmed.starts_with("{")
                && !trimmed.starts_with("}")
            {
                // This is a field
                fields_count += 1;
            }

            // Track brace depth
            brace_depth += trimmed.chars().filter(|&c| c == '{').count() as i32;
            brace_depth -= trimmed.chars().filter(|&c| c == '}').count() as i32;

            // Check if we're at the end of a struct definition
            if in_struct
                && trimmed.contains("}")
                && (brace_depth == 0 || trimmed.trim_end().ends_with(";"))
            {
                in_struct = false;

                // Only add struct if it has a name (avoids anonymous structs)
                if !current_struct_name.is_empty() {
                    self.items.push(AstItem::Struct {
                        name: current_struct_name.clone(),
                        visibility: "public".to_string(),
                        fields_count,
                        derives: vec![],
                        line: struct_start_line,
                    });
                }
            }
        }
        Ok(())
    }

    /// Extracts enum declarations (complexity ≤10)
    fn extract_enum_declarations(&mut self, source: &str) -> Result<(), String> {
        for (line_num, line) in source.lines().enumerate() {
            let trimmed = line.trim();

            if trimmed.starts_with("enum ") && trimmed.contains("{") {
                if let Some(name) = self.extract_enum_name(trimmed) {
                    self.items.push(AstItem::Enum {
                        name,
                        visibility: "public".to_string(),
                        variants_count: 1, // Simplified count
                        line: line_num + 1,
                    });
                }
            }
        }
        Ok(())
    }

    /// Extracts typedef declarations (complexity ≤10)
    fn extract_typedef_declarations(&mut self, source: &str) -> Result<(), String> {
        for (line_num, line) in source.lines().enumerate() {
            let trimmed = line.trim();

            if trimmed.starts_with("typedef ") {
                if let Some(name) = self.extract_typedef_name(trimmed) {
                    self.items.push(AstItem::Struct {
                        name,
                        visibility: "public".to_string(),
                        fields_count: 0,
                        derives: Vec::new(),
                        line: line_num + 1,
                    });
                }
            }
        }
        Ok(())
    }

    /// Extracts global variables (complexity ≤10)
    #[allow(clippy::cast_possible_truncation)]
    fn extract_global_variables(&mut self, source: &str) -> Result<(), String> {
        let mut in_function = false;
        let mut brace_depth = 0;

        for (line_num, line) in source.lines().enumerate() {
            let trimmed = line.trim();

            // Skip comments and preprocessor directives
            if trimmed.starts_with("//") || trimmed.starts_with("/*") || trimmed.starts_with("#") {
                continue;
            }

            // Track function scope
            if self.is_function_declaration(trimmed) {
                in_function = true;
            }

            // Track brace depth
            brace_depth += trimmed.chars().filter(|&c| c == '{').count() as i32;
            brace_depth -= trimmed.chars().filter(|&c| c == '}').count() as i32;

            if in_function && brace_depth == 0 {
                in_function = false;
            }

            // Only process global variables (outside functions)
            if !in_function && brace_depth == 0 && trimmed.contains(";") && !trimmed.contains("(") {
                // Looks like a global variable
                if let Some(name) = self.extract_variable_name(trimmed) {
                    let visibility = if trimmed.contains("static ") {
                        "private"
                    } else {
                        "public"
                    };

                    // Variables not supported in AstItem, use Struct as placeholder
                    self.items.push(AstItem::Struct {
                        name,
                        visibility: visibility.to_string(),
                        fields_count: 0,
                        derives: Vec::new(),
                        line: line_num + 1,
                    });
                }
            }
        }
        Ok(())
    }

    /// Checks if a line is a function declaration (complexity ≤10)
    fn is_function_declaration(&self, line: &str) -> bool {
        // Basic check: contains parentheses and is not a preprocessing directive
        if !line.contains("(") || line.starts_with("#") {
            return false;
        }

        // Check for common function return types
        let common_types = ["void", "int", "char", "float", "double", "size_t", "bool"];

        for typ in &common_types {
            // Check for pattern like "int foo(" or "static void bar("
            let pattern = format!("{} ", typ);
            if line.contains(&pattern) && line.contains("(") {
                return true;
            }
        }

        // Also check for function pointers
        line.contains("(")
            && line.contains(")")
            && line.contains("*")
            && !line.starts_with("if")
            && !line.starts_with("while")
    }

    /// Extracts function name from declaration line (complexity ≤10)
    fn extract_function_name(&self, line: &str) -> Result<String, String> {
        // Simplified extraction - get text between return type and opening parenthesis
        let after_type = line
            .split_whitespace()
            .skip(1)
            .collect::<Vec<&str>>()
            .join(" ");
        let before_paren = after_type.split('(').next().unwrap_or("");

        // Get last word which should be the function name
        let name = before_paren.split_whitespace().last().unwrap_or("");

        if name.is_empty() {
            Err("Could not extract function name".to_string())
        } else {
            Ok(name.to_string())
        }
    }

    /// Extracts struct name from declaration line (complexity ≤10)
    fn extract_struct_name(&self, line: &str) -> Option<String> {
        let words: Vec<&str> = line.split_whitespace().collect();

        // Find the word after "struct"
        for (i, word) in words.iter().enumerate() {
            if *word == "struct" && i + 1 < words.len() {
                let next_word = words[i + 1];
                // Strip any trailing characters like { or ;
                let name = next_word.trim_end_matches(['{', ';']);
                if !name.is_empty() {
                    return Some(name.to_string());
                }
            }
        }
        None
    }

    /// Extracts enum name from declaration line (complexity ≤10)
    fn extract_enum_name(&self, line: &str) -> Option<String> {
        let words: Vec<&str> = line.split_whitespace().collect();

        // Find the word after "enum"
        for (i, word) in words.iter().enumerate() {
            if *word == "enum" && i + 1 < words.len() {
                let next_word = words[i + 1];
                // Strip any trailing characters like { or ;
                let name = next_word.trim_end_matches(['{', ';']);
                if !name.is_empty() {
                    return Some(name.to_string());
                }
            }
        }
        None
    }

    /// Extracts typedef name from declaration line (complexity ≤10)
    fn extract_typedef_name(&self, line: &str) -> Option<String> {
        // For typedef, the name is typically the last token before the semicolon
        let before_semicolon = line.split(';').next().unwrap_or("");
        let words: Vec<&str> = before_semicolon.split_whitespace().collect();

        if !words.is_empty() {
            // Last word is usually the new type name
            Some(words.last().expect("checked is_empty").to_string())
        } else {
            None
        }
    }

    /// Extracts variable name from declaration line (complexity ≤10)
    fn extract_variable_name(&self, line: &str) -> Option<String> {
        // Remove type qualifiers
        let clean_line = line
            .trim()
            .replace("const ", "")
            .replace("static ", "")
            .replace("extern ", "")
            .replace("volatile ", "");

        // Split by whitespace to get the type and name
        let parts: Vec<&str> = clean_line.split_whitespace().collect();

        if parts.len() >= 2 {
            // Second word is usually the variable name (after the type)
            let name_part = parts[1];
            // Handle cases where name might include initialization or array dimensions
            let name = name_part
                .split('=')
                .next()
                .unwrap_or(name_part)
                .split('[')
                .next()
                .unwrap_or(name_part)
                .split('(') // Handle function pointer case
                .next()
                .unwrap_or(name_part)
                .split(';')
                .next()
                .unwrap_or(name_part);

            if !name.is_empty() {
                return Some(name.to_string());
            }
        }
        None
    }
}