Skip to main content

onnx_ir/node/
slice.rs

1//! # Slice
2//!
3//! Extracts a slice from the input tensor along multiple axes.
4//!
5//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__Slice.html>
6//!
7//! ## Type Constraints
8//!
9//! - T: tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(int8), tensor(int16), tensor(int32), tensor(int64), tensor(bfloat16), tensor(float16), tensor(float), tensor(double), tensor(string), tensor(bool), tensor(complex64), tensor(complex128)
10//! - Tind: tensor(int32), tensor(int64)
11//!
12//! ## Opset Versions
13//!
14//! - **Opset 1-9**: `starts`, `ends`, and `axes` were attributes (static only).
15//! - **Opset 10**: **BREAKING CHANGE** - Changed `starts`, `ends`, and `axes` from attributes to inputs
16//!   for dynamic slicing support. This enables runtime determination of slice parameters.
17//! - **Opset 11**: Added optional `steps` input for strided slicing.
18//! - **Opset 13**: Added bfloat16 and additional type support.
19use derive_new::new;
20use onnx_ir_derive::NodeBuilder;
21
22use crate::ir::{ArgType, Argument, Node, RawNode, RuntimeInputRef, TensorDataExt};
23use crate::processor::{
24    InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
25};
26
27/// Configuration for the Slice operation.
28#[derive(Debug, Clone, new)]
29pub struct SliceConfig {
30    pub starts: SliceInput,
31    pub ends: SliceInput,
32    pub axes: Option<SliceInput>,
33    pub steps: Option<SliceInput>,
34}
35
36/// Node representation for Slice operation
37#[derive(Debug, Clone, NodeBuilder)]
38pub struct SliceNode {
39    pub name: String,
40    pub inputs: Vec<Argument>,
41    pub outputs: Vec<Argument>,
42    pub config: SliceConfig,
43}
44
45/// Represents either a static value or a runtime argument for slice parameters.
46#[derive(Debug, Clone)]
47pub enum SliceInput {
48    /// Static value known at compile time.
49    Static(Vec<i64>),
50    /// Runtime argument determined during execution - references node.inputs\[input_index\].
51    Runtime(RuntimeInputRef),
52}
53
54impl Default for SliceInput {
55    fn default() -> Self {
56        Self::Static(Vec::new())
57    }
58}
59
60/// Normalize negative axes to positive indices based on tensor rank.
61fn normalize_axes(axes: &mut [i64], rank: usize, _node_name: &str) {
62    for axis in axes.iter_mut() {
63        if *axis < 0 {
64            *axis += rank as i64;
65        }
66    }
67}
68
69/// Calculate output length for slicing across a dimension.
70///
71/// Follows ONNX/Python semantics: negative indices count from the end, and
72/// out-of-range indices clamp. The ONNX-specific sentinels `i64::MAX` (end with
73/// step > 0, "to end") and `i64::MIN` (end with step < 0, "past first element")
74/// are handled implicitly by clamping — for `step > 0`, `i64::MAX` clamps to
75/// `dim_len`; for `step < 0`, `i64::MIN + dim_len` clamps to `-1`.
76fn calculate_dim_slice_output_len(start: i64, end: i64, step: i64, dim_size: usize) -> usize {
77    if dim_size == 0 {
78        return 0;
79    }
80    let dim_len = dim_size as i64;
81
82    // Normalize an index: negative values count from the end (idx + dim_len),
83    // then the result is clamped into the valid range for this step direction.
84    fn normalize_index(idx: i64, lo: i64, hi: i64, n: i64) -> i64 {
85        let abs = if idx < 0 { idx + n } else { idx };
86        abs.clamp(lo, hi)
87    }
88
89    // For step > 0, valid endpoints are [0, dim_len]: start at dim_len means
90    // empty slice; end at dim_len means slice to the last element.
91    // For step < 0, both endpoints range over [-1, dim_len-1], where -1 is the
92    // conceptual position before the first element. A start that resolves below
93    // -1 begins there and so selects nothing, matching numpy and the ONNX
94    // reference evaluator.
95    let (norm_start, norm_end) = if step > 0 {
96        (
97            normalize_index(start, 0, dim_len, dim_len),
98            normalize_index(end, 0, dim_len, dim_len),
99        )
100    } else {
101        (
102            normalize_index(start, -1, dim_len - 1, dim_len),
103            normalize_index(end, -1, dim_len - 1, dim_len),
104        )
105    };
106
107    let range_len = (norm_end - norm_start) * step.signum();
108    if range_len <= 0 {
109        0
110    } else {
111        // `step` comes straight from the model: `abs()` would overflow on
112        // i64::MIN, and rounding up in i64 would overflow on a huge step.
113        (range_len as u64).div_ceil(step.unsigned_abs()) as usize
114    }
115}
116
117pub(crate) struct SliceProcessor;
118
119impl NodeProcessor for SliceProcessor {
120    type Config = SliceConfig;
121
122    fn spec(&self) -> NodeSpec {
123        NodeSpec {
124            min_opset: 1,
125            max_opset: None,
126            inputs: InputSpec::AtLeast(1),
127            outputs: OutputSpec::Exact(1),
128        }
129    }
130
131    fn input_preferences(
132        &self,
133        node: &RawNode,
134        _opset: usize,
135    ) -> Result<Option<crate::processor::InputPreferences>, ProcessError> {
136        use crate::processor::{ArgPreference, InputPreferences};
137
138        let mut prefs = InputPreferences::new();
139        for input in node.inputs.iter().skip(1) {
140            // Prefer constants to be Shape; scalars must be native (for Slice bounds)
141            prefs = prefs.add(&input.name, ArgPreference::Shape);
142            if input.ty.is_scalar() {
143                prefs = prefs.add(&input.name, ArgPreference::ScalarNative);
144            }
145        }
146
147        Ok(Some(prefs))
148    }
149
150    fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
151        // Lift starts input (input[1]) if present
152        if node.inputs.len() > 1 && node.inputs[1].is_constant() {
153            node.inputs[1].to_static()?;
154        }
155
156        // Lift ends input (input[2]) if present
157        if node.inputs.len() > 2 && node.inputs[2].is_constant() {
158            node.inputs[2].to_static()?;
159        }
160
161        // Lift axes input (input[3]) if present
162        if node.inputs.len() > 3 && node.inputs[3].is_constant() {
163            node.inputs[3].to_static()?;
164        }
165
166        // Lift steps input (input[4]) if present
167        if node.inputs.len() > 4 && node.inputs[4].is_constant() {
168            node.inputs[4].to_static()?;
169        }
170
171        Ok(())
172    }
173
174    fn infer_types(
175        &self,
176        node: &mut RawNode,
177        opset: usize,
178        _output_preferences: &OutputPreferences,
179    ) -> Result<(), ProcessError> {
180        // Get reference to config for type inference
181        let config = self.extract_config(node, opset)?;
182
183        // Infer output type based on input type
184        let input_ty = node.inputs[0].ty.clone();
185
186        match input_ty {
187            ArgType::Tensor(tensor_type) => {
188                // Codegen only honours `steps` when both bounds are static. The
189                // runtime-bound paths emit a plain forward range, so a non-unit
190                // step there would silently slice the wrong elements. Reject the
191                // combination rather than ignoring the step, mirroring the guard
192                // the Shape input path already applies below.
193                //
194                // A runtime `steps` alongside runtime bounds stays allowed: the
195                // ONNX backend test suite passes all four as graph inputs, and
196                // the value cannot be checked here. Those models are assumed to
197                // step by 1, which is what every exporter emits.
198                let runtime_bounds = matches!(config.starts, SliceInput::Runtime(_))
199                    || matches!(config.ends, SliceInput::Runtime(_));
200                match &config.steps {
201                    Some(SliceInput::Runtime(_)) if !runtime_bounds => {
202                        return Err(ProcessError::Custom(format!(
203                            "Slice with static bounds needs static steps; node {} has a runtime steps input",
204                            node.name
205                        )));
206                    }
207                    Some(SliceInput::Static(steps))
208                        if runtime_bounds && steps.iter().any(|&s| s != 1) =>
209                    {
210                        return Err(ProcessError::Custom(format!(
211                            "Slice with runtime bounds only supports step=1; node {} has steps={:?}",
212                            node.name, steps
213                        )));
214                    }
215                    _ => {}
216                }
217
218                // Slice changes dimension sizes along sliced axes. Initialize all dimensions
219                // with sizes from input, then overwrite the axes we can compute statically.
220                let mut static_shape = tensor_type
221                    .static_shape
222                    .clone()
223                    .unwrap_or_else(|| vec![None; tensor_type.rank]);
224
225                if let (
226                    SliceInput::Static(starts),
227                    SliceInput::Static(ends),
228                    Some(SliceInput::Static(axes)),
229                    Some(SliceInput::Static(steps)),
230                ) = (&config.starts, &config.ends, &config.axes, &config.steps)
231                {
232                    for (i, &axis) in axes.iter().enumerate() {
233                        let axis = axis as usize;
234                        if let Some(Some(dim_size)) =
235                            tensor_type.static_shape.as_ref().and_then(|s| s.get(axis))
236                        {
237                            let out_dim = calculate_dim_slice_output_len(
238                                starts[i], ends[i], steps[i], *dim_size,
239                            );
240                            static_shape[axis] = Some(out_dim);
241                        }
242                    }
243                }
244
245                node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
246                    dtype: tensor_type.dtype,
247                    rank: tensor_type.rank,
248                    static_shape: Some(static_shape),
249                });
250            }
251            ArgType::Shape(shape_rank) => {
252                // Runtime path: output_len cannot be computed without the bound
253                // values, so degrade to a rank-1 i64 tensor.
254                let static_bounds = match (&config.starts, &config.ends, &config.steps) {
255                    (SliceInput::Static(s), SliceInput::Static(e), steps_opt) => {
256                        let steps = match steps_opt {
257                            Some(SliceInput::Static(st)) => st.clone(),
258                            Some(SliceInput::Runtime(_)) => vec![],
259                            None => vec![1],
260                        };
261                        if steps.is_empty() {
262                            None
263                        } else {
264                            Some((s, e, steps))
265                        }
266                    }
267                    _ => None,
268                };
269
270                if let Some((starts, ends, steps)) = static_bounds {
271                    if starts.len() != 1 || ends.len() != 1 {
272                        return Err(ProcessError::Custom(format!(
273                            "Slice on Shape input requires exactly one dimension slice config for node {}",
274                            node.name
275                        )));
276                    }
277
278                    let step = if steps.is_empty() { 1 } else { steps[0] };
279                    let output_len =
280                        calculate_dim_slice_output_len(starts[0], ends[0], step, shape_rank);
281                    node.outputs[0].ty = ArgType::Shape(output_len);
282                } else {
283                    // Enforce single-axis, step=1 invariants up front so the
284                    // codegen can rely on them.
285                    let len_of = |input: &SliceInput| -> Option<usize> {
286                        match input {
287                            SliceInput::Static(v) => Some(v.len()),
288                            SliceInput::Runtime(r) => {
289                                let ty = &node.inputs[r.input_index].ty;
290                                match ty {
291                                    ArgType::ScalarNative(_) | ArgType::ScalarTensor(_) => Some(1),
292                                    _ => ty.first_dim_static_len(),
293                                }
294                            }
295                        }
296                    };
297                    let mut any_unknown_len = false;
298                    for (which, input) in [("starts", &config.starts), ("ends", &config.ends)] {
299                        match len_of(input) {
300                            Some(n) if n != 1 => {
301                                return Err(ProcessError::Custom(format!(
302                                    "Slice on Shape input requires single-axis slicing; node {} has {} of length {}",
303                                    node.name, which, n
304                                )));
305                            }
306                            None => any_unknown_len = true,
307                            _ => {}
308                        }
309                    }
310                    if any_unknown_len {
311                        log::debug!(
312                            "Slice node {}: runtime bound length not statically known; \
313                             codegen will assert exactly one element at inference time",
314                            node.name
315                        );
316                    }
317                    match &config.steps {
318                        Some(SliceInput::Static(steps)) if steps.iter().any(|&s| s != 1) => {
319                            return Err(ProcessError::Custom(format!(
320                                "Slice on Shape input with runtime bounds only supports step=1; node {} has steps={:?}",
321                                node.name, steps
322                            )));
323                        }
324                        Some(SliceInput::Runtime(_)) => {
325                            return Err(ProcessError::Custom(format!(
326                                "Slice on Shape input with runtime steps is not supported (node {})",
327                                node.name
328                            )));
329                        }
330                        _ => {}
331                    }
332                    node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
333                        dtype: crate::ir::DType::I64,
334                        rank: 1,
335                        static_shape: None,
336                    });
337                }
338            }
339            ArgType::ScalarTensor(dtype) => {
340                // Treat as rank-1 tensor; slicing may change element count
341                node.outputs[0].ty = ArgType::Tensor(crate::ir::TensorType {
342                    dtype,
343                    rank: 1,
344                    static_shape: None,
345                });
346            }
347            unsupported_type => {
348                return Err(ProcessError::TypeMismatch {
349                    expected: "Tensor, Shape, or ScalarTensor".to_string(),
350                    actual: format!("{:?}", unsupported_type),
351                });
352            }
353        }
354
355        Ok(())
356    }
357
358    fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
359        // For opset < 10, starts/ends/axes are attributes
360        if node.inputs.len() < 2 {
361            let starts = node
362                .attrs
363                .get("starts")
364                .map(|v| v.clone().into_i64s().map(SliceInput::Static))
365                .transpose()?
366                .ok_or_else(|| ProcessError::MissingAttribute("starts".to_string()))?;
367            let ends = node
368                .attrs
369                .get("ends")
370                .map(|v| v.clone().into_i64s().map(SliceInput::Static))
371                .transpose()?
372                .ok_or_else(|| ProcessError::MissingAttribute("ends".to_string()))?;
373            let mut axes = node
374                .attrs
375                .get("axes")
376                .map(|v| v.clone().into_i64s().map(SliceInput::Static))
377                .transpose()?;
378
379            // Apply default axes if not provided
380            if axes.is_none()
381                && let SliceInput::Static(ref starts_vec) = starts
382            {
383                axes = Some(SliceInput::Static((0..starts_vec.len() as i64).collect()));
384            }
385
386            // Normalize negative axes
387            if let Some(SliceInput::Static(ref mut axes_values)) = axes
388                && let ArgType::Tensor(ref tensor_type) = node.inputs[0].ty
389            {
390                normalize_axes(axes_values, tensor_type.rank, &node.name);
391            }
392
393            // No steps in opset < 10
394            let steps = if let SliceInput::Static(ref starts_vec) = starts {
395                Some(SliceInput::Static(vec![1; starts_vec.len()]))
396            } else {
397                None
398            };
399
400            return Ok(SliceConfig {
401                starts,
402                ends,
403                axes,
404                steps,
405            });
406        }
407
408        // Extract config - helper function to get slice inputs (opset 10+)
409        fn get_slice_input(
410            node: &RawNode,
411            index: usize,
412        ) -> Result<Option<SliceInput>, ProcessError> {
413            let input = match node.inputs.get(index) {
414                Some(i) => i,
415                None => return Ok(None),
416            };
417
418            // Check if this is a Shape type (preferred for Slice parameters)
419            if matches!(input.ty, ArgType::Shape(_)) {
420                // Try to get static value if available
421                match input.value() {
422                    Some(tensor_data) => match tensor_data.to_i64_vec() {
423                        Ok(vec) => return Ok(Some(SliceInput::Static(vec))),
424                        Err(_) => {
425                            return Err(ProcessError::Custom(format!(
426                                "Slice Shape input at index {} must be int32 or int64",
427                                index
428                            )));
429                        }
430                    },
431                    None => {
432                        // Shape type without value means it's a runtime Shape (e.g., from Shape node)
433                        // Runtime input - store reference instead of cloning the argument
434                        return Ok(Some(SliceInput::Runtime(RuntimeInputRef::new(
435                            input.name.clone(),
436                            index,
437                        ))));
438                    }
439                }
440            }
441
442            // Otherwise, handle as Tensor (backward compatibility)
443            match input.value() {
444                None => {
445                    // Runtime input - store reference instead of cloning the argument
446                    Ok(Some(SliceInput::Runtime(RuntimeInputRef::new(
447                        input.name.clone(),
448                        index,
449                    ))))
450                }
451                Some(tensor_data) => match tensor_data.to_i64_vec() {
452                    Ok(vec) => Ok(Some(SliceInput::Static(vec))),
453                    Err(_) => Err(ProcessError::Custom(format!(
454                        "Slice input at index {} must be int32 or int64",
455                        index
456                    ))),
457                },
458            }
459        }
460
461        let starts = get_slice_input(node, 1)?
462            .ok_or_else(|| ProcessError::MissingInput("starts".to_string()))?;
463
464        let ends = get_slice_input(node, 2)?
465            .ok_or_else(|| ProcessError::MissingInput("ends".to_string()))?;
466
467        let axes = get_slice_input(node, 3)?;
468        let steps = get_slice_input(node, 4)?;
469
470        // Apply ONNX spec defaults for optional parameters.
471        //
472        // The number of slices is `len(starts)`. We determine it at IR time
473        // either from a static starts vector (opset < 10 attributes, or a
474        // constant tensor input) or from the starts argument's static_shape
475        // (a 1-D tensor whose first dim is known). If neither is available
476        // and `axes` is absent, we cannot fabricate a correct default, so
477        // the codegen must not guess — returning None here forces the
478        // downstream consumer to either supply axes or refuse the model.
479        let num_slices: Option<usize> = match &starts {
480            SliceInput::Static(v) => Some(v.len()),
481            SliceInput::Runtime(r) => node.inputs[r.input_index].ty.first_dim_static_len(),
482        };
483
484        let (mut axes, steps) = if let Some(n) = num_slices.filter(|n| *n > 0) {
485            // If steps not provided, default to all 1s (ONNX spec)
486            let steps = if steps.is_none() {
487                Some(SliceInput::Static(vec![1; n]))
488            } else {
489                steps
490            };
491
492            // If axes not provided, default to [0, 1, ..., n-1] (ONNX spec)
493            let axes = if axes.is_none() {
494                Some(SliceInput::Static((0..n as i64).collect()))
495            } else {
496                axes
497            };
498
499            (axes, steps)
500        } else {
501            // Length unknown: propagate as-is. If axes is None here, the
502            // codegen will reject at emission rather than silently slicing
503            // the wrong number of dimensions.
504            (axes, steps)
505        };
506
507        // Validate steps if present - zeros are not allowed
508        if let Some(SliceInput::Static(ref step_values)) = steps
509            && step_values.contains(&0)
510        {
511            return Err(ProcessError::Custom(
512                "Slice: step values cannot be zero".to_string(),
513            ));
514        }
515
516        // TODO: Missing validation that starts, ends, axes, and steps have same length.
517        // ONNX spec requires: len(starts) == len(ends) == len(axes) == len(steps).
518        // Implementation doesn't validate this constraint, which could cause indexing errors.
519
520        // TODO: Missing validation that axes values are unique and in valid range [-rank, rank-1].
521        // Duplicate axes or out-of-range axes should be rejected but aren't validated.
522
523        // Normalize negative axes if we have static axes and know the input rank
524        if let Some(SliceInput::Static(ref mut axes_values)) = axes
525            && let ArgType::Tensor(ref tensor_type) = node.inputs[0].ty
526        {
527            normalize_axes(axes_values, tensor_type.rank, &node.name);
528        }
529
530        let config = SliceConfig {
531            starts,
532            ends,
533            axes,
534            steps,
535        };
536        Ok(config)
537    }
538
539    fn build_node(&self, builder: RawNode, opset: usize) -> Result<Node, ProcessError> {
540        let config = self.extract_config(&builder, opset)?;
541
542        Ok(Node::Slice(SliceNode {
543            name: builder.name,
544            inputs: builder.inputs,
545            outputs: builder.outputs,
546            config,
547        }))
548    }
549}
550
551#[cfg(test)]
552mod tests {
553    use crate::ir::{DType, NodeType};
554    use crate::node::test_utils::TestNodeBuilder;
555
556    use super::*;
557
558    fn create_test_node(
559        starts: Vec<i64>,
560        ends: Vec<i64>,
561        axes: Option<Vec<i64>>,
562    ) -> TestNodeBuilder {
563        let mut builder = TestNodeBuilder::new(NodeType::Slice, "test_slice")
564            .input_tensor_f32("data", 3, None)
565            .output_default("output");
566
567        // Add inputs as tensors
568        builder = builder.input_tensor_i64_data("starts", starts.clone(), vec![starts.len()]);
569        builder = builder.input_tensor_i64_data("ends", ends.clone(), vec![ends.len()]);
570
571        if let Some(axes_vec) = axes.clone() {
572            builder = builder.input_tensor_i64_data("axes", axes_vec.clone(), vec![axes_vec.len()]);
573        }
574
575        builder
576    }
577
578    fn create_static_shape_slice_node(
579        static_shape: Vec<Option<usize>>,
580        starts: Vec<i64>,
581        ends: Vec<i64>,
582        axes: Vec<i64>,
583        steps: Vec<i64>,
584    ) -> TestNodeBuilder {
585        TestNodeBuilder::new(NodeType::Slice, "test_tensor_slice")
586            .add_input(
587                "data",
588                ArgType::Tensor(crate::ir::TensorType {
589                    dtype: crate::ir::DType::F32,
590                    rank: static_shape.len(),
591                    static_shape: Some(static_shape),
592                }),
593            )
594            .input_tensor_i64_data("starts", starts.clone(), vec![starts.len()])
595            .input_tensor_i64_data("ends", ends.clone(), vec![ends.len()])
596            .input_tensor_i64_data("axes", axes.clone(), vec![axes.len()])
597            .input_tensor_i64_data("steps", steps.clone(), vec![steps.len()])
598            .output_default("output")
599    }
600
601    fn create_shape_input_node(start: i64, end: i64) -> TestNodeBuilder {
602        TestNodeBuilder::new(NodeType::Slice, "test_slice_shape")
603            .input_shape("data", 5)
604            .input_tensor_i64_data("starts", vec![start], vec![1])
605            .input_tensor_i64_data("ends", vec![end], vec![1])
606            .input_tensor_i64_data("axes", vec![0], vec![1])
607            .output_default("output")
608    }
609
610    fn create_runtime_slice_node() -> TestNodeBuilder {
611        TestNodeBuilder::new(NodeType::Slice, "test_runtime_slice")
612            .input_tensor_f32("data", 2, None)
613            .input_tensor_i64("starts", 0, None) // No static value - runtime input
614            .input_tensor_i64("ends", 0, None) // No static value - runtime input
615            .input_tensor_i64_data("axes", vec![0], vec![1])
616            .input_tensor_i64_data("steps", vec![1], vec![1])
617            .output_default("output")
618    }
619
620    fn create_mixed_slice_node_runtime_start() -> TestNodeBuilder {
621        TestNodeBuilder::new(NodeType::Slice, "test_mixed_slice")
622            .input_tensor_f32("data", 2, None)
623            .input_tensor_i64("starts", 0, None) // Runtime input
624            .input_tensor_i64_data("ends", vec![3], vec![1]) // Static input
625            .input_tensor_i64_data("axes", vec![0], vec![1])
626            .input_tensor_i64_data("steps", vec![1], vec![1])
627            .output_default("output")
628    }
629
630    fn create_mixed_slice_node_runtime_end() -> TestNodeBuilder {
631        TestNodeBuilder::new(NodeType::Slice, "test_mixed_slice")
632            .input_tensor_f32("data", 2, None)
633            .input_tensor_i64_data("starts", vec![1], vec![1]) // Static input
634            .input_tensor_i64("ends", 0, None) // Runtime input
635            .input_tensor_i64_data("axes", vec![0], vec![1])
636            .input_tensor_i64_data("steps", vec![1], vec![1])
637            .output_default("output")
638    }
639
640    #[test]
641    fn test_slice_config_basic() {
642        // Create a node with inputs for basic slicing
643        let node =
644            create_test_node(vec![1, 0], vec![3, 2], Some(vec![0, 2])).build_with_graph_data(16);
645
646        let mut node = node;
647
648        let processor = SliceProcessor;
649
650        let prefs = OutputPreferences::new();
651        processor.infer_types(&mut node, 16, &prefs).unwrap();
652
653        let result = processor.extract_config(&node, 16).unwrap();
654
655        // Check that we have static starts and ends
656        match (&result.starts, &result.ends) {
657            (SliceInput::Static(starts), SliceInput::Static(ends)) => {
658                assert_eq!(starts, &vec![1, 0]);
659                assert_eq!(ends, &vec![3, 2]);
660                // Check axes
661                if let Some(SliceInput::Static(axes)) = &result.axes {
662                    assert_eq!(axes, &vec![0, 2]);
663                }
664                // Steps should have ONNX spec default of [1, 1] when not provided
665                if let Some(SliceInput::Static(steps)) = &result.steps {
666                    assert_eq!(steps, &vec![1, 1]);
667                } else {
668                    panic!("Expected steps to have ONNX spec default");
669                }
670            }
671            _ => panic!("Expected static config"),
672        }
673    }
674
675    #[test]
676    fn test_slice_config_negative_axes() {
677        // Test with negative axes values
678        let node = create_test_node(vec![1], vec![3], Some(vec![-3])).build_with_graph_data(16);
679
680        let mut node = node;
681
682        let processor = SliceProcessor;
683
684        let prefs = OutputPreferences::new();
685        processor.infer_types(&mut node, 16, &prefs).unwrap();
686
687        let result = processor.extract_config(&node, 16).unwrap();
688
689        // Check that we have static starts and ends
690        match (&result.starts, &result.ends) {
691            (SliceInput::Static(starts), SliceInput::Static(ends)) => {
692                assert_eq!(starts, &vec![1]);
693                assert_eq!(ends, &vec![3]);
694                // Check axes (should be normalized from -3 to 0 for rank 3 tensor)
695                if let Some(SliceInput::Static(axes)) = &result.axes {
696                    assert_eq!(axes, &vec![0]); // -3 + 3 = 0
697                }
698            }
699            _ => panic!("Expected static config"),
700        }
701    }
702
703    #[test]
704    fn test_slice_config_default_axes() {
705        // Test the default axes behavior (when axes input is not provided)
706        let node = create_test_node(vec![1, 2], vec![3, 4], None).build_with_graph_data(16);
707
708        let mut node = node;
709
710        let processor = SliceProcessor;
711
712        let prefs = OutputPreferences::new();
713        processor.infer_types(&mut node, 16, &prefs).unwrap();
714
715        let result = processor.extract_config(&node, 16).unwrap();
716
717        // Check that we have static starts and ends
718        match (&result.starts, &result.ends) {
719            (SliceInput::Static(starts), SliceInput::Static(ends)) => {
720                assert_eq!(starts, &vec![1, 2]);
721                assert_eq!(ends, &vec![3, 4]);
722                // axes should have ONNX spec default of [0, 1] when not provided
723                if let Some(SliceInput::Static(axes)) = &result.axes {
724                    assert_eq!(axes, &vec![0, 1]);
725                } else {
726                    panic!("Expected axes to have ONNX spec default");
727                }
728            }
729            _ => panic!("Expected static config"),
730        }
731    }
732
733    #[test]
734    fn test_slice_config_runtime() {
735        // Test with runtime bounds (starts/ends have no static values)
736        let mut node = create_runtime_slice_node().build_with_graph_data(16);
737
738        let processor = SliceProcessor;
739
740        let prefs = OutputPreferences::new();
741        processor.infer_types(&mut node, 16, &prefs).unwrap();
742
743        let result = processor.extract_config(&node, 16).unwrap();
744
745        // Check that we have runtime starts and ends
746        match (&result.starts, &result.ends) {
747            (SliceInput::Runtime(starts), SliceInput::Runtime(ends)) => {
748                assert_eq!(starts.name, "starts");
749                assert_eq!(ends.name, "ends");
750                // Constant axes/steps must lift, not degrade to runtime.
751                assert!(
752                    matches!(&result.axes, Some(SliceInput::Static(axes)) if axes == &vec![0]),
753                    "expected static axes, got {:?}",
754                    result.axes
755                );
756                assert!(
757                    matches!(&result.steps, Some(SliceInput::Static(steps)) if steps == &vec![1]),
758                    "expected static steps, got {:?}",
759                    result.steps
760                );
761            }
762            _ => panic!("Expected runtime config"),
763        }
764    }
765
766    #[test]
767    fn test_slice_update_output_rank_tensor_input() {
768        // Test when input is a Tensor - output should preserve the same type
769        let mut node = create_test_node(vec![1, 2], vec![3, 4], None).build_with_graph_data(16);
770
771        // Before calling, input is Tensor and output is default
772        assert!(matches!(node.inputs[0].ty, ArgType::Tensor(_)));
773        assert!(matches!(node.outputs[0].ty, ArgType::Tensor(_)));
774
775        let processor = SliceProcessor;
776        let prefs = OutputPreferences::new();
777        processor.infer_types(&mut node, 16, &prefs).unwrap();
778
779        // After calling, output should be the same type as input
780        assert!(
781            matches!(&node.outputs[0].ty, ArgType::Tensor(tensor_type) if tensor_type.dtype == DType::F32 && tensor_type.rank == 3)
782        );
783    }
784
785    #[test]
786    fn test_slice_update_output_rank_shape_input() {
787        // Test when input is a Shape - output should be a rank-1 Int64 Tensor
788        let mut node = create_shape_input_node(1, 3).build_with_graph_data(16);
789
790        // Before calling, input is Shape and output is default
791        assert!(matches!(node.inputs[0].ty, ArgType::Shape(5)));
792        // Default output type is Tensor with rank 0
793        assert!(matches!(node.outputs[0].ty, ArgType::Tensor(ref t) if t.rank == 0));
794
795        let processor = SliceProcessor;
796        let prefs = OutputPreferences::new();
797        processor.infer_types(&mut node, 16, &prefs).unwrap();
798
799        // After calling, output should be ArgType::Shape with the calculated length
800        // start = 1, end = 3 => output_len = 3 - 1 = 2
801        assert!(matches!(&node.outputs[0].ty, ArgType::Shape(2)));
802    }
803
804    #[test]
805    fn test_slice_shape_input_runtime_bounds_degrades_to_tensor() {
806        // Slicing a Shape with runtime starts/ends. Output length cannot be
807        // computed at IR time, so the type degrades to a rank-1 i64 tensor.
808        let mut node = TestNodeBuilder::new(NodeType::Slice, "test_slice_shape_runtime")
809            .input_shape("data", 5)
810            .input_tensor_i64("starts", 1, None)
811            .input_tensor_i64("ends", 1, None)
812            .output_default("output")
813            .build_with_graph_data(16);
814
815        let processor = SliceProcessor;
816        let prefs = OutputPreferences::new();
817        processor.infer_types(&mut node, 16, &prefs).unwrap();
818
819        match &node.outputs[0].ty {
820            ArgType::Tensor(t) => {
821                assert_eq!(t.dtype, DType::I64);
822                assert_eq!(t.rank, 1);
823                assert!(t.static_shape.is_none());
824            }
825            other => panic!("Expected Tensor output, got {:?}", other),
826        }
827    }
828
829    #[test]
830    fn test_slice_shape_input_runtime_bounds_length_gt_1_rejected() {
831        // Bounds with a statically known length > 1 cannot work for Shape
832        // slicing (codegen reads element 0 only). Reject early with a clear
833        // error rather than silently producing the wrong slice.
834        let mut node = TestNodeBuilder::new(NodeType::Slice, "shape_runtime_len2")
835            .input_shape("data", 5)
836            .input_tensor_i64("starts", 1, Some(vec![2]))
837            .input_tensor_i64("ends", 1, Some(vec![2]))
838            .output_default("output")
839            .build_with_graph_data(16);
840
841        let processor = SliceProcessor;
842        let prefs = OutputPreferences::new();
843        let result = processor.infer_types(&mut node, 16, &prefs);
844        assert!(matches!(result, Err(ProcessError::Custom(ref m)) if m.contains("single-axis")));
845    }
846
847    #[test]
848    fn test_slice_tensor_runtime_bounds_non_unit_step_rejected() {
849        // The runtime-bound tensor codegen emits a plain forward range and
850        // drops `steps` entirely, so a non-1 step would slice the wrong
851        // elements with no diagnostic anywhere.
852        for step in [-1, 2] {
853            let mut node = TestNodeBuilder::new(NodeType::Slice, "tensor_runtime_step")
854                .input_tensor_f32("data", 2, None)
855                .input_tensor_i64("starts", 1, None)
856                .input_tensor_i64("ends", 1, None)
857                .input_tensor_i64_data("axes", vec![0], vec![1])
858                .input_tensor_i64_data("steps", vec![step], vec![1])
859                .output_default("output")
860                .build_with_graph_data(16);
861
862            let processor = SliceProcessor;
863            let result = processor.infer_types(&mut node, 16, &OutputPreferences::new());
864            assert!(
865                matches!(result, Err(ProcessError::Custom(ref m)) if m.contains("step=1")),
866                "step {step} should be rejected, got {result:?}"
867            );
868        }
869    }
870
871    #[test]
872    fn test_slice_tensor_runtime_steps_with_static_bounds_rejected() {
873        // The static-bounds codegen path requires a static `steps`; without
874        // this guard it panics instead.
875        let mut node = TestNodeBuilder::new(NodeType::Slice, "tensor_runtime_steps")
876            .input_tensor_f32("data", 2, None)
877            .input_tensor_i64_data("starts", vec![0], vec![1])
878            .input_tensor_i64_data("ends", vec![2], vec![1])
879            .input_tensor_i64_data("axes", vec![0], vec![1])
880            .input_tensor_i64("steps", 1, None)
881            .output_default("output")
882            .build_with_graph_data(16);
883
884        let processor = SliceProcessor;
885        let result = processor.infer_types(&mut node, 16, &OutputPreferences::new());
886        assert!(
887            matches!(result, Err(ProcessError::Custom(ref m)) if m.contains("static steps")),
888            "runtime steps with static bounds should be rejected, got {result:?}"
889        );
890    }
891
892    #[test]
893    fn test_slice_tensor_all_runtime_allowed() {
894        // The ONNX backend test suite's `test_slice` passes starts, ends, axes
895        // and steps all as graph inputs. Nothing can be checked statically
896        // there, so it must still import.
897        let mut node = TestNodeBuilder::new(NodeType::Slice, "tensor_all_runtime")
898            .input_tensor_f32("data", 2, None)
899            .input_tensor_i64("starts", 1, None)
900            .input_tensor_i64("ends", 1, None)
901            .input_tensor_i64("axes", 1, None)
902            .input_tensor_i64("steps", 1, None)
903            .output_default("output")
904            .build_with_graph_data(16);
905
906        let processor = SliceProcessor;
907        processor
908            .infer_types(&mut node, 16, &OutputPreferences::new())
909            .expect("fully runtime Slice params must still import");
910    }
911
912    #[test]
913    fn test_slice_tensor_runtime_bounds_unit_step_allowed() {
914        // The supported combination must keep working.
915        let mut node = TestNodeBuilder::new(NodeType::Slice, "tensor_runtime_step1")
916            .input_tensor_f32("data", 2, None)
917            .input_tensor_i64("starts", 1, None)
918            .input_tensor_i64("ends", 1, None)
919            .input_tensor_i64_data("axes", vec![0], vec![1])
920            .input_tensor_i64_data("steps", vec![1], vec![1])
921            .output_default("output")
922            .build_with_graph_data(16);
923
924        let processor = SliceProcessor;
925        processor
926            .infer_types(&mut node, 16, &OutputPreferences::new())
927            .expect("runtime bounds with step=1 are supported");
928    }
929
930    #[test]
931    fn test_slice_shape_input_runtime_bounds_step_2_rejected() {
932        // The runtime Shape-slice codegen uses an implicit step of 1.
933        // A non-1 step would produce a wrong slice silently, so reject it.
934        let mut node = TestNodeBuilder::new(NodeType::Slice, "shape_runtime_step2")
935            .input_shape("data", 5)
936            .input_tensor_i64("starts", 1, None)
937            .input_tensor_i64("ends", 1, None)
938            .input_tensor_i64_data("axes", vec![0], vec![1])
939            .input_tensor_i64_data("steps", vec![2], vec![1])
940            .output_default("output")
941            .build_with_graph_data(16);
942
943        let processor = SliceProcessor;
944        let prefs = OutputPreferences::new();
945        let result = processor.infer_types(&mut node, 16, &prefs);
946        assert!(matches!(result, Err(ProcessError::Custom(ref m)) if m.contains("step=1")));
947    }
948
949    #[test]
950    fn test_slice_config_mixed_runtime_start() {
951        // Test with runtime start but static end
952        let node = create_mixed_slice_node_runtime_start().build_with_graph_data(16);
953
954        let mut node = node;
955
956        let processor = SliceProcessor;
957
958        let prefs = OutputPreferences::new();
959        processor.infer_types(&mut node, 16, &prefs).unwrap();
960
961        let result = processor.extract_config(&node, 16).unwrap();
962
963        // Check that we have mixed starts and ends
964        match (&result.starts, &result.ends) {
965            (SliceInput::Runtime(starts), SliceInput::Static(ends)) => {
966                assert_eq!(starts.name, "starts");
967                assert_eq!(ends, &vec![3]);
968            }
969            _ => panic!("Expected mixed config with runtime start and static end"),
970        }
971    }
972
973    #[test]
974    fn test_slice_config_mixed_runtime_end() {
975        // Test with static start but runtime end
976        let node = create_mixed_slice_node_runtime_end().build_with_graph_data(16);
977
978        let mut node = node;
979
980        let processor = SliceProcessor;
981
982        let prefs = OutputPreferences::new();
983        processor.infer_types(&mut node, 16, &prefs).unwrap();
984
985        let result = processor.extract_config(&node, 16).unwrap();
986
987        // Check that we have mixed starts and ends
988        match (&result.starts, &result.ends) {
989            (SliceInput::Static(starts), SliceInput::Runtime(ends)) => {
990                assert_eq!(starts, &vec![1]);
991                assert_eq!(ends.name, "ends");
992            }
993            _ => panic!("Expected mixed config with static start and runtime end"),
994        }
995    }
996
997    #[test]
998    fn test_slice_config_with_steps() {
999        // Create a node with steps input
1000        let builder = TestNodeBuilder::new(NodeType::Slice, "test_slice_with_steps")
1001            .input_tensor_f32("data", 3, None)
1002            .input_tensor_i64_data("starts", vec![0, 0], vec![2])
1003            .input_tensor_i64_data("ends", vec![10, 10], vec![2])
1004            .input_tensor_i64_data("axes", vec![0, 1], vec![2])
1005            .input_tensor_i64_data("steps", vec![2, 3], vec![2])
1006            .output_default("output");
1007
1008        let node = builder.build_with_graph_data(16);
1009        let mut node = node;
1010
1011        let processor = SliceProcessor;
1012
1013        let prefs = OutputPreferences::new();
1014        processor.infer_types(&mut node, 16, &prefs).unwrap();
1015
1016        let result = processor.extract_config(&node, 16).unwrap();
1017
1018        // Check that we have static starts, ends, and steps
1019        match (&result.starts, &result.ends, &result.steps) {
1020            (
1021                SliceInput::Static(starts),
1022                SliceInput::Static(ends),
1023                Some(SliceInput::Static(steps)),
1024            ) => {
1025                assert_eq!(starts, &vec![0, 0]);
1026                assert_eq!(ends, &vec![10, 10]);
1027                assert_eq!(steps, &vec![2, 3]);
1028            }
1029            _ => panic!("Expected static config with steps"),
1030        }
1031    }
1032
1033    #[test]
1034    fn test_slice_config_zero_step() {
1035        // Create a node with zero step value (should return error)
1036        let builder = TestNodeBuilder::new(NodeType::Slice, "test_zero_step")
1037            .input_tensor_f32("data", 2, None)
1038            .input_tensor_i64_data("starts", vec![0], vec![1])
1039            .input_tensor_i64_data("ends", vec![10], vec![1])
1040            .input_tensor_i64_data("axes", vec![0], vec![1])
1041            .input_tensor_i64_data("steps", vec![0], vec![1])
1042            .output_default("output");
1043
1044        let node = builder.build_with_graph_data(16);
1045        let node = node;
1046
1047        let processor = SliceProcessor;
1048
1049        let result = processor.extract_config(&node, 16);
1050        assert!(matches!(result, Err(ProcessError::Custom(_))));
1051    }
1052
1053    #[test]
1054    fn test_slice_config_negative_steps() {
1055        // Create a node with negative step values
1056        let builder = TestNodeBuilder::new(NodeType::Slice, "test_negative_steps")
1057            .input_tensor_f32("data", 2, None)
1058            .input_tensor_i64_data("starts", vec![0, 2], vec![2])
1059            .input_tensor_i64_data("ends", vec![10, 8], vec![2])
1060            .input_tensor_i64_data("axes", vec![0, 1], vec![2])
1061            .input_tensor_i64_data("steps", vec![-1, -2], vec![2])
1062            .output_default("output");
1063
1064        let node = builder.build_with_graph_data(16);
1065        let mut node = node;
1066
1067        let processor = SliceProcessor;
1068
1069        let prefs = OutputPreferences::new();
1070        processor.infer_types(&mut node, 16, &prefs).unwrap();
1071
1072        let result = processor.extract_config(&node, 16).unwrap();
1073
1074        // Check that negative steps are preserved
1075        match &result.steps {
1076            Some(SliceInput::Static(steps)) => {
1077                assert_eq!(steps, &vec![-1, -2]);
1078            }
1079            _ => panic!("Expected static steps with negative values"),
1080        }
1081    }
1082
1083    #[test]
1084    fn test_tensor_static_shape_known_dim_filled() {
1085        // Slice axis 0: start=2, end=7, step=1
1086        let mut node = create_static_shape_slice_node(
1087            vec![Some(10), Some(20)],
1088            vec![2],
1089            vec![7],
1090            vec![0],
1091            vec![1],
1092        )
1093        .build_with_graph_data(16);
1094
1095        let processor = SliceProcessor;
1096        processor
1097            .infer_types(&mut node, 16, &OutputPreferences::new())
1098            .unwrap();
1099
1100        match &node.outputs[0].ty {
1101            ArgType::Tensor(tensor_type) => {
1102                let shape = tensor_type.static_shape.as_ref().unwrap();
1103                assert_eq!(shape[0], Some(5));
1104                assert_eq!(shape[1], Some(20));
1105            }
1106            other => panic!("Expected tensor, got {:?}", other),
1107        }
1108    }
1109
1110    #[test]
1111    fn test_tensor_static_shape_multi_axis_partial_known() {
1112        // Slice axis 0: size=10, start=1, end=6, step=1
1113        // Slice axis 2: size=12, start=0, end=12, step=2
1114        let mut node = create_static_shape_slice_node(
1115            vec![Some(10), Some(5), Some(12)],
1116            vec![1, 0],
1117            vec![6, 12],
1118            vec![0, 2],
1119            vec![1, 2],
1120        )
1121        .build_with_graph_data(16);
1122
1123        let processor = SliceProcessor;
1124        processor
1125            .infer_types(&mut node, 16, &OutputPreferences::new())
1126            .unwrap();
1127
1128        match &node.outputs[0].ty {
1129            ArgType::Tensor(tensor_type) => {
1130                let shape = tensor_type.static_shape.as_ref().unwrap();
1131                assert_eq!(shape[0], Some(5));
1132                assert_eq!(shape[1], Some(5));
1133                assert_eq!(shape[2], Some(6));
1134            }
1135            other => panic!("Expected tensor, got {:?}", other),
1136        }
1137    }
1138
1139    #[test]
1140    fn test_tensor_static_shape_runtime_inputs_all_none() {
1141        // Slice axis 0: size=None, start=None, end=None, step=1
1142        let mut node = create_runtime_slice_node().build_with_graph_data(16);
1143
1144        let processor = SliceProcessor;
1145        processor
1146            .infer_types(&mut node, 16, &OutputPreferences::new())
1147            .unwrap();
1148
1149        match &node.outputs[0].ty {
1150            ArgType::Tensor(tensor_type) => match &tensor_type.static_shape {
1151                Some(shape) => {
1152                    assert_eq!(shape.len(), 2);
1153                    assert!(shape.iter().all(|d| d.is_none()));
1154                }
1155                None => panic!("Expect tensor static shape"),
1156            },
1157            other => panic!("Expected tensor, got {:?}", other),
1158        }
1159    }
1160
1161    #[test]
1162    fn test_dim_slice_output_len_sentinels_and_extreme_steps() {
1163        // i64::MIN for `ends` with step < 0 means "past the first element":
1164        // adding dim_len keeps it far below zero, so it clamps to -1 and the
1165        // whole axis is in range, with `step` then thinning it.
1166        assert_eq!(calculate_dim_slice_output_len(7, i64::MIN, -1, 8), 8);
1167        assert_eq!(calculate_dim_slice_output_len(-1, i64::MIN, -1, 8), 8);
1168        assert_eq!(calculate_dim_slice_output_len(7, i64::MIN, -3, 8), 3);
1169
1170        // i64::MAX for `ends` with step > 0 clamps to dim_len.
1171        assert_eq!(calculate_dim_slice_output_len(3, i64::MAX, 1, 8), 5);
1172
1173        // The opposite sentinel on each path selects nothing.
1174        assert_eq!(calculate_dim_slice_output_len(3, i64::MIN, 1, 8), 0);
1175        assert_eq!(calculate_dim_slice_output_len(3, i64::MAX, -1, 8), 0);
1176
1177        // A reverse start below -dim begins before the first element, so it
1178        // selects nothing (numpy and the ONNX reference agree; the spec prose
1179        // saying starts clamp into [0, dim-1] is misleading here).
1180        assert_eq!(calculate_dim_slice_output_len(-100, i64::MIN, -1, 5), 0);
1181        assert_eq!(calculate_dim_slice_output_len(-6, i64::MIN, -1, 5), 0);
1182        assert_eq!(calculate_dim_slice_output_len(-5, i64::MIN, -1, 5), 1);
1183        assert_eq!(calculate_dim_slice_output_len(99, i64::MIN, -1, 5), 5);
1184
1185        // Steps come from the model unchecked, so the extremes must not
1186        // overflow while rounding the range length up.
1187        assert_eq!(calculate_dim_slice_output_len(0, 10, i64::MAX, 10), 1);
1188        assert_eq!(calculate_dim_slice_output_len(9, 0, i64::MIN, 10), 1);
1189    }
1190
1191    #[test]
1192    fn test_tensor_static_shape_end_i64_max_slices_to_end() {
1193        // Slice axis 0: size=8, start=3, end=i64::MAX, step=1
1194        let mut node = create_static_shape_slice_node(
1195            vec![Some(8)],
1196            vec![3],
1197            vec![i64::MAX],
1198            vec![0],
1199            vec![1],
1200        )
1201        .build_with_graph_data(16);
1202
1203        let processor = SliceProcessor;
1204        processor
1205            .infer_types(&mut node, 16, &OutputPreferences::new())
1206            .unwrap();
1207
1208        match &node.outputs[0].ty {
1209            ArgType::Tensor(t) => {
1210                let shape = t.static_shape.as_ref().unwrap();
1211                assert_eq!(shape[0], Some(5));
1212            }
1213            other => panic!("Expected tensor, got {:?}", other),
1214        }
1215    }
1216
1217    #[test]
1218    fn test_tensor_static_shape_end_i64_min_slices_to_start() {
1219        // Slice axis 0: dim=8, start=7, end=i64::MIN, step=-1
1220        let mut node = create_static_shape_slice_node(
1221            vec![Some(8)],
1222            vec![7],
1223            vec![i64::MIN],
1224            vec![0],
1225            vec![-1],
1226        )
1227        .build_with_graph_data(16);
1228
1229        let processor = SliceProcessor;
1230        processor
1231            .infer_types(&mut node, 16, &OutputPreferences::new())
1232            .unwrap();
1233
1234        match &node.outputs[0].ty {
1235            ArgType::Tensor(t) => {
1236                let shape = t.static_shape.as_ref().unwrap();
1237                assert_eq!(shape[0], Some(8));
1238            }
1239            other => panic!("Expected tensor, got {:?}", other),
1240        }
1241    }
1242
1243    #[test]
1244    fn test_tensor_static_shape_negative_step_typical() {
1245        // start=7, end=2, step=-1 over dim=10 -> indices 7,6,5,4,3 = 5 elements
1246        let mut node =
1247            create_static_shape_slice_node(vec![Some(10)], vec![7], vec![2], vec![0], vec![-1])
1248                .build_with_graph_data(16);
1249
1250        let processor = SliceProcessor;
1251        processor
1252            .infer_types(&mut node, 16, &OutputPreferences::new())
1253            .unwrap();
1254
1255        match &node.outputs[0].ty {
1256            ArgType::Tensor(t) => assert_eq!(t.static_shape.as_ref().unwrap()[0], Some(5)),
1257            other => panic!("Expected tensor, got {:?}", other),
1258        }
1259    }
1260
1261    #[test]
1262    fn test_tensor_static_shape_negative_indices() {
1263        // start=-3, end=-1, step=1 over dim=10 -> indices 7,8 = 2 elements
1264        let mut node =
1265            create_static_shape_slice_node(vec![Some(10)], vec![-3], vec![-1], vec![0], vec![1])
1266                .build_with_graph_data(16);
1267
1268        let processor = SliceProcessor;
1269        processor
1270            .infer_types(&mut node, 16, &OutputPreferences::new())
1271            .unwrap();
1272
1273        match &node.outputs[0].ty {
1274            ArgType::Tensor(t) => assert_eq!(t.static_shape.as_ref().unwrap()[0], Some(2)),
1275            other => panic!("Expected tensor, got {:?}", other),
1276        }
1277    }
1278
1279    #[test]
1280    fn test_tensor_static_shape_empty_slice() {
1281        // start=5, end=5 with positive step yields a zero-length axis.
1282        let mut node =
1283            create_static_shape_slice_node(vec![Some(10)], vec![5], vec![5], vec![0], vec![1])
1284                .build_with_graph_data(16);
1285
1286        let processor = SliceProcessor;
1287        processor
1288            .infer_types(&mut node, 16, &OutputPreferences::new())
1289            .unwrap();
1290
1291        match &node.outputs[0].ty {
1292            ArgType::Tensor(t) => assert_eq!(t.static_shape.as_ref().unwrap()[0], Some(0)),
1293            other => panic!("Expected tensor, got {:?}", other),
1294        }
1295    }
1296
1297    #[test]
1298    fn test_tensor_static_shape_partial_known_preserves_none() {
1299        // Input has a None for axis 1; slicing only axis 0 must keep axis 1 as None.
1300        let mut node = create_static_shape_slice_node(
1301            vec![Some(10), None, Some(8)],
1302            vec![1],
1303            vec![6],
1304            vec![0],
1305            vec![1],
1306        )
1307        .build_with_graph_data(16);
1308
1309        let processor = SliceProcessor;
1310        processor
1311            .infer_types(&mut node, 16, &OutputPreferences::new())
1312            .unwrap();
1313
1314        match &node.outputs[0].ty {
1315            ArgType::Tensor(t) => {
1316                let shape = t.static_shape.as_ref().unwrap();
1317                assert_eq!(shape, &vec![Some(5), None, Some(8)]);
1318            }
1319            other => panic!("Expected tensor, got {:?}", other),
1320        }
1321    }
1322
1323    #[test]
1324    fn test_tensor_no_static_shape_yields_all_none() {
1325        // Input has rank but no static_shape; output should be Some(vec![None; rank]).
1326        let mut node = create_test_node(vec![1], vec![5], Some(vec![0])).build_with_graph_data(16);
1327
1328        let processor = SliceProcessor;
1329        processor
1330            .infer_types(&mut node, 16, &OutputPreferences::new())
1331            .unwrap();
1332
1333        match &node.outputs[0].ty {
1334            ArgType::Tensor(t) => {
1335                let shape = t.static_shape.as_ref().unwrap();
1336                assert_eq!(shape, &vec![None, None, None]);
1337            }
1338            other => panic!("Expected tensor, got {:?}", other),
1339        }
1340    }
1341
1342    #[test]
1343    fn test_shape_input_negative_step() {
1344        // Shape slicing with a negative step. Old impl returned 0 here; the
1345        // refactored normalization correctly returns 3 (indices 4,3,2).
1346        let mut node = TestNodeBuilder::new(NodeType::Slice, "test_shape_neg_step")
1347            .input_shape("data", 5)
1348            .input_tensor_i64_data("starts", vec![4], vec![1])
1349            .input_tensor_i64_data("ends", vec![1], vec![1])
1350            .input_tensor_i64_data("axes", vec![0], vec![1])
1351            .input_tensor_i64_data("steps", vec![-1], vec![1])
1352            .output_default("output")
1353            .build_with_graph_data(16);
1354
1355        let processor = SliceProcessor;
1356        processor
1357            .infer_types(&mut node, 16, &OutputPreferences::new())
1358            .unwrap();
1359
1360        assert!(matches!(&node.outputs[0].ty, ArgType::Shape(3)));
1361    }
1362
1363    // TODO: Missing test for mismatched lengths of starts/ends/axes/steps.
1364    // ONNX spec requires same length but this isn't tested or validated.
1365
1366    // TODO: Missing test for duplicate axes - e.g., axes=[0, 0] should be invalid.
1367    // Spec doesn't allow duplicate axes but implementation doesn't validate this.
1368
1369    // TODO: Missing test for out-of-bounds axes after normalization.
1370    // E.g., for rank-3 tensor, axes=[5] should be invalid even after negative index handling.
1371
1372    #[test]
1373    fn test_slice_scalar_tensor_input() {
1374        // Slicing a ScalarTensor produces a rank-1 Tensor (slice may change element count)
1375        let mut node = TestNodeBuilder::new(NodeType::Slice, "test_slice")
1376            .add_input("data", ArgType::ScalarTensor(DType::I64))
1377            .input_tensor_i64_data("starts", vec![0], vec![1])
1378            .input_tensor_i64_data("ends", vec![1], vec![1])
1379            .output_default("output")
1380            .build_with_graph_data(16);
1381
1382        let processor = SliceProcessor;
1383        let prefs = OutputPreferences::new();
1384        processor.infer_types(&mut node, 16, &prefs).unwrap();
1385
1386        match &node.outputs[0].ty {
1387            ArgType::Tensor(t) => {
1388                assert_eq!(t.dtype, DType::I64);
1389                assert_eq!(t.rank, 1);
1390            }
1391            other => panic!("Expected Tensor, got {:?}", other),
1392        }
1393    }
1394}