kcl_lib/std/
array.rs

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