Skip to main content

incin_diagnostics/
mismatch.rs

1//! Structured parsers for the shape-mismatch diagnostics common to Incin
2//! generic-const trait bounds (`MatMulShape`, `ConcatShape`, ...). Each
3//! `*Mismatch` type mirrors one `#[diagnostic::on_unimplemented]` message
4//! shape: parse the compiler's rendered dimensions out of the message text,
5//! then offer a `Display`-friendly explanation of which dimension conflicts.
6
7use alloc::format;
8use alloc::string::{String, ToString};
9use alloc::vec::Vec;
10
11use crate::humanize::humanize_diagnostic;
12use crate::typenum::matching_bracket;
13
14/// A `matmul` shape mismatch, parsed from the `MatMulShape` trait's
15/// `#[diagnostic::on_unimplemented]` message, with the specific conflicting
16/// dimension identified and ready to render as a pointed-out explanation.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct MatMulMismatch {
19    /// The lhs shape's elements, humanized for display (e.g. `["2", "4"]`).
20    pub lhs: Vec<String>,
21    /// The rhs shape's elements, humanized for display (e.g. `["5", "6"]`).
22    pub rhs: Vec<String>,
23    /// Index into `lhs` of the conflicting "inner" dimension (always the
24    /// last element - matmul's `K` from the lhs side).
25    pub lhs_inner_index: usize,
26    /// Index into `rhs` of the conflicting "inner" dimension (the
27    /// second-to-last element - matmul's `K` from the rhs side; usually
28    /// index `0` for a plain `(K, N)`, but shifts right with batch dims).
29    pub rhs_inner_index: usize,
30}
31
32impl MatMulMismatch {
33    /// Renders the mismatch as a multi-line, ready-to-print explanation:
34    /// both shapes shown with the conflicting dimension pointed out via a
35    /// `^` marker underneath, plus a concrete suggested fix.
36    pub fn render(&self) -> String {
37        const INDENT: &str = "      ";
38        let lhs_inner = &self.lhs[self.lhs_inner_index];
39        let rhs_inner = &self.rhs[self.rhs_inner_index];
40
41        let lhs_label = format!("{INDENT}lhs shape = (");
42        let rhs_label = format!("{INDENT}rhs shape = (");
43        // `{:>N$}` right-aligns within a field of width `N`, so the marker
44        // ends up at index `N - 1` - add 1 to land it exactly at the target
45        // column (the offset of the element's first character).
46        let lhs_caret_width =
47            lhs_label.len() + joined_prefix_len(&self.lhs, self.lhs_inner_index) + 1;
48        let rhs_caret_width =
49            rhs_label.len() + joined_prefix_len(&self.rhs, self.rhs_inner_index) + 1;
50
51        format!(
52            "{lhs_label}{lhs_shape})\n\
53             {lhs_caret:>lhs_caret_width$} inner dim = {lhs_inner}\n\
54             {rhs_label}{rhs_shape})\n\
55             {rhs_caret:>rhs_caret_width$} inner dim = {rhs_inner}\n\
56             {INDENT}{lhs_inner} \u{2260} {rhs_inner} \u{2192} change the lhs inner dim from {lhs_inner} to {rhs_inner}, or the rhs inner dim from {rhs_inner} to {lhs_inner}.",
57            lhs_shape = self.lhs.join(", "),
58            rhs_shape = self.rhs.join(", "),
59            lhs_caret = "^",
60            rhs_caret = "^",
61        )
62    }
63}
64
65/// Length, in characters, of everything that would precede `elements[index]`
66/// once `elements` is joined with `", "` - i.e. where that element's own
67/// text starts within the joined string.
68fn joined_prefix_len(elements: &[String], index: usize) -> usize {
69    elements[..index].iter().map(|e| e.len() + 2).sum()
70}
71
72/// Parses the `MatMulShape` trait's fixed on_unimplemented message -
73/// `` Cannot matrix-multiply shape `{Self}` with `{Rhs}` `` - and, if the
74/// inner dimensions (last element of `Self`, second-to-last of `Rhs`, per
75/// the trait's own rule) actually differ, returns a [`MatMulMismatch`]
76/// ready to render. Returns `None` if `text` isn't this message, either
77/// shape isn't a plain tuple, or the inner dimensions match (nothing to
78/// explain - the real failure is something else, e.g. a rank mismatch).
79pub fn parse_matmul_mismatch(text: &str) -> Option<MatMulMismatch> {
80    // Search rather than `strip_prefix` on the whole input: callers (e.g.
81    // `cargo incin --explain`) pass the *entire* rendered diagnostic -
82    // "error[E0277]: Cannot matrix-multiply shape `...` with `...`\n   -->
83    // file:line:col\n..." - not just this one message in isolation.
84    let start = text.find("Cannot matrix-multiply shape `")?;
85    let after_prefix = &text[start + "Cannot matrix-multiply shape `".len()..];
86    let (lhs_raw, after_lhs) = after_prefix.split_once('`')?;
87    let after_lhs = after_lhs.strip_prefix(" with `")?;
88    let (rhs_raw, _) = after_lhs.split_once('`')?;
89
90    let lhs_inner_text = lhs_raw.strip_prefix('(')?.strip_suffix(')')?;
91    let rhs_inner_text = rhs_raw.strip_prefix('(')?.strip_suffix(')')?;
92
93    let lhs_elems: Vec<&str> = split_top_level_commas(lhs_inner_text);
94    let rhs_elems: Vec<&str> = split_top_level_commas(rhs_inner_text);
95    if lhs_elems.is_empty() || rhs_elems.len() < 2 {
96        return None;
97    }
98
99    let lhs_inner_index = lhs_elems.len() - 1;
100    let rhs_inner_index = rhs_elems.len() - 2;
101
102    let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
103    let lhs: Vec<String> = lhs_elems.iter().map(|e| humanize(e)).collect();
104    let rhs: Vec<String> = rhs_elems.iter().map(|e| humanize(e)).collect();
105
106    if lhs[lhs_inner_index] == rhs[rhs_inner_index] {
107        return None; // inner dims already agree - a different rule failed
108    }
109
110    Some(MatMulMismatch {
111        lhs,
112        rhs,
113        lhs_inner_index,
114        rhs_inner_index,
115    })
116}
117
118/// Splits `s` on top-level commas (i.e. not nested inside `<...>`) - a
119/// typenum shape tuple's elements never contain their own parens, only
120/// angle-bracket generics, so tracking `<`/`>` depth alone is sufficient.
121fn split_top_level_commas(s: &str) -> Vec<&str> {
122    let mut parts = Vec::new();
123    let mut depth = 0i32;
124    let mut start = 0;
125    for (i, ch) in s.char_indices() {
126        match ch {
127            '<' => depth += 1,
128            '>' => depth -= 1,
129            ',' if depth == 0 => {
130                parts.push(s[start..i].trim());
131                start = i + 1;
132            }
133            _ => {}
134        }
135    }
136    let last = s[start..].trim();
137    if !last.is_empty() || !parts.is_empty() {
138        parts.push(last);
139    }
140    parts
141}
142
143/// A `concat` shape mismatch, parsed from the `ConcatShape` trait's message.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct ConcatMismatch {
146    /// The left-hand operand's shape, one dimension per entry.
147    pub lhs: Vec<String>,
148    /// The right-hand operand's shape, one dimension per entry.
149    pub rhs: Vec<String>,
150    /// The concatenation axis the shapes disagreed on.
151    pub axis: usize,
152    /// Index into both `lhs` and `rhs` of the first disagreeing dimension.
153    pub mismatch_index: usize,
154}
155
156impl ConcatMismatch {
157    /// Renders the humanized explanation rustc should append to the diagnostic.
158    pub fn render(&self) -> String {
159        const INDENT: &str = "      ";
160        let lhs_val = &self.lhs[self.mismatch_index];
161        let rhs_val = &self.rhs[self.mismatch_index];
162
163        let lhs_label = format!("{INDENT}lhs shape = (");
164        let rhs_label = format!("{INDENT}rhs shape = (");
165        let lhs_caret_width =
166            lhs_label.len() + joined_prefix_len(&self.lhs, self.mismatch_index) + 1;
167        let rhs_caret_width =
168            rhs_label.len() + joined_prefix_len(&self.rhs, self.mismatch_index) + 1;
169
170        format!(
171            "{lhs_label}{lhs_shape})\n\
172             {lhs_caret:>lhs_caret_width$} non-concat dim = {lhs_val}\n\
173             {rhs_label}{rhs_shape})\n\
174             {rhs_caret:>rhs_caret_width$} non-concat dim = {rhs_val}\n\
175             {INDENT}{lhs_val} \u{2260} {rhs_val} \u{2192} concatenating along axis {axis} requires all other dimensions to match exactly.",
176            lhs_shape = self.lhs.join(", "),
177            rhs_shape = self.rhs.join(", "),
178            lhs_caret = "^",
179            rhs_caret = "^",
180            axis = self.axis,
181        )
182    }
183}
184
185/// Parses a `concat` mismatch from diagnostic text; `None` when the text is not this message.
186pub fn parse_concat_mismatch(text: &str) -> Option<ConcatMismatch> {
187    let start = text.find("Cannot concatenate shape `")?;
188    let after_prefix = &text[start + "Cannot concatenate shape `".len()..];
189    let (lhs_raw, after_lhs) = after_prefix.split_once('`')?;
190    let after_lhs = after_lhs.strip_prefix(" with `")?;
191    let (rhs_raw, after_rhs) = after_lhs.split_once('`')?;
192    let axis_str = after_rhs.strip_prefix(" along axis `")?.split_once('`')?.0;
193
194    let axis: usize = axis_str.trim().parse().ok()?;
195
196    let lhs_inner_text = lhs_raw.strip_prefix('(')?.strip_suffix(')')?;
197    let rhs_inner_text = rhs_raw.strip_prefix('(')?.strip_suffix(')')?;
198
199    let lhs_elems: Vec<&str> = split_top_level_commas(lhs_inner_text);
200    let rhs_elems: Vec<&str> = split_top_level_commas(rhs_inner_text);
201
202    if lhs_elems.len() != rhs_elems.len() {
203        return None;
204    }
205
206    let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
207    let lhs: Vec<String> = lhs_elems.iter().map(|e| humanize(e)).collect();
208    let rhs: Vec<String> = rhs_elems.iter().map(|e| humanize(e)).collect();
209
210    for i in 0..lhs.len() {
211        if i != axis && lhs[i] != rhs[i] {
212            return Some(ConcatMismatch {
213                lhs,
214                rhs,
215                axis,
216                mismatch_index: i,
217            });
218        }
219    }
220
221    None
222}
223
224/// A `broadcast` shape mismatch, parsed from the `BroadcastShape` trait's message.
225#[derive(Debug, Clone, PartialEq, Eq)]
226pub struct BroadcastMismatch {
227    /// The left-hand operand's shape, one dimension per entry.
228    pub lhs: Vec<String>,
229    /// The right-hand operand's shape, one dimension per entry.
230    pub rhs: Vec<String>,
231    /// Index into `lhs` of the first disagreeing dimension.
232    pub lhs_mismatch_index: usize,
233    /// Index into `rhs` of the first disagreeing dimension.
234    pub rhs_mismatch_index: usize,
235}
236
237impl BroadcastMismatch {
238    /// Renders the humanized explanation rustc should append to the diagnostic.
239    pub fn render(&self) -> String {
240        const INDENT: &str = "      ";
241        let lhs_val = &self.lhs[self.lhs_mismatch_index];
242        let rhs_val = &self.rhs[self.rhs_mismatch_index];
243
244        let lhs_label = format!("{INDENT}lhs shape = (");
245        let rhs_label = format!("{INDENT}rhs shape = (");
246        let lhs_caret_width =
247            lhs_label.len() + joined_prefix_len(&self.lhs, self.lhs_mismatch_index) + 1;
248        let rhs_caret_width =
249            rhs_label.len() + joined_prefix_len(&self.rhs, self.rhs_mismatch_index) + 1;
250
251        format!(
252            "{lhs_label}{lhs_shape})\n\
253             {lhs_caret:>lhs_caret_width$} dim = {lhs_val}\n\
254             {rhs_label}{rhs_shape})\n\
255             {rhs_caret:>rhs_caret_width$} dim = {rhs_val}\n\
256             {INDENT}{lhs_val} \u{2260} {rhs_val} \u{2192} broadcast requires corresponding dimensions to be equal, or one of them to be 1.",
257            lhs_shape = self.lhs.join(", "),
258            rhs_shape = self.rhs.join(", "),
259            lhs_caret = "^",
260            rhs_caret = "^",
261        )
262    }
263}
264
265/// Parses a `broadcast` mismatch from diagnostic text; `None` when the text is not this message.
266pub fn parse_broadcast_mismatch(text: &str) -> Option<BroadcastMismatch> {
267    let start = text.find("Cannot broadcast shape `")?;
268    let after_prefix = &text[start + "Cannot broadcast shape `".len()..];
269    let (lhs_raw, after_lhs) = after_prefix.split_once('`')?;
270    let after_lhs = after_lhs.strip_prefix(" to `")?;
271    let (rhs_raw, _) = after_lhs.split_once('`')?;
272
273    let lhs_inner_text = lhs_raw.strip_prefix('(')?.strip_suffix(')')?;
274    let rhs_inner_text = rhs_raw.strip_prefix('(')?.strip_suffix(')')?;
275
276    let lhs_elems: Vec<&str> = split_top_level_commas(lhs_inner_text);
277    let rhs_elems: Vec<&str> = split_top_level_commas(rhs_inner_text);
278
279    let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
280    let lhs: Vec<String> = lhs_elems.iter().map(|e| humanize(e)).collect();
281    let rhs: Vec<String> = rhs_elems.iter().map(|e| humanize(e)).collect();
282
283    let min_rank = lhs.len().min(rhs.len());
284    for i in 1..=min_rank {
285        let l_idx = lhs.len() - i;
286        let r_idx = rhs.len() - i;
287        let l_val = &lhs[l_idx];
288        let r_val = &rhs[r_idx];
289        if l_val != r_val && l_val != "1" && r_val != "1" {
290            return Some(BroadcastMismatch {
291                lhs,
292                rhs,
293                lhs_mismatch_index: l_idx,
294                rhs_mismatch_index: r_idx,
295            });
296        }
297    }
298
299    None
300}
301
302/// A `reshape` shape mismatch, parsed from the `ReshapeShape` trait's message.
303#[derive(Debug, Clone, PartialEq, Eq)]
304pub struct ReshapeMismatch {
305    /// The source shape, one dimension per entry.
306    pub src: Vec<String>,
307    /// The requested target shape, one entry per dimension (`?` where inferred).
308    pub target: Vec<String>,
309    /// Element count implied by `src`.
310    pub src_count: usize,
311    /// Element count implied by `target`.
312    pub target_count: usize,
313}
314
315impl ReshapeMismatch {
316    /// Renders the humanized explanation rustc should append to the diagnostic.
317    pub fn render(&self) -> String {
318        const INDENT: &str = "      ";
319        format!(
320            "{INDENT}src shape    = ({src_shape})  [total elements = {src_count}]\n\
321             {INDENT}target shape = ({target_shape})  [total elements = {target_count}]\n\
322             {INDENT}{src_count} \u{2260} {target_count} \u{2192} reshape requires the product of dimensions (total element count) to remain identical.",
323            src_shape = self.src.join(", "),
324            target_shape = self.target.join(", "),
325            src_count = self.src_count,
326            target_count = self.target_count,
327        )
328    }
329}
330
331/// Parses a `reshape` mismatch from diagnostic text; `None` when the text is not this message.
332pub fn parse_reshape_mismatch(text: &str) -> Option<ReshapeMismatch> {
333    let start = text.find("Cannot reshape from `")?;
334    let after_prefix = &text[start + "Cannot reshape from `".len()..];
335    let (src_raw, after_src) = after_prefix.split_once('`')?;
336    let after_src = after_src.strip_prefix(" to `")?;
337    let (target_raw, _) = after_src.split_once('`')?;
338
339    let src_inner_text = src_raw.strip_prefix('(')?.strip_suffix(')')?;
340    let target_inner_text = target_raw.strip_prefix('(')?.strip_suffix(')')?;
341
342    let src_elems: Vec<&str> = split_top_level_commas(src_inner_text);
343    let target_elems: Vec<&str> = split_top_level_commas(target_inner_text);
344
345    let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
346    let src: Vec<String> = src_elems.iter().map(|e| humanize(e)).collect();
347    let target: Vec<String> = target_elems.iter().map(|e| humanize(e)).collect();
348
349    let mut src_count = 1;
350    for s in &src {
351        src_count *= s.parse::<usize>().ok()?;
352    }
353    let mut target_count = 1;
354    for t in &target {
355        target_count *= t.parse::<usize>().ok()?;
356    }
357
358    if src_count != target_count {
359        Some(ReshapeMismatch {
360            src,
361            target,
362            src_count,
363            target_count,
364        })
365    } else {
366        None
367    }
368}
369
370/// A `conv2d` shape mismatch, parsed from the `Conv2dShape` trait's message.
371#[derive(Debug, Clone, PartialEq, Eq)]
372pub struct Conv2dMismatch {
373    /// The input tensor's shape, one dimension per entry.
374    pub input: Vec<String>,
375    /// The kernel/weight shape, one dimension per entry.
376    pub kernel: Vec<String>,
377    /// Index into `input` of the channel dimension.
378    pub input_channel_idx: usize,
379    /// Index into `kernel` of the channel dimension.
380    pub kernel_channel_idx: usize,
381}
382
383impl Conv2dMismatch {
384    /// Renders the humanized explanation rustc should append to the diagnostic.
385    pub fn render(&self) -> String {
386        const INDENT: &str = "      ";
387        let in_c = &self.input[self.input_channel_idx];
388        let k_c = &self.kernel[self.kernel_channel_idx];
389
390        let in_label = format!("{INDENT}input shape  = (");
391        let k_label = format!("{INDENT}kernel shape = (");
392        let in_caret_width =
393            in_label.len() + joined_prefix_len(&self.input, self.input_channel_idx) + 1;
394        let k_caret_width =
395            k_label.len() + joined_prefix_len(&self.kernel, self.kernel_channel_idx) + 1;
396
397        format!(
398            "{in_label}{in_shape})\n\
399             {in_caret:>in_caret_width$} input channels = {in_c}\n\
400             {k_label}{k_shape})\n\
401             {k_caret:>k_caret_width$} kernel in_channels = {k_c}\n\
402             {INDENT}{in_c} \u{2260} {k_c} \u{2192} Conv2D input channels must match kernel input channels.",
403            in_shape = self.input.join(", "),
404            k_shape = self.kernel.join(", "),
405            in_caret = "^",
406            k_caret = "^",
407        )
408    }
409}
410
411/// Parses a `conv2d` mismatch from diagnostic text; `None` when the text is not this message.
412pub fn parse_conv2d_mismatch(text: &str) -> Option<Conv2dMismatch> {
413    let start = text.find("Cannot apply Conv2D: input shape `")?;
414    let after_prefix = &text[start + "Cannot apply Conv2D: input shape `".len()..];
415    let (in_raw, after_in) = after_prefix.split_once('`')?;
416    let after_in = after_in.strip_prefix(" is incompatible with kernel shape `")?;
417    let (k_raw, _) = after_in.split_once('`')?;
418
419    let in_inner_text = in_raw.strip_prefix('(')?.strip_suffix(')')?;
420    let k_inner_text = k_raw.strip_prefix('(')?.strip_suffix(')')?;
421
422    let in_elems: Vec<&str> = split_top_level_commas(in_inner_text);
423    let k_elems: Vec<&str> = split_top_level_commas(k_inner_text);
424
425    if in_elems.len() < 2 || k_elems.len() < 2 {
426        return None;
427    }
428
429    let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
430    let input: Vec<String> = in_elems.iter().map(|e| humanize(e)).collect();
431    let kernel: Vec<String> = k_elems.iter().map(|e| humanize(e)).collect();
432
433    if input[1] != kernel[1] {
434        Some(Conv2dMismatch {
435            input,
436            kernel,
437            input_channel_idx: 1,
438            kernel_channel_idx: 1,
439        })
440    } else {
441        None
442    }
443}
444
445/// A `transpose` shape mismatch, parsed from the `Transpose` trait's message.
446#[derive(Debug, Clone, PartialEq, Eq)]
447pub struct TransposeMismatch {
448    /// The transposed tensor's shape, one dimension per entry.
449    pub shape: Vec<String>,
450    /// First axis of the transpose pair.
451    pub d1: usize,
452    /// Second axis of the transpose pair.
453    pub d2: usize,
454    /// Rank the axes were checked against.
455    pub rank: usize,
456}
457
458impl TransposeMismatch {
459    /// Renders the humanized explanation rustc should append to the diagnostic.
460    pub fn render(&self) -> String {
461        const INDENT: &str = "      ";
462        format!(
463            "{INDENT}shape = ({shape})  [rank = {rank}]\n\
464             {INDENT}transpose indices = ({d1}, {d2})\n\
465             {INDENT}invalid dimension index \u{2192} both transpose indices must be < rank ({rank}).",
466            shape = self.shape.join(", "),
467            rank = self.rank,
468            d1 = self.d1,
469            d2 = self.d2,
470        )
471    }
472}
473
474/// Parses a `transpose` mismatch from diagnostic text; `None` when the text is not this message.
475pub fn parse_transpose_mismatch(text: &str) -> Option<TransposeMismatch> {
476    let start = text.find("Cannot transpose dimensions `")?;
477    let after_prefix = &text[start + "Cannot transpose dimensions `".len()..];
478    let (d1_str, after_d1) = after_prefix.split_once('`')?;
479    let after_d1 = after_d1.strip_prefix(" and `")?;
480    let (d2_str, after_d2) = after_d1.split_once('`')?;
481    let after_d2 = after_d2.strip_prefix(" on shape `")?;
482    let (shape_raw, _) = after_d2.split_once('`')?;
483
484    let d1: usize = d1_str.trim().parse().ok()?;
485    let d2: usize = d2_str.trim().parse().ok()?;
486
487    let shape_inner = shape_raw.strip_prefix('(')?.strip_suffix(')')?;
488    let elems: Vec<&str> = split_top_level_commas(shape_inner);
489
490    let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
491    let shape: Vec<String> = elems.iter().map(|e| humanize(e)).collect();
492    let rank = shape.len();
493
494    if d1 >= rank || d2 >= rank {
495        Some(TransposeMismatch {
496            shape,
497            d1,
498            d2,
499            rank,
500        })
501    } else {
502        None
503    }
504}
505
506/// A `reduce` shape mismatch, parsed from the `ReduceDim` trait's message.
507#[derive(Debug, Clone, PartialEq, Eq)]
508pub struct ReduceDimMismatch {
509    /// The transposed tensor's shape, one dimension per entry.
510    pub shape: Vec<String>,
511    /// The axis whose extent was rejected.
512    pub dim: usize,
513    /// Rank the axes were checked against.
514    pub rank: usize,
515}
516
517impl ReduceDimMismatch {
518    /// Renders the humanized explanation rustc should append to the diagnostic.
519    pub fn render(&self) -> String {
520        const INDENT: &str = "      ";
521        format!(
522            "{INDENT}shape = ({shape})  [rank = {rank}]\n\
523             {INDENT}reduce dim = {dim}\n\
524             {INDENT}{dim} \u{2265} {rank} \u{2192} reduction dimension must be < rank ({rank}).",
525            shape = self.shape.join(", "),
526            rank = self.rank,
527            dim = self.dim,
528        )
529    }
530}
531
532/// Parses a `reduce_dim` mismatch from diagnostic text; `None` when the text is not this message.
533pub fn parse_reduce_dim_mismatch(text: &str) -> Option<ReduceDimMismatch> {
534    let start = text.find("Cannot reduce dimension `")?;
535    let after_prefix = &text[start + "Cannot reduce dimension `".len()..];
536    let (dim_str, after_dim) = after_prefix.split_once('`')?;
537    let after_dim = after_dim
538        .find("on shape `")
539        .map(|p| &after_dim[p + "on shape `".len()..])?;
540    let (shape_raw, _) = after_dim.split_once('`')?;
541
542    let dim: usize = dim_str.trim().parse().ok()?;
543
544    let shape_inner = shape_raw.strip_prefix('(')?.strip_suffix(')')?;
545    let elems: Vec<&str> = split_top_level_commas(shape_inner);
546
547    let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
548    let shape: Vec<String> = elems.iter().map(|e| humanize(e)).collect();
549    let rank = shape.len();
550
551    if dim >= rank {
552        Some(ReduceDimMismatch { shape, dim, rank })
553    } else {
554        None
555    }
556}
557
558/// A `flatten` shape mismatch, parsed from the `Flatten` trait's message.
559#[derive(Debug, Clone, PartialEq, Eq)]
560pub struct FlattenMismatch {
561    /// The transposed tensor's shape, one dimension per entry.
562    pub shape: Vec<String>,
563    /// First flattened axis.
564    pub start_dim: usize,
565    /// Last flattened axis, inclusive.
566    pub end_dim: usize,
567    /// Rank the axes were checked against.
568    pub rank: usize,
569}
570
571impl FlattenMismatch {
572    /// Renders the humanized explanation rustc should append to the diagnostic.
573    pub fn render(&self) -> String {
574        const INDENT: &str = "      ";
575        format!(
576            "{INDENT}shape = ({shape})  [rank = {rank}]\n\
577             {INDENT}flatten range = [{start_dim}, {end_dim}]\n\
578             {INDENT}invalid range \u{2192} flatten requires start <= end and end < rank ({rank}).",
579            shape = self.shape.join(", "),
580            rank = self.rank,
581            start_dim = self.start_dim,
582            end_dim = self.end_dim,
583        )
584    }
585}
586
587/// Parses a `flatten` mismatch from diagnostic text; `None` when the text is not this message.
588pub fn parse_flatten_mismatch(text: &str) -> Option<FlattenMismatch> {
589    let start = text.find("Cannot flatten shape `")?;
590    let after_prefix = &text[start + "Cannot flatten shape `".len()..];
591    let (shape_raw, after_shape) = after_prefix.split_once('`')?;
592    let after_shape = after_shape.strip_prefix(" from dimension `")?;
593    let (start_str, after_start) = after_shape.split_once('`')?;
594    let after_start = after_start.strip_prefix(" to `")?;
595    let (end_str, _) = after_start.split_once('`')?;
596
597    let start_dim: usize = start_str.trim().parse().ok()?;
598    let end_dim: usize = end_str.trim().parse().ok()?;
599
600    let shape_inner = shape_raw.strip_prefix('(')?.strip_suffix(')')?;
601    let elems: Vec<&str> = split_top_level_commas(shape_inner);
602
603    let humanize = |s: &str| humanize_diagnostic(s.trim()).text;
604    let shape: Vec<String> = elems.iter().map(|e| humanize(e)).collect();
605    let rank = shape.len();
606
607    if start_dim > end_dim || end_dim >= rank {
608        Some(FlattenMismatch {
609            shape,
610            start_dim,
611            end_dim,
612            rank,
613        })
614    } else {
615        None
616    }
617}
618
619/// A `Module::forward` input shape mismatch, parsed from compiler output.
620#[derive(Debug, Clone, PartialEq, Eq)]
621pub struct ModuleForwardMismatch {
622    /// The input shape text the diagnostic reported.
623    pub actual_input: String,
624    /// The input shape text the trait expected.
625    pub expected_input: String,
626}
627
628impl ModuleForwardMismatch {
629    /// Renders the humanized explanation rustc should append to the diagnostic.
630    pub fn render(&self) -> String {
631        const INDENT: &str = "      ";
632        format!(
633            "{INDENT}provided input shape = {actual}\n\
634             {INDENT}expected input shape = {expected}\n\
635             {INDENT}shape mismatch \u{2192} layer forward pass expects {expected}, but received {actual}.",
636            actual = self.actual_input,
637            expected = self.expected_input,
638        )
639    }
640}
641
642/// Parses a `module_forward` mismatch from diagnostic text; `None` when the text is not this message.
643pub fn parse_module_forward_mismatch(text: &str) -> Option<ModuleForwardMismatch> {
644    let mut search = text;
645    let mut actual_raw = None;
646    while let Some(start) = search.find("Module<") {
647        let after = &search[start + "Module<".len()..];
648        if let Some(close) = matching_bracket(after, '<', '>') {
649            let inner = &after[..close];
650            if inner.contains("Tensor") {
651                actual_raw = Some(inner);
652                break;
653            }
654        }
655        if after.is_empty() {
656            break;
657        }
658        search = &after[1..];
659    }
660    let actual_raw = actual_raw?;
661
662    let impl_start = text.find("implements `Module<")?;
663    let after_impl = &text[impl_start + "implements `Module<".len()..];
664    let close_impl = matching_bracket(after_impl, '<', '>')?;
665    let expected_raw = &after_impl[..close_impl];
666
667    let clean = |s: &str| {
668        let mut res = humanize_diagnostic(s.trim()).text.trim().to_string();
669        let open_count = res.chars().filter(|&c| c == '<').count();
670        let close_count = res.chars().filter(|&c| c == '>').count();
671        if open_count > close_count {
672            res.push('>');
673        }
674        res
675    };
676
677    let actual = clean(actual_raw);
678    let expected = clean(expected_raw);
679
680    if actual != expected {
681        Some(ModuleForwardMismatch {
682            actual_input: actual,
683            expected_input: expected,
684        })
685    } else {
686        None
687    }
688}
689
690/// A slice target shape mismatch, parsed from the `SliceTarget` trait's message.
691#[derive(Debug, Clone, PartialEq, Eq)]
692pub struct SliceMismatch {
693    /// The slice specification text the caller supplied.
694    pub slice_spec: String,
695    /// The input shape, one dimension per entry as text.
696    pub in_shape: String,
697}
698
699impl SliceMismatch {
700    /// Renders the humanized explanation rustc should append to the diagnostic.
701    pub fn render(&self) -> String {
702        const INDENT: &str = "      ";
703        format!(
704            "{INDENT}input shape = {in_shape}\n\
705             {INDENT}slice spec  = {slice_spec}\n\
706             {INDENT}invalid slice \u{2192} slice ranges must fall within input dimension bounds.",
707            in_shape = self.in_shape,
708            slice_spec = self.slice_spec,
709        )
710    }
711}
712
713/// Parses a `slice` mismatch from diagnostic text; `None` when the text is not this message.
714pub fn parse_slice_mismatch(text: &str) -> Option<SliceMismatch> {
715    let start = text.find("Cannot slice dimension with `")?;
716    let after = &text[start + "Cannot slice dimension with `".len()..];
717    let (spec_raw, after_spec) = after.split_once('`')?;
718
719    let in_shape_raw = if let Some(pos) = after_spec.find("for shape `") {
720        let after_for = &after_spec[pos + "for shape `".len()..];
721        after_for.split_once('`').map(|(s, _)| s)
722    } else {
723        None
724    };
725
726    let slice_spec = humanize_diagnostic(spec_raw.trim()).text;
727    let in_shape = in_shape_raw
728        .map(|s| humanize_diagnostic(s.trim()).text)
729        .unwrap_or_else(|| "unknown".to_string());
730
731    Some(SliceMismatch {
732        slice_spec,
733        in_shape,
734    })
735}
736
737/// A `conv1d` shape mismatch, parsed from the `SpatialConv1d` trait's message.
738#[derive(Debug, Clone, PartialEq, Eq)]
739pub struct Conv1dMismatch {
740    /// The input shape text the diagnostic reported.
741    pub input_shape: String,
742}
743
744impl Conv1dMismatch {
745    /// Renders the humanized explanation rustc should append to the diagnostic.
746    pub fn render(&self) -> String {
747        const INDENT: &str = "      ";
748        format!(
749            "{INDENT}input shape = {shape}\n\
750             {INDENT}invalid shape \u{2192} Conv1D requires a 2D or 3D tensor (C, L) or (B, C, L).",
751            shape = self.input_shape,
752        )
753    }
754}
755
756/// Parses a `conv1d` mismatch from diagnostic text; `None` when the text is not this message.
757pub fn parse_conv1d_mismatch(text: &str) -> Option<Conv1dMismatch> {
758    let start = text.find("Cannot apply 1D convolution to shape `")?;
759    let after = &text[start + "Cannot apply 1D convolution to shape `".len()..];
760    let (raw_shape, _) = after.split_once('`')?;
761
762    let input_shape = humanize_diagnostic(raw_shape.trim()).text;
763    Some(Conv1dMismatch { input_shape })
764}
765
766/// A 2D pooling shape mismatch, parsed from the `Pool2dShape` trait's message.
767#[derive(Debug, Clone, PartialEq, Eq)]
768pub struct Pool2dMismatch {
769    /// The input shape text the diagnostic reported.
770    pub input_shape: String,
771}
772
773impl Pool2dMismatch {
774    /// Renders the humanized explanation rustc should append to the diagnostic.
775    pub fn render(&self) -> String {
776        const INDENT: &str = "      ";
777        format!(
778            "{INDENT}input shape = {shape}\n\
779             {INDENT}invalid shape \u{2192} Pool2D requires a 3D or 4D tensor (C, H, W) or (B, C, H, W).",
780            shape = self.input_shape,
781        )
782    }
783}
784
785/// Parses a `pool2d` mismatch from diagnostic text; `None` when the text is not this message.
786pub fn parse_pool2d_mismatch(text: &str) -> Option<Pool2dMismatch> {
787    let start = text.find("Cannot apply 2D pooling to shape `")?;
788    let after = &text[start + "Cannot apply 2D pooling to shape `".len()..];
789    let (raw_shape, _) = after.split_once('`')?;
790
791    let input_shape = humanize_diagnostic(raw_shape.trim()).text;
792    Some(Pool2dMismatch { input_shape })
793}
794
795/// A shape equality mismatch, parsed from the `ShapeEq` trait's compile-time error.
796#[derive(Debug, Clone, PartialEq, Eq)]
797pub struct ShapeEqMismatch {
798    /// The verbatim diagnostic message this explanation annotates.
799    pub message: String,
800}
801
802impl ShapeEqMismatch {
803    /// Renders the humanized explanation rustc should append to the diagnostic.
804    pub fn render(&self) -> String {
805        const INDENT: &str = "      ";
806        format!("{INDENT}shape mismatch \u{2192} {msg}", msg = self.message,)
807    }
808}
809
810/// Parses a `shape_eq` mismatch from diagnostic text; `None` when the text is not this message.
811pub fn parse_shape_eq_mismatch(text: &str) -> Option<ShapeEqMismatch> {
812    if let Some(start) = text.find("Shape Mismatch:") {
813        let after = &text[start + "Shape Mismatch:".len()..];
814        let end = after.find('\n').unwrap_or(after.len());
815        let message = after[..end].trim().to_string();
816        Some(ShapeEqMismatch { message })
817    } else {
818        None
819    }
820}
821
822/// A `bmm` rank or shape mismatch.
823#[derive(Debug, Clone, PartialEq, Eq)]
824pub struct BmmMismatch {
825    /// The verbatim diagnostic message this explanation annotates.
826    pub message: String,
827}
828
829impl BmmMismatch {
830    /// Renders the humanized explanation rustc should append to the diagnostic.
831    pub fn render(&self) -> String {
832        const INDENT: &str = "      ";
833        format!("{INDENT}bmm mismatch \u{2192} {msg}", msg = self.message)
834    }
835}
836
837/// Parses a `bmm` mismatch from diagnostic text; `None` when the text is not this message.
838pub fn parse_bmm_mismatch(text: &str) -> Option<BmmMismatch> {
839    if text.contains("bmm") || text.contains("batched matrix multiplication") {
840        Some(BmmMismatch {
841            message: "BMM requires 3D tensors (B, M, K) x (B, K, N)".to_string(),
842        })
843    } else {
844        None
845    }
846}
847
848/// An `unfold` dimension bound mismatch.
849#[derive(Debug, Clone, PartialEq, Eq)]
850pub struct UnfoldMismatch {
851    /// The verbatim diagnostic message this explanation annotates.
852    pub message: String,
853}
854
855impl UnfoldMismatch {
856    /// Renders the humanized explanation rustc should append to the diagnostic.
857    pub fn render(&self) -> String {
858        const INDENT: &str = "      ";
859        format!("{INDENT}unfold mismatch \u{2192} {msg}", msg = self.message)
860    }
861}
862
863/// Parses a `unfold` mismatch from diagnostic text; `None` when the text is not this message.
864pub fn parse_unfold_mismatch(text: &str) -> Option<UnfoldMismatch> {
865    if text.contains("unfold size cannot exceed dimension length") {
866        Some(UnfoldMismatch {
867            message: "unfold size exceeds target dimension length".to_string(),
868        })
869    } else {
870        None
871    }
872}
873
874/// A `pixel_shuffle` channel divisibility mismatch.
875#[derive(Debug, Clone, PartialEq, Eq)]
876pub struct PixelShuffleMismatch {
877    /// The verbatim diagnostic message this explanation annotates.
878    pub message: String,
879}
880
881impl PixelShuffleMismatch {
882    /// Renders the humanized explanation rustc should append to the diagnostic.
883    pub fn render(&self) -> String {
884        const INDENT: &str = "      ";
885        format!(
886            "{INDENT}pixel_shuffle mismatch \u{2192} {msg}",
887            msg = self.message
888        )
889    }
890}
891
892/// Parses a `pixel_shuffle` mismatch from diagnostic text; `None` when the text is not this message.
893pub fn parse_pixel_shuffle_mismatch(text: &str) -> Option<PixelShuffleMismatch> {
894    if text.contains("pixel_shuffle channels must be divisible") {
895        Some(PixelShuffleMismatch {
896            message: "channel count must be divisible by upscale_factor^2".to_string(),
897        })
898    } else {
899        None
900    }
901}
902
903/// A `group_norm` channel divisibility mismatch.
904#[derive(Debug, Clone, PartialEq, Eq)]
905pub struct GroupNormMismatch {
906    /// The verbatim diagnostic message this explanation annotates.
907    pub message: String,
908}
909
910impl GroupNormMismatch {
911    /// Renders the humanized explanation rustc should append to the diagnostic.
912    pub fn render(&self) -> String {
913        const INDENT: &str = "      ";
914        format!(
915            "{INDENT}group_norm mismatch \u{2192} {msg}",
916            msg = self.message
917        )
918    }
919}
920
921/// Parses a `group_norm` mismatch from diagnostic text; `None` when the text is not this message.
922pub fn parse_group_norm_mismatch(text: &str) -> Option<GroupNormMismatch> {
923    if text.contains("group_norm: channels must be divisible by groups") {
924        Some(GroupNormMismatch {
925            message: "channels count must be divisible by groups".to_string(),
926        })
927    } else {
928        None
929    }
930}
931
932/// A math domain error diagnostic (e.g., asin/acos out of bounds, rsqrt non-positive).
933#[derive(Debug, Clone, PartialEq, Eq)]
934pub struct MathDomainError {
935    /// The verbatim diagnostic message this explanation annotates.
936    pub message: String,
937}
938
939impl MathDomainError {
940    /// Renders the humanized explanation rustc should append to the diagnostic.
941    pub fn render(&self) -> String {
942        const INDENT: &str = "      ";
943        format!(
944            "{INDENT}math domain error \u{2192} {msg}",
945            msg = self.message
946        )
947    }
948}
949
950/// Parses a `math_domain_error` mismatch from diagnostic text; `None` when the text is not this message.
951pub fn parse_math_domain_error(text: &str) -> Option<MathDomainError> {
952    if text.contains("out of domain")
953        || text.contains("NaN domain")
954        || text.contains("domain error")
955    {
956        Some(MathDomainError {
957            message: "argument value is outside the real domain of the function".to_string(),
958        })
959    } else {
960        None
961    }
962}
963
964/// An in-place shape mismatch diagnostic.
965#[derive(Debug, Clone, PartialEq, Eq)]
966pub struct InPlaceShapeMismatch {
967    /// The verbatim diagnostic message this explanation annotates.
968    pub message: String,
969}
970
971impl InPlaceShapeMismatch {
972    /// Renders the humanized explanation rustc should append to the diagnostic.
973    pub fn render(&self) -> String {
974        const INDENT: &str = "      ";
975        format!(
976            "{INDENT}in-place shape mismatch \u{2192} {msg}",
977            msg = self.message
978        )
979    }
980}
981
982/// Parses a `inplace_shape` mismatch from diagnostic text; `None` when the text is not this message.
983pub fn parse_inplace_shape_mismatch(text: &str) -> Option<InPlaceShapeMismatch> {
984    if text.contains("in-place operand shape mismatch") || text.contains("cannot mutate in-place") {
985        Some(InPlaceShapeMismatch {
986            message:
987                "target tensor and operand tensor must have identical shapes for in-place mutation"
988                    .to_string(),
989        })
990    } else {
991        None
992    }
993}