candle-einops-macros 0.2.0

Procedural macros for candle-einops tensor transformations and einsum
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};

use quote::ToTokens;
use syn::parse::discouraged::Speculative;
use syn::{parse::ParseStream, token};

// Custom keywords to represent reduce operations
mod kw {
    syn::custom_keyword!(min);
    syn::custom_keyword!(max);
    syn::custom_keyword!(sum);
    syn::custom_keyword!(mean);
    syn::custom_keyword!(prod);
}

#[derive(Debug, Clone)]
pub enum Decomposition {
    // New decomposed dimension with no shape provided
    // by the user
    Derived {
        name: String,
        index: Index,
        operation: Option<Operation>,
        shape_calc: proc_macro2::TokenStream,
    },
    Named {
        name: String,
        index: Index,
        operation: Option<Operation>,
        shape: Option<Shape>,
    },
}

#[derive(Debug, Clone)]
pub enum Shape {
    Lit(usize),
    Expr(proc_macro2::TokenStream),
}

#[derive(Debug)]
pub enum Composition {
    Individual(Index),
    // Start and end index of dimesions to be combined
    // into one
    Combined { from: Index, to: Option<Index> },
}

#[derive(Debug, Clone)]
pub enum Index {
    Known(usize),
    // Position of dimension after '..' symbol
    Unknown(usize),
    // Position of the '..' symbol
    Range(usize),
}

impl Ord for Index {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        match (self, other) {
            (
                Index::Known(i) | Index::Unknown(i) | Index::Range(i),
                Index::Known(j) | Index::Unknown(j) | Index::Range(j),
            ) => i.cmp(j),
        }
    }
}

impl PartialOrd for Index {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Index {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                Index::Known(i) | Index::Unknown(i) | Index::Range(i),
                Index::Known(j) | Index::Unknown(j) | Index::Range(j),
            ) => i == j,
        }
    }
}

impl Eq for Index {}

#[derive(Debug, Clone)]
pub enum Operation {
    Min,
    Max,
    Sum,
    Mean,
    Prod,
}

pub fn parse_decomposition(input: ParseStream) -> syn::Result<(Vec<Decomposition>, bool, usize)> {
    // Length of dimensions inside parenthesis,
    // we need it to account for the dimensions skipped during the iteration
    let mut parenthesized_len = 0;
    let mut minimum_rank = 0;
    let (decomposition, requires_decomposition, _) = (0..)
        // We parse till we reach '->'. The token is consumed after the fold so
        // parsing failures can be propagated instead of panicking here.
        .take_while(|_| !input.peek(syn::Token![->]))
        .try_fold(
            (
                Vec::new(),
                // Boolean to indicate if,
                // - dimensions are decomposed
                // - squeezing is required
                false,
                // Closure that helps construct `Index`,
                // it is updated once we hit '..' to construct `Unknown` indices
                Box::new(Index::Known) as Box<dyn Fn(usize) -> Index>,
            ),
            |(mut decomposition, mut requires_decomposition, mut index_fn), mut i| {
                // We account for dimensions skipped when we parse
                // contents of parenthesized expression
                i += parenthesized_len;
                if input.peek(syn::token::Paren) {
                    let content_expression = parse_left_parenthesized(input, index_fn(i))?;
                    decomposition.extend(content_expression);
                    requires_decomposition = true;
                    minimum_rank += 1;
                } else if peek_reduce_kw(input) {
                    let span = input.span();
                    let identifiers = parse_reduce_fn(input)?;
                    if identifiers.iter().any(|(_, shape, _)| shape.is_some()) {
                        return Err(syn::Error::new(
                            span,
                            "Axis sizes are not allowed in top-level reductions",
                        ));
                    }
                    minimum_rank += identifiers.iter().filter(|(name, ..)| name != "..").count();
                    // We account for dimensions skipped during reduction operations
                    // like `sum(a b c)`, where three dimensions are reduced
                    parenthesized_len += identifiers.len().saturating_sub(1);
                    identifiers.into_iter().enumerate().for_each(
                        |(inner_index, (name, shape, operation))| {
                            // If we encounter '..' inside reduce, we will have to update the closure
                            if name == ".." {
                                index_fn = Box::new(Index::Unknown);
                                decomposition.push(Decomposition::Named {
                                    name,
                                    index: Index::Range(i + inner_index),
                                    shape,
                                    operation: Some(operation),
                                });
                            } else {
                                decomposition.push(Decomposition::Named {
                                    name,
                                    index: index_fn(i + inner_index),
                                    shape,
                                    operation: Some(operation),
                                });
                            }
                        },
                    );
                } else if input.peek(syn::Ident) {
                    let span = input.span();
                    let (name, shape) = parse_identifier(input)?;
                    if shape.is_some() {
                        return Err(syn::Error::new(
                            span,
                            "Axis sizes are only allowed inside a decomposition group on the left",
                        ));
                    }
                    decomposition.push(Decomposition::Named {
                        name,
                        shape,
                        index: index_fn(i),
                        operation: None,
                    });
                    minimum_rank += 1;
                } else if input.peek(syn::LitInt) {
                    let lit_int = input.parse::<syn::LitInt>()?;
                    if lit_int.base10_parse::<usize>()? != 1 {
                        // '1' is the only literal int allowed on the left,
                        // this indicates a squeeze operation
                        return Err(input.error(format!(
                            "Literal Int {} not allowed on the left side",
                            lit_int
                        )));
                    }
                    // We have to reshape to squeeze the 1 sized dimension
                    requires_decomposition = true;
                    minimum_rank += 1;
                } else if input.peek(syn::Token![..]) {
                    input.parse::<syn::Token![..]>()?;
                    decomposition.push(Decomposition::Named {
                        name: "..".to_string(),
                        index: Index::Range(i),
                        shape: None,
                        operation: None,
                    });
                    // We update the closure as we have encountered '..'
                    index_fn = Box::new(Index::Unknown);
                } else {
                    return Err(input
                        .error("Unrecognized charater found in the left side of the expression"));
                }
                Ok((decomposition, requires_decomposition, index_fn))
            },
        )?;

    input.parse::<syn::Token![->]>()?;

    Ok((decomposition, requires_decomposition, minimum_rank))
}

fn parse_left_parenthesized(input: ParseStream, index: Index) -> syn::Result<Vec<Decomposition>> {
    let span = input.span();
    let content;
    syn::parenthesized!(content in input);

    if content.is_empty() {
        return Err(syn::Error::new(
            span,
            "Decomposition groups cannot be empty",
        ));
    }

    let mut content_expression = Vec::new();

    let (derived_name, derived_index, derived_operation, running_mul, shape_expr) = (0..)
        // We continue till we parse everything inside the parenthesis
        .take_while(|_| !content.is_empty())
        .try_fold(
            (None, None, None, 1usize, Vec::new()),
            |(
                mut derived_name,
                mut derived_index,
                mut derived_operation,
                mut running_mul,
                mut shape_expr,
            ),
             i| {
                // Closure to keep a running multiple of the shapes,
                // and updating the list with new dimensions with known shape
                let mut update_values = |name, shape, operation| {
                    if let Some(size) = shape {
                        match size {
                            Shape::Lit(lit_size) => {
                                running_mul =
                                    running_mul.checked_mul(lit_size).ok_or_else(|| {
                                        syn::Error::new(
                                            span,
                                            "Decomposition size product overflows usize",
                                        )
                                    })?;
                            }
                            Shape::Expr(ref expression) => shape_expr.push(expression.clone()),
                        }
                        content_expression.push(Decomposition::Named {
                            name,
                            index: index.clone(),
                            operation,
                            shape: Some(size),
                        });
                    } else {
                        if derived_name.is_some() {
                            // We cannot have more than one dimension with unknown shape
                            return Err(content
                                .error("Shape information required to complete decomposition"));
                        }
                        derived_name = Some(name);
                        derived_index = Some(i);
                        derived_operation = operation;
                    }
                    Ok(())
                };
                if peek_reduce_kw(&content) {
                    parse_reduce_fn(&content)?.into_iter().try_for_each(
                        |(name, shape, operation)| {
                            if name == ".." {
                                return Err(content.error(
                                    "Ignore symbol '..' not allowed inside brackets on the left",
                                ));
                            }
                            update_values(name, shape, Some(operation))
                        },
                    )?;
                } else if content.peek(syn::Ident) {
                    let (name, shape) = parse_identifier(&content)?;
                    update_values(name, shape, None)?
                } else if content.peek(syn::Token![..]) {
                    return Err(
                        content.error("Ignore symbol '..' not allowed inside brackets on the left")
                    );
                } else if content.peek(syn::LitInt) {
                    let lit_int = content.parse::<syn::LitInt>()?;
                    return Err(content.error(format!(
                        "Anonymous integer {} is not allowed inside brackets on the left",
                        lit_int
                    )));
                } else if content.peek(syn::token::Brace) {
                    let (name, shape) = parse_braced_expression(&content)?;
                    update_values(name, Some(shape), None)?;
                } else {
                    return Err(content.error(
                        "Unknown character found inside the brackets of the left expression",
                    ));
                };
                Ok((
                    derived_name,
                    derived_index,
                    derived_operation,
                    running_mul,
                    shape_expr,
                ))
            },
        )?;

    // We add the `Derived` dimension at the end at its index,
    // once we have the running multiple of all the other shapes
    // inside the parenthesis
    if let Some(derived_index) = derived_index {
        let derived_name = derived_name.ok_or_else(|| {
            syn::Error::new(
                content.span(),
                "Internal error while deriving the decomposed axis name",
            )
        })?;
        content_expression.insert(
            derived_index,
            Decomposition::Derived {
                name: derived_name,
                index,
                operation: derived_operation,
                shape_calc: if shape_expr.is_empty() {
                    quote::quote!(::core::option::Option::Some(#running_mul))
                } else {
                    quote::quote!(
                        [#(#shape_expr),*]
                            .into_iter()
                            .try_fold(#running_mul, |product, factor| product.checked_mul(factor))
                    )
                },
            },
        );
    }

    Ok(content_expression)
}

fn parse_braced_expression(content: ParseStream) -> syn::Result<(String, Shape)> {
    let shape_expression;
    syn::braced!(shape_expression in content);

    let span = shape_expression.span();

    let fork = shape_expression.fork();
    let (braced_name, braced_shape) = if let Ok(field) = fork.parse::<syn::ExprField>() {
        shape_expression.advance_to(&fork);
        let mut hasher = DefaultHasher::new();
        field.hash(&mut hasher);
        (
            hasher.finish().to_string(),
            Shape::Expr(field.to_token_stream()),
        )
    } else if shape_expression.peek(syn::Ident) {
        let ident = shape_expression.parse::<syn::Ident>()?;
        (ident.to_string(), Shape::Expr(ident.to_token_stream()))
    } else {
        return Err(syn::Error::new(
            span,
            "Only identifiers and fields are allowed inside '{}'",
        ));
    };

    if !shape_expression.is_empty() {
        return Err(syn::Error::new(
            span,
            "Only one identifier or field is allowed inside '{}'",
        ));
    }

    Ok((braced_name, braced_shape))
}

pub fn parse_reduce(decomposition: &[Decomposition]) -> Vec<(Index, Operation)> {
    // We filter for only the dimensions that have some type of
    // operation associated with them
    decomposition
        .iter()
        .cloned()
        .enumerate()
        .filter_map(|(i, expression)| match expression {
            Decomposition::Named {
                index: Index::Known(_),
                operation: Some(operation),
                ..
            }
            | Decomposition::Derived {
                index: Index::Known(_),
                operation: Some(operation),
                ..
            } => Some((Index::Known(i), operation)),
            Decomposition::Named {
                index: Index::Unknown(_),
                operation: Some(operation),
                ..
            }
            | Decomposition::Derived {
                index: Index::Unknown(_),
                operation: Some(operation),
                ..
            } => Some((Index::Unknown(i), operation)),
            Decomposition::Named {
                index: Index::Range(_),
                operation: Some(operation),
                ..
            } => Some((Index::Range(i), operation)),
            _ => None,
        })
        .collect::<Vec<_>>()
}

#[allow(clippy::type_complexity)]
pub fn parse_composition_permute_repeat(
    input: ParseStream,
    decomposition: &[Decomposition],
) -> syn::Result<(Vec<Composition>, Vec<Index>, Vec<(Index, Shape)>)> {
    // We calculate the span to report errors later
    let input_span = input.span();
    let mut left_names = HashSet::new();
    for expression in decomposition {
        let (name, is_anonymous_literal) = match expression {
            Decomposition::Named {
                name,
                shape: Some(Shape::Lit(size)),
                ..
            } => (name, name == &size.to_string()),
            Decomposition::Named { name, .. } | Decomposition::Derived { name, .. } => {
                (name, false)
            }
        };
        // Literal axes such as `max(2)` are anonymous and may be reused.
        if is_anonymous_literal {
            continue;
        }
        if !left_names.insert(name) {
            let message = if name == ".." {
                "Ellipsis `..` appears more than once on the left".to_string()
            } else {
                format!("Axis `{name}` appears more than once on the left")
            };
            return Err(syn::Error::new(input_span, message));
        }
    }
    // We check if ignored dimensions are reduced
    let is_ignore_reduced = decomposition.iter().any(|expression| {
        matches!(expression, Decomposition::Named {name, operation: Some(_), ..} if name.as_str() == "..")
    });
    // If '..' is reduced, previously unknown indices could change
    // to known
    let unknown_index_fn = |i| {
        if is_ignore_reduced {
            return Index::Known(i);
        }
        Index::Unknown(i)
    };
    // We create a hashmap of identifiers and their positions
    // in the left expression
    let positions = decomposition
        .iter()
        // We ignore all the reduced dimensions
        .filter(|expression| {
            !matches!(
                expression,
                Decomposition::Named {
                    operation: Some(_),
                    ..
                } | Decomposition::Derived {
                    operation: Some(_),
                    ..
                }
            )
        })
        .enumerate()
        .try_fold(HashMap::new(), |mut map, (i, expression)| {
            let (name, index) = match expression {
                Decomposition::Named {
                    name,
                    index: Index::Known(_),
                    ..
                }
                | Decomposition::Derived {
                    name,
                    index: Index::Known(_),
                    ..
                } => (name, Index::Known(i)),
                Decomposition::Named {
                    name,
                    index: Index::Unknown(_),
                    ..
                }
                | Decomposition::Derived {
                    name,
                    index: Index::Unknown(_),
                    ..
                } => (name, unknown_index_fn(i)),
                Decomposition::Named {
                    name,
                    index: Index::Range(_),
                    ..
                } => (name, Index::Range(i)),
                _ => unreachable!(),
            };
            if map.insert(name.clone(), index).is_some() {
                return Err(syn::Error::new(
                    input_span,
                    format!("Axis `{name}` appears more than once on the left"),
                ));
            }
            Ok(map)
        })?;

    let mut consumed = HashSet::new();

    // To keep track of the dimensions skipped inside parenthesis
    let mut parenthesized_len: usize = 0;
    let (composition, permute, repeat, _) = (0..)
        .take_while(|_| !input.is_empty())
        .try_fold::<_, _, syn::Result<(_, _, _, _)>>(
            (
                Vec::new(),
                Vec::new(),
                Vec::new(),
                // Closure to construct `Index`, once we encounter '..',
                // `Known` index becomes `Unknown`
                Box::new(Index::Known) as Box<dyn Fn(usize) -> Index>,
            ),
            |(mut composition, mut permute, mut repeat, mut index_fn), mut i| {
                // We update the iterator's index to account for dimensions skipped
                // inside parenthesis
                i += parenthesized_len;
                if input.peek(token::Paren) {
                    let (combined, combined_permute, combined_repeat, combined_len) =
                        parse_right_parenthesized(
                            input,
                            i,
                            &mut index_fn,
                            &positions,
                            &mut consumed,
                        )?;
                    parenthesized_len += combined_len.saturating_sub(1);
                    permute.extend(combined_permute);
                    repeat.extend(combined_repeat);
                    composition.push(combined);
                } else if input.peek(syn::Ident) {
                    let (name, shape) = parse_identifier(input)?;
                    if let Some(index) = positions.get(&name) {
                        if shape.is_some() {
                            return Err(syn::Error::new(
                                input_span,
                                format!("Axis `{name}` cannot be assigned a size on the right"),
                            ));
                        }
                        permute.push(index.clone());
                    } else {
                        // New identifiers represents repetition
                        let shape = shape.ok_or_else(|| {
                            syn::Error::new(
                                input.span(),
                                format!("New axis `{name}` requires an explicit size"),
                            )
                        })?;
                        repeat.push((index_fn(i), shape));
                    }
                    if !consumed.insert(name.clone()) {
                        return Err(syn::Error::new(
                            input_span,
                            format!("Axis `{name}` appears more than once on the right"),
                        ));
                    }
                    composition.push(Composition::Individual(index_fn(i)))
                } else if input.peek(syn::LitInt) {
                    // Literal ints represent repetition
                    repeat.push((index_fn(i), Shape::Lit(parse_usize(input)?)));
                    composition.push(Composition::Individual(index_fn(i)));
                } else if input.peek(syn::Token![..]) {
                    input.parse::<syn::Token![..]>()?;
                    if !consumed.insert("..".to_string()) {
                        return Err(syn::Error::new(
                            input_span,
                            "Ellipsis `..` appears more than once on the right",
                        ));
                    }
                    composition.push(Composition::Individual(Index::Range(i)));
                    let index = positions.get("..").ok_or_else(|| {
                        syn::Error::new(
                            input.span(),
                            "Ellipsis `..` must appear on both sides of the expression",
                        )
                    })?;
                    permute.push(index.clone());
                    // We update the closure
                    index_fn = Box::new(Index::Unknown);
                } else if input.peek(syn::token::Brace) {
                    let (name, shape) = parse_braced_expression(input)?;
                    if !consumed.insert(name.clone()) {
                        return Err(syn::Error::new(
                            input_span,
                            format!("Axis `{name}` appears more than once on the right"),
                        ));
                    }
                    if let Some(index) = positions.get(&name) {
                        permute.push(index.clone());
                    } else {
                        repeat.push((index_fn(i), shape));
                    }
                    composition.push(Composition::Individual(index_fn(i)));
                } else {
                    return Err(
                        input.error("Unrecognized character on the right side of the expression")
                    );
                }
                Ok((composition, permute, repeat, index_fn))
            },
        )?;

    // We raise an error if the right side of the expression
    // misses a indicator from the left side
    let mut missing = positions
        .keys()
        .filter(|name| !consumed.contains(*name))
        .cloned()
        .collect::<Vec<_>>();
    missing.sort();
    if !missing.is_empty() {
        return Err(syn::Error::new(
            input_span,
            format!("Axes missing on the right: {}", missing.join(", ")),
        ));
    }

    Ok((composition, permute, repeat))
}

#[allow(clippy::type_complexity)]
fn parse_right_parenthesized(
    input: ParseStream,
    start_index: usize,
    index_fn: &mut Box<dyn Fn(usize) -> Index>,
    positions: &HashMap<String, Index>,
    consumed: &mut HashSet<String>,
) -> syn::Result<(Composition, Vec<Index>, Vec<(Index, Shape)>, usize)> {
    let span = input.span();
    let content;
    syn::parenthesized!(content in input);

    if content.is_empty() {
        return Err(syn::Error::new(span, "Composition groups cannot be empty"));
    }

    let mut permute = Vec::new();
    let mut repeat = Vec::new();

    // Closure to parse one entry in the expression and update
    // the relevant lists
    let mut parse_content = |content: ParseStream, index: usize| -> syn::Result<Index> {
        if content.peek(syn::Token![..]) {
            content.parse::<syn::Token![..]>()?;
            if !consumed.insert("..".to_string()) {
                return Err(syn::Error::new(
                    span,
                    "Ellipsis `..` appears more than once on the right",
                ));
            }
            let ignored_index = positions.get("..").ok_or_else(|| {
                syn::Error::new(
                    content.span(),
                    "Ellipsis `..` must appear on both sides of the expression",
                )
            })?;
            permute.push(ignored_index.clone());
            *index_fn = Box::new(Index::Unknown);
            Ok(Index::Range(index))
        } else if content.peek(syn::Ident) {
            let (name, shape) = parse_identifier(content)?;
            if let Some(index) = positions.get(&name) {
                if shape.is_some() {
                    return Err(syn::Error::new(
                        span,
                        format!("Axis `{name}` cannot be assigned a size on the right"),
                    ));
                }
                permute.push(index.clone());
            } else {
                let shape = shape.ok_or_else(|| {
                    syn::Error::new(
                        content.span(),
                        format!("New axis `{name}` requires an explicit size"),
                    )
                })?;
                repeat.push((index_fn(index), shape));
            }
            if !consumed.insert(name.clone()) {
                return Err(syn::Error::new(
                    span,
                    format!("Axis `{name}` appears more than once on the right"),
                ));
            }
            Ok(index_fn(index))
        } else if content.peek(syn::LitInt) {
            repeat.push((index_fn(index), Shape::Lit(parse_usize(content)?)));
            Ok(index_fn(index))
        } else if content.peek(syn::token::Brace) {
            let (name, shape) = parse_braced_expression(content)?;
            if !consumed.insert(name.clone()) {
                return Err(syn::Error::new(
                    span,
                    format!("Axis `{name}` appears more than once on the right"),
                ));
            }
            if let Some(index) = positions.get(&name) {
                permute.push(index.clone());
            } else {
                repeat.push((index_fn(index), shape));
            }
            Ok(index_fn(index))
        } else {
            Err(input.error("Unrecognized character on the right side of the expression"))
        }
    };

    // The starting index of the combined dimensions
    let from = parse_content(&content, start_index)?;

    // The ending index of the combined dimension,
    // we iterate through the entire expression to update relevant lists
    let mut to = None;
    for i in (start_index + 1).. {
        if content.is_empty() {
            break;
        }
        to = Some(parse_content(&content, i)?);
    }

    // We calculate the length of dimesions inside this parenthesis,
    // this helps the main loop keep track of skipped dimensions
    let len = if let Some(
        Index::Known(end_index) | Index::Unknown(end_index) | Index::Range(end_index),
    ) = to
    {
        (end_index - start_index) + 1
    } else {
        0
    };

    Ok((Composition::Combined { from, to }, permute, repeat, len))
}

fn peek_reduce_kw(input: ParseStream) -> bool {
    input.peek(kw::min)
        | input.peek(kw::max)
        | input.peek(kw::sum)
        | input.peek(kw::mean)
        | input.peek(kw::prod)
}

fn parse_reduce_fn(input: ParseStream) -> syn::Result<Vec<(String, Option<Shape>, Operation)>> {
    let span = input.span();
    let operation = if input.peek(kw::min) {
        input.parse::<kw::min>()?;
        Operation::Min
    } else if input.peek(kw::max) {
        input.parse::<kw::max>()?;
        Operation::Max
    } else if input.peek(kw::sum) {
        input.parse::<kw::sum>()?;
        Operation::Sum
    } else if input.peek(kw::mean) {
        input.parse::<kw::mean>()?;
        Operation::Mean
    } else if input.peek(kw::prod) {
        input.parse::<kw::prod>()?;
        Operation::Prod
    } else {
        return Err(input.error("Expected a reduction operation"));
    };

    let content;
    syn::parenthesized!(content in input);

    if content.is_empty() {
        return Err(syn::Error::new(span, "Reduction groups cannot be empty"));
    }

    Ok(content
        // A single operation call can have multiple dimensions,
        .call(parse_identifiers)?
        .into_iter()
        .map(|(name, shape)| (name, shape, operation.clone()))
        .collect())
}

fn parse_identifiers(content: ParseStream) -> syn::Result<Vec<(String, Option<Shape>)>> {
    let mut identifiers = Vec::new();
    while !content.is_empty() {
        if content.peek(syn::Ident) {
            let (name, shape) = content.call(parse_identifier)?;
            identifiers.push((name, shape));
        } else if content.peek(syn::Token![..]) {
            content.parse::<syn::Token![..]>()?;
            identifiers.push(("..".to_string(), None));
        } else if content.peek(syn::LitInt) {
            let lit_int = parse_usize(content)?;
            identifiers.push((lit_int.to_string(), Some(Shape::Lit(lit_int))));
        } else if content.peek(syn::token::Brace) {
            let (name, shape) = parse_braced_expression(content)?;
            identifiers.push((name, Some(shape)));
        } else {
            return Err(content.error("Unknown character introduced in the reduce operation"));
        }
    }
    Ok(identifiers)
}

fn parse_identifier(input: ParseStream) -> syn::Result<(String, Option<Shape>)> {
    let name = input.parse::<syn::Ident>()?.to_string();

    let shape = if input.peek(syn::Token![:]) {
        input.parse::<syn::Token![:]>()?;
        Some(Shape::Lit(parse_usize(input)?))
    } else {
        None
    };

    Ok((name, shape))
}

fn parse_usize(input: ParseStream) -> syn::Result<usize> {
    let len = input.parse::<syn::LitInt>()?;
    len.base10_parse::<usize>()
}