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
573
574
575
576
/// Module for detecting and extracting CGP-specific patterns from compiler diagnostics
/// This module only patterns match on CGP library constructs, never on user code
use cargo_metadata::diagnostic::{Diagnostic, DiagnosticLevel};

/// Checks if a diagnostic is related to CGP constructs
pub fn is_cgp_diagnostic(diagnostic: &Diagnostic) -> bool {
    let cgp_patterns = [
        "CanUseComponent",
        "IsProviderFor",
        "HasField",
        "cgp_impl",
        "cgp_component",
        "cgp_auto_getter",
        "delegate_components",
        "check_components",
    ];

    // Check main message
    if cgp_patterns.iter().any(|p| diagnostic.message.contains(p)) {
        return true;
    }

    // Check children messages
    for child in &diagnostic.children {
        if cgp_patterns.iter().any(|p| child.message.contains(p)) {
            return true;
        }
    }

    false
}

/// Information about a component extracted from CGP patterns
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ComponentInfo {
    /// Full component type name (e.g., "AreaCalculatorComponent", "ScaledArea<RectangleArea>")
    pub component_type: String,
    /// Provider trait name derived from component (e.g., "AreaCalculator" from "AreaCalculatorComponent")
    pub provider_trait: Option<String>,
}

/// Information about a field extracted from HasField patterns
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FieldInfo {
    /// The field name extracted from Symbol pattern
    pub field_name: String,
    /// Whether the field name was fully extracted (false if truncated)
    pub is_complete: bool,
    /// Whether the field name contains unknown characters (shown as �)
    pub has_unknown_chars: bool,
    /// The struct/type that is missing the field
    pub target_type: String,
}

/// Information about provider trait relationships from IsProviderFor patterns
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ProviderRelationship {
    /// The provider implementation type
    pub provider_type: String,
    /// The component being provided
    pub component: String,
    /// The context type
    pub context: String,
}

/// Extracts component information from CanUseComponent patterns
/// Pattern: `CanUseComponent<ComponentType>`
pub fn extract_component_from_can_use(message: &str) -> Option<ComponentInfo> {
    let start = message.find("CanUseComponent<")?;
    let after_start = start + "CanUseComponent<".len();

    let component_type = extract_balanced_generic(message, after_start)?;
    let provider_trait = derive_provider_trait_name(&component_type);

    Some(ComponentInfo {
        component_type,
        provider_trait,
    })
}

/// Extracts component information from various patterns in a message
pub fn extract_component_info(message: &str) -> Option<ComponentInfo> {
    // Try CanUseComponent pattern first
    if let Some(info) = extract_component_from_can_use(message) {
        return Some(info);
    }
    // Try IsProviderFor pattern - extract component from inside the generic
    // Pattern: `IsProviderFor<ComponentName, Context>`
    if let Some(start) = message.find("IsProviderFor<") {
        let after_start = start + "IsProviderFor<".len();

        // Find the first comma (component name ends before it)
        if let Some(comma_pos) = message[after_start..].find(',') {
            let component_type = message[after_start..after_start + comma_pos].trim();

            // Verify it looks like a component (ends with "Component" or contains it)
            if component_type.contains("Component") {
                let provider_trait = derive_provider_trait_name(component_type);
                return Some(ComponentInfo {
                    component_type: component_type.to_string(),
                    provider_trait,
                });
            }
        }
    }

    // Try to find component names by the "*Component" suffix pattern
    // This is a general CGP naming convention
    for word in message.split_whitespace() {
        let clean_word =
            word.trim_matches(|c: char| !c.is_alphanumeric() && c != '<' && c != '>' && c != ',');

        // Skip if this is part of an IsProviderFor pattern
        // We handle that separately above
        if clean_word.contains("IsProviderFor") {
            continue;
        }

        if clean_word.contains("Component") {
            // Extract the component type, handling generics
            if let Some(component_type) = extract_component_type_name(clean_word) {
                let provider_trait = derive_provider_trait_name(&component_type);
                return Some(ComponentInfo {
                    component_type,
                    provider_trait,
                });
            }
        }
    }

    None
}

/// Extracts a component type name from a string that may contain it
fn extract_component_type_name(text: &str) -> Option<String> {
    // Handle simple case: just "XyzComponent"
    if text.ends_with("Component") && !text.contains('<') {
        return Some(text.to_string());
    }

    // Handle generic case: "Xyz<A, B>Component" or more complex patterns
    // Find all text that forms a valid component reference
    if let Some(component_pos) = text.rfind("Component") {
        // Find the start of this component reference
        let before_component = &text[..component_pos + "Component".len()];

        // Walk backward to find the start, handling generics
        let mut depth = 0;
        let mut start_idx = 0;

        for (i, ch) in before_component.char_indices().rev() {
            if ch == '>' {
                depth += 1;
            } else if ch == '<' {
                depth -= 1;
            } else if depth == 0 && !ch.is_alphanumeric() && ch != '_' {
                start_idx = i + 1;
                break;
            }
        }

        return Some(before_component[start_idx..].to_string());
    }

    None
}

/// Derives provider trait name from component name by removing "Component" suffix
/// Example: "AreaCalculatorComponent" -> Some("AreaCalculator")
pub fn derive_provider_trait_name(component_name: &str) -> Option<String> {
    // Handle simple case: "XyzComponent" -> "Xyz"
    if let Some(stripped) = component_name.strip_suffix("Component") {
        if !stripped.is_empty() {
            return Some(stripped.to_string());
        }
    }

    // Handle complex generic cases like "Wrapper<Inner>Component"
    // This shouldn't normally happen in CGP, but handle it gracefully
    if component_name.contains("Component") {
        if let Some(pos) = component_name.rfind("Component") {
            let before = &component_name[..pos];
            if !before.is_empty() {
                return Some(before.to_string());
            }
        }
    }

    None
}

/// Extracts field information from HasField diagnostic patterns
/// Pattern: `HasField<Symbol<N, Chars<'c1', Chars<'c2', ...>>>>` is not implemented for `Type`
pub fn extract_field_info(diagnostic: &Diagnostic) -> Option<FieldInfo> {
    for child in &diagnostic.children {
        if matches!(child.level, DiagnosticLevel::Help) {
            let message = &child.message;

            if message.contains("HasField") && message.contains("is not implemented for") {
                // Extract the field name from Symbol pattern
                let field_name_result = extract_field_name_from_symbol(message)?;

                // Extract the target type
                let target_type = extract_type_from_not_implemented(message)?;

                return Some(FieldInfo {
                    field_name: field_name_result.0,
                    is_complete: field_name_result.1,
                    has_unknown_chars: field_name_result.2,
                    target_type,
                });
            }
        }
    }

    None
}

/// Extracts field name from Symbol<N, Chars<'x', Chars<'y', ...>>> pattern
/// Returns (field_name, is_complete, has_unknown_chars)
fn extract_field_name_from_symbol(message: &str) -> Option<(String, bool, bool)> {
    // Get the part before "but trait" if it exists (to focus on the unsatisfied trait)
    let relevant_part = if let Some(pos) = message.find("but trait") {
        &message[..pos]
    } else {
        message
    };

    // Extract expected length from Symbol<N, ...>
    let expected_length = extract_symbol_length(relevant_part)?;

    // Extract visible characters from Chars<'x', Chars<'y', ...>> chain
    let (chars, has_unknown) = extract_chars_from_pattern(relevant_part);

    if chars.is_empty() {
        return None;
    }

    let field_name: String = chars.iter().collect();
    let is_complete = field_name.len() == expected_length;

    Some((field_name, is_complete, has_unknown))
}

/// Extracts the expected length from Symbol<N, ...> pattern
fn extract_symbol_length(text: &str) -> Option<usize> {
    let start = text.find("Symbol<")?;
    let after_symbol = &text[start + 7..];
    let comma_pos = after_symbol.find(',')?;
    after_symbol[..comma_pos].trim().parse::<usize>().ok()
}

/// Extracts all characters from Chars<'x', Chars<'y', ...>> pattern
/// Returns (chars, has_unknown_chars)
/// Unknown characters (represented as '_' in the original) are replaced with '�' (U+FFFD)
fn extract_chars_from_pattern(text: &str) -> (Vec<char>, bool) {
    let mut chars = Vec::new();
    let mut has_unknown = false;
    let mut idx = 0;

    while idx < text.len() {
        if text[idx..].starts_with("Chars<'") {
            // Look for the character after the quote
            let char_start = idx + 7;
            if let Some(ch) = text[char_start..].chars().next() {
                // Extract the character if it's not the closing quote
                if ch != '\'' {
                    chars.push(ch);
                }
            }
        } else if text[idx..].starts_with("Chars<_") {
            // This is an unknown/hidden character (no quotes around it)
            chars.push('\u{FFFD}'); // Unicode replacement character
            has_unknown = true;
        }
        idx += 1;
    }

    (chars, has_unknown)
}

/// Extracts type name from "is not implemented for `Type`" pattern
fn extract_type_from_not_implemented(message: &str) -> Option<String> {
    let start = message.find("is not implemented for `")?;
    let after_start = start + "is not implemented for `".len();
    let end = message[after_start..].find('`')?;
    let full_name = &message[after_start..after_start + end];

    // Remove module prefix (e.g., "module::Type" -> "Type")
    let simple_name = full_name.split("::").last().unwrap_or(full_name);
    Some(simple_name.to_string())
}

/// Extracts provider relationship from IsProviderFor patterns
/// Pattern: `for `Provider` to implement `IsProviderFor<Component, Context>`
pub fn extract_provider_relationship(message: &str) -> Option<ProviderRelationship> {
    if !message.contains("IsProviderFor") {
        return None;
    }

    // Extract provider type: "for `Provider` to implement"
    let provider_type = extract_type_from_for_to_implement(message)?;

    // Extract component and context from IsProviderFor<Component, Context>
    let start = message.find("IsProviderFor<")?;
    let after_start = start + "IsProviderFor<".len();

    // Find the comma separating component and context
    let comma_pos = find_comma_at_depth(after_start, message)?;
    let component = message[after_start..comma_pos].trim().to_string();

    // Extract context (from comma to closing >)
    let after_comma = comma_pos + 1;
    let context = extract_balanced_generic(message, after_comma)?;

    Some(ProviderRelationship {
        provider_type,
        component,
        context,
    })
}

/// Extracts type from "for `Type` to implement" pattern
fn extract_type_from_for_to_implement(message: &str) -> Option<String> {
    let start = message.find("for `")?;
    let after_start = start + 5;
    let end = message[after_start..].find("` to")?;
    let full_name = &message[after_start..after_start + end];

    // Remove module prefix
    let simple_name = full_name.split("::").last().unwrap_or(full_name);
    Some(simple_name.to_string())
}

/// Finds the position of a comma at the top level of generic nesting
fn find_comma_at_depth(start_pos: usize, text: &str) -> Option<usize> {
    let mut depth = 0;

    for (i, ch) in text[start_pos..].char_indices() {
        match ch {
            '<' => depth += 1,
            '>' => depth -= 1,
            ',' if depth == 0 => return Some(start_pos + i),
            _ => {}
        }
    }

    None
}

/// Extracts a balanced generic type from text starting at position
/// Example: extract "Foo<Bar, Baz>" from position after opening `<`
fn extract_balanced_generic(text: &str, start_pos: usize) -> Option<String> {
    let mut depth = 1; // We've already seen one opening bracket
    let mut end_pos = start_pos;

    for (i, ch) in text[start_pos..].char_indices() {
        match ch {
            '<' => depth += 1,
            '>' => {
                depth -= 1;
                if depth == 0 {
                    end_pos = start_pos + i;
                    break;
                }
            }
            _ => {}
        }
    }

    if depth == 0 {
        Some(text[start_pos..end_pos].trim().to_string())
    } else {
        // Not balanced, return what we have
        Some(text[start_pos..].trim_end_matches('>').trim().to_string())
    }
}

/// Extracts check trait name from "required by a bound in `TraitName`" pattern
/// Note: This extracts the check trait (e.g., CanUseRectangle), NOT the consumer trait
pub fn extract_check_trait(message: &str) -> Option<String> {
    let start = message.find("required by a bound in `")?;
    let after_start = start + "required by a bound in `".len();
    let end = message[after_start..].find('`')?;
    Some(message[after_start..after_start + end].to_string())
}

/// Checks if a diagnostic has help messages indicating other HasField implementations exist
pub fn has_other_hasfield_implementations(diagnostic: &Diagnostic) -> bool {
    for child in &diagnostic.children {
        if matches!(child.level, DiagnosticLevel::Help) {
            if child.message.contains("but trait `HasField")
                || child
                    .message
                    .contains("the following other types implement trait")
            {
                return true;
            }
        }
    }
    false
}

/// Information about a consumer trait dependency extracted from delegation notes
/// This represents a consumer trait that a provider depends on
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConsumerTraitDependency {
    /// The consumer trait name (e.g., "CanCalculateArea")
    pub trait_name: String,
    /// The context type (e.g., "Rectangle")
    pub context_type: String,
    /// The component that provides this consumer trait (if we can derive it)
    pub component_name: Option<String>,
}

/// Extracts consumer trait dependencies from delegation notes
/// These are consumer traits that providers depend on, shown in notes like:
/// "required for `Rectangle` to implement `CanCalculateArea`"
/// Returns None if the trait is not a consumer trait (e.g., internal CGP traits)
pub fn extract_consumer_trait_dependency(note: &str) -> Option<ConsumerTraitDependency> {
    // Look for pattern: "required for `Context` to implement `TraitName`"
    // This indicates that the provider depends on this consumer trait
    if let Some(for_pos) = note.find("required for `") {
        let after_for = for_pos + "required for `".len();

        // Extract context type (between first ` and next `)
        if let Some(context_end) = note[after_for..].find('`') {
            let context_type = &note[after_for..after_for + context_end];

            // Look for the trait name after "to implement `"
            if let Some(implement_pos) = note[after_for + context_end..].find("to implement `") {
                let trait_start = after_for + context_end + implement_pos + "to implement `".len();

                if let Some(trait_end) = note[trait_start..].find('`') {
                    let trait_name = &note[trait_start..trait_start + trait_end];

                    // Filter out internal CGP traits - we only want consumer traits
                    // Consumer traits typically start with "Can" but exclude framework traits
                    let cleaned_trait = strip_module_prefixes(trait_name);

                    // Skip if it's an IsProviderFor or CanUseComponent trait (these are internal)
                    if cleaned_trait.starts_with("Can")
                        && !cleaned_trait.contains("CanUseComponent")
                        && !cleaned_trait.starts_with("IsProviderFor")
                    {
                        // Try to derive the component name from the consumer trait
                        let component_name = derive_component_from_consumer_trait(&cleaned_trait);

                        return Some(ConsumerTraitDependency {
                            trait_name: cleaned_trait,
                            context_type: strip_module_prefixes(context_type),
                            component_name,
                        });
                    }
                }
            }
        }
    }

    None
}

/// Derives a component name from a consumer trait name
/// E.g., "CanCalculateArea" -> "AreaCalculatorComponent"
/// This is a heuristic that works for common CGP naming patterns:
/// - Consumer trait: Can{Action} (e.g., CanCalculateArea)
/// - Component: {Action}Component (e.g., AreaCalculatorComponent)
pub fn derive_component_from_consumer_trait(consumer_trait: &str) -> Option<String> {
    // Check if it starts with "Can"
    if let Some(action_part) = consumer_trait.strip_prefix("Can") {
        // Remove the "Can" prefix and append "Component"
        // E.g., "CalculateArea" -> "AreaCalculatorComponent"
        Some(format!("{}Component", action_part))
    } else {
        None
    }
}

/// Removes all module prefixes from a message (e.g., "foo::bar::Baz" -> "Baz")
pub fn strip_module_prefixes(message: &str) -> String {
    // This is a generic transformation - we don't hardcode specific module names
    let mut result = message.to_string();

    // Remove cgp library prefixes - do this multiple times to handle nested cases
    for _ in 0..5 {
        result = result.replace("cgp::prelude::", "");
        result = result.replace("cgp::", "");
    }

    // Remove IsProviderFor wrapper that sometimes appears
    // This handles cases like "IsProviderFor<AreaCalculator<..."
    if result.starts_with("IsProviderFor<") {
        // Extract what's inside and clean it up
        if let Some(start) = result.find('<') {
            let after_start = start + 1;
            result = result[after_start..].to_string();
        }
    }

    result
}

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

    #[test]
    fn test_derive_provider_trait_name() {
        assert_eq!(
            derive_provider_trait_name("AreaCalculatorComponent"),
            Some("AreaCalculator".to_string())
        );
        assert_eq!(
            derive_provider_trait_name("FooComponent"),
            Some("Foo".to_string())
        );
        assert_eq!(derive_provider_trait_name("Component"), None);
        assert_eq!(derive_provider_trait_name("NoSuffix"), None);
    }

    #[test]
    fn test_extract_symbol_length() {
        let text = "Symbol<6, Chars<'h', Chars<'e', ...>>>";
        assert_eq!(extract_symbol_length(text), Some(6));

        let text2 = "Symbol<5, Chars<'w', ...>>";
        assert_eq!(extract_symbol_length(text2), Some(5));
    }

    #[test]
    fn test_extract_chars_from_pattern() {
        let text = "Chars<'h', Chars<'e', Chars<'i', Chars<'g', Chars<'h', Chars<'t', Nil>>>>>>";
        let (chars, has_unknown) = extract_chars_from_pattern(text);
        assert_eq!(chars, vec!['h', 'e', 'i', 'g', 'h', 't']);
        assert!(!has_unknown);

        // When a character is hidden by the compiler, it appears as Chars<_, (without quotes)
        let text2 = "Chars<'w', Chars<'i', Chars<'d', Chars<_, Chars<'h', Nil>>>>>";
        let (chars2, has_unknown2) = extract_chars_from_pattern(text2);
        // Hidden characters are shown as �
        assert_eq!(chars2, vec!['w', 'i', 'd', '\u{FFFD}', 'h']);
        assert!(has_unknown2);
    }

    #[test]
    fn test_derive_component_from_consumer_trait() {
        assert_eq!(
            derive_component_from_consumer_trait("CanCalculateArea"),
            Some("CalculateAreaComponent".to_string())
        );
        assert_eq!(
            derive_component_from_consumer_trait("CanFoo"),
            Some("FooComponent".to_string())
        );
        assert_eq!(
            derive_component_from_consumer_trait("NotAConsumerTrait"),
            None
        );
    }

    #[test]
    fn test_extract_consumer_trait_dependency() {
        let note = "required for `Rectangle` to implement `CanCalculateArea`";
        let dep = extract_consumer_trait_dependency(note).unwrap();
        assert_eq!(dep.trait_name, "CanCalculateArea");
        assert_eq!(dep.context_type, "Rectangle");
        assert_eq!(
            dep.component_name,
            Some("CalculateAreaComponent".to_string())
        );

        // Should filter out internal traits
        let note2 = "required for `Rectangle` to implement `CanUseComponent<Something>`";
        assert!(extract_consumer_trait_dependency(note2).is_none());
    }
}