kcl_lib/std/
array.rs

1use indexmap::IndexMap;
2
3use crate::{
4    ExecutorContext, SourceRange,
5    errors::{KclError, KclErrorDetails},
6    execution::{
7        ExecState,
8        fn_call::{Arg, Args},
9        kcl_value::{FunctionSource, KclValue},
10        types::RuntimeType,
11    },
12};
13
14/// Apply a function to each element of an array.
15pub async fn map(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
16    let array: Vec<KclValue> = args.get_unlabeled_kw_arg("array", &RuntimeType::any_array(), exec_state)?;
17    let f: FunctionSource = args.get_kw_arg("f", &RuntimeType::function(), exec_state)?;
18    let new_array = inner_map(array, f, exec_state, &args).await?;
19    Ok(KclValue::HomArray {
20        value: new_array,
21        ty: RuntimeType::any(),
22    })
23}
24
25async fn inner_map(
26    array: Vec<KclValue>,
27    f: FunctionSource,
28    exec_state: &mut ExecState,
29    args: &Args,
30) -> Result<Vec<KclValue>, KclError> {
31    let mut new_array = Vec::with_capacity(array.len());
32    for elem in array {
33        let new_elem = call_map_closure(elem, &f, args.source_range, exec_state, &args.ctx).await?;
34        new_array.push(new_elem);
35    }
36    Ok(new_array)
37}
38
39async fn call_map_closure(
40    input: KclValue,
41    map_fn: &FunctionSource,
42    source_range: SourceRange,
43    exec_state: &mut ExecState,
44    ctxt: &ExecutorContext,
45) -> Result<KclValue, KclError> {
46    let args = Args::new(
47        Default::default(),
48        vec![(None, Arg::new(input, source_range))],
49        source_range,
50        exec_state,
51        ctxt.clone(),
52    );
53    let output = map_fn.call_kw(None, exec_state, ctxt, args, source_range).await?;
54    let source_ranges = vec![source_range];
55    let output = output.ok_or_else(|| {
56        KclError::new_semantic(KclErrorDetails::new(
57            "Map function must return a value".to_owned(),
58            source_ranges,
59        ))
60    })?;
61    Ok(output)
62}
63
64/// For each item in an array, update a value.
65pub async fn reduce(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
66    let array: Vec<KclValue> = args.get_unlabeled_kw_arg("array", &RuntimeType::any_array(), exec_state)?;
67    let f: FunctionSource = args.get_kw_arg("f", &RuntimeType::function(), exec_state)?;
68    let initial: KclValue = args.get_kw_arg("initial", &RuntimeType::any(), exec_state)?;
69    inner_reduce(array, initial, f, exec_state, &args).await
70}
71
72async fn inner_reduce(
73    array: Vec<KclValue>,
74    initial: KclValue,
75    f: FunctionSource,
76    exec_state: &mut ExecState,
77    args: &Args,
78) -> Result<KclValue, KclError> {
79    let mut reduced = initial;
80    for elem in array {
81        reduced = call_reduce_closure(elem, reduced, &f, args.source_range, exec_state, &args.ctx).await?;
82    }
83
84    Ok(reduced)
85}
86
87async fn call_reduce_closure(
88    elem: KclValue,
89    accum: KclValue,
90    reduce_fn: &FunctionSource,
91    source_range: SourceRange,
92    exec_state: &mut ExecState,
93    ctxt: &ExecutorContext,
94) -> Result<KclValue, KclError> {
95    // Call the reduce fn for this repetition.
96    let mut labeled = IndexMap::with_capacity(1);
97    labeled.insert("accum".to_string(), Arg::new(accum, source_range));
98    let reduce_fn_args = Args::new(
99        labeled,
100        vec![(None, Arg::new(elem, source_range))],
101        source_range,
102        exec_state,
103        ctxt.clone(),
104    );
105    let transform_fn_return = reduce_fn
106        .call_kw(None, exec_state, ctxt, reduce_fn_args, source_range)
107        .await?;
108
109    // Unpack the returned transform object.
110    let source_ranges = vec![source_range];
111    let out = transform_fn_return.ok_or_else(|| {
112        KclError::new_semantic(KclErrorDetails::new(
113            "Reducer function must return a value".to_string(),
114            source_ranges.clone(),
115        ))
116    })?;
117    Ok(out)
118}
119
120pub async fn push(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
121    let (mut array, ty) = args.get_unlabeled_kw_arg_array_and_type("array", exec_state)?;
122    let item: KclValue = args.get_kw_arg("item", &RuntimeType::any(), exec_state)?;
123
124    array.push(item);
125
126    Ok(KclValue::HomArray { value: array, ty })
127}
128
129pub async fn pop(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
130    let (mut array, ty) = args.get_unlabeled_kw_arg_array_and_type("array", exec_state)?;
131    if array.is_empty() {
132        return Err(KclError::new_semantic(KclErrorDetails::new(
133            "Cannot pop from an empty array".to_string(),
134            vec![args.source_range],
135        )));
136    }
137    array.pop();
138    Ok(KclValue::HomArray { value: array, ty })
139}
140
141pub async fn concat(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
142    let (left, left_el_ty) = args.get_unlabeled_kw_arg_array_and_type("array", exec_state)?;
143    let right_value: KclValue = args.get_kw_arg("items", &RuntimeType::any_array(), exec_state)?;
144
145    match right_value {
146        KclValue::HomArray {
147            value: right,
148            ty: right_el_ty,
149            ..
150        } => Ok(inner_concat(&left, &left_el_ty, &right, &right_el_ty)),
151        KclValue::Tuple { value: right, .. } => {
152            // Tuples are treated as arrays for concatenation.
153            Ok(inner_concat(&left, &left_el_ty, &right, &RuntimeType::any()))
154        }
155        // Any single value is a subtype of an array, so we can treat it as a
156        // single-element array.
157        _ => Ok(inner_concat(&left, &left_el_ty, &[right_value], &RuntimeType::any())),
158    }
159}
160
161fn inner_concat(
162    left: &[KclValue],
163    left_el_ty: &RuntimeType,
164    right: &[KclValue],
165    right_el_ty: &RuntimeType,
166) -> KclValue {
167    if left.is_empty() {
168        return KclValue::HomArray {
169            value: right.to_vec(),
170            ty: right_el_ty.clone(),
171        };
172    }
173    if right.is_empty() {
174        return KclValue::HomArray {
175            value: left.to_vec(),
176            ty: left_el_ty.clone(),
177        };
178    }
179    let mut new = left.to_vec();
180    new.extend_from_slice(right);
181    // Propagate the element type if we can.
182    let ty = if right_el_ty.subtype(left_el_ty) {
183        left_el_ty.clone()
184    } else if left_el_ty.subtype(right_el_ty) {
185        right_el_ty.clone()
186    } else {
187        RuntimeType::any()
188    };
189    KclValue::HomArray { value: new, ty }
190}