cargo-cgp 0.0.1

wrapper around cargo check to improve CGP error messages
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
/// Module for building an internal database of diagnostics and merging related errors
/// This implements the approach described in Chapters 7-8 of the report
use cargo_metadata::diagnostic::{Diagnostic, DiagnosticLevel, DiagnosticSpan};
use cargo_metadata::{CompilerMessage, PackageId, Target};
use std::collections::HashMap;

use crate::cgp_diagnostic::CgpDiagnostic;
use crate::cgp_patterns::{
    ComponentInfo, FieldInfo, ProviderRelationship, extract_check_trait, extract_component_info,
    extract_field_info, extract_provider_relationship, has_other_hasfield_implementations,
};

/// Derives a consumer trait name from a provider trait name
/// This is a heuristic and may not always be accurate
/// Provider: "AreaCalculator" -> Consumer: "CanCalculateArea"
/// Provider: "DensityCalculator" -> Consumer: "CanCalculateDensity"
fn derive_consumer_trait_from_provider(provider_trait: &str) -> String {
    // Common pattern in CGP: Provider ends with action (e.g., "Calculator")
    // Consumer trait is "Can" + action + noun
    // But this is complex to reverse, so we'll just store the provider trait name
    // for fuzzy matching later
    provider_trait.to_string()
}

/// A database that collects and merges related diagnostic information
#[derive(Debug, Default)]
pub struct DiagnosticDatabase {
    /// Map from diagnostic key to merged diagnostic entry
    entries: HashMap<DiagnosticKey, DiagnosticEntry>,
}

/// Key used to identify and group related diagnostics
/// We key only by location to allow merging errors for different components
/// that share the same root cause (e.g., transitive dependencies)
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct DiagnosticKey {
    /// Primary source location (file:line:column)
    /// This is typically the line in check_components! where the error occurs
    location: SourceLocation,
}

/// Source code location
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct SourceLocation {
    file: String,
    line: usize,
    column: usize,
}

impl SourceLocation {
    fn from_span(span: &DiagnosticSpan) -> Self {
        SourceLocation {
            file: span.file_name.clone(),
            line: span.line_start,
            column: span.column_start,
        }
    }
}

/// A merged diagnostic entry combining information from multiple related errors
#[derive(Debug, Clone)]
pub struct DiagnosticEntry {
    /// The original diagnostic (we keep the first one as the primary)
    pub original: Diagnostic,

    /// Package ID from the CompilerMessage
    pub package_id: PackageId,

    /// Target from the CompilerMessage
    pub target: Target,

    /// Extracted field information (missing field errors)
    pub field_info: Option<FieldInfo>,

    /// Component information - supports multiple components at the same location
    /// This allows merging errors for different components that share the same root cause
    pub component_infos: Vec<ComponentInfo>,

    /// Check trait name (from "required by a bound in")
    /// This is the trait generated by check_components!, not the actual consumer trait
    pub check_trait: Option<String>,

    /// Provider relationships extracted from error chain
    pub provider_relationships: Vec<ProviderRelationship>,

    /// Delegation chain notes (raw, for later processing)
    pub delegation_notes: Vec<String>,

    /// Consumer trait dependencies extracted from delegation notes
    /// These are consumer traits that providers depend on
    pub consumer_trait_dependencies: Vec<crate::cgp_patterns::ConsumerTraitDependency>,

    /// Components that this component depends on (derived from consumer trait dependencies)
    /// This is populated during the second pass after all diagnostics are collected
    pub depends_on_components: Vec<String>,

    /// Whether this type has other HasField implementations
    pub has_other_hasfield_impls: bool,

    /// Primary spans for error reporting - one span per component
    /// This allows showing multiple components in a merged error message
    pub primary_spans: Vec<DiagnosticSpan>,

    /// Error code (e.g., "E0277")
    pub error_code: Option<String>,

    /// Main error message
    pub message: String,

    /// Whether this is a root cause or a transitive error
    pub is_root_cause: bool,

    /// Whether this error should be suppressed (because it's redundant)
    pub suppressed: bool,
}

impl DiagnosticDatabase {
    pub fn new() -> Self {
        Self::default()
    }

    /// First pass: Add a compiler message to the database
    /// If a related diagnostic already exists, merge information
    /// Diagnostics at the same location are merged to handle transitive dependencies
    /// For check_components! blocks, errors from consecutive lines with the same check_trait are merged
    pub fn add_diagnostic(&mut self, compiler_message: &CompilerMessage) {
        let diagnostic = &compiler_message.message;

        // Extract key components for grouping
        let primary_span = match diagnostic.spans.iter().find(|s| s.is_primary) {
            Some(span) => span,
            None => {
                // Can't process without a location
                return;
            }
        };

        let location = SourceLocation::from_span(primary_span);

        // Build the key using only location
        // But first check if there's an existing entry in the same file with the same check_trait
        // within a few lines (to handle check_components! blocks)
        let check_trait = Self::extract_check_trait_from_diagnostic(diagnostic);
        let mut matched_key = None;

        if let Some(ref trait_name) = check_trait {
            // Look for existing entries with the same check_trait in the same file
            for (existing_key, existing_entry) in &self.entries {
                if let Some(ref existing_trait) = existing_entry.check_trait {
                    // Check if it's the same check trait and in the same file
                    if existing_trait == trait_name && existing_key.location.file == location.file {
                        // Check if they're close together (within 10 lines - typical for check_components! blocks)
                        let line_diff = if existing_key.location.line > location.line {
                            existing_key.location.line - location.line
                        } else {
                            location.line - existing_key.location.line
                        };

                        if line_diff <= 10 {
                            // These are likely in the same check_components! block
                            matched_key = Some(existing_key.clone());
                            break;
                        }
                    }
                }
            }
        }

        if let Some(existing_key) = matched_key {
            // Merge into existing entry
            Self::merge_diagnostic_info(
                &mut self.entries,
                &existing_key,
                diagnostic,
                primary_span.clone(),
            );
        } else {
            // Create new entry with this location as the key
            let key = DiagnosticKey { location };
            let entry = Self::create_entry(
                diagnostic,
                primary_span.clone(),
                compiler_message.package_id.clone(),
                compiler_message.target.clone(),
            );
            self.entries.insert(key, entry);
        }
    }

    /// Creates a new diagnostic entry from a diagnostic
    fn create_entry(
        diagnostic: &Diagnostic,
        primary_span: DiagnosticSpan,
        package_id: PackageId,
        target: Target,
    ) -> DiagnosticEntry {
        // Extract all available information
        let field_info = extract_field_info(diagnostic);
        let component_info = Self::extract_component_info_from_diagnostic(diagnostic);
        let check_trait = Self::extract_check_trait_from_diagnostic(diagnostic);
        let provider_relationships =
            Self::extract_provider_relationships_from_diagnostic(diagnostic);
        let delegation_notes = Self::extract_delegation_notes(diagnostic);
        let consumer_trait_dependencies =
            Self::extract_consumer_trait_dependencies_from_diagnostic(diagnostic);
        let has_other_hasfield_impls = has_other_hasfield_implementations(diagnostic);
        let error_code = diagnostic.code.as_ref().map(|c| c.code.clone());

        // Build component_infos vector
        let component_infos = if let Some(info) = component_info {
            vec![info]
        } else {
            vec![]
        };

        // Determine if this is a root cause
        // A root cause has field_info (missing field) or is the most specific error
        let is_root_cause = field_info.is_some();

        DiagnosticEntry {
            original: diagnostic.clone(),
            package_id,
            target,
            field_info,
            component_infos,
            check_trait,
            provider_relationships,
            delegation_notes,
            consumer_trait_dependencies,
            depends_on_components: Vec::new(), // Populated in second pass
            has_other_hasfield_impls,
            primary_spans: vec![primary_span],
            error_code,
            message: diagnostic.message.clone(),
            is_root_cause,
            suppressed: false,
        }
    }

    /// Merges information from a new diagnostic into an existing entry
    /// This handles the case where multiple components at the same location fail
    /// due to the same root cause (e.g., transitive dependencies)
    fn merge_diagnostic_info(
        entries: &mut HashMap<DiagnosticKey, DiagnosticEntry>,
        key: &DiagnosticKey,
        new: &Diagnostic,
        new_span: DiagnosticSpan,
    ) {
        if let Some(existing) = entries.get_mut(key) {
            // If the new diagnostic has field info and existing doesn't, add it
            if existing.field_info.is_none() {
                if let Some(field_info) = extract_field_info(new) {
                    existing.field_info = Some(field_info);
                    existing.is_root_cause = true;
                }
            }

            // Merge component info - add new component if not already present
            if let Some(new_component_info) = Self::extract_component_info_from_diagnostic(new) {
                // Check if this component is already in the list
                let already_exists = existing
                    .component_infos
                    .iter()
                    .any(|info| info.component_type == new_component_info.component_type);

                if !already_exists {
                    existing.component_infos.push(new_component_info);

                    // Add the new span to the spans list
                    // Check if this span is already present to avoid duplicates
                    let span_exists = existing.primary_spans.iter().any(|span| {
                        span.file_name == new_span.file_name
                            && span.line_start == new_span.line_start
                            && span.column_start == new_span.column_start
                    });

                    if !span_exists {
                        existing.primary_spans.push(new_span);
                    }
                }
            }

            // Merge check trait
            if existing.check_trait.is_none() {
                existing.check_trait = Self::extract_check_trait_from_diagnostic(new);
            }

            // Add new provider relationships
            let new_relationships = Self::extract_provider_relationships_from_diagnostic(new);
            for rel in new_relationships {
                if !existing.provider_relationships.contains(&rel) {
                    existing.provider_relationships.push(rel);
                }
            }

            // Merge delegation notes
            let new_notes = Self::extract_delegation_notes(new);
            for note in new_notes {
                if !existing.delegation_notes.contains(&note) {
                    existing.delegation_notes.push(note);
                }
            }

            // Merge consumer trait dependencies
            let new_consumer_deps = Self::extract_consumer_trait_dependencies_from_diagnostic(new);
            for dep in new_consumer_deps {
                if !existing.consumer_trait_dependencies.contains(&dep) {
                    existing.consumer_trait_dependencies.push(dep);
                }
            }

            // Update hasfield implementations flag
            if !existing.has_other_hasfield_impls {
                existing.has_other_hasfield_impls = has_other_hasfield_implementations(new);
            }

            // If the new diagnostic has an error code and existing doesn't, use it
            if existing.error_code.is_none() {
                existing.error_code = new.code.as_ref().map(|c| c.code.clone());
            }
        }
    }

    /// Extract component info from anywhere in the diagnostic
    fn extract_component_info_from_diagnostic(diagnostic: &Diagnostic) -> Option<ComponentInfo> {
        // Try main message
        if let Some(info) = extract_component_info(&diagnostic.message) {
            // Check if the component_type is truncated (contains "...")
            // If so, try to extract from span text instead
            if !info.component_type.contains("...") {
                return Some(info);
            }
        }

        // Try all children
        for child in &diagnostic.children {
            if let Some(info) = extract_component_info(&child.message) {
                if !info.component_type.contains("...") {
                    return Some(info);
                }
            }
        }

        // If message-based extraction failed or returned truncated result,
        // try to extract component name from the span text
        if let Some(span) = diagnostic.spans.iter().find(|s| s.is_primary) {
            if let Some(info) = Self::extract_component_info_from_span(span) {
                return Some(info);
            }
        }

        None
    }

    /// Extract component info from the span's source text
    /// This is used as a fallback when the compiler truncates type names in error messages
    fn extract_component_info_from_span(span: &DiagnosticSpan) -> Option<ComponentInfo> {
        // Concatenate all text lines from the span
        let span_text: String = span
            .text
            .iter()
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>()
            .join("\n");

        // Extract component name from the span text
        // The highlighted portion should contain something like "AreaCalculatorComponent"
        extract_component_info(&span_text)
    }

    /// Extract check trait from diagnostic notes
    fn extract_check_trait_from_diagnostic(diagnostic: &Diagnostic) -> Option<String> {
        for child in &diagnostic.children {
            if matches!(child.level, DiagnosticLevel::Note) {
                if let Some(trait_name) = extract_check_trait(&child.message) {
                    return Some(trait_name);
                }
            }
        }
        None
    }

    /// Extract provider relationships from diagnostic notes
    fn extract_provider_relationships_from_diagnostic(
        diagnostic: &Diagnostic,
    ) -> Vec<ProviderRelationship> {
        let mut relationships = Vec::new();

        for child in &diagnostic.children {
            if matches!(child.level, DiagnosticLevel::Note) {
                if let Some(rel) = extract_provider_relationship(&child.message) {
                    relationships.push(rel);
                }
            }
        }

        relationships
    }

    /// Extract delegation chain notes
    fn extract_delegation_notes(diagnostic: &Diagnostic) -> Vec<String> {
        let mut notes = Vec::new();

        for child in &diagnostic.children {
            if matches!(child.level, DiagnosticLevel::Note) {
                if child.message.contains("required for") && child.message.contains("to implement")
                {
                    notes.push(child.message.clone());
                }
            }
        }

        notes
    }

    /// Extract consumer trait dependencies from delegation notes
    fn extract_consumer_trait_dependencies_from_diagnostic(
        diagnostic: &Diagnostic,
    ) -> Vec<crate::cgp_patterns::ConsumerTraitDependency> {
        use crate::cgp_patterns::extract_consumer_trait_dependency;

        let mut dependencies = Vec::new();

        for child in &diagnostic.children {
            if matches!(child.level, DiagnosticLevel::Note) {
                if let Some(dep) = extract_consumer_trait_dependency(&child.message) {
                    dependencies.push(dep);
                }
            }
        }

        dependencies
    }

    /// Get all non-suppressed entries
    pub fn get_active_entries(&self) -> Vec<&DiagnosticEntry> {
        self.entries.values().filter(|e| !e.suppressed).collect()
    }

    /// Get all entries (including suppressed)
    pub fn get_all_entries(&self) -> Vec<&DiagnosticEntry> {
        self.entries.values().collect()
    }

    /// Second pass: resolve component dependencies
    /// This should be called after all diagnostics have been added
    /// It matches consumer trait dependencies to actual components in the list
    pub fn resolve_component_dependencies(&mut self) {
        // Build a map of component names that exist in our diagnostic set
        let mut component_names: std::collections::HashSet<String> =
            std::collections::HashSet::new();
        // Also build a map from consumer traits to components (based on provider traits)
        let mut consumer_trait_to_component: std::collections::HashMap<String, Vec<String>> =
            std::collections::HashMap::new();

        for entry in self.entries.values() {
            for component_info in &entry.component_infos {
                let component_name =
                    crate::cgp_patterns::strip_module_prefixes(&component_info.component_type);
                component_names.insert(component_name.clone());

                // Map provider trait to component
                // Provider trait "AreaCalculator" corresponds to consumer trait "CanCalculateArea"
                // We can derive the consumer trait from the provider trait
                if let Some(ref provider_trait) = component_info.provider_trait {
                    // Try to derive consumer trait from provider trait
                    // Pattern: Provider "XyzCalculator" -> Consumer "CanCalculateXyz"
                    // But this is complex, so instead let's just store the component for fuzzy matching
                    let consumer_trait = derive_consumer_trait_from_provider(provider_trait);
                    consumer_trait_to_component
                        .entry(consumer_trait)
                        .or_default()
                        .push(component_name.clone());
                }
            }
        }

        // Now populate depends_on_components for each entry
        // We need to collect the updates first to avoid borrowing issues
        let mut updates: Vec<(DiagnosticKey, Vec<String>)> = Vec::new();

        for (key, entry) in &self.entries {
            let mut depends_on = Vec::new();

            for consumer_dep in &entry.consumer_trait_dependencies {
                // Check if this consumer trait maps to any component in our set
                // First try exact match with derived component name
                if let Some(ref component_name) = consumer_dep.component_name {
                    if component_names.contains(component_name) {
                        if !depends_on.contains(component_name) {
                            depends_on.push(component_name.clone());
                        }
                        continue;
                    }
                }

                // Try fuzzy match - check if any component could satisfy this consumer trait
                // by checking if the consumer trait matches what any component provides
                if let Some(components) = consumer_trait_to_component.get(&consumer_dep.trait_name)
                {
                    for comp in components {
                        // Only add if it's not the same as one of our own components
                        let is_own_component = entry.component_infos.iter().any(|c| {
                            crate::cgp_patterns::strip_module_prefixes(&c.component_type) == *comp
                        });

                        if !is_own_component && !depends_on.contains(comp) {
                            depends_on.push(comp.clone());
                        }
                    }
                }
            }

            if !depends_on.is_empty() {
                updates.push((key.clone(), depends_on));
            }
        }

        // Apply the updates
        for (key, depends_on) in updates {
            if let Some(entry) = self.entries.get_mut(&key) {
                entry.depends_on_components = depends_on;
            }
        }
    }

    /// Render all CGP error messages as CgpDiagnostic objects
    /// This should be called after all diagnostics have been collected
    /// Returns a vector of CgpDiagnostic objects with improved CGP diagnostics
    pub fn render_cgp_diagnostics(&mut self) -> Vec<CgpDiagnostic> {
        use crate::error_formatting::format_error_message;

        // First, resolve component dependencies
        self.resolve_component_dependencies();

        // Get all active (non-suppressed) entries
        let active_entries = self.get_active_entries();

        // Build CgpDiagnostic for each entry
        let mut results = Vec::new();
        for entry in active_entries {
            if let Some(diagnostic) = format_error_message(entry) {
                results.push(diagnostic);
            }
        }

        results
    }

    /// Render all CGP error messages
    /// This should be called after all diagnostics have been collected
    /// Returns a vector of formatted error message strings ready to print
    pub fn render_cgp_errors(&mut self) -> Vec<String> {
        use crate::error_formatting::render_diagnostic_plain;

        self.render_cgp_diagnostics()
            .iter()
            .map(|diag| render_diagnostic_plain(diag))
            .collect()
    }
}

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

    #[test]
    fn test_diagnostic_database_basic() {
        let db = DiagnosticDatabase::new();
        assert_eq!(db.get_all_entries().len(), 0);
    }
}